3 # build.py - part of the FDroid server tools
4 # Copyright (C) 2010-2014, Ciaran Gultnieks, ciaran@ciarang.com
5 # Copyright (C) 2013-2014 Daniel Martà <mvdan@mvdan.cc>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
32 from configparser import ConfigParser
33 from argparse import ArgumentParser
38 from . import metadata
40 from .common import FDroidPopen, SdkToolsPopen
41 from .exception import FDroidException, BuildException, VCSException
49 def get_vm_provider():
50 """Determine vm provider based on .vagrant directory content
52 if os.path.exists(os.path.join('builder', '.vagrant', 'machines',
53 'default', 'libvirt')):
58 def get_builder_vm_id(provider):
59 vd = os.path.join('builder', '.vagrant')
61 # Vagrant 1.2 (and maybe 1.1?) it's a directory tree...
62 with open(os.path.join(vd, 'machines', 'default',
63 provider, 'id')) as vf:
67 # Vagrant 1.0 - it's a json file...
68 with open(os.path.join('builder', '.vagrant')) as vf:
70 return v['active']['default']
73 def got_valid_builder_vm(provider):
74 """Returns True if we have a valid-looking builder vm
76 if not os.path.exists(os.path.join('builder', 'Vagrantfile')):
78 vd = os.path.join('builder', '.vagrant')
79 if not os.path.exists(vd):
81 if not os.path.isdir(vd):
82 # Vagrant 1.0 - if the directory is there, it's valid...
84 # Vagrant 1.2 - the directory can exist, but the id can be missing...
85 if not os.path.exists(os.path.join(vd, 'machines', 'default',
91 def vagrant(params, cwd=None, printout=False):
92 """Run a vagrant command.
94 :param: list of parameters to pass to vagrant
95 :cwd: directory to run in, or None for current directory
96 :returns: (ret, out) where ret is the return code, and out
97 is the stdout (and stderr) from vagrant
99 p = FDroidPopen(['vagrant'] + params, cwd=cwd)
100 return (p.returncode, p.output)
103 def get_vagrant_sshinfo():
104 """Get ssh connection info for a vagrant VM
106 :returns: A dictionary containing 'hostname', 'port', 'user'
109 if subprocess.call('vagrant ssh-config >sshconfig',
110 cwd='builder', shell=True) != 0:
111 raise BuildException("Error getting ssh config")
112 vagranthost = 'default' # Host in ssh config file
113 sshconfig = paramiko.SSHConfig()
114 sshf = open(os.path.join('builder', 'sshconfig'), 'r')
115 sshconfig.parse(sshf)
117 sshconfig = sshconfig.lookup(vagranthost)
118 idfile = sshconfig['identityfile']
119 if isinstance(idfile, list):
121 elif idfile.startswith('"') and idfile.endswith('"'):
122 idfile = idfile[1:-1]
123 return {'hostname': sshconfig['hostname'],
124 'port': int(sshconfig['port']),
125 'user': sshconfig['user'],
129 def vm_snapshot_list(provider):
130 if provider is 'virtualbox':
131 p = FDroidPopen(['VBoxManage', 'snapshot',
132 get_builder_vm_id(provider), 'list',
133 '--details'], cwd='builder')
134 elif provider is 'libvirt':
135 p = FDroidPopen(['virsh', '-c', 'qemu:///system', 'snapshot-list',
136 get_builder_vm_id(provider)])
140 def vm_snapshot_clean_available(provider):
141 return 'fdroidclean' in vm_snapshot_list(provider)
144 def vm_snapshot_restore(provider):
145 """Does a rollback of the build vm.
147 if provider is 'virtualbox':
148 p = FDroidPopen(['VBoxManage', 'snapshot',
149 get_builder_vm_id(provider), 'restore',
150 'fdroidclean'], cwd='builder')
151 elif provider is 'libvirt':
152 p = FDroidPopen(['virsh', '-c', 'qemu:///system', 'snapshot-revert',
153 get_builder_vm_id(provider), 'fdroidclean'])
154 return p.returncode == 0
157 def vm_snapshot_create(provider):
158 if provider is 'virtualbox':
159 p = FDroidPopen(['VBoxManage', 'snapshot',
160 get_builder_vm_id(provider),
161 'take', 'fdroidclean'], cwd='builder')
162 elif provider is 'libvirt':
163 p = FDroidPopen(['virsh', '-c', 'qemu:///system', 'snapshot-create-as',
164 get_builder_vm_id(provider), 'fdroidclean'])
165 return p.returncode != 0
168 def get_clean_vm(reset=False):
169 """Get a clean VM ready to do a buildserver build.
171 This might involve creating and starting a new virtual machine from
172 scratch, or it might be as simple (unless overridden by the reset
173 parameter) as re-using a snapshot created previously.
175 A BuildException will be raised if anything goes wrong.
177 :reset: True to force creating from scratch.
178 :returns: A dictionary containing 'hostname', 'port', 'user'
181 provider = get_vm_provider()
183 # Reset existing builder machine to a clean state if possible.
186 logging.info("Checking for valid existing build server")
188 if got_valid_builder_vm(provider):
189 logging.info("...VM is present (%s)" % provider)
190 if vm_snapshot_clean_available(provider):
191 logging.info("...snapshot exists - resetting build server to "
193 retcode, output = vagrant(['status'], cwd='builder')
195 if 'running' in output:
196 logging.info("...suspending")
197 vagrant(['suspend'], cwd='builder')
198 logging.info("...waiting a sec...")
201 if vm_snapshot_restore(provider):
202 logging.info("...reset to snapshot - server is valid")
203 retcode, output = vagrant(['up'], cwd='builder')
205 raise BuildException("Failed to start build server")
206 logging.info("...waiting a sec...")
208 sshinfo = get_vagrant_sshinfo()
211 logging.info("...failed to reset to snapshot")
213 logging.info("...snapshot doesn't exist - "
214 "VBoxManage snapshot list:\n" +
215 vm_snapshot_list(provider))
217 # If we can't use the existing machine for any reason, make a
218 # new one from scratch.
220 if os.path.exists('builder'):
221 logging.info("Removing broken/incomplete/unwanted build server")
222 vagrant(['destroy', '-f'], cwd='builder')
223 shutil.rmtree('builder')
226 p = subprocess.Popen(['vagrant', '--version'],
227 universal_newlines=True,
228 stdout=subprocess.PIPE)
229 vver = p.communicate()[0].strip().split(' ')[1]
230 if vver.split('.')[0] != '1' or int(vver.split('.')[1]) < 4:
231 raise BuildException("Unsupported vagrant version {0}".format(vver))
233 with open(os.path.join('builder', 'Vagrantfile'), 'w') as vf:
234 vf.write('Vagrant.configure("2") do |config|\n')
235 vf.write(' config.vm.box = "buildserver"\n')
236 vf.write(' config.vm.synced_folder ".", "/vagrant", disabled: true\n')
239 logging.info("Starting new build server")
240 retcode, _ = vagrant(['up'], cwd='builder')
242 raise BuildException("Failed to start build server")
244 # Open SSH connection to make sure it's working and ready...
245 logging.info("Connecting to virtual machine...")
246 sshinfo = get_vagrant_sshinfo()
247 sshs = paramiko.SSHClient()
248 sshs.set_missing_host_key_policy(paramiko.AutoAddPolicy())
249 sshs.connect(sshinfo['hostname'], username=sshinfo['user'],
250 port=sshinfo['port'], timeout=300,
252 key_filename=sshinfo['idfile'])
255 logging.info("Saving clean state of new build server")
256 retcode, _ = vagrant(['suspend'], cwd='builder')
258 raise BuildException("Failed to suspend build server")
259 logging.info("...waiting a sec...")
261 if vm_snapshot_create(provider):
262 raise BuildException("Failed to take snapshot")
263 logging.info("...waiting a sec...")
265 logging.info("Restarting new build server")
266 retcode, _ = vagrant(['up'], cwd='builder')
268 raise BuildException("Failed to start build server")
269 logging.info("...waiting a sec...")
271 # Make sure it worked...
272 if not vm_snapshot_clean_available(provider):
273 raise BuildException("Failed to take snapshot.")
279 """Release the VM previously started with get_clean_vm().
281 This should always be called.
283 logging.info("Suspending build server")
284 subprocess.call(['vagrant', 'suspend'], cwd='builder')
287 # Note that 'force' here also implies test mode.
288 def build_server(app, build, vcs, build_dir, output_dir, log_dir, force):
289 """Do a build on the builder vm.
291 :param app: app metadata dict
293 :param vcs: version control system controller object
294 :param build_dir: local source-code checkout of app
295 :param output_dir: target folder for the build result
304 raise BuildException("Paramiko is required to use the buildserver")
306 logging.getLogger("paramiko").setLevel(logging.INFO)
308 logging.getLogger("paramiko").setLevel(logging.WARN)
310 sshinfo = get_clean_vm()
313 if not buildserverid:
314 buildserverid = subprocess.check_output(['vagrant', 'ssh', '-c',
315 'cat /home/vagrant/buildserverid'],
316 cwd='builder').rstrip()
318 # Open SSH connection...
319 logging.info("Connecting to virtual machine...")
320 sshs = paramiko.SSHClient()
321 sshs.set_missing_host_key_policy(paramiko.AutoAddPolicy())
322 sshs.connect(sshinfo['hostname'], username=sshinfo['user'],
323 port=sshinfo['port'], timeout=300,
324 look_for_keys=False, key_filename=sshinfo['idfile'])
326 homedir = '/home/' + sshinfo['user']
328 # Get an SFTP connection...
329 ftp = sshs.open_sftp()
330 ftp.get_channel().settimeout(60)
332 # Put all the necessary files in place...
335 # Helper to copy the contents of a directory to the server...
337 root = os.path.dirname(path)
338 main = os.path.basename(path)
340 for r, d, f in os.walk(path):
341 rr = os.path.relpath(r, root)
346 lfile = os.path.join(root, rr, ff)
347 if not os.path.islink(lfile):
349 ftp.chmod(ff, os.stat(lfile).st_mode)
350 for i in range(len(rr.split('/'))):
354 logging.info("Preparing server for build...")
355 serverpath = os.path.abspath(os.path.dirname(__file__))
356 ftp.mkdir('fdroidserver')
357 ftp.chdir('fdroidserver')
358 ftp.put(os.path.join(serverpath, '..', 'fdroid'), 'fdroid')
359 ftp.chmod('fdroid', 0o755)
360 send_dir(os.path.join(serverpath))
363 ftp.put(os.path.join(serverpath, '..', 'buildserver',
364 'config.buildserver.py'), 'config.py')
365 ftp.chmod('config.py', 0o600)
367 # Copy over the ID (head commit hash) of the fdroidserver in use...
368 subprocess.call('git rev-parse HEAD >' +
369 os.path.join(os.getcwd(), 'tmp', 'fdroidserverid'),
370 shell=True, cwd=serverpath)
371 ftp.put('tmp/fdroidserverid', 'fdroidserverid')
373 # Copy the metadata - just the file for this app...
374 ftp.mkdir('metadata')
376 ftp.chdir('metadata')
377 ftp.put(os.path.join('metadata', app.id + '.txt'),
379 # And patches if there are any...
380 if os.path.exists(os.path.join('metadata', app.id)):
381 send_dir(os.path.join('metadata', app.id))
384 # Create the build directory...
389 # Copy any extlibs that are required...
391 ftp.chdir(homedir + '/build/extlib')
392 for lib in build.extlibs:
394 libsrc = os.path.join('build/extlib', lib)
395 if not os.path.exists(libsrc):
396 raise BuildException("Missing extlib {0}".format(libsrc))
399 if d not in ftp.listdir():
402 ftp.put(libsrc, lp[-1])
405 # Copy any srclibs that are required...
408 for lib in build.srclibs:
410 common.getsrclib(lib, 'build/srclib', basepath=True, prepare=False))
412 # If one was used for the main source, add that too.
413 basesrclib = vcs.getsrclib()
415 srclibpaths.append(basesrclib)
416 for name, number, lib in srclibpaths:
417 logging.info("Sending srclib '%s'" % lib)
418 ftp.chdir(homedir + '/build/srclib')
419 if not os.path.exists(lib):
420 raise BuildException("Missing srclib directory '" + lib + "'")
421 fv = '.fdroidvcs-' + name
422 ftp.put(os.path.join('build/srclib', fv), fv)
424 # Copy the metadata file too...
425 ftp.chdir(homedir + '/srclibs')
426 ftp.put(os.path.join('srclibs', name + '.txt'),
428 # Copy the main app source code
429 # (no need if it's a srclib)
430 if (not basesrclib) and os.path.exists(build_dir):
431 ftp.chdir(homedir + '/build')
432 fv = '.fdroidvcs-' + app.id
433 ftp.put(os.path.join('build', fv), fv)
436 # Execute the build script...
437 logging.info("Starting build...")
438 chan = sshs.get_transport().open_session()
440 cmdline = os.path.join(homedir, 'fdroidserver', 'fdroid')
441 cmdline += ' build --on-server'
443 cmdline += ' --force --test'
445 cmdline += ' --verbose'
447 cmdline += ' --skip-scan'
448 cmdline += " %s:%s" % (app.id, build.versionCode)
449 chan.exec_command('bash --login -c "' + cmdline + '"')
452 output += get_android_tools_version_log(build.ndk_path()).encode()
453 while not chan.exit_status_ready():
454 while chan.recv_ready():
455 output += chan.recv(1024)
457 logging.info("...getting exit status")
458 returncode = chan.recv_exit_status()
460 get = chan.recv(1024)
465 raise BuildException(
466 "Build.py failed on server for {0}:{1}".format(
467 app.id, build.versionName), str(output, 'utf-8'))
470 toolsversion_log = common.get_toolsversion_logname(app, build)
472 ftp.chdir(os.path.join(homedir, log_dir))
473 ftp.get(toolsversion_log, os.path.join(log_dir, toolsversion_log))
474 logging.debug('retrieved %s', toolsversion_log)
475 except Exception as e:
476 logging.warn('could not get %s from builder vm: %s' % (toolsversion_log, e))
478 # Retrieve the built files...
479 logging.info("Retrieving build output...")
481 ftp.chdir(homedir + '/tmp')
483 ftp.chdir(homedir + '/unsigned')
484 apkfile = common.get_release_filename(app, build)
485 tarball = common.getsrcname(app, build)
487 ftp.get(apkfile, os.path.join(output_dir, apkfile))
488 if not options.notarball:
489 ftp.get(tarball, os.path.join(output_dir, tarball))
491 raise BuildException(
492 "Build failed for %s:%s - missing output files".format(
493 app.id, build.versionName), output)
498 # Suspend the build server.
502 def force_gradle_build_tools(build_dir, build_tools):
503 for root, dirs, files in os.walk(build_dir):
504 for filename in files:
505 if not filename.endswith('.gradle'):
507 path = os.path.join(root, filename)
508 if not os.path.isfile(path):
510 logging.debug("Forcing build-tools %s in %s" % (build_tools, path))
511 common.regsub_file(r"""(\s*)buildToolsVersion([\s=]+).*""",
512 r"""\1buildToolsVersion\2'%s'""" % build_tools,
516 def capitalize_intact(string):
517 """Like str.capitalize(), but leave the rest of the string intact without
518 switching it to lowercase."""
522 return string.upper()
523 return string[0].upper() + string[1:]
526 def has_native_code(apkobj):
527 """aapt checks if there are architecture folders under the lib/ folder
528 so we are simulating the same behaviour"""
529 arch_re = re.compile("^lib/(.*)/.*$")
530 arch = [file for file in apkobj.get_files() if arch_re.match(file)]
531 return False if not arch else True
534 def get_apk_metadata_aapt(apkfile):
535 """aapt function to extract versionCode, versionName, packageName and nativecode"""
541 p = SdkToolsPopen(['aapt', 'dump', 'badging', apkfile], output=False)
543 for line in p.output.splitlines():
544 if line.startswith("package:"):
545 pat = re.compile(".*name='([a-zA-Z0-9._]*)'.*")
549 pat = re.compile(".*versionCode='([0-9]*)'.*")
553 pat = re.compile(".*versionName='([^']*)'.*")
557 elif line.startswith("native-code:"):
558 nativecode = line[12:]
560 return vercode, version, foundid, nativecode
563 def get_apk_metadata_androguard(apkfile):
564 """androguard function to extract versionCode, versionName, packageName and nativecode"""
566 from androguard.core.bytecodes.apk import APK
567 apkobject = APK(apkfile)
569 raise BuildException("androguard library is not installed and aapt binary not found")
570 except FileNotFoundError:
571 raise BuildException("Could not open apk file for metadata analysis")
573 if not apkobject.is_valid_APK():
574 raise BuildException("Invalid APK provided")
576 foundid = apkobject.get_package()
577 vercode = apkobject.get_androidversion_code()
578 version = apkobject.get_androidversion_name()
579 nativecode = has_native_code(apkobject)
581 return vercode, version, foundid, nativecode
584 def get_metadata_from_apk(app, build, apkfile):
585 """get the required metadata from the built APK"""
587 if common.SdkToolsPopen(['aapt', 'version'], output=False):
588 vercode, version, foundid, nativecode = get_apk_metadata_aapt(apkfile)
590 vercode, version, foundid, nativecode = get_apk_metadata_androguard(apkfile)
592 # Ignore empty strings or any kind of space/newline chars that we don't
594 if nativecode is not None:
595 nativecode = nativecode.strip()
596 nativecode = None if not nativecode else nativecode
598 if build.buildjni and build.buildjni != ['no']:
599 if nativecode is None:
600 raise BuildException("Native code should have been built but none was packaged")
602 vercode = build.versionCode
603 version = build.versionName
604 if not version or not vercode:
605 raise BuildException("Could not find version information in build in output")
607 raise BuildException("Could not find package ID in output")
608 if foundid != app.id:
609 raise BuildException("Wrong package ID - build " + foundid + " but expected " + app.id)
611 return vercode, version
614 def build_local(app, build, vcs, build_dir, output_dir, log_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver, refresh):
615 """Do a build locally."""
616 ndk_path = build.ndk_path()
617 if build.ndk or (build.buildjni and build.buildjni != ['no']):
619 logging.critical("Android NDK version '%s' could not be found!" % build.ndk or 'r12b')
620 logging.critical("Configured versions:")
621 for k, v in config['ndk_paths'].items():
622 if k.endswith("_orig"):
624 logging.critical(" %s: %s" % (k, v))
625 raise FDroidException()
626 elif not os.path.isdir(ndk_path):
627 logging.critical("Android NDK '%s' is not a directory!" % ndk_path)
628 raise FDroidException()
630 common.set_FDroidPopen_env(build)
632 # create ..._toolsversion.log when running in builder vm
634 log_path = os.path.join(log_dir,
635 common.get_toolsversion_logname(app, build))
636 with open(log_path, 'w') as f:
637 f.write(get_android_tools_version_log(build.ndk_path()))
639 # Prepare the source code...
640 root_dir, srclibpaths = common.prepare_source(vcs, app, build,
641 build_dir, srclib_dir,
642 extlib_dir, onserver, refresh)
644 # We need to clean via the build tool in case the binary dirs are
645 # different from the default ones
648 bmethod = build.build_method()
649 if bmethod == 'maven':
650 logging.info("Cleaning Maven project...")
651 cmd = [config['mvn3'], 'clean', '-Dandroid.sdk.path=' + config['sdk_path']]
653 if '@' in build.maven:
654 maven_dir = os.path.join(root_dir, build.maven.split('@', 1)[1])
655 maven_dir = os.path.normpath(maven_dir)
659 p = FDroidPopen(cmd, cwd=maven_dir)
661 elif bmethod == 'gradle':
663 logging.info("Cleaning Gradle project...")
665 if build.preassemble:
666 gradletasks += build.preassemble
668 flavours = build.gradle
669 if flavours == ['yes']:
672 flavours_cmd = ''.join([capitalize_intact(flav) for flav in flavours])
674 gradletasks += ['assemble' + flavours_cmd + 'Release']
676 if config['force_build_tools']:
677 force_gradle_build_tools(build_dir, config['build_tools'])
678 for name, number, libpath in srclibpaths:
679 force_gradle_build_tools(libpath, config['build_tools'])
681 cmd = [config['gradle']]
682 if build.gradleprops:
683 cmd += ['-P' + kv for kv in build.gradleprops]
687 p = FDroidPopen(cmd, cwd=root_dir)
689 elif bmethod == 'kivy':
692 elif bmethod == 'ant':
693 logging.info("Cleaning Ant project...")
694 p = FDroidPopen(['ant', 'clean'], cwd=root_dir)
696 if p is not None and p.returncode != 0:
697 raise BuildException("Error cleaning %s:%s" %
698 (app.id, build.versionName), p.output)
700 for root, dirs, files in os.walk(build_dir):
705 shutil.rmtree(os.path.join(root, d))
710 os.remove(os.path.join(root, f))
712 if 'build.gradle' in files:
713 # Even when running clean, gradle stores task/artifact caches in
714 # .gradle/ as binary files. To avoid overcomplicating the scanner,
715 # manually delete them, just like `gradle clean` should have removed
717 del_dirs(['build', '.gradle'])
718 del_files(['gradlew', 'gradlew.bat'])
720 if 'pom.xml' in files:
723 if any(f in files for f in ['ant.properties', 'project.properties', 'build.xml']):
724 del_dirs(['bin', 'gen'])
731 raise BuildException("Refusing to skip source scan since scandelete is present")
733 # Scan before building...
734 logging.info("Scanning source for common problems...")
735 count = scanner.scan_source(build_dir, root_dir, build)
738 logging.warn('Scanner found %d problems' % count)
740 raise BuildException("Can't build due to %d errors while scanning" % count)
742 if not options.notarball:
743 # Build the source tarball right before we build the release...
744 logging.info("Creating source tarball...")
745 tarname = common.getsrcname(app, build)
746 tarball = tarfile.open(os.path.join(tmp_dir, tarname), "w:gz")
749 return any(f.endswith(s) for s in ['.svn', '.git', '.hg', '.bzr'])
750 tarball.add(build_dir, tarname, exclude=tarexc)
753 # Run a build command if one is required...
755 logging.info("Running 'build' commands in %s" % root_dir)
756 cmd = common.replace_config_vars(build.build, build)
758 # Substitute source library paths into commands...
759 for name, number, libpath in srclibpaths:
760 libpath = os.path.relpath(libpath, root_dir)
761 cmd = cmd.replace('$$' + name + '$$', libpath)
763 p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
765 if p.returncode != 0:
766 raise BuildException("Error running build command for %s:%s" %
767 (app.id, build.versionName), p.output)
769 # Build native stuff if required...
770 if build.buildjni and build.buildjni != ['no']:
771 logging.info("Building the native code")
772 jni_components = build.buildjni
774 if jni_components == ['yes']:
775 jni_components = ['']
776 cmd = [os.path.join(ndk_path, "ndk-build"), "-j1"]
777 for d in jni_components:
779 logging.info("Building native code in '%s'" % d)
781 logging.info("Building native code in the main project")
782 manifest = os.path.join(root_dir, d, 'AndroidManifest.xml')
783 if os.path.exists(manifest):
784 # Read and write the whole AM.xml to fix newlines and avoid
785 # the ndk r8c or later 'wordlist' errors. The outcome of this
786 # under gnu/linux is the same as when using tools like
787 # dos2unix, but the native python way is faster and will
788 # work in non-unix systems.
789 manifest_text = open(manifest, 'U').read()
790 open(manifest, 'w').write(manifest_text)
791 # In case the AM.xml read was big, free the memory
793 p = FDroidPopen(cmd, cwd=os.path.join(root_dir, d))
794 if p.returncode != 0:
795 raise BuildException("NDK build failed for %s:%s" % (app.id, build.versionName), p.output)
798 # Build the release...
799 if bmethod == 'maven':
800 logging.info("Building Maven project...")
802 if '@' in build.maven:
803 maven_dir = os.path.join(root_dir, build.maven.split('@', 1)[1])
807 mvncmd = [config['mvn3'], '-Dandroid.sdk.path=' + config['sdk_path'],
808 '-Dmaven.jar.sign.skip=true', '-Dmaven.test.skip=true',
809 '-Dandroid.sign.debug=false', '-Dandroid.release=true',
812 target = build.target.split('-')[1]
813 common.regsub_file(r'<platform>[0-9]*</platform>',
814 r'<platform>%s</platform>' % target,
815 os.path.join(root_dir, 'pom.xml'))
816 if '@' in build.maven:
817 common.regsub_file(r'<platform>[0-9]*</platform>',
818 r'<platform>%s</platform>' % target,
819 os.path.join(maven_dir, 'pom.xml'))
821 p = FDroidPopen(mvncmd, cwd=maven_dir)
823 bindir = os.path.join(root_dir, 'target')
825 elif bmethod == 'kivy':
826 logging.info("Building Kivy project...")
828 spec = os.path.join(root_dir, 'buildozer.spec')
829 if not os.path.exists(spec):
830 raise BuildException("Expected to find buildozer-compatible spec at {0}"
833 defaults = {'orientation': 'landscape', 'icon': '',
834 'permissions': '', 'android.api': "18"}
835 bconfig = ConfigParser(defaults, allow_no_value=True)
838 distdir = os.path.join('python-for-android', 'dist', 'fdroid')
839 if os.path.exists(distdir):
840 shutil.rmtree(distdir)
842 modules = bconfig.get('app', 'requirements').split(',')
844 cmd = 'ANDROIDSDK=' + config['sdk_path']
845 cmd += ' ANDROIDNDK=' + ndk_path
846 cmd += ' ANDROIDNDKVER=' + build.ndk
847 cmd += ' ANDROIDAPI=' + str(bconfig.get('app', 'android.api'))
848 cmd += ' VIRTUALENV=virtualenv'
849 cmd += ' ./distribute.sh'
850 cmd += ' -m ' + "'" + ' '.join(modules) + "'"
852 p = subprocess.Popen(cmd, cwd='python-for-android', shell=True)
853 if p.returncode != 0:
854 raise BuildException("Distribute build failed")
856 cid = bconfig.get('app', 'package.domain') + '.' + bconfig.get('app', 'package.name')
858 raise BuildException("Package ID mismatch between metadata and spec")
860 orientation = bconfig.get('app', 'orientation', 'landscape')
861 if orientation == 'all':
862 orientation = 'sensor'
866 '--name', bconfig.get('app', 'title'),
868 '--version', bconfig.get('app', 'version'),
869 '--orientation', orientation
872 perms = bconfig.get('app', 'permissions')
873 for perm in perms.split(','):
874 cmd.extend(['--permission', perm])
876 if config.get('app', 'fullscreen') == 0:
877 cmd.append('--window')
879 icon = bconfig.get('app', 'icon.filename')
881 cmd.extend(['--icon', os.path.join(root_dir, icon)])
883 cmd.append('release')
884 p = FDroidPopen(cmd, cwd=distdir)
886 elif bmethod == 'gradle':
887 logging.info("Building Gradle project...")
889 cmd = [config['gradle']]
890 if build.gradleprops:
891 cmd += ['-P' + kv for kv in build.gradleprops]
895 p = FDroidPopen(cmd, cwd=root_dir)
897 elif bmethod == 'ant':
898 logging.info("Building Ant project...")
900 if build.antcommands:
901 cmd += build.antcommands
904 p = FDroidPopen(cmd, cwd=root_dir)
906 bindir = os.path.join(root_dir, 'bin')
908 if p is not None and p.returncode != 0:
909 raise BuildException("Build failed for %s:%s" % (app.id, build.versionName), p.output)
910 logging.info("Successfully built version " + build.versionName + ' of ' + app.id)
912 omethod = build.output_method()
913 if omethod == 'maven':
914 stdout_apk = '\n'.join([
915 line for line in p.output.splitlines() if any(
916 a in line for a in ('.apk', '.ap_', '.jar'))])
917 m = re.match(r".*^\[INFO\] .*apkbuilder.*/([^/]*)\.apk",
918 stdout_apk, re.S | re.M)
920 m = re.match(r".*^\[INFO\] Creating additional unsigned apk file .*/([^/]+)\.apk[^l]",
921 stdout_apk, re.S | re.M)
923 m = re.match(r'.*^\[INFO\] [^$]*aapt \[package,[^$]*' + bindir + r'/([^/]+)\.ap[_k][,\]]',
924 stdout_apk, re.S | re.M)
927 m = re.match(r".*^\[INFO\] Building jar: .*/" + bindir + r"/(.+)\.jar",
928 stdout_apk, re.S | re.M)
930 raise BuildException('Failed to find output')
932 src = os.path.join(bindir, src) + '.apk'
933 elif omethod == 'kivy':
934 src = os.path.join('python-for-android', 'dist', 'default', 'bin',
935 '{0}-{1}-release.apk'.format(
936 bconfig.get('app', 'title'),
937 bconfig.get('app', 'version')))
938 elif omethod == 'gradle':
941 os.path.join(root_dir, 'build', 'outputs', 'apk'),
942 os.path.join(root_dir, 'build', 'apk'),
944 for apkglob in ['*-release-unsigned.apk', '*-unsigned.apk', '*.apk']:
945 apks = glob.glob(os.path.join(apks_dir, apkglob))
948 raise BuildException('More than one resulting apks found in %s' % apks_dir,
957 raise BuildException('Failed to find any output apks')
959 elif omethod == 'ant':
960 stdout_apk = '\n'.join([
961 line for line in p.output.splitlines() if '.apk' in line])
962 src = re.match(r".*^.*Creating (.+) for release.*$.*", stdout_apk,
963 re.S | re.M).group(1)
964 src = os.path.join(bindir, src)
965 elif omethod == 'raw':
966 output_path = common.replace_build_vars(build.output, build)
967 globpath = os.path.join(root_dir, output_path)
968 apks = glob.glob(globpath)
970 raise BuildException('Multiple apks match %s' % globpath, '\n'.join(apks))
972 raise BuildException('No apks match %s' % globpath)
973 src = os.path.normpath(apks[0])
975 # Make sure it's not debuggable...
976 if common.isApkAndDebuggable(src, config):
977 raise BuildException("APK is debuggable")
979 # By way of a sanity check, make sure the version and version
980 # code in our new apk match what we expect...
981 logging.debug("Checking " + src)
982 if not os.path.exists(src):
983 raise BuildException("Unsigned apk is not at expected location of " + src)
985 if common.get_file_extension(src) == 'apk':
986 vercode, version = get_metadata_from_apk(app, build, src)
987 if (version != build.versionName or vercode != build.versionCode):
988 raise BuildException(("Unexpected version/version code in output;"
989 " APK: '%s' / '%s', "
990 " Expected: '%s' / '%s'")
991 % (version, str(vercode), build.versionName,
992 str(build.versionCode)))
994 vercode = build.versionCode
995 version = build.versionName
997 # Add information for 'fdroid verify' to be able to reproduce the build
1000 metadir = os.path.join(tmp_dir, 'META-INF')
1001 if not os.path.exists(metadir):
1003 homedir = os.path.expanduser('~')
1004 for fn in ['buildserverid', 'fdroidserverid']:
1005 shutil.copyfile(os.path.join(homedir, fn),
1006 os.path.join(metadir, fn))
1007 subprocess.call(['jar', 'uf', os.path.abspath(src),
1008 'META-INF/' + fn], cwd=tmp_dir)
1010 # Copy the unsigned apk to our destination directory for further
1011 # processing (by publish.py)...
1012 dest = os.path.join(output_dir, common.get_release_filename(app, build))
1013 shutil.copyfile(src, dest)
1015 # Move the source tarball into the output directory...
1016 if output_dir != tmp_dir and not options.notarball:
1017 shutil.move(os.path.join(tmp_dir, tarname),
1018 os.path.join(output_dir, tarname))
1021 def trybuild(app, build, build_dir, output_dir, log_dir, also_check_dir,
1022 srclib_dir, extlib_dir, tmp_dir, repo_dir, vcs, test,
1023 server, force, onserver, refresh):
1025 Build a particular version of an application, if it needs building.
1027 :param output_dir: The directory where the build output will go. Usually
1028 this is the 'unsigned' directory.
1029 :param repo_dir: The repo directory - used for checking if the build is
1031 :paaram also_check_dir: An additional location for checking if the build
1032 is necessary (usually the archive repo)
1033 :param test: True if building in test mode, in which case the build will
1034 always happen, even if the output already exists. In test mode, the
1035 output directory should be a temporary location, not any of the real
1038 :returns: True if the build was done, False if it wasn't necessary.
1041 dest_file = common.get_release_filename(app, build)
1043 dest = os.path.join(output_dir, dest_file)
1044 dest_repo = os.path.join(repo_dir, dest_file)
1047 if os.path.exists(dest) or os.path.exists(dest_repo):
1051 dest_also = os.path.join(also_check_dir, dest_file)
1052 if os.path.exists(dest_also):
1055 if build.disable and not options.force:
1058 logging.info("Building version %s (%s) of %s" % (
1059 build.versionName, build.versionCode, app.id))
1062 # When using server mode, still keep a local cache of the repo, by
1063 # grabbing the source now.
1064 vcs.gotorevision(build.commit)
1066 build_server(app, build, vcs, build_dir, output_dir, log_dir, force)
1068 build_local(app, build, vcs, build_dir, output_dir, log_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver, refresh)
1072 def get_android_tools_versions(ndk_path=None):
1073 '''get a list of the versions of all installed Android SDK/NDK components'''
1076 sdk_path = config['sdk_path']
1077 if sdk_path[-1] != '/':
1081 ndk_release_txt = os.path.join(ndk_path, 'RELEASE.TXT')
1082 if os.path.isfile(ndk_release_txt):
1083 with open(ndk_release_txt, 'r') as fp:
1084 components.append((os.path.basename(ndk_path), fp.read()[:-1]))
1086 pattern = re.compile('^Pkg.Revision=(.+)', re.MULTILINE)
1087 for root, dirs, files in os.walk(sdk_path):
1088 if 'source.properties' in files:
1089 source_properties = os.path.join(root, 'source.properties')
1090 with open(source_properties, 'r') as fp:
1091 m = pattern.search(fp.read())
1093 components.append((root[len(sdk_path):], m.group(1)))
1098 def get_android_tools_version_log(ndk_path):
1099 '''get a list of the versions of all installed Android SDK/NDK components'''
1100 log = '== Installed Android Tools ==\n\n'
1101 components = get_android_tools_versions(ndk_path)
1102 for name, version in sorted(components):
1103 log += '* ' + name + ' (' + version + ')\n'
1108 def parse_commandline():
1109 """Parse the command line. Returns options, parser."""
1111 parser = ArgumentParser(usage="%(prog)s [options] [APPID[:VERCODE] [APPID[:VERCODE] ...]]")
1112 common.setup_global_opts(parser)
1113 parser.add_argument("appid", nargs='*', help="app-id with optional versionCode in the form APPID[:VERCODE]")
1114 parser.add_argument("-l", "--latest", action="store_true", default=False,
1115 help="Build only the latest version of each package")
1116 parser.add_argument("-s", "--stop", action="store_true", default=False,
1117 help="Make the build stop on exceptions")
1118 parser.add_argument("-t", "--test", action="store_true", default=False,
1119 help="Test mode - put output in the tmp directory only, and always build, even if the output already exists.")
1120 parser.add_argument("--server", action="store_true", default=False,
1121 help="Use build server")
1122 parser.add_argument("--resetserver", action="store_true", default=False,
1123 help="Reset and create a brand new build server, even if the existing one appears to be ok.")
1124 parser.add_argument("--on-server", dest="onserver", action="store_true", default=False,
1125 help="Specify that we're running on the build server")
1126 parser.add_argument("--skip-scan", dest="skipscan", action="store_true", default=False,
1127 help="Skip scanning the source code for binaries and other problems")
1128 parser.add_argument("--dscanner", action="store_true", default=False,
1129 help="Setup an emulator, install the apk on it and perform a drozer scan")
1130 parser.add_argument("--no-tarball", dest="notarball", action="store_true", default=False,
1131 help="Don't create a source tarball, useful when testing a build")
1132 parser.add_argument("--no-refresh", dest="refresh", action="store_false", default=True,
1133 help="Don't refresh the repository, useful when testing a build with no internet connection")
1134 parser.add_argument("-f", "--force", action="store_true", default=False,
1135 help="Force build of disabled apps, and carries on regardless of scan problems. Only allowed in test mode.")
1136 parser.add_argument("-a", "--all", action="store_true", default=False,
1137 help="Build all applications available")
1138 parser.add_argument("-w", "--wiki", default=False, action="store_true",
1139 help="Update the wiki")
1140 metadata.add_metadata_arguments(parser)
1141 options = parser.parse_args()
1142 metadata.warnings_action = options.W
1144 # Force --stop with --on-server to get correct exit code
1145 if options.onserver:
1148 if options.force and not options.test:
1149 parser.error("option %s: Force is only allowed in test mode" % "force")
1151 return options, parser
1156 buildserverid = None
1161 global options, config, buildserverid
1163 options, parser = parse_commandline()
1165 # The defaults for .fdroid.* metadata that is included in a git repo are
1166 # different than for the standard metadata/ layout because expectations
1167 # are different. In this case, the most common user will be the app
1168 # developer working on the latest update of the app on their own machine.
1169 local_metadata_files = common.get_local_metadata_files()
1170 if len(local_metadata_files) == 1: # there is local metadata in an app's source
1171 config = dict(common.default_config)
1172 # `fdroid build` should build only the latest version by default since
1173 # most of the time the user will be building the most recent update
1175 options.latest = True
1176 elif len(local_metadata_files) > 1:
1177 raise FDroidException("Only one local metadata file allowed! Found: "
1178 + " ".join(local_metadata_files))
1180 if not os.path.isdir('metadata') and len(local_metadata_files) == 0:
1181 raise FDroidException("No app metadata found, nothing to process!")
1182 if not options.appid and not options.all:
1183 parser.error("option %s: If you really want to build all the apps, use --all" % "all")
1185 config = common.read_config(options)
1187 if config['build_server_always']:
1188 options.server = True
1189 if options.resetserver and not options.server:
1190 parser.error("option %s: Using --resetserver without --server makes no sense" % "resetserver")
1193 if not os.path.isdir(log_dir):
1194 logging.info("Creating log directory")
1195 os.makedirs(log_dir)
1198 if not os.path.isdir(tmp_dir):
1199 logging.info("Creating temporary directory")
1200 os.makedirs(tmp_dir)
1203 output_dir = tmp_dir
1205 output_dir = 'unsigned'
1206 if not os.path.isdir(output_dir):
1207 logging.info("Creating output directory")
1208 os.makedirs(output_dir)
1210 if config['archive_older'] != 0:
1211 also_check_dir = 'archive'
1213 also_check_dir = None
1218 if not os.path.isdir(build_dir):
1219 logging.info("Creating build directory")
1220 os.makedirs(build_dir)
1221 srclib_dir = os.path.join(build_dir, 'srclib')
1222 extlib_dir = os.path.join(build_dir, 'extlib')
1224 # Read all app and srclib metadata
1225 pkgs = common.read_pkg_args(options.appid, True)
1226 allapps = metadata.read_metadata(not options.onserver, pkgs)
1227 apps = common.read_app_args(options.appid, allapps, True)
1229 for appid, app in list(apps.items()):
1230 if (app.Disabled and not options.force) or not app.RepoType or not app.builds:
1234 raise FDroidException("No apps to process.")
1237 for app in apps.values():
1238 for build in reversed(app.builds):
1239 if build.disable and not options.force:
1241 app.builds = [build]
1246 site = mwclient.Site((config['wiki_protocol'], config['wiki_server']),
1247 path=config['wiki_path'])
1248 site.login(config['wiki_user'], config['wiki_password'])
1250 # Build applications...
1252 build_succeeded = []
1253 for appid, app in apps.items():
1257 for build in app.builds:
1259 tools_version_log = ''
1260 if not options.onserver:
1261 tools_version_log = get_android_tools_version_log(build.ndk_path())
1264 # For the first build of a particular app, we need to set up
1265 # the source repo. We can reuse it on subsequent builds, if
1268 vcs, build_dir = common.setup_vcs(app)
1271 logging.debug("Checking " + build.versionName)
1272 if trybuild(app, build, build_dir, output_dir, log_dir,
1273 also_check_dir, srclib_dir, extlib_dir,
1274 tmp_dir, repo_dir, vcs, options.test,
1275 options.server, options.force,
1276 options.onserver, options.refresh):
1277 toolslog = os.path.join(log_dir,
1278 common.get_toolsversion_logname(app, build))
1279 if not options.onserver and os.path.exists(toolslog):
1280 with open(toolslog, 'r') as f:
1281 tools_version_log = ''.join(f.readlines())
1284 if app.Binaries is not None:
1285 # This is an app where we build from source, and
1286 # verify the apk contents against a developer's
1287 # binary. We get that binary now, and save it
1288 # alongside our built one in the 'unsigend'
1291 url = url.replace('%v', build.versionName)
1292 url = url.replace('%c', str(build.versionCode))
1293 logging.info("...retrieving " + url)
1294 of = common.get_release_filename(app, build) + '.binary'
1295 of = os.path.join(output_dir, of)
1297 net.download_file(url, local_filename=of)
1298 except requests.exceptions.HTTPError as e:
1299 raise FDroidException(
1300 'Downloading Binaries from %s failed. %s' % (url, e))
1302 # Now we check weather the build can be verified to
1303 # match the supplied binary or not. Should the
1304 # comparison fail, we mark this build as a failure
1305 # and remove everything from the unsigend folder.
1306 with tempfile.TemporaryDirectory() as tmpdir:
1308 common.get_release_filename(app, build)
1310 os.path.join(output_dir, unsigned_apk)
1312 common.verify_apks(of, unsigned_apk, tmpdir)
1314 logging.debug('removing %s', unsigned_apk)
1315 os.remove(unsigned_apk)
1316 logging.debug('removing %s', of)
1318 compare_result = compare_result.split('\n')
1319 line_count = len(compare_result)
1320 compare_result = compare_result[:299]
1321 if line_count > len(compare_result):
1323 line_count - len(compare_result)
1324 compare_result.append('%d more lines ...' %
1326 compare_result = '\n'.join(compare_result)
1327 raise FDroidException('compared built binary '
1328 'to supplied reference '
1329 'binary but failed',
1332 logging.info('compared built binary to '
1333 'supplied reference binary '
1336 build_succeeded.append(app)
1337 wikilog = "Build succeeded"
1339 except VCSException as vcse:
1340 reason = str(vcse).split('\n', 1)[0] if options.verbose else str(vcse)
1341 logging.error("VCS error while building app %s: %s" % (
1345 failed_apps[appid] = vcse
1347 except FDroidException as e:
1348 with open(os.path.join(log_dir, appid + '.log'), 'a+') as f:
1349 f.write('\n\n============================================================\n')
1350 f.write('versionCode: %s\nversionName: %s\ncommit: %s\n' %
1351 (build.versionCode, build.versionName, build.commit))
1352 f.write('Build completed at '
1353 + time.strftime("%Y-%m-%d %H:%M:%SZ", time.gmtime()) + '\n')
1354 f.write('\n' + tools_version_log + '\n')
1356 logging.error("Could not build app %s: %s" % (appid, e))
1359 failed_apps[appid] = e
1360 wikilog = e.get_wikitext()
1361 except Exception as e:
1362 logging.error("Could not build app %s due to unknown error: %s" % (
1363 appid, traceback.format_exc()))
1366 failed_apps[appid] = e
1369 if options.wiki and wikilog:
1371 # Write a page with the last build log for this version code
1372 lastbuildpage = appid + '/lastbuild_' + build.versionCode
1373 newpage = site.Pages[lastbuildpage]
1374 with open(os.path.join('tmp', 'fdroidserverid')) as fp:
1375 fdroidserverid = fp.read().rstrip()
1376 txt = "* build completed at " + time.strftime("%Y-%m-%d %H:%M:%SZ", time.gmtime()) + '\n' \
1377 + '* fdroidserverid: [https://gitlab.com/fdroid/fdroidserver/commit/' \
1378 + fdroidserverid + ' ' + fdroidserverid + ']\n\n'
1379 if options.onserver:
1380 txt += '* buildserverid: [https://gitlab.com/fdroid/fdroidserver/commit/' \
1381 + buildserverid + ' ' + buildserverid + ']\n\n'
1382 txt += tools_version_log + '\n\n'
1383 txt += '== Build Log ==\n\n' + wikilog
1384 newpage.save(txt, summary='Build log')
1385 # Redirect from /lastbuild to the most recent build log
1386 newpage = site.Pages[appid + '/lastbuild']
1387 newpage.save('#REDIRECT [[' + lastbuildpage + ']]', summary='Update redirect')
1388 except Exception as e:
1389 logging.error("Error while attempting to publish build log: %s" % e)
1391 for app in build_succeeded:
1392 logging.info("success: %s" % (app.id))
1394 if not options.verbose:
1395 for fa in failed_apps:
1396 logging.info("Build for app %s failed:\n%s" % (fa, failed_apps[fa]))
1398 # perform a drozer scan of all successful builds
1399 if options.dscanner and build_succeeded:
1400 from .dscanner import DockerDriver
1402 docker = DockerDriver()
1405 for app in build_succeeded:
1407 logging.info("Need to sign the app before we can install it.")
1408 subprocess.call("fdroid publish {0}".format(app.id), shell=True)
1412 for f in os.listdir(repo_dir):
1413 if f.endswith('.apk') and f.startswith(app.id):
1414 apk_path = os.path.join(repo_dir, f)
1418 raise Exception("No signed APK found at path: {0}".format(apk_path))
1420 if not os.path.isdir(repo_dir):
1423 logging.info("Performing Drozer scan on {0}.".format(app))
1424 docker.perform_drozer_scan(apk_path, app.id, repo_dir)
1425 except Exception as e:
1426 logging.error(str(e))
1427 logging.error("An exception happened. Making sure to clean up")
1429 logging.info("Scan succeeded.")
1431 logging.info("Cleaning up after ourselves.")
1434 logging.info("Finished.")
1435 if len(build_succeeded) > 0:
1436 logging.info(str(len(build_succeeded)) + ' builds succeeded')
1437 if len(failed_apps) > 0:
1438 logging.info(str(len(failed_apps)) + ' builds failed')
1443 if __name__ == "__main__":