chiark / gitweb /
Merge branch 'some-compatibility-fixes' of https://gitlab.com/eighthave/fdroidserver
[fdroidserver.git] / fdroidserver / build.py
index 498cd4139464ca29160006e2628bba552bcb7949..84af7f41c5b0497e422a36bf6aa7833771a59227 100644 (file)
@@ -48,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:
@@ -71,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
 
@@ -175,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'):
@@ -302,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...
@@ -348,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()
@@ -428,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.debug("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']]
@@ -472,12 +500,30 @@ 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 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)
 
+        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':
@@ -501,13 +547,16 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
             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)
 
@@ -525,7 +574,7 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
     # 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:
@@ -545,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)
@@ -618,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")
 
@@ -661,25 +710,14 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
 
     elif thisbuild['type'] == 'gradle':
         logging.info("Building Gradle project...")
-        flavours = thisbuild['gradle']
-        if flavours == ['yes']:
-            flavours = []
-
-        commands = [config['gradle']]
-        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']
 
         # 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")
 
+        commands = [config['gradle']] + gradletasks
+
         p = FDroidPopen(commands, cwd=root_dir)
 
     elif thisbuild['type'] == 'ant':
@@ -754,7 +792,7 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
     if not os.path.exists(src):
         raise BuildException("Unsigned apk is not at expected location of " + src)
 
-    p = SdkToolsPopen(['aapt', 'dump', 'badging', src])
+    p = SdkToolsPopen(['aapt', 'dump', 'badging', src], output=False)
 
     vercode = None
     version = None
@@ -824,7 +862,7 @@ def build_local(app, thisbuild, vcs, build_dir, output_dir, srclib_dir, extlib_d
             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)
+                             'META-INF/' + fn], cwd=tmp_dir)
 
     # Copy the unsigned apk to our destination directory for further
     # processing (by publish.py)...
@@ -838,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,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
 
 
@@ -911,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,
@@ -1036,7 +1076,22 @@ 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: