2 # -*- coding: utf-8 -*-
4 # build.py - part of the FDroid server tools
5 # Copyright (C) 2010-13, 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
34 import common, metadata
35 from common import BuildException, VCSException, FDroidPopen, SilentPopen
37 def get_builder_vm_id():
38 vd = os.path.join('builder', '.vagrant')
40 # Vagrant 1.2 (and maybe 1.1?) it's a directory tree...
41 with open(os.path.join(vd, 'machines', 'default', 'virtualbox', 'id')) as vf:
45 # Vagrant 1.0 - it's a json file...
46 with open(os.path.join('builder', '.vagrant')) as vf:
48 return v['active']['default']
50 def got_valid_builder_vm():
51 """Returns True if we have a valid-looking builder vm
53 if not os.path.exists(os.path.join('builder', 'Vagrantfile')):
55 vd = os.path.join('builder', '.vagrant')
56 if not os.path.exists(vd):
58 if not os.path.isdir(vd):
59 # Vagrant 1.0 - if the directory is there, it's valid...
61 # Vagrant 1.2 - the directory can exist, but the id can be missing...
62 if not os.path.exists(os.path.join(vd, 'machines', 'default', 'virtualbox', 'id')):
67 def vagrant(params, cwd=None, printout=False):
70 :param: list of parameters to pass to vagrant
71 :cwd: directory to run in, or None for current directory
72 :returns: (ret, out) where ret is the return code, and out
73 is the stdout (and stderr) from vagrant
75 p = FDroidPopen(['vagrant'] + params, cwd=cwd)
76 return (p.returncode, p.stdout)
79 # Note that 'force' here also implies test mode.
80 def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
81 """Do a build on the build server."""
85 logging.getLogger("paramiko").setLevel(logging.DEBUG)
87 logging.getLogger("paramiko").setLevel(logging.WARN)
89 # Reset existing builder machine to a clean state if possible.
91 if not options.resetserver:
92 logging.info("Checking for valid existing build server")
94 if got_valid_builder_vm():
95 logging.info("...VM is present")
96 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'list', '--details'], cwd='builder')
97 if 'fdroidclean' in p.stdout:
98 logging.info("...snapshot exists - resetting build server to clean state")
99 retcode, output = vagrant(['status'], cwd='builder')
101 if 'running' in output:
102 logging.info("...suspending")
103 vagrant(['suspend'], cwd='builder')
104 logging.info("...waiting a sec...")
106 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'restore', 'fdroidclean'],
109 if p.returncode == 0:
110 logging.info("...reset to snapshot - server is valid")
111 retcode, output = vagrant(['up'], cwd='builder')
113 raise BuildException("Failed to start build server")
114 logging.info("...waiting a sec...")
118 logging.info("...failed to reset to snapshot")
120 logging.info("...snapshot doesn't exist - VBoxManage snapshot list:\n" + p.stdout)
122 # If we can't use the existing machine for any reason, make a
123 # new one from scratch.
125 if os.path.exists('builder'):
126 logging.info("Removing broken/incomplete/unwanted build server")
127 vagrant(['destroy', '-f'], cwd='builder')
128 shutil.rmtree('builder')
131 p = subprocess.Popen('vagrant --version', shell=True, stdout=subprocess.PIPE)
132 vver = p.communicate()[0]
133 if vver.startswith('Vagrant version 1.2'):
134 with open('builder/Vagrantfile', 'w') as vf:
135 vf.write('Vagrant.configure("2") do |config|\n')
136 vf.write('config.vm.box = "buildserver"\n')
139 with open('builder/Vagrantfile', 'w') as vf:
140 vf.write('Vagrant::Config.run do |config|\n')
141 vf.write('config.vm.box = "buildserver"\n')
144 logging.info("Starting new build server")
145 retcode, _ = vagrant(['up'], cwd='builder')
147 raise BuildException("Failed to start build server")
149 # Open SSH connection to make sure it's working and ready...
150 logging.info("Connecting to virtual machine...")
151 if subprocess.call('vagrant ssh-config >sshconfig',
152 cwd='builder', shell=True) != 0:
153 raise BuildException("Error getting ssh config")
154 vagranthost = 'default' # Host in ssh config file
155 sshconfig = paramiko.SSHConfig()
156 sshf = open('builder/sshconfig', 'r')
157 sshconfig.parse(sshf)
159 sshconfig = sshconfig.lookup(vagranthost)
160 sshs = paramiko.SSHClient()
161 sshs.set_missing_host_key_policy(paramiko.AutoAddPolicy())
162 idfile = sshconfig['identityfile']
163 if isinstance(idfile, list):
165 elif idfile.startswith('"') and idfile.endswith('"'):
166 idfile = idfile[1:-1]
167 sshs.connect(sshconfig['hostname'], username=sshconfig['user'],
168 port=int(sshconfig['port']), timeout=300, look_for_keys=False,
172 logging.info("Saving clean state of new build server")
173 retcode, _ = vagrant(['suspend'], cwd='builder')
175 raise BuildException("Failed to suspend build server")
176 logging.info("...waiting a sec...")
178 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'take', 'fdroidclean'],
180 if p.returncode != 0:
181 raise BuildException("Failed to take snapshot")
182 logging.info("...waiting a sec...")
184 logging.info("Restarting new build server")
185 retcode, _ = vagrant(['up'], cwd='builder')
187 raise BuildException("Failed to start build server")
188 logging.info("...waiting a sec...")
190 # Make sure it worked...
191 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'list', '--details'],
193 if 'fdroidclean' not in p.stdout:
194 raise BuildException("Failed to take snapshot.")
198 # Get SSH configuration settings for us to connect...
199 logging.info("Getting ssh configuration...")
200 subprocess.call('vagrant ssh-config >sshconfig',
201 cwd='builder', shell=True)
202 vagranthost = 'default' # Host in ssh config file
204 # Load and parse the SSH config...
205 sshconfig = paramiko.SSHConfig()
206 sshf = open('builder/sshconfig', 'r')
207 sshconfig.parse(sshf)
209 sshconfig = sshconfig.lookup(vagranthost)
211 # Open SSH connection...
212 logging.info("Connecting to virtual machine...")
213 sshs = paramiko.SSHClient()
214 sshs.set_missing_host_key_policy(paramiko.AutoAddPolicy())
215 idfile = sshconfig['identityfile'][0]
216 if idfile.startswith('"') and idfile.endswith('"'):
217 idfile = idfile[1:-1]
218 sshs.connect(sshconfig['hostname'], username=sshconfig['user'],
219 port=int(sshconfig['port']), timeout=300, look_for_keys=False,
222 # Get an SFTP connection...
223 ftp = sshs.open_sftp()
224 ftp.get_channel().settimeout(15)
226 # Put all the necessary files in place...
227 ftp.chdir('/home/vagrant')
229 # Helper to copy the contents of a directory to the server...
231 root = os.path.dirname(path)
232 main = os.path.basename(path)
234 for r, d, f in os.walk(path):
235 rr = os.path.relpath(r, root)
240 lfile = os.path.join(root, rr, ff)
241 if not os.path.islink(lfile):
243 ftp.chmod(ff, os.stat(lfile).st_mode)
244 for i in range(len(rr.split('/'))):
248 logging.info("Preparing server for build...")
249 serverpath = os.path.abspath(os.path.dirname(__file__))
250 ftp.put(os.path.join(serverpath, 'build.py'), 'build.py')
251 ftp.put(os.path.join(serverpath, 'common.py'), 'common.py')
252 ftp.put(os.path.join(serverpath, 'metadata.py'), 'metadata.py')
253 ftp.put(os.path.join(serverpath, '..', 'buildserver',
254 'config.buildserver.py'), 'config.py')
255 ftp.chmod('config.py', 0o600)
257 # Copy over the ID (head commit hash) of the fdroidserver in use...
258 subprocess.call('git rev-parse HEAD >' +
259 os.path.join(os.getcwd(), 'tmp', 'fdroidserverid'),
260 shell=True, cwd=serverpath)
261 ftp.put('tmp/fdroidserverid', 'fdroidserverid')
263 # Copy the metadata - just the file for this app...
264 ftp.mkdir('metadata')
266 ftp.chdir('metadata')
267 ftp.put(os.path.join('metadata', app['id'] + '.txt'),
269 # And patches if there are any...
270 if os.path.exists(os.path.join('metadata', app['id'])):
271 send_dir(os.path.join('metadata', app['id']))
273 ftp.chdir('/home/vagrant')
274 # Create the build directory...
279 # Copy any extlibs that are required...
280 if 'extlibs' in thisbuild:
281 ftp.chdir('/home/vagrant/build/extlib')
282 for lib in thisbuild['extlibs']:
284 libsrc = os.path.join('build/extlib', lib)
285 if not os.path.exists(libsrc):
286 raise BuildException("Missing extlib {0}".format(libsrc))
289 if d not in ftp.listdir():
292 ftp.put(libsrc, lp[-1])
295 # Copy any srclibs that are required...
297 if 'srclibs' in thisbuild:
298 for lib in thisbuild['srclibs']:
299 srclibpaths.append(common.getsrclib(lib, 'build/srclib', srclibpaths,
300 basepath=True, prepare=False))
302 # If one was used for the main source, add that too.
303 basesrclib = vcs.getsrclib()
305 srclibpaths.append(basesrclib)
306 for name, number, lib in srclibpaths:
307 logging.info("Sending srclib '%s'" % lib)
308 ftp.chdir('/home/vagrant/build/srclib')
309 if not os.path.exists(lib):
310 raise BuildException("Missing srclib directory '" + lib + "'")
311 fv = '.fdroidvcs-' + name
312 ftp.put(os.path.join('build/srclib', fv), fv)
314 # Copy the metadata file too...
315 ftp.chdir('/home/vagrant/srclibs')
316 ftp.put(os.path.join('srclibs', name + '.txt'),
318 # Copy the main app source code
319 # (no need if it's a srclib)
320 if (not basesrclib) and os.path.exists(build_dir):
321 ftp.chdir('/home/vagrant/build')
322 fv = '.fdroidvcs-' + app['id']
323 ftp.put(os.path.join('build', fv), fv)
326 # Execute the build script...
327 logging.info("Starting build...")
328 chan = sshs.get_transport().open_session()
330 cmdline = 'python build.py --on-server'
332 cmdline += ' --force --test'
334 cmdline += ' --verbose'
335 cmdline += " %s:%s" % (app['id'], thisbuild['vercode'])
336 chan.exec_command('bash -c ". ~/.bsenv && ' + cmdline + '"')
338 while not chan.exit_status_ready():
339 while chan.recv_ready():
340 output += chan.recv(1024)
342 logging.info("...getting exit status")
343 returncode = chan.recv_exit_status()
345 get = chan.recv(1024)
350 raise BuildException("Build.py failed on server for %s:%s" % (app['id'], thisbuild['version']), output)
352 # Retrieve the built files...
353 logging.info("Retrieving build output...")
355 ftp.chdir('/home/vagrant/tmp')
357 ftp.chdir('/home/vagrant/unsigned')
358 apkfile = common.getapkname(app,thisbuild)
359 tarball = common.getsrcname(app,thisbuild)
361 ftp.get(apkfile, os.path.join(output_dir, apkfile))
362 if not options.notarball:
363 ftp.get(tarball, os.path.join(output_dir, tarball))
365 raise BuildException("Build failed for %s:%s - missing output files" % (app['id'], thisbuild['version']), output)
370 # Suspend the build server.
371 logging.info("Suspending build server")
372 subprocess.call(['vagrant', 'suspend'], cwd='builder')
374 def adapt_gradle(build_dir):
375 for root, dirs, files in os.walk(build_dir):
376 if 'build.gradle' in files:
377 path = os.path.join(root, 'build.gradle')
378 logging.info("Adapting build.gradle at %s" % path)
380 FDroidPopen(['sed', '-i',
381 r's@buildToolsVersion\([ =]*\)["\'][0-9\.]*["\']@buildToolsVersion\1"'
382 + config['build_tools'] + '"@g', path])
385 def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver):
386 """Do a build locally."""
388 if thisbuild.get('buildjni') not in (None, ['no']):
389 if not config['ndk_path']:
390 logging.critical("$ANDROID_NDK is not set!")
392 elif not os.path.isdir(config['sdk_path']):
393 logging.critical("$ANDROID_NDK points to a non-existing directory!")
396 # Prepare the source code...
397 root_dir, srclibpaths = common.prepare_source(vcs, app, thisbuild,
398 build_dir, srclib_dir, extlib_dir, onserver)
400 # We need to clean via the build tool in case the binary dirs are
401 # different from the default ones
403 if thisbuild['type'] == 'maven':
404 logging.info("Cleaning Maven project...")
405 cmd = [config['mvn3'], 'clean', '-Dandroid.sdk.path=' + config['sdk_path']]
407 if '@' in thisbuild['maven']:
408 maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@',1)[1])
409 maven_dir = os.path.normpath(maven_dir)
413 p = FDroidPopen(cmd, cwd=maven_dir)
415 elif thisbuild['type'] == 'gradle':
417 logging.info("Cleaning Gradle project...")
418 cmd = [config['gradle'], 'clean']
420 if '@' in thisbuild['gradle']:
421 gradle_dir = os.path.join(root_dir, thisbuild['gradle'].split('@',1)[1])
422 gradle_dir = os.path.normpath(gradle_dir)
424 gradle_dir = root_dir
426 adapt_gradle(build_dir)
427 for name, number, libpath in srclibpaths:
428 adapt_gradle(libpath)
430 p = FDroidPopen(cmd, cwd=gradle_dir)
432 elif thisbuild['type'] == 'kivy':
435 elif thisbuild['type'] == 'ant':
436 logging.info("Cleaning Ant project...")
437 p = FDroidPopen(['ant', 'clean'], cwd=root_dir)
439 if p is not None and p.returncode != 0:
440 raise BuildException("Error cleaning %s:%s" %
441 (app['id'], thisbuild['version']), p.stdout)
443 logging.info("Getting rid of Gradle wrapper binaries...")
444 for root, dirs, files in os.walk(build_dir):
445 # Don't remove possibly necessary 'gradle' dirs if 'gradlew' is not there
446 if 'gradlew' in files:
447 os.remove(os.path.join(root, 'gradlew'))
448 if 'gradlew.bat' in files:
449 os.remove(os.path.join(root, 'gradlew.bat'))
451 shutil.rmtree(os.path.join(root, 'gradle'))
453 if not options.skipscan:
454 # Scan before building...
455 logging.info("Scanning source for common problems...")
456 count = common.scan_source(build_dir, root_dir, thisbuild)
459 logging.warn('Scanner found %d problems:' % count)
461 raise BuildException("Can't build due to %d errors while scanning" % count)
463 if not options.notarball:
464 # Build the source tarball right before we build the release...
465 logging.info("Creating source tarball...")
466 tarname = common.getsrcname(app,thisbuild)
467 tarball = tarfile.open(os.path.join(tmp_dir, tarname), "w:gz")
469 return any(f.endswith(s) for s in ['.svn', '.git', '.hg', '.bzr'])
470 tarball.add(build_dir, tarname, exclude=tarexc)
474 manifest = os.path.join(root_dir, 'AndroidManifest.xml')
475 if os.path.exists(manifest):
476 with open('/home/vagrant/buildserverid', 'r') as f:
477 buildserverid = f.read()
478 with open('/home/vagrant/fdroidserverid', 'r') as f:
479 fdroidserverid = f.read()
480 with open(manifest, 'r') as f:
481 manifestcontent = f.read()
482 manifestcontent = manifestcontent.replace('</manifest>',
483 '<fdroid buildserverid="' + buildserverid + '"' +
484 ' fdroidserverid="' + fdroidserverid + '"' +
486 with open(manifest, 'w') as f:
487 f.write(manifestcontent)
489 # Run a build command if one is required...
490 if 'build' in thisbuild:
491 cmd = common.replace_config_vars(thisbuild['build'])
492 # Substitute source library paths into commands...
493 for name, number, libpath in srclibpaths:
494 libpath = os.path.relpath(libpath, root_dir)
495 cmd = cmd.replace('$$' + name + '$$', libpath)
496 logging.info("Running 'build' commands in %s" % root_dir)
498 p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
500 if p.returncode != 0:
501 raise BuildException("Error running build command for %s:%s" %
502 (app['id'], thisbuild['version']), p.stdout)
504 # Build native stuff if required...
505 if thisbuild.get('buildjni') not in (None, ['no']):
506 logging.info("Building native libraries...")
507 jni_components = thisbuild.get('buildjni')
508 if jni_components == ['yes']:
509 jni_components = ['']
510 cmd = [ os.path.join(config['ndk_path'], "ndk-build"), "-j1" ]
511 for d in jni_components:
513 logging.info("Building native code in '%s'" % d)
515 logging.info("Building native code in the main project")
516 manifest = root_dir + '/' + d + '/AndroidManifest.xml'
517 if os.path.exists(manifest):
518 # Read and write the whole AM.xml to fix newlines and avoid
519 # the ndk r8c or later 'wordlist' errors. The outcome of this
520 # under gnu/linux is the same as when using tools like
521 # dos2unix, but the native python way is faster and will
522 # work in non-unix systems.
523 manifest_text = open(manifest, 'U').read()
524 open(manifest, 'w').write(manifest_text)
525 # In case the AM.xml read was big, free the memory
527 p = FDroidPopen(cmd, cwd=os.path.join(root_dir,d))
528 if p.returncode != 0:
529 raise BuildException("NDK build failed for %s:%s" % (app['id'], thisbuild['version']), p.stdout)
532 # Build the release...
533 if thisbuild['type'] == 'maven':
534 logging.info("Building Maven project...")
536 if '@' in thisbuild['maven']:
537 maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@',1)[1])
541 mvncmd = [config['mvn3'], '-Dandroid.sdk.path=' + config['sdk_path'],
542 '-Dandroid.sign.debug=false', '-Dmaven.test.skip=true',
543 '-Dandroid.release=true', 'package']
544 if 'target' in thisbuild:
545 target = thisbuild["target"].split('-')[1]
546 FDroidPopen(['sed', '-i',
547 's@<platform>[0-9]*</platform>@<platform>'+target+'</platform>@g',
548 'pom.xml'], cwd=root_dir)
549 if '@' in thisbuild['maven']:
550 FDroidPopen(['sed', '-i',
551 's@<platform>[0-9]*</platform>@<platform>'+target+'</platform>@g',
552 'pom.xml'], cwd=maven_dir)
554 if 'mvnflags' in thisbuild:
555 mvncmd += thisbuild['mvnflags']
557 p = FDroidPopen(mvncmd, cwd=maven_dir)
559 bindir = os.path.join(root_dir, 'target')
561 elif thisbuild['type'] == 'kivy':
562 logging.info("Building Kivy project...")
564 spec = os.path.join(root_dir, 'buildozer.spec')
565 if not os.path.exists(spec):
566 raise BuildException("Expected to find buildozer-compatible spec at {0}"
569 defaults = {'orientation': 'landscape', 'icon': '',
570 'permissions': '', 'android.api': "18"}
571 bconfig = ConfigParser(defaults, allow_no_value=True)
574 distdir = 'python-for-android/dist/fdroid'
575 if os.path.exists(distdir):
576 shutil.rmtree(distdir)
578 modules = bconfig.get('app', 'requirements').split(',')
580 cmd = 'ANDROIDSDK=' + config['sdk_path']
581 cmd += ' ANDROIDNDK=' + config['ndk_path']
582 cmd += ' ANDROIDNDKVER=r9'
583 cmd += ' ANDROIDAPI=' + str(bconfig.get('app', 'android.api'))
584 cmd += ' VIRTUALENV=virtualenv'
585 cmd += ' ./distribute.sh'
586 cmd += ' -m ' + "'" + ' '.join(modules) + "'"
588 p = FDroidPopen(cmd, cwd='python-for-android', shell=True)
589 if p.returncode != 0:
590 raise BuildException("Distribute build failed")
592 cid = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
594 raise BuildException("Package ID mismatch between metadata and spec")
596 orientation = bconfig.get('app', 'orientation', 'landscape')
597 if orientation == 'all':
598 orientation = 'sensor'
602 '--name', bconfig.get('app', 'title'),
603 '--package', app['id'],
604 '--version', bconfig.get('app', 'version'),
605 '--orientation', orientation,
608 perms = bconfig.get('app', 'permissions')
609 for perm in perms.split(','):
610 cmd.extend(['--permission', perm])
612 if config.get('app', 'fullscreen') == 0:
613 cmd.append('--window')
615 icon = bconfig.get('app', 'icon.filename')
617 cmd.extend(['--icon', os.path.join(root_dir, icon)])
619 cmd.append('release')
620 p = FDroidPopen(cmd, cwd=distdir)
622 elif thisbuild['type'] == 'gradle':
623 logging.info("Building Gradle project...")
624 if '@' in thisbuild['gradle']:
625 flavours = thisbuild['gradle'].split('@')[0].split(',')
626 gradle_dir = thisbuild['gradle'].split('@')[1]
627 gradle_dir = os.path.join(root_dir, gradle_dir)
629 flavours = thisbuild['gradle'].split(',')
630 gradle_dir = root_dir
632 if len(flavours) == 1 and flavours[0] in ['main', 'yes', '']:
635 commands = [config['gradle']]
636 if 'preassemble' in thisbuild:
637 commands += thisbuild['preassemble'].split()
639 flavours_cmd = ''.join(flavours)
641 flavours_cmd = flavours_cmd[0].upper() + flavours_cmd[1:]
643 commands += ['assemble'+flavours_cmd+'Release']
645 p = FDroidPopen(commands, cwd=gradle_dir)
647 elif thisbuild['type'] == 'ant':
648 logging.info("Building Ant project...")
650 if 'antcommand' in thisbuild:
651 cmd += [thisbuild['antcommand']]
654 p = FDroidPopen(cmd, cwd=root_dir)
656 bindir = os.path.join(root_dir, 'bin')
658 if p is not None and p.returncode != 0:
659 raise BuildException("Build failed for %s:%s" % (app['id'], thisbuild['version']), p.stdout)
660 logging.info("Successfully built version " + thisbuild['version'] + ' of ' + app['id'])
662 if thisbuild['type'] == 'maven':
663 stdout_apk = '\n'.join([
664 line for line in p.stdout.splitlines() if any(a in line for a in ('.apk','.ap_'))])
665 m = re.match(r".*^\[INFO\] .*apkbuilder.*/([^/]*)\.apk",
666 stdout_apk, re.S|re.M)
668 m = re.match(r".*^\[INFO\] Creating additional unsigned apk file .*/([^/]+)\.apk[^l]",
669 stdout_apk, re.S|re.M)
671 m = re.match(r'.*^\[INFO\] [^$]*aapt \[package,[^$]*' + bindir + r'/([^/]+)\.ap[_k][,\]]',
672 stdout_apk, re.S|re.M)
674 raise BuildException('Failed to find output')
676 src = os.path.join(bindir, src) + '.apk'
677 elif thisbuild['type'] == 'kivy':
678 src = 'python-for-android/dist/default/bin/{0}-{1}-release.apk'.format(
679 bconfig.get('app', 'title'), bconfig.get('app', 'version'))
680 elif thisbuild['type'] == 'gradle':
683 if 'subdir' in thisbuild:
684 dd = os.path.join(dd, thisbuild['subdir'])
685 basename = os.path.basename(thisbuild['subdir'])
686 if '@' in thisbuild['gradle']:
687 dd = os.path.join(dd, thisbuild['gradle'].split('@')[1])
689 if len(flavours) == 1 and flavours[0] == '':
690 name = '-'.join([basename, 'release', 'unsigned'])
692 name = '-'.join([basename, '-'.join(flavours), 'release', 'unsigned'])
693 dd = os.path.normpath(dd)
694 src = os.path.join(dd, 'build', 'apk', name+'.apk')
695 elif thisbuild['type'] == 'ant':
696 stdout_apk = '\n'.join([
697 line for line in p.stdout.splitlines() if '.apk' in line])
698 src = re.match(r".*^.*Creating (.+) for release.*$.*", stdout_apk,
700 src = os.path.join(bindir, src)
701 elif thisbuild['type'] == 'raw':
702 src = os.path.join(root_dir, thisbuild['output'])
703 src = os.path.normpath(src)
705 # Make sure it's not debuggable...
706 if common.isApkDebuggable(src, config):
707 raise BuildException("APK is debuggable")
709 # By way of a sanity check, make sure the version and version
710 # code in our new apk match what we expect...
711 logging.info("Checking " + src)
712 if not os.path.exists(src):
713 raise BuildException("Unsigned apk is not at expected location of " + src)
715 p = SilentPopen([os.path.join(config['sdk_path'],
716 'build-tools', config['build_tools'], 'aapt'),
717 'dump', 'badging', src])
723 for line in p.stdout.splitlines():
724 if line.startswith("package:"):
725 pat = re.compile(".*name='([a-zA-Z0-9._]*)'.*")
729 pat = re.compile(".*versionCode='([0-9]*)'.*")
733 pat = re.compile(".*versionName='([^']*)'.*")
737 elif line.startswith("native-code:"):
738 nativecode = line[12:]
740 if thisbuild.get('buildjni') is not None:
741 if nativecode is None or "'" not in nativecode:
742 raise BuildException("Native code should have been built but none was packaged")
743 if thisbuild['novcheck']:
744 vercode = thisbuild['vercode']
745 version = thisbuild['version']
746 if not version or not vercode:
747 raise BuildException("Could not find version information in build in output")
749 raise BuildException("Could not find package ID in output")
750 if foundid != app['id']:
751 raise BuildException("Wrong package ID - build " + foundid + " but expected " + app['id'])
753 # Some apps (e.g. Timeriffic) have had the bonkers idea of
754 # including the entire changelog in the version number. Remove
755 # it so we can compare. (TODO: might be better to remove it
756 # before we compile, in fact)
757 index = version.find(" //")
759 version = version[:index]
761 if (version != thisbuild['version'] or
762 vercode != thisbuild['vercode']):
763 raise BuildException(("Unexpected version/version code in output;"
764 " APK: '%s' / '%s', "
765 " Expected: '%s' / '%s'")
766 % (version, str(vercode), thisbuild['version'], str(thisbuild['vercode']))
769 # Copy the unsigned apk to our destination directory for further
770 # processing (by publish.py)...
771 dest = os.path.join(output_dir, common.getapkname(app,thisbuild))
772 shutil.copyfile(src, dest)
774 # Move the source tarball into the output directory...
775 if output_dir != tmp_dir and not options.notarball:
776 shutil.move(os.path.join(tmp_dir, tarname),
777 os.path.join(output_dir, tarname))
780 def trybuild(app, thisbuild, build_dir, output_dir, also_check_dir, srclib_dir, extlib_dir,
781 tmp_dir, repo_dir, vcs, test, server, force, onserver):
783 Build a particular version of an application, if it needs building.
785 :param output_dir: The directory where the build output will go. Usually
786 this is the 'unsigned' directory.
787 :param repo_dir: The repo directory - used for checking if the build is
789 :paaram also_check_dir: An additional location for checking if the build
790 is necessary (usually the archive repo)
791 :param test: True if building in test mode, in which case the build will
792 always happen, even if the output already exists. In test mode, the
793 output directory should be a temporary location, not any of the real
796 :returns: True if the build was done, False if it wasn't necessary.
799 dest_apk = common.getapkname(app, thisbuild)
801 dest = os.path.join(output_dir, dest_apk)
802 dest_repo = os.path.join(repo_dir, dest_apk)
805 if os.path.exists(dest) or os.path.exists(dest_repo):
809 dest_also = os.path.join(also_check_dir, dest_apk)
810 if os.path.exists(dest_also):
813 if 'disable' in thisbuild:
816 logging.info("Building version " + thisbuild['version'] + ' of ' + app['id'])
819 # When using server mode, still keep a local cache of the repo, by
820 # grabbing the source now.
821 vcs.gotorevision(thisbuild['commit'])
823 build_server(app, thisbuild, vcs, build_dir, output_dir, force)
825 build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver)
829 def parse_commandline():
830 """Parse the command line. Returns options, args."""
832 parser = OptionParser(usage="Usage: %prog [options] [APPID[:VERCODE] [APPID[:VERCODE] ...]]")
833 parser.add_option("-v", "--verbose", action="store_true", default=False,
834 help="Spew out even more information than normal")
835 parser.add_option("-q", "--quiet", action="store_true", default=False,
836 help="Restrict output to warnings and errors")
837 parser.add_option("-l", "--latest", action="store_true", default=False,
838 help="Build only the latest version of each package")
839 parser.add_option("-s", "--stop", action="store_true", default=False,
840 help="Make the build stop on exceptions")
841 parser.add_option("-t", "--test", action="store_true", default=False,
842 help="Test mode - put output in the tmp directory only, and always build, even if the output already exists.")
843 parser.add_option("--server", action="store_true", default=False,
844 help="Use build server")
845 parser.add_option("--resetserver", action="store_true", default=False,
846 help="Reset and create a brand new build server, even if the existing one appears to be ok.")
847 parser.add_option("--on-server", dest="onserver", action="store_true", default=False,
848 help="Specify that we're running on the build server")
849 parser.add_option("--skip-scan", dest="skipscan", action="store_true", default=False,
850 help="Skip scanning the source code for binaries and other problems")
851 parser.add_option("--no-tarball", dest="notarball", action="store_true", default=False,
852 help="Don't create a source tarball, useful when testing a build")
853 parser.add_option("-f", "--force", action="store_true", default=False,
854 help="Force build of disabled apps, and carries on regardless of scan problems. Only allowed in test mode.")
855 parser.add_option("-a", "--all", action="store_true", default=False,
856 help="Build all applications available")
857 parser.add_option("-w", "--wiki", default=False, action="store_true",
858 help="Update the wiki")
859 options, args = parser.parse_args()
861 # Force --stop with --on-server to get correct exit code
865 if options.force and not options.test:
866 raise OptionError("Force is only allowed in test mode", "force")
875 global options, config
877 options, args = parse_commandline()
878 if not args and not options.all:
879 raise OptionError("If you really want to build all the apps, use --all", "all")
881 config = common.read_config(options)
883 if config['build_server_always']:
884 options.server = True
885 if options.resetserver and not options.server:
886 raise OptionError("Using --resetserver without --server makes no sense", "resetserver")
889 if not os.path.isdir(log_dir):
890 logging.info("Creating log directory")
894 if not os.path.isdir(tmp_dir):
895 logging.info("Creating temporary directory")
901 output_dir = 'unsigned'
902 if not os.path.isdir(output_dir):
903 logging.info("Creating output directory")
904 os.makedirs(output_dir)
906 if config['archive_older'] != 0:
907 also_check_dir = 'archive'
909 also_check_dir = None
914 if not os.path.isdir(build_dir):
915 logging.info("Creating build directory")
916 os.makedirs(build_dir)
917 srclib_dir = os.path.join(build_dir, 'srclib')
918 extlib_dir = os.path.join(build_dir, 'extlib')
921 allapps = metadata.read_metadata(xref=not options.onserver)
923 apps = common.read_app_args(args, allapps, True)
924 apps = [app for app in apps if (options.force or not app['Disabled']) and
925 len(app['Repo Type']) > 0 and len(app['builds']) > 0]
928 raise Exception("No apps to process.")
932 for build in reversed(app['builds']):
933 if 'disable' in build:
935 app['builds'] = [ build ]
940 site = mwclient.Site((config['wiki_protocol'], config['wiki_server']),
941 path=config['wiki_path'])
942 site.login(config['wiki_user'], config['wiki_password'])
944 # Build applications...
951 for thisbuild in app['builds']:
955 # For the first build of a particular app, we need to set up
956 # the source repo. We can reuse it on subsequent builds, if
959 if app['Repo Type'] == 'srclib':
960 build_dir = os.path.join('build', 'srclib', app['Repo'])
962 build_dir = os.path.join('build', app['id'])
964 # Set up vcs interface and make sure we have the latest code...
965 logging.debug("Getting {0} vcs interface for {1}".format(
966 app['Repo Type'], app['Repo']))
967 vcs = common.getvcs(app['Repo Type'], app['Repo'], build_dir)
971 logging.debug("Checking " + thisbuild['version'])
972 if trybuild(app, thisbuild, build_dir, output_dir, also_check_dir,
973 srclib_dir, extlib_dir, tmp_dir, repo_dir, vcs, options.test,
974 options.server, options.force, options.onserver):
975 build_succeeded.append(app)
976 wikilog = "Build succeeded"
977 except BuildException as be:
978 logfile = open(os.path.join(log_dir, app['id'] + '.log'), 'a+')
979 logfile.write(str(be))
981 reason = str(be).split('\n',1)[0] if options.verbose else str(be)
982 print("Could not build app %s due to BuildException: %s" % (
986 failed_apps[app['id']] = be
987 wikilog = be.get_wikitext()
988 except VCSException as vcse:
989 print("VCS error while building app %s: %s" % (app['id'], vcse))
992 failed_apps[app['id']] = vcse
994 except Exception as e:
995 print("Could not build app %s due to unknown error: %s" % (app['id'], traceback.format_exc()))
998 failed_apps[app['id']] = e
1001 if options.wiki and wikilog:
1003 newpage = site.Pages[app['id'] + '/lastbuild']
1004 txt = "Build completed at " + time.strftime("%Y-%m-%d %H:%M:%SZ", time.gmtime()) + "\n\n" + wikilog
1005 newpage.save(txt, summary='Build log')
1007 logging.info("Error while attempting to publish build log")
1009 for app in build_succeeded:
1010 logging.info("success: %s" % (app['id']))
1012 if not options.verbose:
1013 for fa in failed_apps:
1014 logging.info("Build for app %s failed:\n%s" % (fa, failed_apps[fa]))
1016 logging.info("Finished.")
1017 if len(build_succeeded) > 0:
1018 logging.info(str(len(build_succeeded)) + ' builds succeeded')
1019 if len(failed_apps) > 0:
1020 logging.info(str(len(failed_apps)) + ' builds failed')
1024 if __name__ == "__main__":