1 # -*- coding: utf-8 -*-
3 # common.py - part of the FDroid server tools
4 # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
5 # Copyright (C) 2013-2014 Daniel Martà <mvdan@mvdan.cc>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
36 def read_config(opts, config_file='config.py'):
37 """Read the repository config
39 The config is read from config_file, which is in the current directory when
40 any of the repo management commands are used.
42 global config, options
44 if config is not None:
46 if not os.path.isfile(config_file):
47 logging.critical("Missing config file - is this a repo directory?")
54 logging.debug("Reading %s" % config_file)
55 execfile(config_file, config)
57 # smartcardoptions must be a list since its command line args for Popen
58 if 'smartcardoptions' in config:
59 config['smartcardoptions'] = config['smartcardoptions'].split(' ')
60 elif 'keystore' in config and config['keystore'] == 'NONE':
61 # keystore='NONE' means use smartcard, these are required defaults
62 config['smartcardoptions'] = ['-storetype', 'PKCS11', '-providerName',
63 'SunPKCS11-OpenSC', '-providerClass',
64 'sun.security.pkcs11.SunPKCS11',
65 '-providerArg', 'opensc-fdroid.cfg']
68 'sdk_path': "$ANDROID_HOME",
69 'ndk_path': "$ANDROID_NDK",
70 'build_tools': "19.0.3",
75 'update_stats': False,
76 'stats_to_carbon': False,
78 'build_server_always': False,
79 'keystore': '$HOME/.local/share/fdroidserver/keystore.jks',
80 'smartcardoptions': [],
87 for k, v in defconfig.items():
91 # Expand environment variables
92 for k, v in config.items():
95 v = os.path.expanduser(v)
96 config[k] = os.path.expandvars(v)
98 if not config['sdk_path']:
99 logging.critical("Neither $ANDROID_HOME nor sdk_path is set, no Android SDK found!")
101 if not os.path.exists(config['sdk_path']):
102 logging.critical('Android SDK path "' + config['sdk_path'] + '" does not exist!')
104 if not os.path.isdir(config['sdk_path']):
105 logging.critical('Android SDK path "' + config['sdk_path'] + '" is not a directory!')
108 if any(k in config for k in ["keystore", "keystorepass", "keypass"]):
109 st = os.stat(config_file)
110 if st.st_mode & stat.S_IRWXG or st.st_mode & stat.S_IRWXO:
111 logging.warn("unsafe permissions on {0} (should be 0600)!".format(config_file))
113 for k in ["keystorepass", "keypass"]:
115 write_password_file(k)
119 def write_password_file(pwtype, password=None):
121 writes out passwords to a protected file instead of passing passwords as
122 command line argments
124 filename = '.fdroid.' + pwtype + '.txt'
125 fd = os.open(filename, os.O_CREAT | os.O_WRONLY, 0600)
127 os.write(fd, config[pwtype])
129 os.write(fd, password)
131 config[pwtype + 'file'] = filename
133 # Given the arguments in the form of multiple appid:[vc] strings, this returns
134 # a dictionary with the set of vercodes specified for each package.
135 def read_pkg_args(args, allow_vercodes=False):
142 if allow_vercodes and ':' in p:
143 package, vercode = p.split(':')
145 package, vercode = p, None
146 if package not in vercodes:
147 vercodes[package] = [vercode] if vercode else []
149 elif vercode and vercode not in vercodes[package]:
150 vercodes[package] += [vercode] if vercode else []
154 # On top of what read_pkg_args does, this returns the whole app metadata, but
155 # limiting the builds list to the builds matching the vercodes specified.
156 def read_app_args(args, allapps, allow_vercodes=False):
158 vercodes = read_pkg_args(args, allow_vercodes)
163 apps = [app for app in allapps if app['id'] in vercodes]
165 if len(apps) != len(vercodes):
166 allids = [app["id"] for app in allapps]
169 logging.critical("No such package: %s" % p)
170 raise Exception("Found invalid app ids in arguments")
172 raise Exception("No packages specified")
176 vc = vercodes[app['id']]
179 app['builds'] = [b for b in app['builds'] if b['vercode'] in vc]
180 if len(app['builds']) != len(vercodes[app['id']]):
182 allvcs = [b['vercode'] for b in app['builds']]
183 for v in vercodes[app['id']]:
185 logging.critical("No such vercode %s for app %s" % (v, app['id']))
188 raise Exception("Found invalid vercodes for some apps")
192 def has_extension(filename, extension):
193 name, ext = os.path.splitext(filename)
194 ext = ext.lower()[1:]
195 return ext == extension
199 def apknameinfo(filename):
201 filename = os.path.basename(filename)
202 if apk_regex is None:
203 apk_regex = re.compile(r"^(.+)_([0-9]+)\.apk$")
204 m = apk_regex.match(filename)
206 result = (m.group(1), m.group(2))
207 except AttributeError:
208 raise Exception("Invalid apk name: %s" % filename)
211 def getapkname(app, build):
212 return "%s_%s.apk" % (app['id'], build['vercode'])
214 def getsrcname(app, build):
215 return "%s_%s_src.tar.gz" % (app['id'], build['vercode'])
221 return app['Auto Name']
225 return '%s (%s)' % (app['Current Version'], app['Current Version Code'])
227 def getvcs(vcstype, remote, local):
229 return vcs_git(remote, local)
231 return vcs_svn(remote, local)
232 if vcstype == 'git-svn':
233 return vcs_gitsvn(remote, local)
235 return vcs_hg(remote, local)
237 return vcs_bzr(remote, local)
238 if vcstype == 'srclib':
239 if local != 'build/srclib/' + remote:
240 raise VCSException("Error: srclib paths are hard-coded!")
241 return getsrclib(remote, 'build/srclib', raw=True)
242 raise VCSException("Invalid vcs type " + vcstype)
244 def getsrclibvcs(name):
245 srclib_path = os.path.join('srclibs', name + ".txt")
246 if not os.path.exists(srclib_path):
247 raise VCSException("Missing srclib " + name)
248 return metadata.parse_srclib(srclib_path)['Repo Type']
251 def __init__(self, remote, local):
253 # svn, git-svn and bzr may require auth
255 if self.repotype() in ('svn', 'git-svn', 'bzr'):
257 self.username, remote = remote.split('@')
258 if ':' not in self.username:
259 raise VCSException("Password required with username")
260 self.username, self.password = self.username.split(':')
264 self.refreshed = False
270 # Take the local repository to a clean version of the given revision, which
271 # is specificed in the VCS's native format. Beforehand, the repository can
272 # be dirty, or even non-existent. If the repository does already exist
273 # locally, it will be updated from the origin, but only once in the
274 # lifetime of the vcs object.
275 # None is acceptable for 'rev' if you know you are cloning a clean copy of
276 # the repo - otherwise it must specify a valid revision.
277 def gotorevision(self, rev):
279 # The .fdroidvcs-id file for a repo tells us what VCS type
280 # and remote that directory was created from, allowing us to drop it
281 # automatically if either of those things changes.
282 fdpath = os.path.join(self.local, '..',
283 '.fdroidvcs-' + os.path.basename(self.local))
284 cdata = self.repotype() + ' ' + self.remote
287 if os.path.exists(self.local):
288 if os.path.exists(fdpath):
289 with open(fdpath, 'r') as f:
290 fsdata = f.read().strip()
295 logging.info("Repository details changed - deleting")
298 logging.info("Repository details missing - deleting")
300 shutil.rmtree(self.local)
302 self.gotorevisionx(rev)
304 # If necessary, write the .fdroidvcs file.
306 with open(fdpath, 'w') as f:
309 # Derived classes need to implement this. It's called once basic checking
310 # has been performend.
311 def gotorevisionx(self, rev):
312 raise VCSException("This VCS type doesn't define gotorevisionx")
314 # Initialise and update submodules
315 def initsubmodules(self):
316 raise VCSException('Submodules not supported for this vcs type')
318 # Get a list of all known tags
320 raise VCSException('gettags not supported for this vcs type')
322 # Get current commit reference (hash, revision, etc)
324 raise VCSException('getref not supported for this vcs type')
326 # Returns the srclib (name, path) used in setting up the current
336 # If the local directory exists, but is somehow not a git repository, git
337 # will traverse up the directory tree until it finds one that is (i.e.
338 # fdroidserver) and then we'll proceed to destroy it! This is called as
341 p = SilentPopen(['git', 'rev-parse', '--show-toplevel'], cwd=self.local)
342 result = p.stdout.rstrip()
343 if not result.endswith(self.local):
344 raise VCSException('Repository mismatch')
346 def gotorevisionx(self, rev):
347 if not os.path.exists(self.local):
349 p = FDroidPopen(['git', 'clone', self.remote, self.local])
350 if p.returncode != 0:
351 raise VCSException("Git clone failed")
355 # Discard any working tree changes
356 p = SilentPopen(['git', 'reset', '--hard'], cwd=self.local)
357 if p.returncode != 0:
358 raise VCSException("Git reset failed")
359 # Remove untracked files now, in case they're tracked in the target
360 # revision (it happens!)
361 p = SilentPopen(['git', 'clean', '-dffx'], cwd=self.local)
362 if p.returncode != 0:
363 raise VCSException("Git clean failed")
364 if not self.refreshed:
365 # Get latest commits and tags from remote
366 p = FDroidPopen(['git', 'fetch', 'origin'], cwd=self.local)
367 if p.returncode != 0:
368 raise VCSException("Git fetch failed")
369 p = SilentPopen(['git', 'fetch', '--prune', '--tags', 'origin'], cwd=self.local)
370 if p.returncode != 0:
371 raise VCSException("Git fetch failed")
372 self.refreshed = True
373 # Check out the appropriate revision
374 rev = str(rev if rev else 'origin/master')
375 p = SilentPopen(['git', 'checkout', '-f', rev], cwd=self.local)
376 if p.returncode != 0:
377 raise VCSException("Git checkout failed")
378 # Get rid of any uncontrolled files left behind
379 p = SilentPopen(['git', 'clean', '-dffx'], cwd=self.local)
380 if p.returncode != 0:
381 raise VCSException("Git clean failed")
383 def initsubmodules(self):
385 submfile = os.path.join(self.local, '.gitmodules')
386 if not os.path.isfile(submfile):
387 raise VCSException("No git submodules available")
389 # fix submodules not accessible without an account and public key auth
390 with open(submfile, 'r') as f:
391 lines = f.readlines()
392 with open(submfile, 'w') as f:
394 if 'git@github.com' in line:
395 line = line.replace('git@github.com:', 'https://github.com/')
399 ['git', 'reset', '--hard'],
400 ['git', 'clean', '-dffx'],
402 p = SilentPopen(['git', 'submodule', 'foreach', '--recursive'] + cmd, cwd=self.local)
403 if p.returncode != 0:
404 raise VCSException("Git submodule reset failed")
405 p = FDroidPopen(['git', 'submodule', 'update', '--init', '--force', '--recursive'], cwd=self.local)
406 if p.returncode != 0:
407 raise VCSException("Git submodule update failed")
411 p = SilentPopen(['git', 'tag'], cwd=self.local)
412 return p.stdout.splitlines()
415 class vcs_gitsvn(vcs):
420 # Damn git-svn tries to use a graphical password prompt, so we have to
421 # trick it into taking the password from stdin
423 if self.username is None:
425 return ('echo "%s" | DISPLAY="" ' % self.password, ' --username "%s"' % self.username)
427 # If the local directory exists, but is somehow not a git repository, git
428 # will traverse up the directory tree until it finds one that is (i.e.
429 # fdroidserver) and then we'll proceed to destory it! This is called as
432 p = SilentPopen(['git', 'rev-parse', '--show-toplevel'], cwd=self.local)
433 result = p.stdout.rstrip()
434 if not result.endswith(self.local):
435 raise VCSException('Repository mismatch')
437 def gotorevisionx(self, rev):
438 if not os.path.exists(self.local):
440 gitsvn_cmd = '%sgit svn clone%s' % self.userargs()
441 if ';' in self.remote:
442 remote_split = self.remote.split(';')
443 for i in remote_split[1:]:
444 if i.startswith('trunk='):
445 gitsvn_cmd += ' -T %s' % i[6:]
446 elif i.startswith('tags='):
447 gitsvn_cmd += ' -t %s' % i[5:]
448 elif i.startswith('branches='):
449 gitsvn_cmd += ' -b %s' % i[9:]
450 p = SilentPopen([gitsvn_cmd + " %s %s" % (remote_split[0], self.local)], shell=True)
451 if p.returncode != 0:
452 raise VCSException("Git clone failed")
454 p = SilentPopen([gitsvn_cmd + " %s %s" % (self.remote, self.local)], shell=True)
455 if p.returncode != 0:
456 raise VCSException("Git clone failed")
460 # Discard any working tree changes
461 p = SilentPopen(['git', 'reset', '--hard'], cwd=self.local)
462 if p.returncode != 0:
463 raise VCSException("Git reset failed")
464 # Remove untracked files now, in case they're tracked in the target
465 # revision (it happens!)
466 p = SilentPopen(['git', 'clean', '-dffx'], cwd=self.local)
467 if p.returncode != 0:
468 raise VCSException("Git clean failed")
469 if not self.refreshed:
470 # Get new commits, branches and tags from repo
471 p = SilentPopen(['%sgit svn fetch %s' % self.userargs()], cwd=self.local, shell=True)
472 if p.returncode != 0:
473 raise VCSException("Git svn fetch failed")
474 p = SilentPopen(['%sgit svn rebase %s' % self.userargs()], cwd=self.local, shell=True)
475 if p.returncode != 0:
476 raise VCSException("Git svn rebase failed")
477 self.refreshed = True
479 rev = str(rev if rev else 'master')
481 nospaces_rev = rev.replace(' ', '%20')
482 # Try finding a svn tag
483 p = SilentPopen(['git', 'checkout', 'tags/' + nospaces_rev], cwd=self.local)
484 if p.returncode != 0:
485 # No tag found, normal svn rev translation
486 # Translate svn rev into git format
487 rev_split = rev.split('/')
488 if len(rev_split) > 1:
489 treeish = rev_split[0]
490 svn_rev = rev_split[1]
493 # if no branch is specified, then assume trunk (ie. 'master'
498 p = SilentPopen(['git', 'svn', 'find-rev', 'r' + svn_rev, treeish], cwd=self.local)
499 git_rev = p.stdout.rstrip()
501 if p.returncode != 0 or not git_rev:
502 # Try a plain git checkout as a last resort
503 p = SilentPopen(['git', 'checkout', rev], cwd=self.local)
504 if p.returncode != 0:
505 raise VCSException("No git treeish found and direct git checkout failed")
507 # Check out the git rev equivalent to the svn rev
508 p = SilentPopen(['git', 'checkout', git_rev], cwd=self.local)
509 if p.returncode != 0:
510 raise VCSException("Git svn checkout failed")
512 # Get rid of any uncontrolled files left behind
513 p = SilentPopen(['git', 'clean', '-dffx'], cwd=self.local)
514 if p.returncode != 0:
515 raise VCSException("Git clean failed")
519 return os.listdir(os.path.join(self.local, '.git/svn/refs/remotes/tags'))
523 p = SilentPopen(['git', 'svn', 'find-rev', 'HEAD'], cwd=self.local)
524 if p.returncode != 0:
526 return p.stdout.strip()
534 if self.username is None:
535 return ['--non-interactive']
536 return ['--username', self.username,
537 '--password', self.password,
540 def gotorevisionx(self, rev):
541 if not os.path.exists(self.local):
542 p = SilentPopen(['svn', 'checkout', self.remote, self.local] + self.userargs())
543 if p.returncode != 0:
544 raise VCSException("Svn checkout failed")
548 r"svn status | awk '/\?/ {print $2}' | xargs rm -rf"):
549 p = SilentPopen([svncommand], cwd=self.local, shell=True)
550 if p.returncode != 0:
551 raise VCSException("Svn reset ({0}) failed in {1}".format(svncommand, self.local))
552 if not self.refreshed:
553 p = SilentPopen(['svn', 'update'] + self.userargs(), cwd=self.local)
554 if p.returncode != 0:
555 raise VCSException("Svn update failed")
556 self.refreshed = True
558 revargs = list(['-r', rev] if rev else [])
559 p = SilentPopen(['svn', 'update', '--force'] + revargs + self.userargs(), cwd=self.local)
560 if p.returncode != 0:
561 raise VCSException("Svn update failed")
564 p = SilentPopen(['svn', 'info'], cwd=self.local)
565 for line in p.stdout.splitlines():
566 if line and line.startswith('Last Changed Rev: '):
575 def gotorevisionx(self, rev):
576 if not os.path.exists(self.local):
577 p = SilentPopen(['hg', 'clone', self.remote, self.local])
578 if p.returncode != 0:
579 raise VCSException("Hg clone failed")
581 p = SilentPopen(['hg status -uS | xargs rm -rf'], cwd=self.local, shell=True)
582 if p.returncode != 0:
583 raise VCSException("Hg clean failed")
584 if not self.refreshed:
585 p = SilentPopen(['hg', 'pull'], cwd=self.local)
586 if p.returncode != 0:
587 raise VCSException("Hg pull failed")
588 self.refreshed = True
590 rev = str(rev if rev else 'default')
593 p = SilentPopen(['hg', 'update', '-C', rev], cwd=self.local)
594 if p.returncode != 0:
595 raise VCSException("Hg checkout failed")
596 p = SilentPopen(['hg', 'purge', '--all'], cwd=self.local)
597 # Also delete untracked files, we have to enable purge extension for that:
598 if "'purge' is provided by the following extension" in p.stdout:
599 with open(self.local+"/.hg/hgrc", "a") as myfile:
600 myfile.write("\n[extensions]\nhgext.purge=\n")
601 p = SilentPopen(['hg', 'purge', '--all'], cwd=self.local)
602 if p.returncode != 0:
603 raise VCSException("HG purge failed")
604 elif p.returncode != 0:
605 raise VCSException("HG purge failed")
608 p = SilentPopen(['hg', 'tags', '-q'], cwd=self.local)
609 return p.stdout.splitlines()[1:]
617 def gotorevisionx(self, rev):
618 if not os.path.exists(self.local):
619 p = SilentPopen(['bzr', 'branch', self.remote, self.local])
620 if p.returncode != 0:
621 raise VCSException("Bzr branch failed")
623 p = SilentPopen(['bzr', 'clean-tree', '--force', '--unknown', '--ignored'], cwd=self.local)
624 if p.returncode != 0:
625 raise VCSException("Bzr revert failed")
626 if not self.refreshed:
627 p = SilentPopen(['bzr', 'pull'], cwd=self.local)
628 if p.returncode != 0:
629 raise VCSException("Bzr update failed")
630 self.refreshed = True
632 revargs = list(['-r', rev] if rev else [])
633 p = SilentPopen(['bzr', 'revert'] + revargs, cwd=self.local)
634 if p.returncode != 0:
635 raise VCSException("Bzr revert failed")
638 p = SilentPopen(['bzr', 'tags'], cwd=self.local)
639 return [tag.split(' ')[0].strip() for tag in
640 p.stdout.splitlines()]
642 def retrieve_string(app_dir, string, xmlfiles=None):
645 os.path.join(app_dir, 'res'),
646 os.path.join(app_dir, 'src/main/res'),
651 for res_dir in res_dirs:
652 for r,d,f in os.walk(res_dir):
653 if r.endswith('/values'):
654 xmlfiles += [os.path.join(r,x) for x in f if x.endswith('.xml')]
657 if string.startswith('@string/'):
658 string_search = re.compile(r'.*"'+string[8:]+'".*?>([^<]+?)<.*').search
659 elif string.startswith('&') and string.endswith(';'):
660 string_search = re.compile(r'.*<!ENTITY.*'+string[1:-1]+'.*?"([^"]+?)".*>').search
662 if string_search is not None:
663 for xmlfile in xmlfiles:
664 for line in file(xmlfile):
665 matches = string_search(line)
667 return retrieve_string(app_dir, matches.group(1), xmlfiles)
670 return string.replace("\\'","'")
672 # Return list of existing files that will be used to find the highest vercode
673 def manifest_paths(app_dir, flavour):
675 possible_manifests = [ os.path.join(app_dir, 'AndroidManifest.xml'),
676 os.path.join(app_dir, 'src', 'main', 'AndroidManifest.xml'),
677 os.path.join(app_dir, 'src', 'AndroidManifest.xml'),
678 os.path.join(app_dir, 'build.gradle') ]
681 possible_manifests.append(
682 os.path.join(app_dir, 'src', flavour, 'AndroidManifest.xml'))
684 return [path for path in possible_manifests if os.path.isfile(path)]
686 # Retrieve the package name. Returns the name, or None if not found.
687 def fetch_real_name(app_dir, flavour):
688 app_search = re.compile(r'.*<application.*').search
689 name_search = re.compile(r'.*android:label="([^"]+)".*').search
691 for f in manifest_paths(app_dir, flavour):
692 if not has_extension(f, 'xml'):
694 logging.debug("fetch_real_name: Checking manifest at " + f)
700 matches = name_search(line)
702 stringname = matches.group(1)
703 logging.debug("fetch_real_name: using string " + stringname)
704 result = retrieve_string(app_dir, stringname)
706 result = result.strip()
710 # Retrieve the version name
711 def version_name(original, app_dir, flavour):
712 for f in manifest_paths(app_dir, flavour):
713 if not has_extension(f, 'xml'):
715 string = retrieve_string(app_dir, original)
720 def get_library_references(root_dir):
722 proppath = os.path.join(root_dir, 'project.properties')
723 if not os.path.isfile(proppath):
725 with open(proppath) as f:
726 for line in f.readlines():
727 if not line.startswith('android.library.reference.'):
729 path = line.split('=')[1].strip()
730 relpath = os.path.join(root_dir, path)
731 if not os.path.isdir(relpath):
733 logging.info("Found subproject at %s" % path)
734 libraries.append(path)
737 def ant_subprojects(root_dir):
738 subprojects = get_library_references(root_dir)
739 for subpath in subprojects:
740 subrelpath = os.path.join(root_dir, subpath)
741 for p in get_library_references(subrelpath):
742 relp = os.path.normpath(os.path.join(subpath,p))
743 if relp not in subprojects:
744 subprojects.insert(0, relp)
747 def remove_debuggable_flags(root_dir):
748 # Remove forced debuggable flags
749 logging.info("Removing debuggable flags")
750 for root, dirs, files in os.walk(root_dir):
751 if 'AndroidManifest.xml' in files:
752 path = os.path.join(root, 'AndroidManifest.xml')
753 p = FDroidPopen(['sed','-i', 's/android:debuggable="[^"]*"//g', path])
754 if p.returncode != 0:
755 raise BuildException("Failed to remove debuggable flags of %s" % path)
757 # Extract some information from the AndroidManifest.xml at the given path.
758 # Returns (version, vercode, package), any or all of which might be None.
759 # All values returned are strings.
760 def parse_androidmanifests(paths):
763 return (None, None, None)
765 vcsearch = re.compile(r'.*:versionCode="([0-9]+?)".*').search
766 vnsearch = re.compile(r'.*:versionName="([^"]+?)".*').search
767 psearch = re.compile(r'.*package="([^"]+)".*').search
769 vcsearch_g = re.compile(r'.*versionCode *=* *["\']*([0-9]+)["\']*').search
770 vnsearch_g = re.compile(r'.*versionName *=* *(["\'])((?:(?=(\\?))\3.)*?)\1.*').search
771 psearch_g = re.compile(r'.*packageName *=* *["\']([^"]+)["\'].*').search
779 gradle = has_extension(path, 'gradle')
782 # Remember package name, may be defined separately from version+vercode
783 package = max_package
785 for line in file(path):
788 matches = psearch_g(line)
790 matches = psearch(line)
792 package = matches.group(1)
795 matches = vnsearch_g(line)
797 matches = vnsearch(line)
799 version = matches.group(2 if gradle else 1)
802 matches = vcsearch_g(line)
804 matches = vcsearch(line)
806 vercode = matches.group(1)
808 # Better some package name than nothing
809 if max_package is None:
810 max_package = package
812 if max_vercode is None or (vercode is not None and vercode > max_vercode):
813 max_version = version
814 max_vercode = vercode
815 max_package = package
817 if max_version is None:
818 max_version = "Unknown"
820 return (max_version, max_vercode, max_package)
822 class BuildException(Exception):
823 def __init__(self, value, detail = None):
827 def get_wikitext(self):
828 ret = repr(self.value) + "\n"
832 txt = self.detail[-8192:] if len(self.detail) > 8192 else self.detail
838 ret = repr(self.value)
840 ret += "\n==== detail begin ====\n%s\n==== detail end ====" % self.detail.strip()
843 class VCSException(Exception):
844 def __init__(self, value):
848 return repr(self.value)
850 # Get the specified source library.
851 # Returns the path to it. Normally this is the path to be used when referencing
852 # it, which may be a subdirectory of the actual project. If you want the base
853 # directory of the project, pass 'basepath=True'.
854 def getsrclib(spec, srclib_dir, srclibpaths=[], subdir=None,
855 basepath=False, raw=False, prepare=True, preponly=False):
863 name, ref = spec.split('@')
865 number, name = name.split(':', 1)
867 name, subdir = name.split('/',1)
869 srclib_path = os.path.join('srclibs', name + ".txt")
871 if not os.path.exists(srclib_path):
872 raise BuildException('srclib ' + name + ' not found.')
874 srclib = metadata.parse_srclib(srclib_path)
876 sdir = os.path.join(srclib_dir, name)
879 vcs = getvcs(srclib["Repo Type"], srclib["Repo"], sdir)
880 vcs.srclib = (name, number, sdir)
882 vcs.gotorevision(ref)
889 libdir = os.path.join(sdir, subdir)
890 elif srclib["Subdir"]:
891 for subdir in srclib["Subdir"]:
892 libdir_candidate = os.path.join(sdir, subdir)
893 if os.path.exists(libdir_candidate):
894 libdir = libdir_candidate
900 if srclib["Srclibs"]:
902 for lib in srclib["Srclibs"].replace(';',',').split(','):
904 for t in srclibpaths:
909 raise BuildException('Missing recursive srclib %s for %s' % (
911 place_srclib(libdir, n, s_tuple[2])
914 remove_signing_keys(sdir)
915 remove_debuggable_flags(sdir)
919 if srclib["Prepare"]:
920 cmd = replace_config_vars(srclib["Prepare"])
922 p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=libdir)
923 if p.returncode != 0:
924 raise BuildException("Error running prepare command for srclib %s"
930 return (name, number, libdir)
933 # Prepare the source code for a particular build
934 # 'vcs' - the appropriate vcs object for the application
935 # 'app' - the application details from the metadata
936 # 'build' - the build details from the metadata
937 # 'build_dir' - the path to the build directory, usually
939 # 'srclib_dir' - the path to the source libraries directory, usually
941 # 'extlib_dir' - the path to the external libraries directory, usually
943 # Returns the (root, srclibpaths) where:
944 # 'root' is the root directory, which may be the same as 'build_dir' or may
945 # be a subdirectory of it.
946 # 'srclibpaths' is information on the srclibs being used
947 def prepare_source(vcs, app, build, build_dir, srclib_dir, extlib_dir, onserver=False):
949 # Optionally, the actual app source can be in a subdirectory
950 if 'subdir' in build:
951 root_dir = os.path.join(build_dir, build['subdir'])
955 # Get a working copy of the right revision
956 logging.info("Getting source for revision " + build['commit'])
957 vcs.gotorevision(build['commit'])
959 # Initialise submodules if requred
960 if build['submodules']:
961 logging.info("Initialising submodules")
964 # Check that a subdir (if we're using one) exists. This has to happen
965 # after the checkout, since it might not exist elsewhere
966 if not os.path.exists(root_dir):
967 raise BuildException('Missing subdir ' + root_dir)
969 # Run an init command if one is required
971 cmd = replace_config_vars(build['init'])
972 logging.info("Running 'init' commands in %s" % root_dir)
974 p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
975 if p.returncode != 0:
976 raise BuildException("Error running init command for %s:%s" %
977 (app['id'], build['version']), p.stdout)
979 # Apply patches if any
981 for patch in build['patch']:
982 patch = patch.strip()
983 logging.info("Applying " + patch)
984 patch_path = os.path.join('metadata', app['id'], patch)
985 p = FDroidPopen(['patch', '-p1', '-i', os.path.abspath(patch_path)], cwd=build_dir)
986 if p.returncode != 0:
987 raise BuildException("Failed to apply patch %s" % patch_path)
989 # Get required source libraries
991 if 'srclibs' in build:
992 logging.info("Collecting source libraries")
993 for lib in build['srclibs']:
994 srclibpaths.append(getsrclib(lib, srclib_dir, srclibpaths,
997 for name, number, libpath in srclibpaths:
998 place_srclib(root_dir, int(number) if number else None, libpath)
1000 basesrclib = vcs.getsrclib()
1001 # If one was used for the main source, add that too.
1003 srclibpaths.append(basesrclib)
1005 # Update the local.properties file
1006 localprops = [ os.path.join(build_dir, 'local.properties') ]
1007 if 'subdir' in build:
1008 localprops += [ os.path.join(root_dir, 'local.properties') ]
1009 for path in localprops:
1010 if not os.path.isfile(path):
1012 logging.info("Updating properties file at %s" % path)
1017 # Fix old-fashioned 'sdk-location' by copying
1018 # from sdk.dir, if necessary
1019 if build['oldsdkloc']:
1020 sdkloc = re.match(r".*^sdk.dir=(\S+)$.*", props,
1022 props += "sdk-location=%s\n" % sdkloc
1024 props += "sdk.dir=%s\n" % config['sdk_path']
1025 props += "sdk-location=%s\n" % config['sdk_path']
1026 if 'ndk_path' in config:
1028 props += "ndk.dir=%s\n" % config['ndk_path']
1029 props += "ndk-location=%s\n" % config['ndk_path']
1030 # Add java.encoding if necessary
1031 if 'encoding' in build:
1032 props += "java.encoding=%s\n" % build['encoding']
1038 if build['type'] == 'gradle':
1039 flavour = build['gradle'].split('@')[0]
1040 if flavour in ['main', 'yes', '']:
1043 if 'target' in build:
1044 n = build["target"].split('-')[1]
1045 FDroidPopen(['sed', '-i',
1046 's@compileSdkVersion *[0-9]*@compileSdkVersion '+n+'@g',
1047 'build.gradle'], cwd=root_dir)
1048 if '@' in build['gradle']:
1049 gradle_dir = os.path.join(root_dir, build['gradle'].split('@',1)[1])
1050 gradle_dir = os.path.normpath(gradle_dir)
1051 FDroidPopen(['sed', '-i',
1052 's@compileSdkVersion *[0-9]*@compileSdkVersion '+n+'@g',
1053 'build.gradle'], cwd=gradle_dir)
1055 # Remove forced debuggable flags
1056 remove_debuggable_flags(root_dir)
1058 # Insert version code and number into the manifest if necessary
1059 if build['forceversion']:
1060 logging.info("Changing the version name")
1061 for path in manifest_paths(root_dir, flavour):
1062 if not os.path.isfile(path):
1064 if has_extension(path, 'xml'):
1065 p = SilentPopen(['sed', '-i',
1066 's/android:versionName="[^"]*"/android:versionName="' + build['version'] + '"/g',
1068 if p.returncode != 0:
1069 raise BuildException("Failed to amend manifest")
1070 elif has_extension(path, 'gradle'):
1071 p = SilentPopen(['sed', '-i',
1072 's/versionName *=* *"[^"]*"/versionName = "' + build['version'] + '"/g',
1074 if p.returncode != 0:
1075 raise BuildException("Failed to amend build.gradle")
1076 if build['forcevercode']:
1077 logging.info("Changing the version code")
1078 for path in manifest_paths(root_dir, flavour):
1079 if not os.path.isfile(path):
1081 if has_extension(path, 'xml'):
1082 p = SilentPopen(['sed', '-i',
1083 's/android:versionCode="[^"]*"/android:versionCode="' + build['vercode'] + '"/g',
1085 if p.returncode != 0:
1086 raise BuildException("Failed to amend manifest")
1087 elif has_extension(path, 'gradle'):
1088 p = SilentPopen(['sed', '-i',
1089 's/versionCode *=* *[0-9]*/versionCode = ' + build['vercode'] + '/g',
1091 if p.returncode != 0:
1092 raise BuildException("Failed to amend build.gradle")
1094 # Delete unwanted files
1096 for part in build['rm']:
1097 dest = os.path.join(build_dir, part)
1098 logging.info("Removing {0}".format(part))
1099 if os.path.lexists(dest):
1100 if os.path.islink(dest):
1101 SilentPopen(['unlink ' + dest], shell=True)
1103 SilentPopen(['rm -rf ' + dest], shell=True)
1105 logging.info("...but it didn't exist")
1107 remove_signing_keys(build_dir)
1109 # Add required external libraries
1110 if 'extlibs' in build:
1111 logging.info("Collecting prebuilt libraries")
1112 libsdir = os.path.join(root_dir, 'libs')
1113 if not os.path.exists(libsdir):
1115 for lib in build['extlibs']:
1117 logging.info("...installing extlib {0}".format(lib))
1118 libf = os.path.basename(lib)
1119 libsrc = os.path.join(extlib_dir, lib)
1120 if not os.path.exists(libsrc):
1121 raise BuildException("Missing extlib file {0}".format(libsrc))
1122 shutil.copyfile(libsrc, os.path.join(libsdir, libf))
1124 # Run a pre-build command if one is required
1125 if 'prebuild' in build:
1126 cmd = replace_config_vars(build['prebuild'])
1128 # Substitute source library paths into prebuild commands
1129 for name, number, libpath in srclibpaths:
1130 libpath = os.path.relpath(libpath, root_dir)
1131 cmd = cmd.replace('$$' + name + '$$', libpath)
1133 logging.info("Running 'prebuild' commands in %s" % root_dir)
1135 p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
1136 if p.returncode != 0:
1137 raise BuildException("Error running prebuild command for %s:%s" %
1138 (app['id'], build['version']), p.stdout)
1140 updatemode = build.get('update', ['auto'])
1141 # Generate (or update) the ant build file, build.xml...
1142 if updatemode != ['no'] and build['type'] == 'ant':
1143 parms = [os.path.join(config['sdk_path'], 'tools', 'android'), 'update']
1144 lparms = parms + ['lib-project']
1145 parms = parms + ['project']
1147 if 'target' in build and build['target']:
1148 parms += ['-t', build['target']]
1149 lparms += ['-t', build['target']]
1150 if updatemode == ['auto']:
1151 update_dirs = ant_subprojects(root_dir) + ['.']
1153 update_dirs = updatemode
1155 for d in update_dirs:
1156 subdir = os.path.join(root_dir, d)
1158 print("Updating main project")
1159 cmd = parms + ['-p', d]
1161 print("Updating subproject %s" % d)
1162 cmd = lparms + ['-p', d]
1163 p = FDroidPopen(cmd, cwd=root_dir)
1164 # Check to see whether an error was returned without a proper exit
1165 # code (this is the case for the 'no target set or target invalid'
1167 if p.returncode != 0 or p.stdout.startswith("Error: "):
1168 raise BuildException("Failed to update project at %s" % d, p.stdout)
1169 # Clean update dirs via ant
1171 logging.info("Cleaning subproject %s" % d)
1172 p = FDroidPopen(['ant', 'clean'], cwd=subdir)
1174 return (root_dir, srclibpaths)
1176 # Scan the source code in the given directory (and all subdirectories)
1177 # and return the number of fatal problems encountered
1178 def scan_source(build_dir, root_dir, thisbuild):
1182 # Common known non-free blobs (always lower case):
1184 re.compile(r'flurryagent', re.IGNORECASE),
1185 re.compile(r'paypal.*mpl', re.IGNORECASE),
1186 re.compile(r'libgoogleanalytics', re.IGNORECASE),
1187 re.compile(r'admob.*sdk.*android', re.IGNORECASE),
1188 re.compile(r'googleadview', re.IGNORECASE),
1189 re.compile(r'googleadmobadssdk', re.IGNORECASE),
1190 re.compile(r'google.*play.*services', re.IGNORECASE),
1191 re.compile(r'crittercism', re.IGNORECASE),
1192 re.compile(r'heyzap', re.IGNORECASE),
1193 re.compile(r'jpct.*ae', re.IGNORECASE),
1194 re.compile(r'youtubeandroidplayerapi', re.IGNORECASE),
1195 re.compile(r'bugsense', re.IGNORECASE),
1196 re.compile(r'crashlytics', re.IGNORECASE),
1197 re.compile(r'ouya.*sdk', re.IGNORECASE),
1200 def getpaths(field):
1202 if field not in thisbuild:
1204 for p in thisbuild[field]:
1208 elif p.startswith('./'):
1210 elif not p.startswith('/'):
1216 scanignore = getpaths('scanignore')
1217 scandelete = getpaths('scandelete')
1220 ms = magic.open(magic.MIME_TYPE)
1222 except AttributeError:
1226 for i in scanignore:
1227 if fd.startswith(i):
1232 for i in scandelete:
1233 if fd.startswith(i):
1237 def removeproblem(what, fd, fp):
1238 logging.info('Removing %s at %s' % (what, fd))
1241 def warnproblem(what, fd):
1242 logging.warn('Found %s at %s' % (what, fd))
1244 def handleproblem(what, fd, fp):
1246 removeproblem(what, fd, fp)
1248 logging.error('Found %s at %s' % (what, fd))
1252 def insidedir(path, dirname):
1253 return path.endswith('/%s' % dirname) or '/%s/' % dirname in path
1255 # Iterate through all files in the source code
1256 for r,d,f in os.walk(build_dir):
1258 if any(insidedir(r, igndir) for igndir in ('.hg', '.git', '.svn')):
1263 # Path (relative) to the file
1264 fp = os.path.join(r, curfile)
1265 fd = fp[len(build_dir):]
1267 # Check if this file has been explicitly excluded from scanning
1271 mime = magic.from_file(fp, mime=True) if ms is None else ms.file(fp)
1273 if mime == 'application/x-sharedlib':
1274 count += handleproblem('shared library', fd, fp)
1276 elif mime == 'application/x-archive':
1277 count += handleproblem('static library', fd, fp)
1279 elif mime == 'application/x-executable':
1280 count += handleproblem('binary executable', fd, fp)
1282 elif mime == 'application/x-java-applet':
1283 count += handleproblem('Java compiled class', fd, fp)
1288 'application/java-archive',
1289 'application/octet-stream',
1293 if has_extension(fp, 'apk'):
1294 removeproblem('APK file', fd, fp)
1296 elif has_extension(fp, 'jar'):
1298 if any(suspect.match(curfile) for suspect in usual_suspects):
1299 count += handleproblem('usual supect', fd, fp)
1301 warnproblem('JAR file', fd)
1303 elif has_extension(fp, 'zip'):
1304 warnproblem('ZIP file', fd)
1307 warnproblem('unknown compressed or binary file', fd)
1309 elif has_extension(fp, 'java'):
1310 for line in file(fp):
1311 if 'DexClassLoader' in line:
1312 count += handleproblem('DexClassLoader', fd, fp)
1317 # Presence of a jni directory without buildjni=yes might
1318 # indicate a problem (if it's not a problem, explicitly use
1319 # buildjni=no to bypass this check)
1320 if (os.path.exists(os.path.join(root_dir, 'jni')) and
1321 thisbuild.get('buildjni') is None):
1322 logging.warn('Found jni directory, but buildjni is not enabled')
1331 self.path = os.path.join('stats', 'known_apks.txt')
1333 if os.path.exists(self.path):
1334 for line in file( self.path):
1335 t = line.rstrip().split(' ')
1337 self.apks[t[0]] = (t[1], None)
1339 self.apks[t[0]] = (t[1], time.strptime(t[2], '%Y-%m-%d'))
1340 self.changed = False
1342 def writeifchanged(self):
1344 if not os.path.exists('stats'):
1346 f = open(self.path, 'w')
1348 for apk, app in self.apks.iteritems():
1350 line = apk + ' ' + appid
1352 line += ' ' + time.strftime('%Y-%m-%d', added)
1354 for line in sorted(lst):
1355 f.write(line + '\n')
1358 # Record an apk (if it's new, otherwise does nothing)
1359 # Returns the date it was added.
1360 def recordapk(self, apk, app):
1361 if not apk in self.apks:
1362 self.apks[apk] = (app, time.gmtime(time.time()))
1364 _, added = self.apks[apk]
1367 # Look up information - given the 'apkname', returns (app id, date added/None).
1368 # Or returns None for an unknown apk.
1369 def getapp(self, apkname):
1370 if apkname in self.apks:
1371 return self.apks[apkname]
1374 # Get the most recent 'num' apps added to the repo, as a list of package ids
1375 # with the most recent first.
1376 def getlatest(self, num):
1378 for apk, app in self.apks.iteritems():
1382 if apps[appid] > added:
1386 sortedapps = sorted(apps.iteritems(), key=operator.itemgetter(1))[-num:]
1387 lst = [app for app,_ in sortedapps]
1391 def isApkDebuggable(apkfile, config):
1392 """Returns True if the given apk file is debuggable
1394 :param apkfile: full path to the apk to check"""
1396 p = SilentPopen([os.path.join(config['sdk_path'],
1397 'build-tools', config['build_tools'], 'aapt'),
1398 'dump', 'xmltree', apkfile, 'AndroidManifest.xml'])
1399 if p.returncode != 0:
1400 logging.critical("Failed to get apk manifest information")
1402 for line in p.stdout.splitlines():
1403 if 'android:debuggable' in line and not line.endswith('0x0'):
1408 class AsynchronousFileReader(threading.Thread):
1410 Helper class to implement asynchronous reading of a file
1411 in a separate thread. Pushes read lines on a queue to
1412 be consumed in another thread.
1415 def __init__(self, fd, queue):
1416 assert isinstance(queue, Queue.Queue)
1417 assert callable(fd.readline)
1418 threading.Thread.__init__(self)
1423 '''The body of the tread: read lines and put them on the queue.'''
1424 for line in iter(self._fd.readline, ''):
1425 self._queue.put(line)
1428 '''Check whether there is no more content to expect.'''
1429 return not self.is_alive() and self._queue.empty()
1435 def SilentPopen(commands, cwd=None, shell=False):
1436 return FDroidPopen(commands, cwd=cwd, shell=shell, output=False)
1438 def FDroidPopen(commands, cwd=None, shell=False, output=True):
1440 Run a command and capture the possibly huge output.
1442 :param commands: command and argument list like in subprocess.Popen
1443 :param cwd: optionally specifies a working directory
1444 :returns: A PopenResult.
1448 cwd = os.path.normpath(cwd)
1449 logging.info("Directory: %s" % cwd)
1450 logging.info("> %s" % ' '.join(commands))
1452 result = PopenResult()
1453 p = subprocess.Popen(commands, cwd=cwd, shell=shell,
1454 universal_newlines=True,
1455 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
1457 stdout_queue = Queue.Queue()
1458 stdout_reader = AsynchronousFileReader(p.stdout, stdout_queue)
1459 stdout_reader.start()
1461 # Check the queue for output (until there is no more to get)
1462 while not stdout_reader.eof():
1463 while not stdout_queue.empty():
1464 line = stdout_queue.get()
1465 if output and options.verbose:
1466 # Output directly to console
1467 sys.stdout.write(line)
1469 result.stdout += line
1474 result.returncode = p.returncode
1477 def remove_signing_keys(build_dir):
1478 comment = re.compile(r'[ ]*//')
1479 signing_configs = re.compile(r'^[\t ]*signingConfigs[ \t]*{[ \t]*$')
1481 re.compile(r'^[\t ]*signingConfig [^ ]*$'),
1482 re.compile(r'.*android\.signingConfigs\..*'),
1483 re.compile(r'.*variant\.outputFile = .*'),
1484 re.compile(r'.*\.readLine\(.*'),
1486 for root, dirs, files in os.walk(build_dir):
1487 if 'build.gradle' in files:
1488 path = os.path.join(root, 'build.gradle')
1490 with open(path, "r") as o:
1491 lines = o.readlines()
1494 with open(path, "w") as o:
1496 if comment.match(line):
1500 opened += line.count('{')
1501 opened -= line.count('}')
1504 if signing_configs.match(line):
1508 if any(s.match(line) for s in line_matches):
1514 logging.info("Cleaned build.gradle of keysigning configs at %s" % path)
1517 'project.properties',
1519 'default.properties',
1522 if propfile in files:
1523 path = os.path.join(root, propfile)
1525 with open(path, "r") as o:
1526 lines = o.readlines()
1528 with open(path, "w") as o:
1530 if line.startswith('key.store'):
1532 if line.startswith('key.alias'):
1536 logging.info("Cleaned %s of keysigning configs at %s" % (propfile,path))
1538 def replace_config_vars(cmd):
1539 cmd = cmd.replace('$$SDK$$', config['sdk_path'])
1540 cmd = cmd.replace('$$NDK$$', config['ndk_path'])
1541 cmd = cmd.replace('$$MVN3$$', config['mvn3'])
1544 def place_srclib(root_dir, number, libpath):
1547 relpath = os.path.relpath(libpath, root_dir)
1548 proppath = os.path.join(root_dir, 'project.properties')
1551 if os.path.isfile(proppath):
1552 with open(proppath, "r") as o:
1553 lines = o.readlines()
1555 with open(proppath, "w") as o:
1558 if line.startswith('android.library.reference.%d=' % number):
1559 o.write('android.library.reference.%d=%s\n' % (number,relpath))
1564 o.write('android.library.reference.%d=%s\n' % (number,relpath))