chiark / gitweb /
Apply some autopep8-python2 suggestions
[fdroidserver.git] / fdroidserver / build.py
index c5842e673cd6c4fb89680615430eda5f4d82d1f4..677e4c88fa3caf1d523b576ebf992807344d061c 100644 (file)
@@ -2,7 +2,7 @@
 # -*- coding: utf-8 -*-
 #
 # build.py - part of the FDroid server tools
-# Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
+# Copyright (C) 2010-2014, Ciaran Gultnieks, ciaran@ciarang.com
 # Copyright (C) 2013-2014 Daniel Martí <mvdan@mvdan.cc>
 #
 # This program is free software: you can redistribute it and/or modify
@@ -21,6 +21,7 @@
 import sys
 import os
 import shutil
+import glob
 import subprocess
 import re
 import tarfile
@@ -29,16 +30,25 @@ import time
 import json
 from ConfigParser import ConfigParser
 from optparse import OptionParser, OptionError
+from distutils.version import LooseVersion
 import logging
 
-import common, metadata
-from common import BuildException, VCSException, FDroidPopen, SilentPopen
+import common
+import metadata
+from common import FDroidException, BuildException, VCSException, FDroidPopen, SdkToolsPopen
+
+try:
+    import paramiko
+except ImportError:
+    pass
+
 
 def get_builder_vm_id():
     vd = os.path.join('builder', '.vagrant')
     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:
+        with open(os.path.join(vd, 'machines', 'default',
+                               'virtualbox', 'id')) as vf:
             id = vf.read()
         return id
     else:
@@ -47,6 +57,7 @@ def get_builder_vm_id():
             v = json.load(vf)
         return v['active']['default']
 
+
 def got_valid_builder_vm():
     """Returns True if we have a valid-looking builder vm
     """
@@ -59,13 +70,14 @@ def got_valid_builder_vm():
         # Vagrant 1.0 - if the directory is there, it's valid...
         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')):
+    if not os.path.exists(os.path.join(vd, 'machines', 'default',
+                                       'virtualbox', 'id')):
         return False
     return True
 
 
 def vagrant(params, cwd=None, printout=False):
-    """Run vagrant.
+    """Run a vagrant command.
 
     :param: list of parameters to pass to vagrant
     :cwd: directory to run in, or None for current directory
@@ -73,29 +85,61 @@ 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)
 
 
-# Note that 'force' here also implies test mode.
-def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
-    """Do a build on the build server."""
-
-    import paramiko
-    if options.verbose:
-        logging.getLogger("paramiko").setLevel(logging.DEBUG)
-    else:
-        logging.getLogger("paramiko").setLevel(logging.WARN)
+def get_vagrant_sshinfo():
+    """Get ssh connection info for a vagrant VM
 
+    :returns: A dictionary containing 'hostname', 'port', 'user'
+        and 'idfile'
+    """
+    if subprocess.call('vagrant ssh-config >sshconfig',
+                       cwd='builder', shell=True) != 0:
+        raise BuildException("Error getting ssh config")
+    vagranthost = 'default'  # Host in ssh config file
+    sshconfig = paramiko.SSHConfig()
+    sshf = open('builder/sshconfig', 'r')
+    sshconfig.parse(sshf)
+    sshf.close()
+    sshconfig = sshconfig.lookup(vagranthost)
+    idfile = sshconfig['identityfile']
+    if isinstance(idfile, list):
+        idfile = idfile[0]
+    elif idfile.startswith('"') and idfile.endswith('"'):
+        idfile = idfile[1:-1]
+    return {'hostname': sshconfig['hostname'],
+            'port': int(sshconfig['port']),
+            'user': sshconfig['user'],
+            'idfile': idfile}
+
+
+def get_clean_vm(reset=False):
+    """Get a clean VM ready to do a buildserver build.
+
+    This might involve creating and starting a new virtual machine from
+    scratch, or it might be as simple (unless overridden by the reset
+    parameter) as re-using a snapshot created previously.
+
+    A BuildException will be raised if anything goes wrong.
+
+    :reset: True to force creating from scratch.
+    :returns: A dictionary containing 'hostname', 'port', 'user'
+        and 'idfile'
+    """
     # Reset existing builder machine to a clean state if possible.
     vm_ok = False
-    if not options.resetserver:
+    if not reset:
         logging.info("Checking for valid existing build server")
 
         if got_valid_builder_vm():
             logging.info("...VM is present")
-            p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'list', '--details'], cwd='builder')
-            if 'fdroidclean' in p.stdout:
-                logging.info("...snapshot exists - resetting build server to clean state")
+            p = FDroidPopen(['VBoxManage', 'snapshot',
+                             get_builder_vm_id(), 'list',
+                             '--details'], cwd='builder')
+            if 'fdroidclean' in p.output:
+                logging.info("...snapshot exists - resetting build server to "
+                             "clean state")
                 retcode, output = vagrant(['status'], cwd='builder')
 
                 if 'running' in output:
@@ -103,8 +147,9 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
                     vagrant(['suspend'], cwd='builder')
                     logging.info("...waiting a sec...")
                     time.sleep(10)
-                p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'restore', 'fdroidclean'],
-                    cwd='builder')
+                p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(),
+                                 'restore', 'fdroidclean'],
+                                cwd='builder')
 
                 if p.returncode == 0:
                     logging.info("...reset to snapshot - server is valid")
@@ -113,11 +158,13 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
                         raise BuildException("Failed to start build server")
                     logging.info("...waiting a sec...")
                     time.sleep(10)
+                    sshinfo = get_vagrant_sshinfo()
                     vm_ok = True
                 else:
                     logging.info("...failed to reset to snapshot")
             else:
-                logging.info("...snapshot doesn't exist - VBoxManage snapshot list:\n" + output)
+                logging.info("...snapshot doesn't exist - "
+                             "VBoxManage snapshot list:\n" + p.output)
 
     # If we can't use the existing machine for any reason, make a
     # new one from scratch.
@@ -128,7 +175,8 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
             shutil.rmtree('builder')
         os.mkdir('builder')
 
-        p = subprocess.Popen('vagrant --version', shell=True, stdout=subprocess.PIPE)
+        p = subprocess.Popen('vagrant --version', shell=True,
+                             stdout=subprocess.PIPE)
         vver = p.communicate()[0]
         if vver.startswith('Vagrant version 1.2'):
             with open('builder/Vagrantfile', 'w') as vf:
@@ -148,23 +196,13 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
 
         # Open SSH connection to make sure it's working and ready...
         logging.info("Connecting to virtual machine...")
-        if subprocess.call('vagrant ssh-config >sshconfig',
-                cwd='builder', shell=True) != 0:
-            raise BuildException("Error getting ssh config")
-        vagranthost = 'default' # Host in ssh config file
-        sshconfig = paramiko.SSHConfig()
-        sshf = open('builder/sshconfig', 'r')
-        sshconfig.parse(sshf)
-        sshf.close()
-        sshconfig = sshconfig.lookup(vagranthost)
+        sshinfo = get_vagrant_sshinfo()
         sshs = paramiko.SSHClient()
         sshs.set_missing_host_key_policy(paramiko.AutoAddPolicy())
-        idfile = sshconfig['identityfile']
-        if idfile.startswith('"') and idfile.endswith('"'):
-            idfile = idfile[1:-1]
-        sshs.connect(sshconfig['hostname'], username=sshconfig['user'],
-            port=int(sshconfig['port']), timeout=300, look_for_keys=False,
-            key_filename=idfile)
+        sshs.connect(sshinfo['hostname'], username=sshinfo['user'],
+                     port=sshinfo['port'], timeout=300,
+                     look_for_keys=False,
+                     key_filename=sshinfo['idfile'])
         sshs.close()
 
         logging.info("Saving clean state of new build server")
@@ -173,8 +211,9 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
             raise BuildException("Failed to suspend build server")
         logging.info("...waiting a sec...")
         time.sleep(10)
-        p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'take', 'fdroidclean'],
-                cwd='builder')
+        p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(),
+                         'take', 'fdroidclean'],
+                        cwd='builder')
         if p.returncode != 0:
             raise BuildException("Failed to take snapshot")
         logging.info("...waiting a sec...")
@@ -186,43 +225,57 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
         logging.info("...waiting a sec...")
         time.sleep(10)
         # Make sure it worked...
-        p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(), 'list', '--details'],
-            cwd='builder')
-        if 'fdroidclean' not in p.stdout:
+        p = FDroidPopen(['VBoxManage', 'snapshot', get_builder_vm_id(),
+                         'list', '--details'],
+                        cwd='builder')
+        if 'fdroidclean' not in p.output:
             raise BuildException("Failed to take snapshot.")
 
+    return sshinfo
+
+
+def release_vm():
+    """Release the VM previously started with get_clean_vm().
+
+    This should always be called.
+    """
+    logging.info("Suspending build server")
+    subprocess.call(['vagrant', 'suspend'], cwd='builder')
+
+
+# Note that 'force' here also implies test mode.
+def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
+    """Do a build on the build server."""
+
     try:
+        paramiko
+    except NameError:
+        raise BuildException("Paramiko is required to use the buildserver")
+    if options.verbose:
+        logging.getLogger("paramiko").setLevel(logging.DEBUG)
+    else:
+        logging.getLogger("paramiko").setLevel(logging.WARN)
 
-        # Get SSH configuration settings for us to connect...
-        logging.info("Getting ssh configuration...")
-        subprocess.call('vagrant ssh-config >sshconfig',
-                cwd='builder', shell=True)
-        vagranthost = 'default' # Host in ssh config file
+    sshinfo = get_clean_vm()
 
-        # Load and parse the SSH config...
-        sshconfig = paramiko.SSHConfig()
-        sshf = open('builder/sshconfig', 'r')
-        sshconfig.parse(sshf)
-        sshf.close()
-        sshconfig = sshconfig.lookup(vagranthost)
+    try:
 
         # Open SSH connection...
         logging.info("Connecting to virtual machine...")
         sshs = paramiko.SSHClient()
         sshs.set_missing_host_key_policy(paramiko.AutoAddPolicy())
-        idfile = sshconfig['identityfile'][0]
-        if idfile.startswith('"') and idfile.endswith('"'):
-            idfile = idfile[1:-1]
-        sshs.connect(sshconfig['hostname'], username=sshconfig['user'],
-            port=int(sshconfig['port']), timeout=300, look_for_keys=False,
-            key_filename=idfile)
+        sshs.connect(sshinfo['hostname'], username=sshinfo['user'],
+                     port=sshinfo['port'], timeout=300,
+                     look_for_keys=False, key_filename=sshinfo['idfile'])
+
+        homedir = '/home/' + sshinfo['user']
 
         # Get an SFTP connection...
         ftp = sshs.open_sftp()
         ftp.get_channel().settimeout(15)
 
         # Put all the necessary files in place...
-        ftp.chdir('/home/vagrant')
+        ftp.chdir(homedir)
 
         # Helper to copy the contents of a directory to the server...
         def send_dir(path):
@@ -249,9 +302,15 @@ 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...
+        subprocess.call('git rev-parse HEAD >' +
+                        os.path.join(os.getcwd(), 'tmp', 'fdroidserverid'),
+                        shell=True, cwd=serverpath)
+        ftp.put('tmp/fdroidserverid', 'fdroidserverid')
+
         # Copy the metadata - just the file for this app...
         ftp.mkdir('metadata')
         ftp.mkdir('srclibs')
@@ -262,15 +321,15 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
         if os.path.exists(os.path.join('metadata', app['id'])):
             send_dir(os.path.join('metadata', app['id']))
 
-        ftp.chdir('/home/vagrant')
+        ftp.chdir(homedir)
         # Create the build directory...
         ftp.mkdir('build')
         ftp.chdir('build')
         ftp.mkdir('extlib')
         ftp.mkdir('srclib')
         # Copy any extlibs that are required...
-        if 'extlibs' in thisbuild:
-            ftp.chdir('/home/vagrant/build/extlib')
+        if thisbuild['extlibs']:
+            ftp.chdir(homedir + '/build/extlib')
             for lib in thisbuild['extlibs']:
                 lib = lib.strip()
                 libsrc = os.path.join('build/extlib', lib)
@@ -286,10 +345,11 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
                     ftp.chdir('..')
         # Copy any srclibs that are required...
         srclibpaths = []
-        if 'srclibs' in thisbuild:
+        if thisbuild['srclibs']:
             for lib in thisbuild['srclibs']:
-                srclibpaths.append(common.getsrclib(lib, 'build/srclib', srclibpaths,
-                    basepath=True, prepare=False))
+                srclibpaths.append(
+                    common.getsrclib(lib, 'build/srclib', srclibpaths,
+                                     basepath=True, prepare=False))
 
         # If one was used for the main source, add that too.
         basesrclib = vcs.getsrclib()
@@ -297,20 +357,20 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
             srclibpaths.append(basesrclib)
         for name, number, lib in srclibpaths:
             logging.info("Sending srclib '%s'" % lib)
-            ftp.chdir('/home/vagrant/build/srclib')
+            ftp.chdir(homedir + '/build/srclib')
             if not os.path.exists(lib):
                 raise BuildException("Missing srclib directory '" + lib + "'")
             fv = '.fdroidvcs-' + name
             ftp.put(os.path.join('build/srclib', fv), fv)
             send_dir(lib)
             # Copy the metadata file too...
-            ftp.chdir('/home/vagrant/srclibs')
+            ftp.chdir(homedir + '/srclibs')
             ftp.put(os.path.join('srclibs', name + '.txt'),
                     name + '.txt')
         # Copy the main app source code
         # (no need if it's a srclib)
         if (not basesrclib) and os.path.exists(build_dir):
-            ftp.chdir('/home/vagrant/build')
+            ftp.chdir(homedir + '/build')
             fv = '.fdroidvcs-' + app['id']
             ftp.put(os.path.join('build', fv), fv)
             send_dir(build_dir)
@@ -339,45 +399,49 @@ def build_server(app, thisbuild, vcs, build_dir, output_dir, force):
                 break
             output += get
         if returncode != 0:
-            raise BuildException("Build.py failed on server for %s:%s" % (app['id'], thisbuild['version']), output)
+            raise BuildException(
+                "Build.py failed on server for {0}:{1}".format(
+                    app['id'], thisbuild['version']), output)
 
         # Retrieve the built files...
         logging.info("Retrieving build output...")
         if force:
-            ftp.chdir('/home/vagrant/tmp')
+            ftp.chdir(homedir + '/tmp')
         else:
-            ftp.chdir('/home/vagrant/unsigned')
-        apkfile = common.getapkname(app,thisbuild)
-        tarball = common.getsrcname(app,thisbuild)
+            ftp.chdir(homedir + '/unsigned')
+        apkfile = common.getapkname(app, thisbuild)
+        tarball = common.getsrcname(app, thisbuild)
         try:
             ftp.get(apkfile, os.path.join(output_dir, apkfile))
             if not options.notarball:
                 ftp.get(tarball, os.path.join(output_dir, tarball))
         except:
-            raise BuildException("Build failed for %s:%s - missing output files" % (app['id'], thisbuild['version']), output)
+            raise BuildException(
+                "Build failed for %s:%s - missing output files".format(
+                    app['id'], thisbuild['version']), output)
         ftp.close()
 
     finally:
 
         # Suspend the build server.
-        logging.info("Suspending build server")
-        subprocess.call(['vagrant', 'suspend'], cwd='builder')
+        release_vm()
+
 
 def adapt_gradle(build_dir):
     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)
+            logging.debug("Adapting build.gradle at %s" % path)
 
             FDroidPopen(['sed', '-i',
-                    r's@buildToolsVersion\([ =]*\)["\'][0-9\.]*["\']@buildToolsVersion\1"'
-                    + config['build_tools'] + '"@g', path])
+                         r's@buildToolsVersion\([ =]*\)["\'][0-9\.]*["\']@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):
     """Do a build locally."""
 
-    if thisbuild.get('buildjni') not in (None, ['no']):
+    if thisbuild['buildjni'] and thisbuild['buildjni'] != ['no']:
         if not config['ndk_path']:
             logging.critical("$ANDROID_NDK is not set!")
             sys.exit(3)
@@ -387,7 +451,8 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
 
     # Prepare the source code...
     root_dir, srclibpaths = common.prepare_source(vcs, app, thisbuild,
-            build_dir, srclib_dir, extlib_dir, onserver)
+                                                  build_dir, srclib_dir,
+                                                  extlib_dir, onserver)
 
     # We need to clean via the build tool in case the binary dirs are
     # different from the default ones
@@ -397,7 +462,7 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         cmd = [config['mvn3'], 'clean', '-Dandroid.sdk.path=' + config['sdk_path']]
 
         if '@' in thisbuild['maven']:
-            maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@',1)[1])
+            maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@', 1)[1])
             maven_dir = os.path.normpath(maven_dir)
         else:
             maven_dir = root_dir
@@ -409,17 +474,11 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         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
-
         adapt_gradle(build_dir)
         for name, number, libpath in srclibpaths:
             adapt_gradle(libpath)
 
-        p = FDroidPopen(cmd, cwd=gradle_dir)
+        p = FDroidPopen(cmd, cwd=root_dir)
 
     elif thisbuild['type'] == 'kivy':
         pass
@@ -430,12 +489,12 @@ 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'))
@@ -450,40 +509,43 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
             if force:
                 logging.warn('Scanner found %d problems:' % count)
             else:
-                raise BuildException("Can't build due to %d scanned problems" % count)
+                raise BuildException("Can't build due to %d errors while scanning" % count)
 
     if not options.notarball:
         # Build the source tarball right before we build the release...
         logging.info("Creating source tarball...")
-        tarname = common.getsrcname(app,thisbuild)
+        tarname = common.getsrcname(app, thisbuild)
         tarball = tarfile.open(os.path.join(tmp_dir, tarname), "w:gz")
+
         def tarexc(f):
             return any(f.endswith(s) for s in ['.svn', '.git', '.hg', '.bzr'])
         tarball.add(build_dir, tarname, exclude=tarexc)
         tarball.close()
 
     # Run a build command if one is required...
-    if 'build' in thisbuild:
+    if thisbuild['build']:
+        logging.info("Running 'build' commands in %s" % root_dir)
         cmd = common.replace_config_vars(thisbuild['build'])
+
         # Substitute source library paths into commands...
         for name, number, libpath in srclibpaths:
             libpath = os.path.relpath(libpath, root_dir)
             cmd = cmd.replace('$$' + name + '$$', libpath)
-        logging.info("Running 'build' commands in %s" % root_dir)
 
         p = FDroidPopen(['bash', '-x', '-c', cmd], cwd=root_dir)
 
         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.get('buildjni') not in (None, ['no']):
-        logging.info("Building native libraries...")
-        jni_components = thisbuild.get('buildjni')
+    if thisbuild['buildjni'] and thisbuild['buildjni'] != ['no']:
+        logging.info("Building the native code")
+        jni_components = thisbuild['buildjni']
+
         if jni_components == ['yes']:
             jni_components = ['']
-        cmd = [ os.path.join(config['ndk_path'], "ndk-build"), "-j1" ]
+        cmd = [os.path.join(config['ndk_path'], "ndk-build"), "-j1"]
         for d in jni_components:
             if d:
                 logging.info("Building native code in '%s'" % d)
@@ -500,9 +562,9 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
                 open(manifest, 'w').write(manifest_text)
                 # In case the AM.xml read was big, free the memory
                 del manifest_text
-            p = FDroidPopen(cmd, cwd=os.path.join(root_dir,d))
+            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...
@@ -510,25 +572,27 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         logging.info("Building Maven project...")
 
         if '@' in thisbuild['maven']:
-            maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@',1)[1])
+            maven_dir = os.path.join(root_dir, thisbuild['maven'].split('@', 1)[1])
         else:
             maven_dir = root_dir
 
         mvncmd = [config['mvn3'], '-Dandroid.sdk.path=' + config['sdk_path'],
-                '-Dandroid.sign.debug=false', '-Dmaven.test.skip=true',
-                '-Dandroid.release=true', 'package']
-        if 'target' in thisbuild:
+                  '-Dmaven.jar.sign.skip=true', '-Dmaven.test.skip=true',
+                  '-Dandroid.sign.debug=false', '-Dandroid.release=true',
+                  'package']
+        if thisbuild['target']:
             target = thisbuild["target"].split('-')[1]
             FDroidPopen(['sed', '-i',
-                    's@<platform>[0-9]*</platform>@<platform>'+target+'</platform>@g',
-                    'pom.xml'], cwd=root_dir)
+                         's@<platform>[0-9]*</platform>@<platform>'
+                         + target + '</platform>@g',
+                         'pom.xml'],
+                        cwd=root_dir)
             if '@' in thisbuild['maven']:
                 FDroidPopen(['sed', '-i',
-                        's@<platform>[0-9]*</platform>@<platform>'+target+'</platform>@g',
-                        'pom.xml'], cwd=maven_dir)
-
-        if 'mvnflags' in thisbuild:
-            mvncmd += thisbuild['mvnflags']
+                             's@<platform>[0-9]*</platform>@<platform>'
+                             + target + '</platform>@g',
+                             'pom.xml'],
+                            cwd=maven_dir)
 
         p = FDroidPopen(mvncmd, cwd=maven_dir)
 
@@ -540,10 +604,10 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
         spec = os.path.join(root_dir, 'buildozer.spec')
         if not os.path.exists(spec):
             raise BuildException("Expected to find buildozer-compatible spec at {0}"
-                    .format(spec))
+                                 .format(spec))
 
         defaults = {'orientation': 'landscape', 'icon': '',
-                'permissions': '', 'android.api': "18"}
+                    'permissions': '', 'android.api': "18"}
         bconfig = ConfigParser(defaults, allow_no_value=True)
         bconfig.read(spec)
 
@@ -574,12 +638,12 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
             orientation = 'sensor'
 
         cmd = ['./build.py'
-                '--dir', root_dir,
-                '--name', bconfig.get('app', 'title'),
-                '--package', app['id'],
-                '--version', bconfig.get('app', 'version'),
-                '--orientation', orientation,
-                ]
+               '--dir', root_dir,
+               '--name', bconfig.get('app', 'title'),
+               '--package', app['id'],
+               '--version', bconfig.get('app', 'version'),
+               '--orientation', orientation
+               ]
 
         perms = bconfig.get('app', 'permissions')
         for perm in perms.split(','):
@@ -597,34 +661,32 @@ 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] = ''
+        flavours = thisbuild['gradle']
+        if flavours == ['yes']:
+            flavours = []
 
         commands = [config['gradle']]
-        if 'preassemble' in thisbuild:
-            commands += thisbuild['preassemble'].split()
+        if thisbuild['preassemble']:
+            commands += thisbuild['preassemble']
 
         flavours_cmd = ''.join(flavours)
         if flavours_cmd:
             flavours_cmd = flavours_cmd[0].upper() + flavours_cmd[1:]
 
-        commands += ['assemble'+flavours_cmd+'Release']
+        commands += ['assemble' + flavours_cmd + 'Release']
+
+        # Avoid having to use lintOptions.abortOnError false
+        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")
 
-        p = FDroidPopen(commands, cwd=gradle_dir)
+        p = FDroidPopen(commands, cwd=root_dir)
 
     elif thisbuild['type'] == 'ant':
         logging.info("Building Ant project...")
         cmd = ['ant']
-        if 'antcommand' in thisbuild:
-            cmd += [thisbuild['antcommand']]
+        if thisbuild['antcommands']:
+            cmd += thisbuild['antcommands']
         else:
             cmd += ['release']
         p = FDroidPopen(cmd, cwd=root_dir)
@@ -632,47 +694,51 @@ 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)
+                     stdout_apk, re.S | re.M)
         if not m:
             m = re.match(r".*^\[INFO\] Creating additional unsigned apk file .*/([^/]+)\.apk[^l]",
-                    stdout_apk, re.S|re.M)
+                         stdout_apk, re.S | re.M)
         if not m:
             m = re.match(r'.*^\[INFO\] [^$]*aapt \[package,[^$]*' + bindir + r'/([^/]+)\.ap[_k][,\]]',
-                    stdout_apk, re.S|re.M)
+                         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)
         src = os.path.join(bindir, src) + '.apk'
     elif thisbuild['type'] == 'kivy':
         src = 'python-for-android/dist/default/bin/{0}-{1}-release.apk'.format(
-                bconfig.get('app', 'title'), bconfig.get('app', 'version'))
+            bconfig.get('app', 'title'), bconfig.get('app', 'version'))
     elif thisbuild['type'] == 'gradle':
-        basename = app['id']
-        dd = build_dir
-        if 'subdir' in thisbuild:
-            dd = os.path.join(dd, thisbuild['subdir'])
-            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'])
+
+        if thisbuild['gradlepluginver'] >= LooseVersion('0.11'):
+            apks_dir = os.path.join(root_dir, 'build', 'outputs', 'apk')
         else:
-            name = '-'.join([basename, '-'.join(flavours), 'release', 'unsigned'])
-        dd = os.path.normpath(dd)
-        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)
+                       re.S | re.M).group(1)
         src = os.path.join(bindir, src)
     elif thisbuild['type'] == 'raw':
         src = os.path.join(root_dir, thisbuild['output'])
@@ -684,19 +750,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)
@@ -713,8 +777,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.get('buildjni') is not None:
-        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']
@@ -737,24 +807,38 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
     if (version != thisbuild['version'] or
             vercode != thisbuild['vercode']):
         raise BuildException(("Unexpected version/version code in output;"
-                             " APK: '%s' / '%s', "
-                             " Expected: '%s' / '%s'")
-                             % (version, str(vercode), thisbuild['version'], str(thisbuild['vercode']))
-                            )
+                              " APK: '%s' / '%s', "
+                              " Expected: '%s' / '%s'")
+                             % (version, str(vercode), thisbuild['version'],
+                                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))
+    dest = os.path.join(output_dir, common.getapkname(app, thisbuild))
     shutil.copyfile(src, dest)
 
     # Move the source tarball into the output directory...
     if output_dir != tmp_dir and not options.notarball:
         shutil.move(os.path.join(tmp_dir, tarname),
-            os.path.join(output_dir, tarname))
+                    os.path.join(output_dir, tarname))
 
 
 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):
     """
     Build a particular version of an application, if it needs building.
 
@@ -786,10 +870,11 @@ def trybuild(app, thisbuild, build_dir, output_dir, also_check_dir, srclib_dir,
             if os.path.exists(dest_also):
                 return False
 
-    if 'disable' in thisbuild:
+    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
@@ -846,6 +931,7 @@ def parse_commandline():
 options = None
 config = None
 
+
 def main():
 
     global options, config
@@ -893,34 +979,35 @@ def main():
     srclib_dir = os.path.join(build_dir, 'srclib')
     extlib_dir = os.path.join(build_dir, 'extlib')
 
-    # Get all apps...
+    # Read all app and srclib metadata
     allapps = metadata.read_metadata(xref=not options.onserver)
 
     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 'disable' in build:
+                if build['disable'] and not options.force:
                     continue
-                app['builds'] = [ build ]
+                app['builds'] = [build]
                 break
 
     if options.wiki:
         import mwclient
         site = mwclient.Site((config['wiki_protocol'], config['wiki_server']),
-                path=config['wiki_path'])
+                             path=config['wiki_path'])
         site.login(config['wiki_user'], config['wiki_password'])
 
     # Build applications...
     failed_apps = {}
     build_succeeded = []
-    for app in apps:
+    for appid, app in apps.iteritems():
 
         first = True
 
@@ -935,52 +1022,60 @@ 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}".format(
-                            app['Repo Type'], app['Repo']))
+                    logging.debug("Getting {0} vcs interface for {1}"
+                                  .format(app['Repo Type'], app['Repo']))
                     vcs = common.getvcs(app['Repo Type'], app['Repo'], build_dir)
 
                     first = False
 
                 logging.debug("Checking " + thisbuild['version'])
-                if trybuild(app, thisbuild, build_dir, output_dir, also_check_dir,
-                        srclib_dir, extlib_dir, tmp_dir, repo_dir, vcs, options.test,
-                        options.server, options.force, options.onserver):
+                if trybuild(app, thisbuild, build_dir, output_dir,
+                            also_check_dir, srclib_dir, extlib_dir,
+                            tmp_dir, repo_dir, vcs, options.test,
+                            options.server, options.force,
+                            options.onserver):
                     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']))
@@ -999,4 +1094,3 @@ def main():
 
 if __name__ == "__main__":
     main()
-