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("ssh").setLevel(logging.DEBUG)
87 logging.getLogger("ssh").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" + output)
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 = ssh.SSHConfig()
156 sshf = open('builder/sshconfig', 'r')
157 sshconfig.parse(sshf)
159 sshconfig = sshconfig.lookup(vagranthost)
160 sshs = ssh.SSHClient()
161 sshs.set_missing_host_key_policy(ssh.AutoAddPolicy())
162 idfile = sshconfig['identityfile']
163 if idfile.startswith('"') and idfile.endswith('"'):
164 idfile = idfile[1:-1]
165 sshs.connect(sshconfig['hostname'], username=sshconfig['user'],
166 port=int(sshconfig['port']), timeout=300, look_for_keys=False,
170 logging.info("Saving clean state of new build server")
171 retcode, _ = vagrant(['suspend'], cwd='builder')
173 raise BuildException("Failed to suspend build server")
174 logging.info("...waiting a sec...")
176 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'take', 'fdroidclean'],
178 if p.returncode != 0:
179 raise BuildException("Failed to take snapshot")
180 logging.info("...waiting a sec...")
182 logging.info("Restarting new build server")
183 retcode, _ = vagrant(['up'], cwd='builder')
185 raise BuildException("Failed to start build server")
186 logging.info("...waiting a sec...")
188 # Make sure it worked...
189 p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'list', '--details'],
191 if 'fdroidclean' not in p.stdout:
192 raise BuildException("Failed to take snapshot.")
196 # Get SSH configuration settings for us to connect...
197 logging.info("Getting ssh configuration...")
198 subprocess.call('vagrant ssh-config >sshconfig',
199 cwd='builder', shell=True)
200 vagranthost = 'default' # Host in ssh config file
202 # Load and parse the SSH config...
203 sshconfig = ssh.SSHConfig()
204 sshf = open('builder/sshconfig', 'r')
205 sshconfig.parse(sshf)
207 sshconfig = sshconfig.lookup(vagranthost)
209 # Open SSH connection...
210 logging.info("Connecting to virtual machine...")
211 sshs = ssh.SSHClient()
212 sshs.set_missing_host_key_policy(ssh.AutoAddPolicy())
213 idfile = sshconfig['identityfile']
214 if idfile.startswith('"') and idfile.endswith('"'):
215 idfile = idfile[1:-1]
216 sshs.connect(sshconfig['hostname'], username=sshconfig['user'],
217 port=int(sshconfig['port']), timeout=300, look_for_keys=False,
220 # Get an SFTP connection...
221 ftp = sshs.open_sftp()
222 ftp.get_channel().settimeout(15)
224 # Put all the necessary files in place...
225 ftp.chdir('/home/vagrant')
227 # Helper to copy the contents of a directory to the server...
229 root = os.path.dirname(path)
230 main = os.path.basename(path)
232 for r, d, f in os.walk(path):
233 rr = os.path.relpath(r, root)
238 lfile = os.path.join(root, rr, ff)
239 if not os.path.islink(lfile):
241 ftp.chmod(ff, os.stat(lfile).st_mode)
242 for i in range(len(rr.split('/'))):
246 logging.info("Preparing server for build...")
247 serverpath = os.path.abspath(os.path.dirname(__file__))
248 ftp.put(os.path.join(serverpath, 'build.py'), 'build.py')
249 ftp.put(os.path.join(serverpath, 'common.py'), 'common.py')
250 ftp.put(os.path.join(serverpath, 'metadata.py'), 'metadata.py')
251 ftp.put(os.path.join(serverpath, '..', 'buildserver',
252 'config.buildserver.py'), 'config.py')
253 ftp.chmod('config.py', 0o600)
255 # Copy the metadata - just the file for this app...
256 ftp.mkdir('metadata')
258 ftp.chdir('metadata')
259 ftp.put(os.path.join('metadata', app['id'] + '.txt'),
261 # And patches if there are any...
262 if os.path.exists(os.path.join('metadata', app['id'])):
263 send_dir(os.path.join('metadata', app['id']))
265 ftp.chdir('/home/vagrant')
266 # Create the build directory...
271 # Copy any extlibs that are required...
272 if 'extlibs' in thisbuild:
273 ftp.chdir('/home/vagrant/build/extlib')
274 for lib in thisbuild['extlibs']:
276 libsrc = os.path.join('build/extlib', lib)
277 if not os.path.exists(libsrc):
278 raise BuildException("Missing extlib {0}".format(libsrc))
281 if d not in ftp.listdir():
284 ftp.put(libsrc, lp[-1])
287 # Copy any srclibs that are required...
289 if 'srclibs' in thisbuild:
290 for lib in thisbuild['srclibs']:
291 srclibpaths.append(common.getsrclib(lib, 'build/srclib', srclibpaths,
292 basepath=True, prepare=False))
294 # If one was used for the main source, add that too.
295 basesrclib = vcs.getsrclib()
297 srclibpaths.append(basesrclib)
298 for name, number, lib in srclibpaths:
299 logging.info("Sending srclib '%s'" % lib)
300 ftp.chdir('/home/vagrant/build/srclib')
301 if not os.path.exists(lib):
302 raise BuildException("Missing srclib directory '" + lib + "'")
303 fv = '.fdroidvcs-' + name
304 ftp.put(os.path.join('build/srclib', fv), fv)
306 # Copy the metadata file too...
307 ftp.chdir('/home/vagrant/srclibs')
308 ftp.put(os.path.join('srclibs', name + '.txt'),
310 # Copy the main app source code
311 # (no need if it's a srclib)
312 if (not basesrclib) and os.path.exists(build_dir):
313 ftp.chdir('/home/vagrant/build')
314 fv = '.fdroidvcs-' + app['id']
315 ftp.put(os.path.join('build', fv), fv)
318 # Execute the build script...
319 logging.info("Starting build...")
320 chan = sshs.get_transport().open_session()
322 cmdline = 'python build.py --on-server'
324 cmdline += ' --force --test'
326 cmdline += ' --verbose'
327 cmdline += " %s:%s" % (app['id'], thisbuild['vercode'])
328 chan.exec_command('bash -c ". ~/.bsenv && ' + cmdline + '"')
330 while not chan.exit_status_ready():
331 while chan.recv_ready():
332 output += chan.recv(1024)
334 logging.info("...getting exit status")
335 returncode = chan.recv_exit_status()
337 get = chan.recv(1024)
342 raise BuildException("Build.py failed on server for %s:%s" % (app['id'], thisbuild['version']), output)
344 # Retrieve the built files...
345 logging.info("Retrieving build output...")
347 ftp.chdir('/home/vagrant/tmp')
349 ftp.chdir('/home/vagrant/unsigned')
350 apkfile = common.getapkname(app,thisbuild)
351 tarball = common.getsrcname(app,thisbuild)
353 ftp.get(apkfile, os.path.join(output_dir, apkfile))
354 if not options.notarball:
355 ftp.get(tarball, os.path.join(output_dir, tarball))
357 raise BuildException("Build failed for %s:%s - missing output files" % (app['id'], thisbuild['version']), output)
362 # Suspend the build server.
363 logging.info("Suspending build server")
364 subprocess.call(['vagrant', 'suspend'], cwd='builder')
366 def adapt_gradle(build_dir):
367 for root, dirs, files in os.walk(build_dir):
368 if 'build.gradle' in files:
369 path = os.path.join(root, 'build.gradle')
370 logging.info("Adapting build.gradle at %s" % path)
372 FDroidPopen(['sed', '-i',
373 r's@buildToolsVersion\([ =]*\)["\'][0-9\.]*["\']@buildToolsVersion\1"'
374 + config['build_tools'] + '"@g', path])
377 def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver):
378 """Do a build locally."""
380 if thisbuild.get('buildjni') not in (None, ['no']):
381 if not config['ndk_path']:
382 logging.critical("$ANDROID_NDK is not set!")
384 elif not os.path.isdir(config['sdk_path']):
385 logging.critical("$ANDROID_NDK points to a non-existing directory!")
388 # Prepare the source code...
389 root_dir, srclibpaths = common.prepare_source(vcs, app, thisbuild,
390 build_dir, srclib_dir, extlib_dir, onserver)
392 # We need to clean via the build tool in case the binary dirs are
393 # different from the default ones
395 if thisbuild['type'] == 'maven':
396 logging.info("Cleaning Maven project...")
397 cmd = [config['mvn3'], 'clean', '-Dandroid.sdk.path=' + config['sdk_path']]
399 if '@' in thisbuild['maven']:
400 maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@',1)[1])
401 maven_dir = os.path.normpath(maven_dir)
405 p = FDroidPopen(cmd, cwd=maven_dir)
407 elif thisbuild['type'] == 'gradle':
409 logging.info("Cleaning Gradle project...")
410 cmd = [config['gradle'], 'clean']
412 if '@' in thisbuild['gradle']:
413 gradle_dir = os.path.join(root_dir, thisbuild['gradle'].split('@',1)[1])
414 gradle_dir = os.path.normpath(gradle_dir)
416 gradle_dir = root_dir
418 adapt_gradle(build_dir)
419 for name, number, libpath in srclibpaths:
420 adapt_gradle(libpath)
422 p = FDroidPopen(cmd, cwd=gradle_dir)
424 elif thisbuild['type'] == 'kivy':
427 elif thisbuild['type'] == 'ant':
428 logging.info("Cleaning Ant project...")
429 p = FDroidPopen(['ant', 'clean'], cwd=root_dir)
431 if p is not None and p.returncode != 0:
432 raise BuildException("Error cleaning %s:%s" %
433 (app['id'], thisbuild['version']), p.stdout)
435 logging.info("Getting rid of Gradle wrapper binaries...")
436 for root, dirs, files in os.walk(build_dir):
437 # Don't remove possibly necessary 'gradle' dirs if 'gradlew' is not there
438 if 'gradlew' in files:
439 os.remove(os.path.join(root, 'gradlew'))
440 if 'gradlew.bat' in files:
441 os.remove(os.path.join(root, 'gradlew.bat'))
443 shutil.rmtree(os.path.join(root, 'gradle'))
445 if not options.skipscan:
446 # Scan before building...
447 logging.info("Scanning source for common problems...")
448 buildprobs = common.scan_source(build_dir, root_dir, thisbuild)
449 if len(buildprobs) > 0:
450 logging.warn('Scanner found %d problems:' % len(buildprobs))
451 for problem in buildprobs:
452 logging.info(' %s' % problem)
454 raise BuildException("Can't build due to " +
455 str(len(buildprobs)) + " scanned problems")
457 if not options.notarball:
458 # Build the source tarball right before we build the release...
459 logging.info("Creating source tarball...")
460 tarname = common.getsrcname(app,thisbuild)
461 tarball = tarfile.open(os.path.join(tmp_dir, tarname), "w:gz")
463 return any(f.endswith(s) for s in ['.svn', '.git', '.hg', '.bzr'])
464 tarball.add(build_dir, tarname, exclude=tarexc)
467 # Run a build command if one is required...
468 if 'build' in thisbuild:
469 cmd = common.replace_config_vars(thisbuild['build'])
470 # Substitute source library paths into commands...
471 for name, number, libpath in srclibpaths:
472 libpath = os.path.relpath(libpath, root_dir)
473 cmd = cmd.replace('$$' + name + '$$', libpath)
474 logging.info("Running 'build' commands in %s" % root_dir)
476 p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
478 if p.returncode != 0:
479 raise BuildException("Error running build command for %s:%s" %
480 (app['id'], thisbuild['version']), p.stdout)
482 # Build native stuff if required...
483 if thisbuild.get('buildjni') not in (None, ['no']):
484 logging.info("Building native libraries...")
485 jni_components = thisbuild.get('buildjni')
486 if jni_components == ['yes']:
487 jni_components = ['']
488 cmd = [ os.path.join(config['ndk_path'], "ndk-build"), "-j1" ]
489 for d in jni_components:
490 logging.info("Building native code in '%s'" % d)
491 manifest = root_dir + '/' + d + '/AndroidManifest.xml'
492 if os.path.exists(manifest):
493 # Read and write the whole AM.xml to fix newlines and avoid
494 # the ndk r8c or later 'wordlist' errors. The outcome of this
495 # under gnu/linux is the same as when using tools like
496 # dos2unix, but the native python way is faster and will
497 # work in non-unix systems.
498 manifest_text = open(manifest, 'U').read()
499 open(manifest, 'w').write(manifest_text)
500 # In case the AM.xml read was big, free the memory
502 p = FDroidPopen(cmd, cwd=os.path.join(root_dir,d))
503 if p.returncode != 0:
504 raise BuildException("NDK build failed for %s:%s" % (app['id'], thisbuild['version']), p.stdout)
507 # Build the release...
508 if thisbuild['type'] == 'maven':
509 logging.info("Building Maven project...")
511 if '@' in thisbuild['maven']:
512 maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@',1)[1])
516 mvncmd = [config['mvn3'], '-Dandroid.sdk.path=' + config['sdk_path'],
517 '-Dandroid.sign.debug=false', '-Dmaven.test.skip=true',
518 '-Dandroid.release=true', 'package']
519 if 'target' in thisbuild:
520 target = thisbuild["target"].split('-')[1]
521 FDroidPopen(['sed', '-i',
522 's@<platform>[0-9]*</platform>@<platform>'+target+'</platform>@g',
523 'pom.xml'], cwd=root_dir)
524 if '@' in thisbuild['maven']:
525 FDroidPopen(['sed', '-i',
526 's@<platform>[0-9]*</platform>@<platform>'+target+'</platform>@g',
527 'pom.xml'], cwd=maven_dir)
529 if 'mvnflags' in thisbuild:
530 mvncmd += thisbuild['mvnflags']
532 p = FDroidPopen(mvncmd, cwd=maven_dir)
534 bindir = os.path.join(root_dir, 'target')
536 elif thisbuild['type'] == 'kivy':
537 logging.info("Building Kivy project...")
539 spec = os.path.join(root_dir, 'buildozer.spec')
540 if not os.path.exists(spec):
541 raise BuildException("Expected to find buildozer-compatible spec at {0}"
544 defaults = {'orientation': 'landscape', 'icon': '',
545 'permissions': '', 'android.api': "18"}
546 bconfig = ConfigParser(defaults, allow_no_value=True)
549 distdir = 'python-for-android/dist/fdroid'
550 if os.path.exists(distdir):
551 shutil.rmtree(distdir)
553 modules = bconfig.get('app', 'requirements').split(',')
555 cmd = 'ANDROIDSDK=' + config['sdk_path']
556 cmd += ' ANDROIDNDK=' + config['ndk_path']
557 cmd += ' ANDROIDNDKVER=r9'
558 cmd += ' ANDROIDAPI=' + str(bconfig.get('app', 'android.api'))
559 cmd += ' VIRTUALENV=virtualenv'
560 cmd += ' ./distribute.sh'
561 cmd += ' -m ' + "'" + ' '.join(modules) + "'"
563 p = FDroidPopen(cmd, cwd='python-for-android', shell=True)
564 if p.returncode != 0:
565 raise BuildException("Distribute build failed")
567 cid = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
569 raise BuildException("Package ID mismatch between metadata and spec")
571 orientation = bconfig.get('app', 'orientation', 'landscape')
572 if orientation == 'all':
573 orientation = 'sensor'
577 '--name', bconfig.get('app', 'title'),
578 '--package', app['id'],
579 '--version', bconfig.get('app', 'version'),
580 '--orientation', orientation,
583 perms = bconfig.get('app', 'permissions')
584 for perm in perms.split(','):
585 cmd.extend(['--permission', perm])
587 if config.get('app', 'fullscreen') == 0:
588 cmd.append('--window')
590 icon = bconfig.get('app', 'icon.filename')
592 cmd.extend(['--icon', os.path.join(root_dir, icon)])
594 cmd.append('release')
595 p = FDroidPopen(cmd, cwd=distdir)
597 elif thisbuild['type'] == 'gradle':
598 logging.info("Building Gradle project...")
599 if '@' in thisbuild['gradle']:
600 flavours = thisbuild['gradle'].split('@')[0].split(',')
601 gradle_dir = thisbuild['gradle'].split('@')[1]
602 gradle_dir = os.path.join(root_dir, gradle_dir)
604 flavours = thisbuild['gradle'].split(',')
605 gradle_dir = root_dir
607 if len(flavours) == 1 and flavours[0] in ['main', 'yes', '']:
610 commands = [config['gradle']]
611 if 'preassemble' in thisbuild:
612 commands += thisbuild['preassemble'].split()
614 flavours_cmd = ''.join(flavours)
616 flavours_cmd = flavours_cmd[0].upper() + flavours_cmd[1:]
618 commands += ['assemble'+flavours_cmd+'Release']
620 p = FDroidPopen(commands, cwd=gradle_dir)
622 elif thisbuild['type'] == 'ant':
623 logging.info("Building Ant project...")
625 if 'antcommand' in thisbuild:
626 cmd += [thisbuild['antcommand']]
629 p = FDroidPopen(cmd, cwd=root_dir)
631 bindir = os.path.join(root_dir, 'bin')
633 if p is not None and p.returncode != 0:
634 raise BuildException("Build failed for %s:%s" % (app['id'], thisbuild['version']), p.stdout)
635 logging.info("Successfully built version " + thisbuild['version'] + ' of ' + app['id'])
637 if thisbuild['type'] == 'maven':
638 stdout_apk = '\n'.join([
639 line for line in p.stdout.splitlines() if any(a in line for a in ('.apk','.ap_'))])
640 m = re.match(r".*^\[INFO\] .*apkbuilder.*/([^/]*)\.apk",
641 stdout_apk, re.S|re.M)
643 m = re.match(r".*^\[INFO\] Creating additional unsigned apk file .*/([^/]+)\.apk[^l]",
644 stdout_apk, re.S|re.M)
646 m = re.match(r'.*^\[INFO\] [^$]*aapt \[package,[^$]*' + bindir + r'/([^/]+)\.ap[_k][,\]]',
647 stdout_apk, re.S|re.M)
649 raise BuildException('Failed to find output')
651 src = os.path.join(bindir, src) + '.apk'
652 elif thisbuild['type'] == 'kivy':
653 src = 'python-for-android/dist/default/bin/{0}-{1}-release.apk'.format(
654 bconfig.get('app', 'title'), bconfig.get('app', 'version'))
655 elif thisbuild['type'] == 'gradle':
657 if 'subdir' in thisbuild:
658 dd = os.path.join(dd, thisbuild['subdir'])
659 if len(flavours) == 1 and flavours[0] == '':
660 name = '-'.join([os.path.basename(dd), 'release', 'unsigned'])
662 name = '-'.join([os.path.basename(dd), '-'.join(flavours), 'release', 'unsigned'])
663 src = os.path.join(dd, 'build', 'apk', name+'.apk')
664 elif thisbuild['type'] == 'ant':
665 stdout_apk = '\n'.join([
666 line for line in p.stdout.splitlines() if '.apk' in line])
667 src = re.match(r".*^.*Creating (.+) for release.*$.*", stdout_apk,
669 src = os.path.join(bindir, src)
670 elif thisbuild['type'] == 'raw':
671 src = os.path.join(root_dir, thisbuild['output'])
672 src = os.path.normpath(src)
674 # Make sure it's not debuggable...
675 if common.isApkDebuggable(src, config):
676 raise BuildException("APK is debuggable")
678 # By way of a sanity check, make sure the version and version
679 # code in our new apk match what we expect...
680 logging.info("Checking " + src)
681 if not os.path.exists(src):
682 raise BuildException("Unsigned apk is not at expected location of " + src)
684 p = SilentPopen([os.path.join(config['sdk_path'],
685 'build-tools', config['build_tools'], 'aapt'),
686 'dump', 'badging', src])
692 for line in p.stdout.splitlines():
693 if line.startswith("package:"):
694 pat = re.compile(".*name='([a-zA-Z0-9._]*)'.*")
698 pat = re.compile(".*versionCode='([0-9]*)'.*")
702 pat = re.compile(".*versionName='([^']*)'.*")
706 elif line.startswith("native-code:"):
707 nativecode = line[12:]
709 if thisbuild.get('buildjni') is not None:
710 if nativecode is None or "'" not in nativecode:
711 raise BuildException("Native code should have been built but none was packaged")
712 if thisbuild['novcheck']:
713 vercode = thisbuild['vercode']
714 version = thisbuild['version']
715 if not version or not vercode:
716 raise BuildException("Could not find version information in build in output")
718 raise BuildException("Could not find package ID in output")
719 if foundid != app['id']:
720 raise BuildException("Wrong package ID - build " + foundid + " but expected " + app['id'])
722 # Some apps (e.g. Timeriffic) have had the bonkers idea of
723 # including the entire changelog in the version number. Remove
724 # it so we can compare. (TODO: might be better to remove it
725 # before we compile, in fact)
726 index = version.find(" //")
728 version = version[:index]
730 if (version != thisbuild['version'] or
731 vercode != thisbuild['vercode']):
732 raise BuildException(("Unexpected version/version code in output;"
733 " APK: '%s' / '%s', "
734 " Expected: '%s' / '%s'")
735 % (version, str(vercode), thisbuild['version'], str(thisbuild['vercode']))
738 # Copy the unsigned apk to our destination directory for further
739 # processing (by publish.py)...
740 dest = os.path.join(output_dir, common.getapkname(app,thisbuild))
741 shutil.copyfile(src, dest)
743 # Move the source tarball into the output directory...
744 if output_dir != tmp_dir and not options.notarball:
745 shutil.move(os.path.join(tmp_dir, tarname),
746 os.path.join(output_dir, tarname))
749 def trybuild(app, thisbuild, build_dir, output_dir, also_check_dir, srclib_dir, extlib_dir,
750 tmp_dir, repo_dir, vcs, test, server, force, onserver):
752 Build a particular version of an application, if it needs building.
754 :param output_dir: The directory where the build output will go. Usually
755 this is the 'unsigned' directory.
756 :param repo_dir: The repo directory - used for checking if the build is
758 :paaram also_check_dir: An additional location for checking if the build
759 is necessary (usually the archive repo)
760 :param test: True if building in test mode, in which case the build will
761 always happen, even if the output already exists. In test mode, the
762 output directory should be a temporary location, not any of the real
765 :returns: True if the build was done, False if it wasn't necessary.
768 dest_apk = common.getapkname(app, thisbuild)
770 dest = os.path.join(output_dir, dest_apk)
771 dest_repo = os.path.join(repo_dir, dest_apk)
774 if os.path.exists(dest) or os.path.exists(dest_repo):
778 dest_also = os.path.join(also_check_dir, dest_apk)
779 if os.path.exists(dest_also):
782 if 'disable' in thisbuild:
785 logging.info("Building version " + thisbuild['version'] + ' of ' + app['id'])
788 # When using server mode, still keep a local cache of the repo, by
789 # grabbing the source now.
790 vcs.gotorevision(thisbuild['commit'])
792 build_server(app, thisbuild, vcs, build_dir, output_dir, force)
794 build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver)
798 def parse_commandline():
799 """Parse the command line. Returns options, args."""
801 parser = OptionParser(usage="Usage: %prog [options] [APPID[:VERCODE] [APPID[:VERCODE] ...]]")
802 parser.add_option("-v", "--verbose", action="store_true", default=False,
803 help="Spew out even more information than normal")
804 parser.add_option("-q", "--quiet", action="store_true", default=False,
805 help="Restrict output to warnings and errors")
806 parser.add_option("-l", "--latest", action="store_true", default=False,
807 help="Build only the latest version of each package")
808 parser.add_option("-s", "--stop", action="store_true", default=False,
809 help="Make the build stop on exceptions")
810 parser.add_option("-t", "--test", action="store_true", default=False,
811 help="Test mode - put output in the tmp directory only, and always build, even if the output already exists.")
812 parser.add_option("--server", action="store_true", default=False,
813 help="Use build server")
814 parser.add_option("--resetserver", action="store_true", default=False,
815 help="Reset and create a brand new build server, even if the existing one appears to be ok.")
816 parser.add_option("--on-server", dest="onserver", action="store_true", default=False,
817 help="Specify that we're running on the build server")
818 parser.add_option("--skip-scan", dest="skipscan", action="store_true", default=False,
819 help="Skip scanning the source code for binaries and other problems")
820 parser.add_option("--no-tarball", dest="notarball", action="store_true", default=False,
821 help="Don't create a source tarball, useful when testing a build")
822 parser.add_option("-f", "--force", action="store_true", default=False,
823 help="Force build of disabled apps, and carries on regardless of scan problems. Only allowed in test mode.")
824 parser.add_option("-a", "--all", action="store_true", default=False,
825 help="Build all applications available")
826 parser.add_option("-w", "--wiki", default=False, action="store_true",
827 help="Update the wiki")
828 options, args = parser.parse_args()
830 # Force --stop with --on-server to get correct exit code
834 if options.force and not options.test:
835 raise OptionError("Force is only allowed in test mode", "force")
844 global options, config
846 options, args = parse_commandline()
847 if not args and not options.all:
848 raise OptionError("If you really want to build all the apps, use --all", "all")
850 config = common.read_config(options)
852 if config['build_server_always']:
853 options.server = True
854 if options.resetserver and not options.server:
855 raise OptionError("Using --resetserver without --server makes no sense", "resetserver")
858 if not os.path.isdir(log_dir):
859 logging.info("Creating log directory")
863 if not os.path.isdir(tmp_dir):
864 logging.info("Creating temporary directory")
870 output_dir = 'unsigned'
871 if not os.path.isdir(output_dir):
872 logging.info("Creating output directory")
873 os.makedirs(output_dir)
875 if config['archive_older'] != 0:
876 also_check_dir = 'archive'
878 also_check_dir = None
883 if not os.path.isdir(build_dir):
884 logging.info("Creating build directory")
885 os.makedirs(build_dir)
886 srclib_dir = os.path.join(build_dir, 'srclib')
887 extlib_dir = os.path.join(build_dir, 'extlib')
890 allapps = metadata.read_metadata(xref=not options.onserver)
892 apps = common.read_app_args(args, allapps, True)
893 apps = [app for app in apps if (options.force or not app['Disabled']) and
894 len(app['Repo Type']) > 0 and len(app['builds']) > 0]
897 raise Exception("No apps to process.")
901 for build in reversed(app['builds']):
902 if 'disable' in build:
904 app['builds'] = [ build ]
909 site = mwclient.Site((config['wiki_protocol'], config['wiki_server']),
910 path=config['wiki_path'])
911 site.login(config['wiki_user'], config['wiki_password'])
913 # Build applications...
920 for thisbuild in app['builds']:
924 # For the first build of a particular app, we need to set up
925 # the source repo. We can reuse it on subsequent builds, if
928 if app['Repo Type'] == 'srclib':
929 build_dir = os.path.join('build', 'srclib', app['Repo'])
931 build_dir = os.path.join('build', app['id'])
933 # Set up vcs interface and make sure we have the latest code...
934 logging.debug("Getting {0} vcs interface for {1}".format(
935 app['Repo Type'], app['Repo']))
936 vcs = common.getvcs(app['Repo Type'], app['Repo'], build_dir)
940 logging.debug("Checking " + thisbuild['version'])
941 if trybuild(app, thisbuild, build_dir, output_dir, also_check_dir,
942 srclib_dir, extlib_dir, tmp_dir, repo_dir, vcs, options.test,
943 options.server, options.force, options.onserver):
944 build_succeeded.append(app)
945 wikilog = "Build succeeded"
946 except BuildException as be:
947 logfile = open(os.path.join(log_dir, app['id'] + '.log'), 'a+')
948 logfile.write(str(be))
950 reason = str(be).split('\n',1)[0] if options.verbose else str(be)
951 print("Could not build app %s due to BuildException: %s" % (
955 failed_apps[app['id']] = be
956 wikilog = be.get_wikitext()
957 except VCSException as vcse:
958 print("VCS error while building app %s: %s" % (app['id'], vcse))
961 failed_apps[app['id']] = vcse
963 except Exception as e:
964 print("Could not build app %s due to unknown error: %s" % (app['id'], traceback.format_exc()))
967 failed_apps[app['id']] = e
970 if options.wiki and wikilog:
972 newpage = site.Pages[app['id'] + '/lastbuild']
973 txt = "Build completed at " + time.strftime("%Y-%m-%d %H:%M:%SZ", time.gmtime()) + "\n\n" + wikilog
974 newpage.save(txt, summary='Build log')
976 logging.info("Error while attempting to publish build log")
978 for app in build_succeeded:
979 logging.info("success: %s" % (app['id']))
981 if not options.verbose:
982 for fa in failed_apps:
983 logging.info("Build for app %s failed:\n%s" % (fa, failed_apps[fa]))
985 logging.info("Finished.")
986 if len(build_succeeded) > 0:
987 logging.info(str(len(build_succeeded)) + ' builds succeeded')
988 if len(failed_apps) > 0:
989 logging.info(str(len(failed_apps)) + ' builds failed')
993 if __name__ == "__main__":