chiark / gitweb /
Merge branch 'some-compatibility-fixes' of https://gitlab.com/eighthave/fdroidserver
[fdroidserver.git] / fdroidserver / build.py
index 55b2b8d68147c7e1f7ef3ca486a16971f2fd6028..84af7f41c5b0497e422a36bf6aa7833771a59227 100644 (file)
@@ -21,6 +21,7 @@
 import sys
 import os
 import shutil
+import glob
 import subprocess
 import re
 import tarfile
@@ -34,7 +35,7 @@ import logging
 
 import common
 import metadata
-from common import BuildException, VCSException, FDroidPopen, SilentPopen
+from common import FDroidException, BuildException, VCSException, FDroidPopen, SdkToolsPopen
 
 try:
     import paramiko
@@ -47,7 +48,7 @@ def get_builder_vm_id():
     if os.path.isdir(vd):
         # Vagrant 1.2 (and maybe 1.1?) it's a directory tree...
         with open(os.path.join(vd, 'machines', 'default',
-                  'virtualbox', 'id')) as vf:
+                               'virtualbox', 'id')) as vf:
             id = vf.read()
         return id
     else:
@@ -70,7 +71,7 @@ def got_valid_builder_vm():
         return True
     # Vagrant 1.2 - the directory can exist, but the id can be missing...
     if not os.path.exists(os.path.join(vd, 'machines', 'default',
-                          'virtualbox', 'id')):
+                                       'virtualbox', 'id')):
         return False
     return True
 
@@ -84,7 +85,7 @@ def vagrant(params, cwd=None, printout=False):
                is the stdout (and stderr) from vagrant
     """
     p = FDroidPopen(['vagrant'] + params, cwd=cwd)
-    return (p.returncode, p.stdout)
+    return (p.returncode, p.output)
 
 
 def get_vagrant_sshinfo():
@@ -136,7 +137,7 @@ def get_clean_vm(reset=False):
             p = FDroidPopen(['VBoxManage', 'snapshot',
                              get_builder_vm_id(), 'list',
                              '--details'], cwd='builder')
-            if 'fdroidclean' in p.stdout:
+            if 'fdroidclean' in p.output:
                 logging.info("...snapshot exists - resetting build server to "
                              "clean state")
                 retcode, output = vagrant(['status'], cwd='builder')
@@ -163,7 +164,7 @@ def get_clean_vm(reset=False):
                     logging.info("...failed to reset to snapshot")
             else:
                 logging.info("...snapshot doesn't exist - "
-                             "VBoxManage snapshot list:\n" + p.stdout)
+                             "VBoxManage snapshot list:\n" + p.output)
 
     # If we can't use the existing machine for any reason, make a
     # new one from scratch.
@@ -174,7 +175,7 @@ def get_clean_vm(reset=False):
             shutil.rmtree('builder')
         os.mkdir('builder')
 
-        p = subprocess.Popen('vagrant --version', shell=True,
+        p = subprocess.Popen(['vagrant', '--version'],
                              stdout=subprocess.PIPE)
         vver = p.communicate()[0]
         if vver.startswith('Vagrant version 1.2'):
@@ -227,7 +228,7 @@ def get_clean_vm(reset=False):
         p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(),
                          'list', '--details'],
                         cwd='builder')
-        if 'fdroidclean' not in p.stdout:
+        if 'fdroidclean' not in p.output:
             raise BuildException("Failed to take snapshot.")
 
     return sshinfo
@@ -301,7 +302,7 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
         ftp.put(os.path.join(serverpath, 'common.py'), 'common.py')
         ftp.put(os.path.join(serverpath, 'metadata.py'), 'metadata.py')
         ftp.put(os.path.join(serverpath, '..', 'buildserver',
-                'config.buildserver.py'), 'config.py')
+                             'config.buildserver.py'), 'config.py')
         ftp.chmod('config.py', 0o600)
 
         # Copy over the ID (head commit hash) of the fdroidserver in use...
@@ -347,8 +348,7 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
         if thisbuild['srclibs']:
             for lib in thisbuild['srclibs']:
                 srclibpaths.append(
-                    common.getsrclib(lib, 'build/srclib', srclibpaths,
-                                     basepath=True, prepare=False))
+                    common.getsrclib(lib, 'build/srclib', basepath=True, prepare=False))
 
         # If one was used for the main source, add that too.
         basesrclib = vcs.getsrclib()
@@ -427,35 +427,64 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
 
 
 def adapt_gradle(build_dir):
+    filename = 'build.gradle'
     for root, dirs, files in os.walk(build_dir):
-        if 'build.gradle' in files:
-            path = os.path.join(root, 'build.gradle')
-            logging.info("Adapting build.gradle at %s" % path)
+        for filename in files:
+            if not filename.endswith('.gradle'):
+                continue
+            path = os.path.join(root, filename)
+            if not os.path.isfile(path):
+                continue
+            logging.debug("Adapting %s at %s" % (filename, path))
 
             FDroidPopen(['sed', '-i',
-                         r's@buildToolsVersion\([ =]*\)["\'][0-9\.]*["\']@buildToolsVersion\1"'
+                         r's@buildToolsVersion\([ =]\+\).*@buildToolsVersion\1"'
                          + config['build_tools'] + '"@g', path])
 
 
-def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver):
+def capitalize_intact(string):
+    """Like str.capitalize(), but leave the rest of the string intact without
+    switching it to lowercase."""
+    if len(string) == 0:
+        return string
+    if len(string) == 1:
+        return string.upper()
+    return string[0].upper() + string[1:]
+
+
+def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver, refresh):
     """Do a build locally."""
 
     if thisbuild['buildjni'] and thisbuild['buildjni'] != ['no']:
-        if not config['ndk_path']:
-            logging.critical("$ANDROID_NDK is not set!")
+        if not thisbuild['ndk_path']:
+            logging.critical("Android NDK version '%s' could not be found!" % thisbuild['ndk'])
+            logging.critical("Configured versions:")
+            for k, v in config['ndk_paths'].iteritems():
+                if k.endswith("_orig"):
+                    continue
+                logging.critical("  %s: %s" % (k, v))
             sys.exit(3)
-        elif not os.path.isdir(config['sdk_path']):
-            logging.critical("$ANDROID_NDK points to a non-existing directory!")
+        elif not os.path.isdir(thisbuild['ndk_path']):
+            logging.critical("Android NDK '%s' is not a directory!" % thisbuild['ndk_path'])
             sys.exit(3)
 
+    # Set up environment vars that depend on each build
+    for n in ['ANDROID_NDK', 'NDK', 'ANDROID_NDK_HOME']:
+        common.env[n] = thisbuild['ndk_path']
+
+    common.reset_env_path()
+    # Set up the current NDK to the PATH
+    common.add_to_env_path(thisbuild['ndk_path'])
+
     # Prepare the source code...
     root_dir, srclibpaths = common.prepare_source(vcs, app, thisbuild,
                                                   build_dir, srclib_dir,
-                                                  extlib_dir, onserver)
+                                                  extlib_dir, onserver, refresh)
 
     # We need to clean via the build tool in case the binary dirs are
     # different from the default ones
     p = None
+    gradletasks = []
     if thisbuild['type'] == 'maven':
         logging.info("Cleaning Maven project...")
         cmd = [config['mvn3'], 'clean', '-Dandroid.sdk.path=' + config['sdk_path']]
@@ -471,19 +500,31 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
     elif thisbuild['type'] == 'gradle':
 
         logging.info("Cleaning Gradle project...")
-        cmd = [config['gradle'], 'clean']
 
-        if '@' in thisbuild['gradle']:
-            gradle_dir = os.path.join(root_dir, thisbuild['gradle'].split('@', 1)[1])
-            gradle_dir = os.path.normpath(gradle_dir)
-        else:
-            gradle_dir = root_dir
+        if thisbuild['preassemble']:
+            gradletasks += thisbuild['preassemble']
+
+        flavours = thisbuild['gradle']
+        if flavours == ['yes']:
+            flavours = []
+
+        flavours_cmd = ''.join([capitalize_intact(f) for f in flavours])
+
+        gradletasks += ['assemble' + flavours_cmd + 'Release']
 
         adapt_gradle(build_dir)
         for name, number, libpath in srclibpaths:
             adapt_gradle(libpath)
 
-        p = FDroidPopen(cmd, cwd=gradle_dir)
+        cmd = [config['gradle']]
+        for task in gradletasks:
+            parts = task.split(':')
+            parts[-1] = 'clean' + capitalize_intact(parts[-1])
+            cmd += [':'.join(parts)]
+
+        cmd += ['clean']
+
+        p = FDroidPopen(cmd, cwd=root_dir)
 
     elif thisbuild['type'] == 'kivy':
         pass
@@ -494,25 +535,28 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
 
     if p is not None and p.returncode != 0:
         raise BuildException("Error cleaning %s:%s" %
-                             (app['id'], thisbuild['version']), p.stdout)
+                             (app['id'], thisbuild['version']), p.output)
 
-    logging.info("Getting rid of Gradle wrapper binaries...")
     for root, dirs, files in os.walk(build_dir):
         # Don't remove possibly necessary 'gradle' dirs if 'gradlew' is not there
         if 'gradlew' in files:
+            logging.debug("Getting rid of Gradle wrapper stuff in %s" % root)
             os.remove(os.path.join(root, 'gradlew'))
             if 'gradlew.bat' in files:
                 os.remove(os.path.join(root, 'gradlew.bat'))
             if 'gradle' in dirs:
                 shutil.rmtree(os.path.join(root, 'gradle'))
 
-    if not options.skipscan:
+    if options.skipscan:
+        if thisbuild['scandelete']:
+            raise BuildException("Refusing to skip source scan since scandelete is present")
+    else:
         # Scan before building...
         logging.info("Scanning source for common problems...")
         count = common.scan_source(build_dir, root_dir, thisbuild)
         if count > 0:
             if force:
-                logging.warn('Scanner found %d problems:' % count)
+                logging.warn('Scanner found %d problems' % count)
             else:
                 raise BuildException("Can't build due to %d errors while scanning" % count)
 
@@ -527,29 +571,10 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         tarball.add(build_dir, tarname, exclude=tarexc)
         tarball.close()
 
-    if onserver:
-        manifest = os.path.join(root_dir, 'AndroidManifest.xml')
-        if os.path.exists(manifest):
-            homedir = os.path.expanduser('~')
-            with open(os.path.join(homedir, 'buildserverid'), 'r') as f:
-                buildserverid = f.read()
-            with open(os.path.join(homedir, 'fdroidserverid'), 'r') as f:
-                fdroidserverid = f.read()
-            with open(manifest, 'r') as f:
-                manifestcontent = f.read()
-            manifestcontent = manifestcontent.replace('</manifest>',
-                                                      '<fdroid buildserverid="'
-                                                      + buildserverid + '"'
-                                                      + ' fdroidserverid="'
-                                                      + fdroidserverid + '"'
-                                                      + '/></manifest>')
-            with open(manifest, 'w') as f:
-                f.write(manifestcontent)
-
     # Run a build command if one is required...
     if thisbuild['build']:
         logging.info("Running 'build' commands in %s" % root_dir)
-        cmd = common.replace_config_vars(thisbuild['build'])
+        cmd = common.replace_config_vars(thisbuild['build'], thisbuild)
 
         # Substitute source library paths into commands...
         for name, number, libpath in srclibpaths:
@@ -560,7 +585,7 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
 
         if p.returncode != 0:
             raise BuildException("Error running build command for %s:%s" %
-                                 (app['id'], thisbuild['version']), p.stdout)
+                                 (app['id'], thisbuild['version']), p.output)
 
     # Build native stuff if required...
     if thisbuild['buildjni'] and thisbuild['buildjni'] != ['no']:
@@ -569,7 +594,7 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
 
         if jni_components == ['yes']:
             jni_components = ['']
-        cmd = [os.path.join(config['ndk_path'], "ndk-build"), "-j1"]
+        cmd = [os.path.join(thisbuild['ndk_path'], "ndk-build"), "-j1"]
         for d in jni_components:
             if d:
                 logging.info("Building native code in '%s'" % d)
@@ -588,7 +613,7 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
                 del manifest_text
             p = FDroidPopen(cmd, cwd=os.path.join(root_dir, d))
             if p.returncode != 0:
-                raise BuildException("NDK build failed for %s:%s" % (app['id'], thisbuild['version']), p.stdout)
+                raise BuildException("NDK build failed for %s:%s" % (app['id'], thisbuild['version']), p.output)
 
     p = None
     # Build the release...
@@ -642,14 +667,14 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         modules = bconfig.get('app', 'requirements').split(',')
 
         cmd = 'ANDROIDSDK=' + config['sdk_path']
-        cmd += ' ANDROIDNDK=' + config['ndk_path']
-        cmd += ' ANDROIDNDKVER=r9'
+        cmd += ' ANDROIDNDK=' + thisbuild['ndk_path']
+        cmd += ' ANDROIDNDKVER=' + thisbuild['ndk']
         cmd += ' ANDROIDAPI=' + str(bconfig.get('app', 'android.api'))
         cmd += ' VIRTUALENV=virtualenv'
         cmd += ' ./distribute.sh'
         cmd += ' -m ' + "'" + ' '.join(modules) + "'"
         cmd += ' -d fdroid'
-        p = FDroidPopen(cmd, cwd='python-for-android', shell=True)
+        p = subprocess.Popen(cmd, cwd='python-for-android', shell=True)
         if p.returncode != 0:
             raise BuildException("Distribute build failed")
 
@@ -685,39 +710,21 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
 
     elif thisbuild['type'] == 'gradle':
         logging.info("Building Gradle project...")
-        if '@' in thisbuild['gradle']:
-            flavours = thisbuild['gradle'].split('@')[0].split(',')
-            gradle_dir = thisbuild['gradle'].split('@')[1]
-            gradle_dir = os.path.join(root_dir, gradle_dir)
-        else:
-            flavours = thisbuild['gradle'].split(',')
-            gradle_dir = root_dir
-
-        if len(flavours) == 1 and flavours[0] in ['main', 'yes', '']:
-            flavours[0] = ''
-
-        commands = [config['gradle']]
-        if thisbuild['preassemble']:
-            commands += thisbuild['preassemble'].split()
-
-        flavours_cmd = ''.join(flavours)
-        if flavours_cmd:
-            flavours_cmd = flavours_cmd[0].upper() + flavours_cmd[1:]
-
-        commands += ['assemble' + flavours_cmd + 'Release']
 
         # Avoid having to use lintOptions.abortOnError false
-        # TODO: Do flavours or project names change this task name?
-        if LooseVersion('0.8') <= thisbuild['gradlepluginver'] < LooseVersion('0.11'):
-            commands += ['-x', 'lintVital' + flavours_cmd + 'Release']
+        if thisbuild['gradlepluginver'] >= LooseVersion('0.7'):
+            with open(os.path.join(root_dir, 'build.gradle'), "a") as f:
+                f.write("\nandroid { lintOptions { checkReleaseBuilds false } }\n")
+
+        commands = [config['gradle']] + gradletasks
 
-        p = FDroidPopen(commands, cwd=gradle_dir)
+        p = FDroidPopen(commands, cwd=root_dir)
 
     elif thisbuild['type'] == 'ant':
         logging.info("Building Ant project...")
         cmd = ['ant']
-        if thisbuild['antcommand']:
-            cmd += [thisbuild['antcommand']]
+        if thisbuild['antcommands']:
+            cmd += thisbuild['antcommands']
         else:
             cmd += ['release']
         p = FDroidPopen(cmd, cwd=root_dir)
@@ -725,12 +732,13 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         bindir = os.path.join(root_dir, 'bin')
 
     if p is not None and p.returncode != 0:
-        raise BuildException("Build failed for %s:%s" % (app['id'], thisbuild['version']), p.stdout)
+        raise BuildException("Build failed for %s:%s" % (app['id'], thisbuild['version']), p.output)
     logging.info("Successfully built version " + thisbuild['version'] + ' of ' + app['id'])
 
     if thisbuild['type'] == 'maven':
         stdout_apk = '\n'.join([
-            line for line in p.stdout.splitlines() if any(a in line for a in ('.apk', '.ap_'))])
+            line for line in p.output.splitlines() if any(
+                a in line for a in ('.apk', '.ap_', '.jar'))])
         m = re.match(r".*^\[INFO\] .*apkbuilder.*/([^/]*)\.apk",
                      stdout_apk, re.S | re.M)
         if not m:
@@ -739,6 +747,10 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         if not m:
             m = re.match(r'.*^\[INFO\] [^$]*aapt \[package,[^$]*' + bindir + r'/([^/]+)\.ap[_k][,\]]',
                          stdout_apk, re.S | re.M)
+
+        if not m:
+            m = re.match(r".*^\[INFO\] Building jar: .*/" + bindir + r"/(.+)\.jar",
+                         stdout_apk, re.S | re.M)
         if not m:
             raise BuildException('Failed to find output')
         src = m.group(1)
@@ -747,26 +759,22 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         src = 'python-for-android/dist/default/bin/{0}-{1}-release.apk'.format(
             bconfig.get('app', 'title'), bconfig.get('app', 'version'))
     elif thisbuild['type'] == 'gradle':
-        basename = app['id']
-        dd = build_dir
-        if thisbuild['subdir']:
-            dd = os.path.join(dd, thisbuild['subdir'])
-            basename = os.path.basename(thisbuild['subdir'])
-        if '@' in thisbuild['gradle']:
-            dd = os.path.join(dd, thisbuild['gradle'].split('@')[1])
-            basename = app['id']
-        if len(flavours) == 1 and flavours[0] == '':
-            name = '-'.join([basename, 'release', 'unsigned'])
-        else:
-            name = '-'.join([basename, '-'.join(flavours), 'release', 'unsigned'])
-        dd = os.path.normpath(dd)
+
         if thisbuild['gradlepluginver'] >= LooseVersion('0.11'):
-            src = os.path.join(dd, 'build', 'outputs', 'apk', name + '.apk')
+            apks_dir = os.path.join(root_dir, 'build', 'outputs', 'apk')
         else:
-            src = os.path.join(dd, 'build', 'apk', name + '.apk')
+            apks_dir = os.path.join(root_dir, 'build', 'apk')
+
+        apks = glob.glob(os.path.join(apks_dir, '*-release-unsigned.apk'))
+        if len(apks) > 1:
+            raise BuildException('More than one resulting apks found in %s' % apks_dir,
+                                 '\n'.join(apks))
+        if len(apks) < 1:
+            raise BuildException('Failed to find gradle output in %s' % apks_dir)
+        src = apks[0]
     elif thisbuild['type'] == 'ant':
         stdout_apk = '\n'.join([
-            line for line in p.stdout.splitlines() if '.apk' in line])
+            line for line in p.output.splitlines() if '.apk' in line])
         src = re.match(r".*^.*Creating (.+) for release.*$.*", stdout_apk,
                        re.S | re.M).group(1)
         src = os.path.join(bindir, src)
@@ -780,19 +788,17 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
 
     # By way of a sanity check, make sure the version and version
     # code in our new apk match what we expect...
-    logging.info("Checking " + src)
+    logging.debug("Checking " + src)
     if not os.path.exists(src):
         raise BuildException("Unsigned apk is not at expected location of " + src)
 
-    p = SilentPopen([os.path.join(config['sdk_path'], 'build-tools',
-                                  config['build_tools'], 'aapt'),
-                     'dump', 'badging', src])
+    p = SdkToolsPopen(['aapt', 'dump', 'badging', src], output=False)
 
     vercode = None
     version = None
     foundid = None
     nativecode = None
-    for line in p.stdout.splitlines():
+    for line in p.output.splitlines():
         if line.startswith("package:"):
             pat = re.compile(".*name='([a-zA-Z0-9._]*)'.*")
             m = pat.match(line)
@@ -809,8 +815,14 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         elif line.startswith("native-code:"):
             nativecode = line[12:]
 
-    if thisbuild['buildjni']:
-        if nativecode is None or "'" not in nativecode:
+    # Ignore empty strings or any kind of space/newline chars that we don't
+    # care about
+    if nativecode is not None:
+        nativecode = nativecode.strip()
+        nativecode = None if not nativecode else nativecode
+
+    if thisbuild['buildjni'] and thisbuild['buildjni'] != ['no']:
+        if nativecode is None:
             raise BuildException("Native code should have been built but none was packaged")
     if thisbuild['novcheck']:
         vercode = thisbuild['vercode']
@@ -839,6 +851,19 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
                                 str(thisbuild['vercode']))
                              )
 
+    # Add information for 'fdroid verify' to be able to reproduce the build
+    # environment.
+    if onserver:
+        metadir = os.path.join(tmp_dir, 'META-INF')
+        if not os.path.exists(metadir):
+            os.mkdir(metadir)
+        homedir = os.path.expanduser('~')
+        for fn in ['buildserverid', 'fdroidserverid']:
+            shutil.copyfile(os.path.join(homedir, fn),
+                            os.path.join(metadir, fn))
+            subprocess.call(['jar', 'uf', os.path.abspath(src),
+                             'META-INF/' + fn], cwd=tmp_dir)
+
     # Copy the unsigned apk to our destination directory for further
     # processing (by publish.py)...
     dest = os.path.join(output_dir, common.getapkname(app, thisbuild))
@@ -851,7 +876,7 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
 
 
 def trybuild(app, thisbuild, build_dir, output_dir, also_check_dir, srclib_dir, extlib_dir,
-             tmp_dir, repo_dir, vcs, test, server, force, onserver):
+             tmp_dir, repo_dir, vcs, test, server, force, onserver, refresh):
     """
     Build a particular version of an application, if it needs building.
 
@@ -883,10 +908,11 @@ def trybuild(app, thisbuild, build_dir, output_dir, also_check_dir, srclib_dir,
             if os.path.exists(dest_also):
                 return False
 
-    if thisbuild['disable']:
+    if thisbuild['disable'] and not options.force:
         return False
 
-    logging.info("Building version " + thisbuild['version'] + ' of ' + app['id'])
+    logging.info("Building version %s (%s) of %s" % (
+        thisbuild['version'], thisbuild['vercode'], app['id']))
 
     if server:
         # When using server mode, still keep a local cache of the repo, by
@@ -895,7 +921,7 @@ def trybuild(app, thisbuild, build_dir, output_dir, also_check_dir, srclib_dir,
 
         build_server(app, thisbuild, vcs, build_dir, output_dir, force)
     else:
-        build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver)
+        build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_dir, tmp_dir, force, onserver, refresh)
     return True
 
 
@@ -923,6 +949,8 @@ def parse_commandline():
                       help="Skip scanning the source code for binaries and other problems")
     parser.add_option("--no-tarball", dest="notarball", action="store_true", default=False,
                       help="Don't create a source tarball, useful when testing a build")
+    parser.add_option("--no-refresh", dest="refresh", action="store_false", default=True,
+                      help="Don't refresh the repository, useful when testing a build with no internet connection")
     parser.add_option("-f", "--force", action="store_true", default=False,
                       help="Force build of disabled apps, and carries on regardless of scan problems. Only allowed in test mode.")
     parser.add_option("-a", "--all", action="store_true", default=False,
@@ -993,19 +1021,19 @@ def main():
 
     # Read all app and srclib metadata
     allapps = metadata.read_metadata(xref=not options.onserver)
-    metadata.read_srclibs()
 
     apps = common.read_app_args(args, allapps, True)
-    apps = [app for app in apps if (options.force or not app['Disabled']) and
-            len(app['Repo Type']) > 0 and len(app['builds']) > 0]
+    for appid, app in apps.items():
+        if (app['Disabled'] and not options.force) or not app['Repo Type'] or not app['builds']:
+            del apps[appid]
 
-    if len(apps) == 0:
-        raise Exception("No apps to process.")
+    if not apps:
+        raise FDroidException("No apps to process.")
 
     if options.latest:
-        for app in apps:
+        for app in apps.itervalues():
             for build in reversed(app['builds']):
-                if build['disable']:
+                if build['disable'] and not options.force:
                     continue
                 app['builds'] = [build]
                 break
@@ -1019,7 +1047,7 @@ def main():
     # Build applications...
     failed_apps = {}
     build_succeeded = []
-    for app in apps:
+    for appid, app in apps.iteritems():
 
         first = True
 
@@ -1034,7 +1062,7 @@ def main():
                     if app['Repo Type'] == 'srclib':
                         build_dir = os.path.join('build', 'srclib', app['Repo'])
                     else:
-                        build_dir = os.path.join('build', app['id'])
+                        build_dir = os.path.join('build', appid)
 
                     # Set up vcs interface and make sure we have the latest code...
                     logging.debug("Getting {0} vcs interface for {1}"
@@ -1048,40 +1076,61 @@ def main():
                             also_check_dir, srclib_dir, extlib_dir,
                             tmp_dir, repo_dir, vcs, options.test,
                             options.server, options.force,
-                            options.onserver):
+                            options.onserver, options.refresh):
+
+                    if app.get('Binaries', None):
+                        # This is an app where we build from source, and
+                        # verify the apk contents against a developer's
+                        # binary. We get that binary now, and save it
+                        # alongside our built one in the 'unsigend'
+                        # directory.
+                        url = app['Binaries']
+                        url = url.replace('%v', thisbuild['version'])
+                        url = url.replace('%c', str(thisbuild['vercode']))
+                        logging.info("...retrieving " + url)
+                        of = "{0}_{1}.apk.binary".format(app['id'], thisbuild['vercode'])
+                        of = os.path.join(output_dir, of)
+                        common.download_file(url, local_filename=of)
+
                     build_succeeded.append(app)
                     wikilog = "Build succeeded"
             except BuildException as be:
-                logfile = open(os.path.join(log_dir, app['id'] + '.log'), 'a+')
+                logfile = open(os.path.join(log_dir, appid + '.log'), 'a+')
                 logfile.write(str(be))
                 logfile.close()
-                reason = str(be).split('\n', 1)[0] if options.verbose else str(be)
-                print("Could not build app %s due to BuildException: %s" % (
-                    app['id'], reason))
+                print("Could not build app %s due to BuildException: %s" % (appid, be))
                 if options.stop:
                     sys.exit(1)
-                failed_apps[app['id']] = be
+                failed_apps[appid] = be
                 wikilog = be.get_wikitext()
             except VCSException as vcse:
-                print("VCS error while building app %s: %s" % (app['id'], vcse))
+                reason = str(vcse).split('\n', 1)[0] if options.verbose else str(vcse)
+                logging.error("VCS error while building app %s: %s" % (
+                    appid, reason))
                 if options.stop:
                     sys.exit(1)
-                failed_apps[app['id']] = vcse
+                failed_apps[appid] = vcse
                 wikilog = str(vcse)
             except Exception as e:
-                print("Could not build app %s due to unknown error: %s" % (app['id'], traceback.format_exc()))
+                logging.error("Could not build app %s due to unknown error: %s" % (
+                    appid, traceback.format_exc()))
                 if options.stop:
                     sys.exit(1)
-                failed_apps[app['id']] = e
+                failed_apps[appid] = e
                 wikilog = str(e)
 
             if options.wiki and wikilog:
                 try:
-                    newpage = site.Pages[app['id'] + '/lastbuild']
+                    # Write a page with the last build log for this version code
+                    lastbuildpage = appid + '/lastbuild_' + thisbuild['vercode']
+                    newpage = site.Pages[lastbuildpage]
                     txt = "Build completed at " + time.strftime("%Y-%m-%d %H:%M:%SZ", time.gmtime()) + "\n\n" + wikilog
                     newpage.save(txt, summary='Build log')
+                    # Redirect from /lastbuild to the most recent build log
+                    newpage = site.Pages[appid + '/lastbuild']
+                    newpage.save('#REDIRECT [[' + lastbuildpage + ']]', summary='Update redirect')
                 except:
-                    logging.info("Error while attempting to publish build log")
+                    logging.error("Error while attempting to publish build log")
 
     for app in build_succeeded:
         logging.info("success: %s" % (app['id']))