2 # -*- coding: utf-8 -*-
4 # build.py - part of the FDroid server tools
5 # Copyright (C) 2010-2014, Ciaran Gultnieks, ciaran@ciarang.com
6 # Copyright (C) 2013-2014 Daniel Martà <mvdan@mvdan.cc>
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Affero General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Affero General Public License for more details.
18 # You should have received a copy of the GNU Affero General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
30 from ConfigParser import ConfigParser
31 from optparse import OptionParser, OptionError
32 from distutils.version import LooseVersion
37 from common import BuildException, VCSException, FDroidPopen, SilentPopen
45 def get_builder_vm_id():
46 vd = os.path.join('builder', '.vagrant')
48 # Vagrant 1.2 (and maybe 1.1?) it's a directory tree...
49 with open(os.path.join(vd, 'machines', 'default',
50 'virtualbox', 'id')) as vf:
54 # Vagrant 1.0 - it's a json file...
55 with open(os.path.join('builder', '.vagrant')) as vf:
57 return v['active']['default']
60 def got_valid_builder_vm():
61 """Returns True if we have a valid-looking builder vm
63 if not os.path.exists(os.path.join('builder', 'Vagrantfile')):
65 vd = os.path.join('builder', '.vagrant')
66 if not os.path.exists(vd):
68 if not os.path.isdir(vd):
69 # Vagrant 1.0 - if the directory is there, it's valid...
71 # Vagrant 1.2 - the directory can exist, but the id can be missing...
72 if not os.path.exists(os.path.join(vd, 'machines', 'default',
78 def vagrant(params, cwd=None, printout=False):
79 """Run a vagrant command.
81 :param: list of parameters to pass to vagrant
82 :cwd: directory to run in, or None for current directory
83 :returns: (ret, out) where ret is the return code, and out
84 is the stdout (and stderr) from vagrant
86 p = FDroidPopen(['vagrant'] + params, cwd=cwd)
87 return (p.returncode, p.output)
90 def get_vagrant_sshinfo():
91 """Get ssh connection info for a vagrant VM
93 :returns: A dictionary containing 'hostname', 'port', 'user'
96 if subprocess.call('vagrant ssh-config >sshconfig',
97 cwd='builder', shell=True) != 0:
98 raise BuildException("Error getting ssh config")
99 vagranthost = 'default' # Host in ssh config file
100 sshconfig = paramiko.SSHConfig()
101 sshf = open('builder/sshconfig', 'r')
102 sshconfig.parse(sshf)
104 sshconfig = sshconfig.lookup(vagranthost)
105 idfile = sshconfig['identityfile']
106 if isinstance(idfile, list):
108 elif idfile.startswith('"') and idfile.endswith('"'):
109 idfile = idfile[1:-1]
110 return {'hostname': sshconfig['hostname'],
111 'port': int(sshconfig['port']),
112 'user': sshconfig['user'],
116 def get_clean_vm(reset=False):
117 """Get a clean VM ready to do a buildserver build.
119 This might involve creating and starting a new virtual machine from
120 scratch, or it might be as simple (unless overridden by the reset
121 parameter) as re-using a snapshot created previously.
123 A BuildException will be raised if anything goes wrong.
125 :reset: True to force creating from scratch.
126 :returns: A dictionary containing 'hostname', 'port', 'user'
129 # Reset existing builder machine to a clean state if possible.
132 logging.info("Checking for valid existing build server")
134 if got_valid_builder_vm():
135 logging.info("...VM is present")
136 p = FDroidPopen(['VBoxManage', 'snapshot',
137 get_builder_vm_id(), 'list',
138 '--details'], cwd='builder')
139 if 'fdroidclean' in p.output:
140 logging.info("...snapshot exists - resetting build server to "
142 retcode, output = vagrant(['status'], cwd='builder')
144 if 'running' in output:
145 logging.info("...suspending")
146 vagrant(['suspend'], cwd='builder')
147 logging.info("...waiting a sec...")
149 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(),
150 'restore', 'fdroidclean'],
153 if p.returncode == 0:
154 logging.info("...reset to snapshot - server is valid")
155 retcode, output = vagrant(['up'], cwd='builder')
157 raise BuildException("Failed to start build server")
158 logging.info("...waiting a sec...")
160 sshinfo = get_vagrant_sshinfo()
163 logging.info("...failed to reset to snapshot")
165 logging.info("...snapshot doesn't exist - "
166 "VBoxManage snapshot list:\n" + p.output)
168 # If we can't use the existing machine for any reason, make a
169 # new one from scratch.
171 if os.path.exists('builder'):
172 logging.info("Removing broken/incomplete/unwanted build server")
173 vagrant(['destroy', '-f'], cwd='builder')
174 shutil.rmtree('builder')
177 p = subprocess.Popen('vagrant --version', shell=True,
178 stdout=subprocess.PIPE)
179 vver = p.communicate()[0]
180 if vver.startswith('Vagrant version 1.2'):
181 with open('builder/Vagrantfile', 'w') as vf:
182 vf.write('Vagrant.configure("2") do |config|\n')
183 vf.write('config.vm.box = "buildserver"\n')
186 with open('builder/Vagrantfile', 'w') as vf:
187 vf.write('Vagrant::Config.run do |config|\n')
188 vf.write('config.vm.box = "buildserver"\n')
191 logging.info("Starting new build server")
192 retcode, _ = vagrant(['up'], cwd='builder')
194 raise BuildException("Failed to start build server")
196 # Open SSH connection to make sure it's working and ready...
197 logging.info("Connecting to virtual machine...")
198 sshinfo = get_vagrant_sshinfo()
199 sshs = paramiko.SSHClient()
200 sshs.set_missing_host_key_policy(paramiko.AutoAddPolicy())
201 sshs.connect(sshinfo['hostname'], username=sshinfo['user'],
202 port=sshinfo['port'], timeout=300,
204 key_filename=sshinfo['idfile'])
207 logging.info("Saving clean state of new build server")
208 retcode, _ = vagrant(['suspend'], cwd='builder')
210 raise BuildException("Failed to suspend build server")
211 logging.info("...waiting a sec...")
213 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(),
214 'take', 'fdroidclean'],
216 if p.returncode != 0:
217 raise BuildException("Failed to take snapshot")
218 logging.info("...waiting a sec...")
220 logging.info("Restarting new build server")
221 retcode, _ = vagrant(['up'], cwd='builder')
223 raise BuildException("Failed to start build server")
224 logging.info("...waiting a sec...")
226 # Make sure it worked...
227 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(),
228 'list', '--details'],
230 if 'fdroidclean' not in p.output:
231 raise BuildException("Failed to take snapshot.")
237 """Release the VM previously started with get_clean_vm().
239 This should always be called.
241 logging.info("Suspending build server")
242 subprocess.call(['vagrant', 'suspend'], cwd='builder')
245 # Note that 'force' here also implies test mode.
246 def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
247 """Do a build on the build server."""
252 raise BuildException("Paramiko is required to use the buildserver")
254 logging.getLogger("paramiko").setLevel(logging.DEBUG)
256 logging.getLogger("paramiko").setLevel(logging.WARN)
258 sshinfo = get_clean_vm()
262 # Open SSH connection...
263 logging.info("Connecting to virtual machine...")
264 sshs = paramiko.SSHClient()
265 sshs.set_missing_host_key_policy(paramiko.AutoAddPolicy())
266 sshs.connect(sshinfo['hostname'], username=sshinfo['user'],
267 port=sshinfo['port'], timeout=300,
268 look_for_keys=False, key_filename=sshinfo['idfile'])
270 homedir = '/home/' + sshinfo['user']
272 # Get an SFTP connection...
273 ftp = sshs.open_sftp()
274 ftp.get_channel().settimeout(15)
276 # Put all the necessary files in place...
279 # Helper to copy the contents of a directory to the server...
281 root = os.path.dirname(path)
282 main = os.path.basename(path)
284 for r, d, f in os.walk(path):
285 rr = os.path.relpath(r, root)
290 lfile = os.path.join(root, rr, ff)
291 if not os.path.islink(lfile):
293 ftp.chmod(ff, os.stat(lfile).st_mode)
294 for i in range(len(rr.split('/'))):
298 logging.info("Preparing server for build...")
299 serverpath = os.path.abspath(os.path.dirname(__file__))
300 ftp.put(os.path.join(serverpath, 'build.py'), 'build.py')
301 ftp.put(os.path.join(serverpath, 'common.py'), 'common.py')
302 ftp.put(os.path.join(serverpath, 'metadata.py'), 'metadata.py')
303 ftp.put(os.path.join(serverpath, '..', 'buildserver',
304 'config.buildserver.py'), 'config.py')
305 ftp.chmod('config.py', 0o600)
307 # Copy over the ID (head commit hash) of the fdroidserver in use...
308 subprocess.call('git rev-parse HEAD >' +
309 os.path.join(os.getcwd(), 'tmp', 'fdroidserverid'),
310 shell=True, cwd=serverpath)
311 ftp.put('tmp/fdroidserverid', 'fdroidserverid')
313 # Copy the metadata - just the file for this app...
314 ftp.mkdir('metadata')
316 ftp.chdir('metadata')
317 ftp.put(os.path.join('metadata', app['id'] + '.txt'),
319 # And patches if there are any...
320 if os.path.exists(os.path.join('metadata', app['id'])):
321 send_dir(os.path.join('metadata', app['id']))
324 # Create the build directory...
329 # Copy any extlibs that are required...
330 if thisbuild['extlibs']:
331 ftp.chdir(homedir + '/build/extlib')
332 for lib in thisbuild['extlibs']:
334 libsrc = os.path.join('build/extlib', lib)
335 if not os.path.exists(libsrc):
336 raise BuildException("Missing extlib {0}".format(libsrc))
339 if d not in ftp.listdir():
342 ftp.put(libsrc, lp[-1])
345 # Copy any srclibs that are required...
347 if thisbuild['srclibs']:
348 for lib in thisbuild['srclibs']:
350 common.getsrclib(lib, 'build/srclib', srclibpaths,
351 basepath=True, prepare=False))
353 # If one was used for the main source, add that too.
354 basesrclib = vcs.getsrclib()
356 srclibpaths.append(basesrclib)
357 for name, number, lib in srclibpaths:
358 logging.info("Sending srclib '%s'" % lib)
359 ftp.chdir(homedir + '/build/srclib')
360 if not os.path.exists(lib):
361 raise BuildException("Missing srclib directory '" + lib + "'")
362 fv = '.fdroidvcs-' + name
363 ftp.put(os.path.join('build/srclib', fv), fv)
365 # Copy the metadata file too...
366 ftp.chdir(homedir + '/srclibs')
367 ftp.put(os.path.join('srclibs', name + '.txt'),
369 # Copy the main app source code
370 # (no need if it's a srclib)
371 if (not basesrclib) and os.path.exists(build_dir):
372 ftp.chdir(homedir + '/build')
373 fv = '.fdroidvcs-' + app['id']
374 ftp.put(os.path.join('build', fv), fv)
377 # Execute the build script...
378 logging.info("Starting build...")
379 chan = sshs.get_transport().open_session()
381 cmdline = 'python build.py --on-server'
383 cmdline += ' --force --test'
385 cmdline += ' --verbose'
386 cmdline += " %s:%s" % (app['id'], thisbuild['vercode'])
387 chan.exec_command('bash -c ". ~/.bsenv && ' + cmdline + '"')
389 while not chan.exit_status_ready():
390 while chan.recv_ready():
391 output += chan.recv(1024)
393 logging.info("...getting exit status")
394 returncode = chan.recv_exit_status()
396 get = chan.recv(1024)
401 raise BuildException(
402 "Build.py failed on server for {0}:{1}".format(
403 app['id'], thisbuild['version']), output)
405 # Retrieve the built files...
406 logging.info("Retrieving build output...")
408 ftp.chdir(homedir + '/tmp')
410 ftp.chdir(homedir + '/unsigned')
411 apkfile = common.getapkname(app, thisbuild)
412 tarball = common.getsrcname(app, thisbuild)
414 ftp.get(apkfile, os.path.join(output_dir, apkfile))
415 if not options.notarball:
416 ftp.get(tarball, os.path.join(output_dir, tarball))
418 raise BuildException(
419 "Build failed for %s:%s - missing output files".format(
420 app['id'], thisbuild['version']), output)
425 # Suspend the build server.
429 def adapt_gradle(build_dir):
430 for root, dirs, files in os.walk(build_dir):
431 if 'build.gradle' in files:
432 path = os.path.join(root, 'build.gradle')
433 logging.info("Adapting build.gradle at %s" % path)
435 FDroidPopen(['sed', '-i',
436 r's@buildToolsVersion\([ =]*\)["\'][0-9\.]*["\']@buildToolsVersion\1"'
437 + config['build_tools'] + '"@g', path])
440 def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver):
441 """Do a build locally."""
443 if thisbuild['buildjni'] and thisbuild['buildjni'] != ['no']:
444 if not config['ndk_path']:
445 logging.critical("$ANDROID_NDK is not set!")
447 elif not os.path.isdir(config['sdk_path']):
448 logging.critical("$ANDROID_NDK points to a non-existing directory!")
451 # Prepare the source code...
452 root_dir, srclibpaths = common.prepare_source(vcs, app, thisbuild,
453 build_dir, srclib_dir,
454 extlib_dir, onserver)
456 # We need to clean via the build tool in case the binary dirs are
457 # different from the default ones
459 if thisbuild['type'] == 'maven':
460 logging.info("Cleaning Maven project...")
461 cmd = [config['mvn3'], 'clean', '-Dandroid.sdk.path=' + config['sdk_path']]
463 if '@' in thisbuild['maven']:
464 maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@', 1)[1])
465 maven_dir = os.path.normpath(maven_dir)
469 p = FDroidPopen(cmd, cwd=maven_dir)
471 elif thisbuild['type'] == 'gradle':
473 logging.info("Cleaning Gradle project...")
474 cmd = [config['gradle'], 'clean']
476 adapt_gradle(build_dir)
477 for name, number, libpath in srclibpaths:
478 adapt_gradle(libpath)
480 p = FDroidPopen(cmd, cwd=root_dir)
482 elif thisbuild['type'] == 'kivy':
485 elif thisbuild['type'] == 'ant':
486 logging.info("Cleaning Ant project...")
487 p = FDroidPopen(['ant', 'clean'], cwd=root_dir)
489 if p is not None and p.returncode != 0:
490 raise BuildException("Error cleaning %s:%s" %
491 (app['id'], thisbuild['version']), p.output)
493 logging.info("Getting rid of Gradle wrapper binaries...")
494 for root, dirs, files in os.walk(build_dir):
495 # Don't remove possibly necessary 'gradle' dirs if 'gradlew' is not there
496 if 'gradlew' in files:
497 os.remove(os.path.join(root, 'gradlew'))
498 if 'gradlew.bat' in files:
499 os.remove(os.path.join(root, 'gradlew.bat'))
501 shutil.rmtree(os.path.join(root, 'gradle'))
503 if not options.skipscan:
504 # Scan before building...
505 logging.info("Scanning source for common problems...")
506 count = common.scan_source(build_dir, root_dir, thisbuild)
509 logging.warn('Scanner found %d problems:' % count)
511 raise BuildException("Can't build due to %d errors while scanning" % count)
513 if not options.notarball:
514 # Build the source tarball right before we build the release...
515 logging.info("Creating source tarball...")
516 tarname = common.getsrcname(app, thisbuild)
517 tarball = tarfile.open(os.path.join(tmp_dir, tarname), "w:gz")
520 return any(f.endswith(s) for s in ['.svn', '.git', '.hg', '.bzr'])
521 tarball.add(build_dir, tarname, exclude=tarexc)
525 manifest = os.path.join(root_dir, 'AndroidManifest.xml')
526 if os.path.exists(manifest):
527 homedir = os.path.expanduser('~')
528 with open(os.path.join(homedir, 'buildserverid'), 'r') as f:
529 buildserverid = f.read()
530 with open(os.path.join(homedir, 'fdroidserverid'), 'r') as f:
531 fdroidserverid = f.read()
532 with open(manifest, 'r') as f:
533 manifestcontent = f.read()
534 manifestcontent = manifestcontent.replace('</manifest>',
535 '<fdroid buildserverid="'
536 + buildserverid + '"'
537 + ' fdroidserverid="'
538 + fdroidserverid + '"'
540 with open(manifest, 'w') as f:
541 f.write(manifestcontent)
543 # Run a build command if one is required...
544 if thisbuild['build']:
545 logging.info("Running 'build' commands in %s" % root_dir)
546 cmd = common.replace_config_vars(thisbuild['build'])
548 # Substitute source library paths into commands...
549 for name, number, libpath in srclibpaths:
550 libpath = os.path.relpath(libpath, root_dir)
551 cmd = cmd.replace('$$' + name + '$$', libpath)
553 p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
555 if p.returncode != 0:
556 raise BuildException("Error running build command for %s:%s" %
557 (app['id'], thisbuild['version']), p.output)
559 # Build native stuff if required...
560 if thisbuild['buildjni'] and thisbuild['buildjni'] != ['no']:
561 logging.info("Building the native code")
562 jni_components = thisbuild['buildjni']
564 if jni_components == ['yes']:
565 jni_components = ['']
566 cmd = [os.path.join(config['ndk_path'], "ndk-build"), "-j1"]
567 for d in jni_components:
569 logging.info("Building native code in '%s'" % d)
571 logging.info("Building native code in the main project")
572 manifest = root_dir + '/' + d + '/AndroidManifest.xml'
573 if os.path.exists(manifest):
574 # Read and write the whole AM.xml to fix newlines and avoid
575 # the ndk r8c or later 'wordlist' errors. The outcome of this
576 # under gnu/linux is the same as when using tools like
577 # dos2unix, but the native python way is faster and will
578 # work in non-unix systems.
579 manifest_text = open(manifest, 'U').read()
580 open(manifest, 'w').write(manifest_text)
581 # In case the AM.xml read was big, free the memory
583 p = FDroidPopen(cmd, cwd=os.path.join(root_dir, d))
584 if p.returncode != 0:
585 raise BuildException("NDK build failed for %s:%s" % (app['id'], thisbuild['version']), p.output)
588 # Build the release...
589 if thisbuild['type'] == 'maven':
590 logging.info("Building Maven project...")
592 if '@' in thisbuild['maven']:
593 maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@', 1)[1])
597 mvncmd = [config['mvn3'], '-Dandroid.sdk.path=' + config['sdk_path'],
598 '-Dmaven.jar.sign.skip=true', '-Dmaven.test.skip=true',
599 '-Dandroid.sign.debug=false', '-Dandroid.release=true',
601 if thisbuild['target']:
602 target = thisbuild["target"].split('-')[1]
603 FDroidPopen(['sed', '-i',
604 's@<platform>[0-9]*</platform>@<platform>'
605 + target + '</platform>@g',
608 if '@' in thisbuild['maven']:
609 FDroidPopen(['sed', '-i',
610 's@<platform>[0-9]*</platform>@<platform>'
611 + target + '</platform>@g',
615 p = FDroidPopen(mvncmd, cwd=maven_dir)
617 bindir = os.path.join(root_dir, 'target')
619 elif thisbuild['type'] == 'kivy':
620 logging.info("Building Kivy project...")
622 spec = os.path.join(root_dir, 'buildozer.spec')
623 if not os.path.exists(spec):
624 raise BuildException("Expected to find buildozer-compatible spec at {0}"
627 defaults = {'orientation': 'landscape', 'icon': '',
628 'permissions': '', 'android.api': "18"}
629 bconfig = ConfigParser(defaults, allow_no_value=True)
632 distdir = 'python-for-android/dist/fdroid'
633 if os.path.exists(distdir):
634 shutil.rmtree(distdir)
636 modules = bconfig.get('app', 'requirements').split(',')
638 cmd = 'ANDROIDSDK=' + config['sdk_path']
639 cmd += ' ANDROIDNDK=' + config['ndk_path']
640 cmd += ' ANDROIDNDKVER=r9'
641 cmd += ' ANDROIDAPI=' + str(bconfig.get('app', 'android.api'))
642 cmd += ' VIRTUALENV=virtualenv'
643 cmd += ' ./distribute.sh'
644 cmd += ' -m ' + "'" + ' '.join(modules) + "'"
646 p = FDroidPopen(cmd, cwd='python-for-android', shell=True)
647 if p.returncode != 0:
648 raise BuildException("Distribute build failed")
650 cid = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
652 raise BuildException("Package ID mismatch between metadata and spec")
654 orientation = bconfig.get('app', 'orientation', 'landscape')
655 if orientation == 'all':
656 orientation = 'sensor'
660 '--name', bconfig.get('app', 'title'),
661 '--package', app['id'],
662 '--version', bconfig.get('app', 'version'),
663 '--orientation', orientation
666 perms = bconfig.get('app', 'permissions')
667 for perm in perms.split(','):
668 cmd.extend(['--permission', perm])
670 if config.get('app', 'fullscreen') == 0:
671 cmd.append('--window')
673 icon = bconfig.get('app', 'icon.filename')
675 cmd.extend(['--icon', os.path.join(root_dir, icon)])
677 cmd.append('release')
678 p = FDroidPopen(cmd, cwd=distdir)
680 elif thisbuild['type'] == 'gradle':
681 logging.info("Building Gradle project...")
682 flavours = thisbuild['gradle'].split(',')
684 if len(flavours) == 1 and flavours[0] in ['main', 'yes', '']:
687 commands = [config['gradle']]
688 if thisbuild['preassemble']:
689 commands += thisbuild['preassemble'].split()
691 flavours_cmd = ''.join(flavours)
693 flavours_cmd = flavours_cmd[0].upper() + flavours_cmd[1:]
695 commands += ['assemble' + flavours_cmd + 'Release']
697 # Avoid having to use lintOptions.abortOnError false
698 # TODO: Do flavours or project names change this task name?
699 if LooseVersion('0.8') <= thisbuild['gradlepluginver'] < LooseVersion('0.11'):
700 commands += ['-x', 'lintVital' + flavours_cmd + 'Release']
702 p = FDroidPopen(commands, cwd=root_dir)
704 elif thisbuild['type'] == 'ant':
705 logging.info("Building Ant project...")
707 if thisbuild['antcommand']:
708 cmd += [thisbuild['antcommand']]
711 p = FDroidPopen(cmd, cwd=root_dir)
713 bindir = os.path.join(root_dir, 'bin')
715 if p is not None and p.returncode != 0:
716 raise BuildException("Build failed for %s:%s" % (app['id'], thisbuild['version']), p.output)
717 logging.info("Successfully built version " + thisbuild['version'] + ' of ' + app['id'])
719 if thisbuild['type'] == 'maven':
720 stdout_apk = '\n'.join([
721 line for line in p.output.splitlines() if any(a in line for a in ('.apk', '.ap_'))])
722 m = re.match(r".*^\[INFO\] .*apkbuilder.*/([^/]*)\.apk",
723 stdout_apk, re.S | re.M)
725 m = re.match(r".*^\[INFO\] Creating additional unsigned apk file .*/([^/]+)\.apk[^l]",
726 stdout_apk, re.S | re.M)
728 m = re.match(r'.*^\[INFO\] [^$]*aapt \[package,[^$]*' + bindir + r'/([^/]+)\.ap[_k][,\]]',
729 stdout_apk, re.S | re.M)
731 raise BuildException('Failed to find output')
733 src = os.path.join(bindir, src) + '.apk'
734 elif thisbuild['type'] == 'kivy':
735 src = 'python-for-android/dist/default/bin/{0}-{1}-release.apk'.format(
736 bconfig.get('app', 'title'), bconfig.get('app', 'version'))
737 elif thisbuild['type'] == 'gradle':
740 if thisbuild['subdir']:
741 dd = os.path.join(dd, thisbuild['subdir'])
742 basename = os.path.basename(thisbuild['subdir'])
743 if '@' in thisbuild['gradle']:
744 dd = os.path.join(dd, thisbuild['gradle'].split('@')[1])
746 if len(flavours) == 1 and flavours[0] == '':
747 name = '-'.join([basename, 'release', 'unsigned'])
749 name = '-'.join([basename, '-'.join(flavours), 'release', 'unsigned'])
750 dd = os.path.normpath(dd)
751 if thisbuild['gradlepluginver'] >= LooseVersion('0.11'):
752 src = os.path.join(dd, 'build', 'outputs', 'apk', name + '.apk')
754 src = os.path.join(dd, 'build', 'apk', name + '.apk')
755 elif thisbuild['type'] == 'ant':
756 stdout_apk = '\n'.join([
757 line for line in p.output.splitlines() if '.apk' in line])
758 src = re.match(r".*^.*Creating (.+) for release.*$.*", stdout_apk,
759 re.S | re.M).group(1)
760 src = os.path.join(bindir, src)
761 elif thisbuild['type'] == 'raw':
762 src = os.path.join(root_dir, thisbuild['output'])
763 src = os.path.normpath(src)
765 # Make sure it's not debuggable...
766 if common.isApkDebuggable(src, config):
767 raise BuildException("APK is debuggable")
769 # By way of a sanity check, make sure the version and version
770 # code in our new apk match what we expect...
771 logging.info("Checking " + src)
772 if not os.path.exists(src):
773 raise BuildException("Unsigned apk is not at expected location of " + src)
775 p = SilentPopen([os.path.join(config['sdk_path'], 'build-tools',
776 config['build_tools'], 'aapt'),
777 'dump', 'badging', src])
783 for line in p.output.splitlines():
784 if line.startswith("package:"):
785 pat = re.compile(".*name='([a-zA-Z0-9._]*)'.*")
789 pat = re.compile(".*versionCode='([0-9]*)'.*")
793 pat = re.compile(".*versionName='([^']*)'.*")
797 elif line.startswith("native-code:"):
798 nativecode = line[12:]
800 # Ignore empty strings or any kind of space/newline chars that we don't
802 if nativecode is not None:
803 nativecode = nativecode.strip()
804 nativecode = None if not nativecode else nativecode
806 if thisbuild['buildjni'] and thisbuild['buildjni'] != ['no']:
807 if nativecode is None:
808 raise BuildException("Native code should have been built but none was packaged")
809 if thisbuild['novcheck']:
810 vercode = thisbuild['vercode']
811 version = thisbuild['version']
812 if not version or not vercode:
813 raise BuildException("Could not find version information in build in output")
815 raise BuildException("Could not find package ID in output")
816 if foundid != app['id']:
817 raise BuildException("Wrong package ID - build " + foundid + " but expected " + app['id'])
819 # Some apps (e.g. Timeriffic) have had the bonkers idea of
820 # including the entire changelog in the version number. Remove
821 # it so we can compare. (TODO: might be better to remove it
822 # before we compile, in fact)
823 index = version.find(" //")
825 version = version[:index]
827 if (version != thisbuild['version'] or
828 vercode != thisbuild['vercode']):
829 raise BuildException(("Unexpected version/version code in output;"
830 " APK: '%s' / '%s', "
831 " Expected: '%s' / '%s'")
832 % (version, str(vercode), thisbuild['version'],
833 str(thisbuild['vercode']))
836 # Copy the unsigned apk to our destination directory for further
837 # processing (by publish.py)...
838 dest = os.path.join(output_dir, common.getapkname(app, thisbuild))
839 shutil.copyfile(src, dest)
841 # Move the source tarball into the output directory...
842 if output_dir != tmp_dir and not options.notarball:
843 shutil.move(os.path.join(tmp_dir, tarname),
844 os.path.join(output_dir, tarname))
847 def trybuild(app, thisbuild, build_dir, output_dir, also_check_dir, srclib_dir, extlib_dir,
848 tmp_dir, repo_dir, vcs, test, server, force, onserver):
850 Build a particular version of an application, if it needs building.
852 :param output_dir: The directory where the build output will go. Usually
853 this is the 'unsigned' directory.
854 :param repo_dir: The repo directory - used for checking if the build is
856 :paaram also_check_dir: An additional location for checking if the build
857 is necessary (usually the archive repo)
858 :param test: True if building in test mode, in which case the build will
859 always happen, even if the output already exists. In test mode, the
860 output directory should be a temporary location, not any of the real
863 :returns: True if the build was done, False if it wasn't necessary.
866 dest_apk = common.getapkname(app, thisbuild)
868 dest = os.path.join(output_dir, dest_apk)
869 dest_repo = os.path.join(repo_dir, dest_apk)
872 if os.path.exists(dest) or os.path.exists(dest_repo):
876 dest_also = os.path.join(also_check_dir, dest_apk)
877 if os.path.exists(dest_also):
880 if thisbuild['disable']:
883 logging.info("Building version %s (%s) of %s" % (
884 thisbuild['version'], thisbuild['vercode'], app['id']))
887 # When using server mode, still keep a local cache of the repo, by
888 # grabbing the source now.
889 vcs.gotorevision(thisbuild['commit'])
891 build_server(app, thisbuild, vcs, build_dir, output_dir, force)
893 build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver)
897 def parse_commandline():
898 """Parse the command line. Returns options, args."""
900 parser = OptionParser(usage="Usage: %prog [options] [APPID[:VERCODE] [APPID[:VERCODE] ...]]")
901 parser.add_option("-v", "--verbose", action="store_true", default=False,
902 help="Spew out even more information than normal")
903 parser.add_option("-q", "--quiet", action="store_true", default=False,
904 help="Restrict output to warnings and errors")
905 parser.add_option("-l", "--latest", action="store_true", default=False,
906 help="Build only the latest version of each package")
907 parser.add_option("-s", "--stop", action="store_true", default=False,
908 help="Make the build stop on exceptions")
909 parser.add_option("-t", "--test", action="store_true", default=False,
910 help="Test mode - put output in the tmp directory only, and always build, even if the output already exists.")
911 parser.add_option("--server", action="store_true", default=False,
912 help="Use build server")
913 parser.add_option("--resetserver", action="store_true", default=False,
914 help="Reset and create a brand new build server, even if the existing one appears to be ok.")
915 parser.add_option("--on-server", dest="onserver", action="store_true", default=False,
916 help="Specify that we're running on the build server")
917 parser.add_option("--skip-scan", dest="skipscan", action="store_true", default=False,
918 help="Skip scanning the source code for binaries and other problems")
919 parser.add_option("--no-tarball", dest="notarball", action="store_true", default=False,
920 help="Don't create a source tarball, useful when testing a build")
921 parser.add_option("-f", "--force", action="store_true", default=False,
922 help="Force build of disabled apps, and carries on regardless of scan problems. Only allowed in test mode.")
923 parser.add_option("-a", "--all", action="store_true", default=False,
924 help="Build all applications available")
925 parser.add_option("-w", "--wiki", default=False, action="store_true",
926 help="Update the wiki")
927 options, args = parser.parse_args()
929 # Force --stop with --on-server to get correct exit code
933 if options.force and not options.test:
934 raise OptionError("Force is only allowed in test mode", "force")
944 global options, config
946 options, args = parse_commandline()
947 if not args and not options.all:
948 raise OptionError("If you really want to build all the apps, use --all", "all")
950 config = common.read_config(options)
952 if config['build_server_always']:
953 options.server = True
954 if options.resetserver and not options.server:
955 raise OptionError("Using --resetserver without --server makes no sense", "resetserver")
958 if not os.path.isdir(log_dir):
959 logging.info("Creating log directory")
963 if not os.path.isdir(tmp_dir):
964 logging.info("Creating temporary directory")
970 output_dir = 'unsigned'
971 if not os.path.isdir(output_dir):
972 logging.info("Creating output directory")
973 os.makedirs(output_dir)
975 if config['archive_older'] != 0:
976 also_check_dir = 'archive'
978 also_check_dir = None
983 if not os.path.isdir(build_dir):
984 logging.info("Creating build directory")
985 os.makedirs(build_dir)
986 srclib_dir = os.path.join(build_dir, 'srclib')
987 extlib_dir = os.path.join(build_dir, 'extlib')
989 # Read all app and srclib metadata
990 allapps = metadata.read_metadata(xref=not options.onserver)
992 apps = common.read_app_args(args, allapps, True)
993 apps = [app for app in apps if (options.force or not app['Disabled']) and
994 len(app['Repo Type']) > 0 and len(app['builds']) > 0]
997 raise Exception("No apps to process.")
1001 for build in reversed(app['builds']):
1002 if build['disable']:
1004 app['builds'] = [build]
1009 site = mwclient.Site((config['wiki_protocol'], config['wiki_server']),
1010 path=config['wiki_path'])
1011 site.login(config['wiki_user'], config['wiki_password'])
1013 # Build applications...
1015 build_succeeded = []
1020 for thisbuild in app['builds']:
1024 # For the first build of a particular app, we need to set up
1025 # the source repo. We can reuse it on subsequent builds, if
1028 if app['Repo Type'] == 'srclib':
1029 build_dir = os.path.join('build', 'srclib', app['Repo'])
1031 build_dir = os.path.join('build', app['id'])
1033 # Set up vcs interface and make sure we have the latest code...
1034 logging.debug("Getting {0} vcs interface for {1}"
1035 .format(app['Repo Type'], app['Repo']))
1036 vcs = common.getvcs(app['Repo Type'], app['Repo'], build_dir)
1040 logging.debug("Checking " + thisbuild['version'])
1041 if trybuild(app, thisbuild, build_dir, output_dir,
1042 also_check_dir, srclib_dir, extlib_dir,
1043 tmp_dir, repo_dir, vcs, options.test,
1044 options.server, options.force,
1046 build_succeeded.append(app)
1047 wikilog = "Build succeeded"
1048 except BuildException as be:
1049 logfile = open(os.path.join(log_dir, app['id'] + '.log'), 'a+')
1050 logfile.write(str(be))
1052 reason = str(be).split('\n', 1)[0] if options.verbose else str(be)
1053 print("Could not build app %s due to BuildException: %s" % (
1057 failed_apps[app['id']] = be
1058 wikilog = be.get_wikitext()
1059 except VCSException as vcse:
1060 print("VCS error while building app %s: %s" % (app['id'], vcse))
1063 failed_apps[app['id']] = vcse
1065 except Exception as e:
1066 print("Could not build app %s due to unknown error: %s" % (app['id'], traceback.format_exc()))
1069 failed_apps[app['id']] = e
1072 if options.wiki and wikilog:
1074 newpage = site.Pages[app['id'] + '/lastbuild']
1075 txt = "Build completed at " + time.strftime("%Y-%m-%d %H:%M:%SZ", time.gmtime()) + "\n\n" + wikilog
1076 newpage.save(txt, summary='Build log')
1078 logging.info("Error while attempting to publish build log")
1080 for app in build_succeeded:
1081 logging.info("success: %s" % (app['id']))
1083 if not options.verbose:
1084 for fa in failed_apps:
1085 logging.info("Build for app %s failed:\n%s" % (fa, failed_apps[fa]))
1087 logging.info("Finished.")
1088 if len(build_succeeded) > 0:
1089 logging.info(str(len(build_succeeded)) + ' builds succeeded')
1090 if len(failed_apps) > 0:
1091 logging.info(str(len(failed_apps)) + ' builds failed')
1095 if __name__ == "__main__":