Move some options into subparsers, and add --no-implicit-build to test.
[cdist.git] / cdist
diff --git a/cdist b/cdist
index 82df7436d3612f15398546b6f673c3326f29687a..28c174ea95ad5485d5df54634a4aa3662a66c995 100755 (executable)
--- a/cdist
+++ b/cdist
@@ -1,6 +1,6 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
-#    Copyright (C) 2012-2017 Carl Hetherington <cth@carlh.net>
+#    Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
 #
 #    This program is free software; you can redistribute it and/or modify
 #    it under the terms of the GNU General Public License as published by
 #    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
 from __future__ import print_function
-import os
-import sys
-import shutil
-import glob
-import tempfile
+
 import argparse
-import datetime
-import subprocess
-import re
 import copy
-import inspect
+import datetime
 import getpass
+import glob
+import inspect
+import multiprocessing
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
 
 TEMPORARY_DIRECTORY = '/var/tmp'
 
@@ -54,10 +58,10 @@ class Trees:
             if t.name == name and t.specifier == specifier and t.target == target:
                 return t
             elif t.name == name and t.specifier != specifier:
-                a = specifier
+                a = specifier if specifier is not None else "[Any]"
                 if required_by is not None:
                     a += ' by %s' % required_by
-                b = t.specifier
+                b = t.specifier if t.specifier is not None else "[Any]"
                 if t.required_by is not None:
                     b += ' by %s' % t.required_by
                 raise Error('conflicting versions of %s required (%s versus %s)' % (name, a, b))
@@ -66,6 +70,10 @@ class Trees:
         self.trees.append(nt)
         return nt
 
+    def add_built(self, name, specifier, target):
+        self.trees.append(Tree(name, specifier, target, None, built=True))
+
+
 class Globals:
     quiet = False
     command = None
@@ -101,11 +109,31 @@ class Config:
     def __init__(self):
         self.options = [ Option('mxe_prefix'),
                          Option('git_prefix'),
+                         Option('git_reference'),
                          Option('osx_environment_prefix'),
                          Option('osx_sdk_prefix'),
                          Option('osx_sdk'),
+                         Option('osx_keychain_file'),
+                         Option('osx_keychain_password'),
+                         Option('apple_id'),
+                         Option('apple_password'),
                          BoolOption('docker_sudo'),
-                         Option('parallel', 4) ]
+                         BoolOption('docker_no_user'),
+                         Option('docker_hub_repository'),
+                         Option('flatpak_state_dir'),
+                         Option('parallel', multiprocessing.cpu_count()) ]
+
+        config_dir = '%s/.config' % os.path.expanduser('~')
+        if not os.path.exists(config_dir):
+            os.mkdir(config_dir)
+        config_file = '%s/cdist' % config_dir
+        if not os.path.exists(config_file):
+            f = open(config_file, 'w')
+            for o in self.options:
+                print('# %s ' % o.key, file=f)
+            f.close()
+            print('Template config file written to %s; please edit and try again.' % config_file, file=sys.stderr)
+            sys.exit(1)
 
         try:
             f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
@@ -124,6 +152,12 @@ class Config:
         except:
             raise
 
+    def has(self, k):
+        for o in self.options:
+            if o.key == k and o.value is not None:
+                return True
+        return False
+
     def get(self, k):
         for o in self.options:
             if o.key == k:
@@ -147,10 +181,17 @@ config = Config()
 # Utility bits
 #
 
-def log(m):
+def log_normal(m):
     if not globals.quiet:
         print('\x1b[33m* %s\x1b[0m' % m)
 
+def log_verbose(m):
+    if globals.verbose:
+        print('\x1b[35m* %s\x1b[0m' % m)
+
+def escape_spaces(s):
+    return s.replace(' ', '\\ ')
+
 def scp_escape(n):
     """Escape a host:filename string for use with an scp command"""
     s = n.split(':')
@@ -160,19 +201,30 @@ def scp_escape(n):
     else:
         return '\"%s\"' % s[0]
 
+def mv_escape(n):
+    return '\"%s\"' % n.substr(' ', '\\ ')
+
 def copytree(a, b):
-    log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
+    log_normal('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
     if b.startswith('s3://'):
         command('s3cmd -P -r put "%s" "%s"' % (a, b))
     else:
         command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
 
 def copyfile(a, b):
-    log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
+    log_normal('copy %s -> %s with cwd %s' % (scp_escape(a), scp_escape(b), os.getcwd()))
     if b.startswith('s3://'):
         command('s3cmd -P put "%s" "%s"' % (a, b))
     else:
-        command('scp %s %s' % (scp_escape(a), scp_escape(b)))
+        bc = b.find(":")
+        if bc != -1:
+            host = b[:bc]
+            path = b[bc+1:]
+            temp_path = os.path.join(os.path.dirname(path), ".tmp." + os.path.basename(path))
+            command('scp %s %s' % (scp_escape(a), scp_escape(host + ":" + temp_path)))
+            command('ssh %s -- mv "%s" "%s"' % (host, escape_spaces(temp_path), escape_spaces(path)))
+        else:
+            command('scp %s %s' % (scp_escape(a), scp_escape(b)))
 
 def makedirs(d):
     """
@@ -194,24 +246,26 @@ def makedirs(d):
         command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
 
 def rmdir(a):
-    log('remove %s' % a)
+    log_normal('remove %s' % a)
     os.rmdir(a)
 
 def rmtree(a):
-    log('remove %s' % a)
+    log_normal('remove %s' % a)
     shutil.rmtree(a, ignore_errors=True)
 
 def command(c):
-    log(c)
+    log_normal(c)
     r = os.system(c)
     if (r >> 8):
         raise Error('command %s failed' % c)
 
 def command_and_read(c):
-    log(c)
-    p = subprocess.Popen(c.split(), stdout=subprocess.PIPE)
-    f = os.fdopen(os.dup(p.stdout.fileno()))
-    return f
+    log_normal(c)
+    p = subprocess.Popen(c.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    (out, err) = p.communicate()
+    if p.returncode != 0:
+        raise Error('command %s failed (%s)' % (c, err))
+    return str(out, 'utf-8').splitlines()
 
 def read_wscript_variable(directory, variable):
     f = open('%s/wscript' % directory, 'r')
@@ -228,52 +282,30 @@ def read_wscript_variable(directory, variable):
     f.close()
     return None
 
-def set_version_in_wscript(version):
-    f = open('wscript', 'rw')
-    o = open('wscript.tmp', 'w')
-    while True:
-        l = f.readline()
-        if l == '':
-            break
-
-        s = l.split()
-        if len(s) == 3 and s[0] == "VERSION":
-            print("Writing %s" % version)
-            print("VERSION = '%s'" % version, file=o)
-        else:
-            print(l, file=o, end="")
-    f.close()
-    o.close()
-
-    os.rename('wscript.tmp', 'wscript')
-
-def append_version_to_changelog(version):
-    try:
-        f = open('ChangeLog', 'r')
-    except:
-        log('Could not open ChangeLog')
-        return
-
-    c = f.read()
-    f.close()
-
-    f = open('ChangeLog', 'w')
-    now = datetime.datetime.now()
-    f.write('%d-%02d-%02d  Carl Hetherington  <cth@carlh.net>\n\n\t* Version %s released.\n\n' % (now.year, now.month, now.day, version))
-    f.write(c)
-
-def append_version_to_debian_changelog(version):
-    if not os.path.exists('debian'):
-        log('Could not find debian directory')
-        return
-
-    command('dch -b -v %s-1 "New upstream release."' % version)
 
 def devel_to_git(git_commit, filename):
     if git_commit is not None:
         filename = filename.replace('devel', '-%s' % git_commit)
     return filename
 
+
+def get_command_line_options(args):
+    """Get the options specified by --option on the command line"""
+    options = dict()
+    if args.option is not None:
+        for o in args.option:
+            b = o.split(':')
+            if len(b) != 2:
+                raise Error("Bad option `%s'" % o)
+            if b[1] == 'False':
+                options[b[0]] = False
+            elif b[1] == 'True':
+                options[b[0]] = True
+            else:
+                options[b[0]] = b[1]
+    return options
+
+
 class TreeDirectory:
     def __init__(self, tree):
         self.tree = tree
@@ -311,6 +343,14 @@ class Version:
         else:
             self.micro = 0
 
+    @classmethod
+    def from_git_tag(cls, tag):
+        bits = tag.split('-')
+        c = cls(bits[0])
+        if len(bits) > 1 and int(bits[1]) > 0:
+            c.devel = True
+        return c
+
     def bump_minor(self):
         self.minor += 1
         self.micro = 0
@@ -345,6 +385,7 @@ class Target(object):
     directory: directory to work in
     variables: dict of environment variables
     debug: True to build a debug version, otherwise False
+    ccache: True to use ccache, False to not
     set(a, b): set the value of variable 'a' to 'b'
     unset(a): unset the value of variable 'a'
     command(c): run the command 'c' in the build environment
@@ -360,41 +401,64 @@ class Target(object):
         self.platform = platform
         self.parallel = int(config.get('parallel'))
 
+        # Environment variables that we will use when we call cscripts
+        self.variables = {}
+        self.debug = False
+        self._ccache = False
+        # True to build our dependencies ourselves; False if this is taken care
+        # of in some other way
+        self.build_dependencies = True
+
         if directory is None:
             self.directory = tempfile.mkdtemp('', 'tmp', TEMPORARY_DIRECTORY)
             self.rmdir = True
+            self.set('CCACHE_BASEDIR', os.path.realpath(self.directory))
+            self.set('CCACHE_NOHASHDIR', '')
         else:
-            self.directory = directory
+            self.directory = os.path.realpath(directory)
             self.rmdir = False
 
-        # Environment variables that we will use when we call cscripts
-        self.variables = {}
-        self.debug = False
 
     def setup(self):
         pass
 
-    def package(self, project, checkout, output_dir):
-        tree = globals.trees.get(project, checkout, self)
-        tree.build_dependencies()
-        tree.build()
-        packages = tree.call('package', tree.version)
-        if isinstance(packages, (str, unicode)):
-            copyfile(packages, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, packages))))
+    def _build_packages(self, tree, options):
+        if len(inspect.getfullargspec(tree.cscript['package']).args) == 3:
+            packages = tree.call('package', tree.version, options)
         else:
-            for p in packages:
-                copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
+            log_normal("Deprecated cscript package() method with no options parameter")
+            packages = tree.call('package', tree.version)
+
+        return packages if isinstance(packages, list) else [packages]
+
+    def _copy_packages(self, tree, packages, output_dir):
+        for p in packages:
+            copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
+
+    def package(self, project, checkout, output_dir, options, no_notarize):
+        tree = self.build(project, checkout, options)
+        tree.add_defaults(options)
+        p = self._build_packages(tree, options)
+        self._copy_packages(tree, p, output_dir)
 
-    def build(self, project, checkout):
+    def build(self, project, checkout, options):
         tree = globals.trees.get(project, checkout, self)
-        tree.build_dependencies()
-        tree.build()
+        if self.build_dependencies:
+            tree.build_dependencies(options)
+        tree.build(options)
+        return tree
 
-    def test(self, tree, test):
+    def test(self, project, checkout, target, test, options):
         """test is the test case to run, or None"""
-        tree.build_dependencies()
-        tree.build()
-        return tree.call('test', test)
+        tree = globals.trees.get(project, checkout, target)
+
+        tree.add_defaults(options)
+        with TreeDirectory(tree):
+            if len(inspect.getfullargspec(tree.cscript['test']).args) == 3:
+                return tree.call('test', options, test)
+            else:
+                log_normal('Deprecated cscript test() method with no options parameter')
+                return tree.call('test', test)
 
     def set(self, a, b):
         self.variables[a] = b
@@ -436,20 +500,99 @@ class Target(object):
     def mount(self, m):
         pass
 
+    @property
+    def ccache(self):
+        return self._ccache
+
+    @ccache.setter
+    def ccache(self, v):
+        self._ccache = v
 
-class WindowsTarget(Target):
+
+class DockerTarget(Target):
+    def __init__(self, platform, directory):
+        super(DockerTarget, self).__init__(platform, directory)
+        self.mounts = []
+        self.privileged = False
+
+    def _user_tag(self):
+        if config.get('docker_no_user'):
+            return ''
+        return '-u %s' % getpass.getuser()
+
+    def _mount_option(self, d):
+        return '-v %s:%s ' % (os.path.realpath(d), os.path.realpath(d))
+
+    def setup(self):
+        opts = self._mount_option(self.directory)
+        for m in self.mounts:
+            opts += self._mount_option(m)
+        if config.has('git_reference'):
+            opts += self._mount_option(config.get('git_reference'))
+        if self.privileged:
+            opts += '--privileged=true '
+        if self.ccache:
+            opts += "-e CCACHE_DIR=/ccache/%s-%d --mount source=ccache,target=/ccache" % (self.image, os.getuid())
+
+        tag = self.image
+        if config.has('docker_hub_repository'):
+            tag = '%s:%s' % (config.get('docker_hub_repository'), tag)
+
+        self.container = command_and_read('%s run %s %s -itd %s /bin/bash' % (config.docker(), self._user_tag(), opts, tag))[0].strip()
+
+    def command(self, cmd):
+        dir = os.path.join(self.directory, os.path.relpath(os.getcwd(), self.directory))
+        interactive_flag = '-i ' if sys.stdin.isatty() else ''
+        command('%s exec %s %s -t %s /bin/bash -c \'export %s; cd %s; %s\'' % (config.docker(), self._user_tag(), interactive_flag, self.container, self.variables_string(), dir, cmd))
+
+    def cleanup(self):
+        super(DockerTarget, self).cleanup()
+        command('%s kill %s' % (config.docker(), self.container))
+
+    def mount(self, m):
+        self.mounts.append(m)
+
+
+class FlatpakTarget(Target):
+    def __init__(self, project, checkout):
+        super(FlatpakTarget, self).__init__('flatpak')
+        self.build_dependencies = False
+        self.project = project
+        self.checkout = checkout
+
+    def setup(self):
+        pass
+
+    def command(self, cmd):
+        command(cmd)
+
+    def checkout_dependencies(self):
+        tree = globals.trees.get(self.project, self.checkout, self)
+        return tree.checkout_dependencies()
+
+    def flatpak(self):
+        return 'flatpak'
+
+    def flatpak_builder(self):
+        b = 'flatpak-builder'
+        if config.has('flatpak_state_dir'):
+            b += ' --state-dir=%s' % config.get('flatpak_state_dir')
+        return b
+
+
+class WindowsTarget(DockerTarget):
     """
     This target exposes the following additional API:
 
     version: Windows version ('xp' or None)
     bits: bitness of Windows (32 or 64)
     name: name of our target e.g. x86_64-w64-mingw32.shared
-    library_prefix: path to Windows libraries
-    tool_path: path to toolchain binaries
+    environment_prefix: path to Windows environment for the appropriate target (libraries and some tools)
+    tool_path: path to 32- and 64-bit tools
     """
-    def __init__(self, version, bits, directory=None):
+    def __init__(self, windows_version, bits, directory, environment_version):
         super(WindowsTarget, self).__init__('windows', directory)
-        self.version = version
+        self.version = windows_version
         self.bits = bits
 
         self.tool_path = '%s/usr/bin' % config.get('mxe_prefix')
@@ -457,48 +600,61 @@ class WindowsTarget(Target):
             self.name = 'i686-w64-mingw32.shared'
         else:
             self.name = 'x86_64-w64-mingw32.shared'
-        self.library_prefix = '%s/usr/%s' % (config.get('mxe_prefix'), self.name)
+        self.environment_prefix = '%s/usr/%s' % (config.get('mxe_prefix'), self.name)
 
-        self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.library_prefix)
+        self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.environment_prefix)
         self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
-        self.set('PATH', '%s/bin:%s:%s' % (self.library_prefix, self.tool_path, os.environ['PATH']))
-        self.set('CC', '%s-gcc' % self.name)
-        self.set('CXX', '%s-g++' % self.name)
+        self.set('PATH', '%s/bin:%s:%s' % (self.environment_prefix, self.tool_path, os.environ['PATH']))
         self.set('LD', '%s-ld' % self.name)
         self.set('RANLIB', '%s-ranlib' % self.name)
         self.set('WINRC', '%s-windres' % self.name)
-        cxx = '-I%s/include -I%s/include' % (self.library_prefix, self.directory)
-        link = '-L%s/lib -L%s/lib' % (self.library_prefix, self.directory)
+        cxx = '-I%s/include -I%s/include' % (self.environment_prefix, self.directory)
+        link = '-L%s/lib -L%s/lib' % (self.environment_prefix, self.directory)
         self.set('CXXFLAGS', '"%s"' % cxx)
         self.set('CPPFLAGS', '')
         self.set('LINKFLAGS', '"%s"' % link)
         self.set('LDFLAGS', '"%s"' % link)
 
+        self.image = 'windows'
+        if environment_version is not None:
+            self.image += '_%s' % environment_version
+
+    def setup(self):
+        super().setup()
+        if self.ccache:
+            self.set('CC', '"ccache %s-gcc"' % self.name)
+            self.set('CXX', '"ccache %s-g++"' % self.name)
+        else:
+            self.set('CC', '%s-gcc' % self.name)
+            self.set('CXX', '%s-g++' % self.name)
+
+    @property
+    def library_prefix(self):
+        log_normal('Deprecated property library_prefix: use environment_prefix')
+        return self.environment_prefix
+
     @property
     def windows_prefix(self):
-        log('Deprecated property windows_prefix')
-        return self.library_prefix
+        log_normal('Deprecated property windows_prefix: use environment_prefix')
+        return self.environment_prefix
 
     @property
     def mingw_prefixes(self):
-        log('Deprecated property mingw_prefixes')
-        return [self.library_prefix]
+        log_normal('Deprecated property mingw_prefixes: use environment_prefix')
+        return [self.environment_prefix]
 
     @property
     def mingw_path(self):
-        log('Deprecated property mingw_path')
+        log_normal('Deprecated property mingw_path: use tool_path')
         return self.tool_path
 
     @property
     def mingw_name(self):
-        log('Deprecated property mingw_name')
+        log_normal('Deprecated property mingw_name: use name')
         return self.name
 
-    def command(self, c):
-        log('host -> %s' % c)
-        command('%s %s' % (self.variables_string(), c))
 
-class LinuxTarget(Target):
+class LinuxTarget(DockerTarget):
     """
     Build for Linux in a docker container.
     This target exposes the following additional API:
@@ -506,6 +662,7 @@ class LinuxTarget(Target):
     distro: distribution ('debian', 'ubuntu', 'centos' or 'fedora')
     version: distribution version (e.g. '12.04', '8', '6.5')
     bits: bitness of the distribution (32 or 64)
+    detail: None or 'appimage' if we are building for appimage
     """
 
     def __init__(self, distro, version, bits, directory=None):
@@ -513,7 +670,7 @@ class LinuxTarget(Target):
         self.distro = distro
         self.version = version
         self.bits = bits
-        self.mounts = []
+        self.detail = None
 
         self.set('CXXFLAGS', '-I%s/include' % self.directory)
         self.set('CPPFLAGS', '')
@@ -522,28 +679,61 @@ class LinuxTarget(Target):
                  '%s/lib/pkgconfig:%s/lib64/pkgconfig:/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig' % (self.directory, self.directory))
         self.set('PATH', '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin')
 
-    def setup(self):
-        image = '%s-%s-%s' % (self.distro, self.version, self.bits)
-        mounts = '-v %s:%s ' % (self.directory, self.directory)
-        for m in self.mounts:
-            mounts += '-v %s:%s ' % (m, m)
-        self.container = command_and_read('%s run -u %s %s -itd %s /bin/bash' % (config.docker(), getpass.getuser(), mounts, image)).read().strip()
-
-    def command(self, cmd):
-        dir = os.path.join(self.directory, os.path.relpath(os.getcwd(), self.directory))
-        command('%s exec -u %s -t %s /bin/bash -c \'export %s; cd %s; %s\'' % (config.docker(), getpass.getuser(), self.container, self.variables_string(), dir, cmd))
+        if self.version is None:
+            self.image = '%s-%s' % (self.distro, self.bits)
+        else:
+            self.image = '%s-%s-%s' % (self.distro, self.version, self.bits)
 
-    def cleanup(self):
-        super(LinuxTarget, self).cleanup()
-        command('%s kill %s' % (config.docker(), self.container))
+    def setup(self):
+        super(LinuxTarget, self).setup()
+        if self.ccache:
+            self.set('CC', '"ccache gcc"')
+            self.set('CXX', '"ccache g++"')
 
-    def test(self, tree, test):
+    def test(self, project, checkout, target, test, options):
         self.append_with_colon('PATH', '%s/bin' % self.directory)
         self.append_with_colon('LD_LIBRARY_PATH', '%s/lib' % self.directory)
-        super(LinuxTarget, self).test(tree, test)
+        super(LinuxTarget, self).test(project, checkout, target, test, options)
+
+
+class AppImageTarget(LinuxTarget):
+    def __init__(self, work):
+        super(AppImageTarget, self).__init__('ubuntu', '18.04', 64, work)
+        self.detail = 'appimage'
+        self.privileged = True
+
+
+def notarize(dmg, bundle_id):
+    p = subprocess.run(
+        ['xcrun', 'altool', '--notarize-app', '-t', 'osx', '-f', dmg, '--primary-bundle-id', bundle_id, '-u', config.get('apple_id'), '-p', config.get('apple_password'), '--output-format', 'xml'],
+        capture_output=True
+        )
+
+    def string_after(process, key):
+        lines = p.stdout.decode('utf-8').splitlines()
+        request_uuid = None
+        for i in range(0, len(lines)):
+            if lines[i].find(key) != -1:
+                return lines[i+1].strip().replace('<string>', '').replace('</string>', '')
+
+        raise Error("Missing expected response %s from Apple" % key)
+
+    request_uuid = string_after(p, "RequestUUID")
+
+    for i in range(0, 30):
+        print('Checking up on %s' % request_uuid)
+        p = subprocess.run(['xcrun', 'altool', '--notarization-info', request_uuid, '-u', apple_id, '-p', apple_password, '--output-format', 'xml'], capture_output=True)
+        status = string_after(p, 'Status')
+        print('Got %s' % status)
+        if status == 'invalid':
+            raise Error("Notarization failed")
+        elif status == 'success':
+            subprocess.run(['xcrun', 'stapler', 'staple', dmg])
+            return
+        time.sleep(30)
+
+    raise Error("Notarization timed out")
 
-    def mount(self, m):
-        self.mounts.append(m)
 
 class OSXTarget(Target):
     def __init__(self, directory=None):
@@ -551,10 +741,18 @@ class OSXTarget(Target):
         self.sdk = config.get('osx_sdk')
         self.sdk_prefix = config.get('osx_sdk_prefix')
         self.environment_prefix = config.get('osx_environment_prefix')
+        self.apple_id = config.get('apple_id')
+        self.apple_password = config.get('apple_password')
+        self.osx_keychain_file = config.get('osx_keychain_file')
+        self.osx_keychain_password = config.get('osx_keychain_password')
 
     def command(self, c):
         command('%s %s' % (self.variables_string(False), c))
 
+    def build(self, *a, **k):
+        self.command('security unlock-keychain -p %s %s' % (self.osx_keychain_password, self.osx_keychain_file))
+        return super().build(*a, **k)
+
 
 class OSXSingleTarget(OSXTarget):
     def __init__(self, bits, directory=None):
@@ -578,26 +776,49 @@ class OSXSingleTarget(OSXTarget):
         self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
         self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
         self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
-
-    def package(self, project, checkout, output_dir):
-        raise Error('cannot package non-universal OS X versions')
+        self.set('CCACHE_BASEDIR', self.directory)
+
+    @Target.ccache.setter
+    def ccache(self, v):
+        Target.ccache.fset(self, v)
+        if v:
+            self.set('CC', '"ccache gcc"')
+            self.set('CXX', '"ccache g++"')
+
+    def package(self, project, checkout, output_dir, options, no_notarize):
+        tree = self.build(project, checkout, options)
+        tree.add_defaults(options)
+        p = self._build_packages(tree, options)
+        for x in p:
+            if not isinstance(x, tuple):
+                raise Error('macOS packages must be returned from cscript as tuples of (dmg-filename, bundle-id)')
+        if not no_notarize:
+            notarize(x[0], x[1])
+        self._copy_packages(tree, [x[0] for x in p], output_dir)
 
 
 class OSXUniversalTarget(OSXTarget):
     def __init__(self, directory=None):
         super(OSXUniversalTarget, self).__init__(directory)
+        self.bits = None
 
-    def package(self, project, checkout, output_dir):
+    def package(self, project, checkout, output_dir, options, no_notarize):
 
         for b in [32, 64]:
             target = OSXSingleTarget(b, os.path.join(self.directory, '%d' % b))
+            target.ccache = self.ccache
             tree = globals.trees.get(project, checkout, target)
-            tree.build_dependencies()
-            tree.build()
+            tree.build_dependencies(options)
+            tree.build(options)
 
         tree = globals.trees.get(project, checkout, self)
         with TreeDirectory(tree):
-            for p in tree.call('package', tree.version):
+            if len(inspect.getfullargspec(tree.cscript['package']).args) == 3:
+                packages = tree.call('package', tree.version, options)
+            else:
+                log_normal("Deprecated cscript package() method with no options parameter")
+                packages = tree.call('package', tree.version)
+            for p in packages:
                 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
 
 class SourceTarget(Target):
@@ -606,13 +827,13 @@ class SourceTarget(Target):
         super(SourceTarget, self).__init__('source')
 
     def command(self, c):
-        log('host -> %s' % c)
+        log_normal('host -> %s' % c)
         command('%s %s' % (self.variables_string(), c))
 
     def cleanup(self):
         rmtree(self.directory)
 
-    def package(self, project, checkout, output_dir):
+    def package(self, project, checkout, output_dir, options):
         tree = globals.trees.get(project, checkout, self)
         with TreeDirectory(tree):
             name = read_wscript_variable(os.getcwd(), 'APPNAME')
@@ -629,6 +850,8 @@ class SourceTarget(Target):
 #    or mageia-version-{32,64}
 #    or osx-{32,64}
 #    or source
+#    or flatpak
+#    or appimage
 # @param debug True to build with debugging symbols (where possible)
 def target_factory(args):
     s = args.target
@@ -636,9 +859,9 @@ def target_factory(args):
     if s.startswith('windows-'):
         x = s.split('-')
         if len(x) == 2:
-            target = WindowsTarget(None, int(x[1]), args.work)
+            target = WindowsTarget(None, int(x[1]), args.work, args.environment_version)
         elif len(x) == 3:
-            target = WindowsTarget(x[1], int(x[2]), args.work)
+            target = WindowsTarget(x[1], int(x[2]), args.work, args.environment_version)
         else:
             raise Error("Bad Windows target name `%s'")
     elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-') or s.startswith('fedora-') or s.startswith('mageia-'):
@@ -650,23 +873,28 @@ def target_factory(args):
         p = s.split('-')
         if len(p) != 2:
             raise Error("Bad Arch target name `%s'; must be arch-32 or arch-64")
-        target = LinuxTarget(p[0], None, p[1], args.work)
+        target = LinuxTarget(p[0], None, int(p[1]), args.work)
     elif s == 'raspbian':
         target = LinuxTarget(s, None, None, args.work)
     elif s.startswith('osx-'):
         target = OSXSingleTarget(int(s.split('-')[1]), args.work)
     elif s == 'osx':
-        if globals.command == 'build':
+        if args.command == 'build':
             target = OSXSingleTarget(64, args.work)
         else:
             target = OSXUniversalTarget(args.work)
     elif s == 'source':
         target = SourceTarget()
+    elif s == 'flatpak':
+        target = FlatpakTarget(args.project, args.checkout)
+    elif s == 'appimage':
+        target = AppImageTarget(args.work)
 
     if target is None:
         raise Error("Bad target `%s'" % s)
 
     target.debug = args.debug
+    target.ccache = args.ccache
 
     if args.environment is not None:
         for e in args.environment:
@@ -697,43 +925,65 @@ class Tree(object):
            required_by -- name of the tree that requires this one
     """
 
-    def __init__(self, name, specifier, target, required_by):
+    def __init__(self, name, specifier, target, required_by, built=False):
         self.name = name
         self.specifier = specifier
         self.target = target
         self.version = None
         self.git_commit = None
-        self.built = False
+        self.built = built
         self.required_by = required_by
 
         cwd = os.getcwd()
+        proj = '%s/src/%s' % (target.directory, self.name)
 
-        flags = ''
-        redirect = ''
-        if globals.quiet:
-            flags = '-q'
-            redirect = '>/dev/null'
-        command('git clone %s %s/%s.git %s/src/%s' % (flags, config.get('git_prefix'), self.name, target.directory, self.name))
-        os.chdir('%s/src/%s' % (target.directory, self.name))
-
-        spec = self.specifier
-        if spec is None:
-            spec = 'master'
+        if not built:
+            flags = ''
+            redirect = ''
+            if globals.quiet:
+                flags = '-q'
+                redirect = '>/dev/null'
+            if config.has('git_reference'):
+                ref = '--reference-if-able %s/%s.git' % (config.get('git_reference'), self.name)
+            else:
+                ref = ''
+            command('git clone %s %s %s/%s.git %s/src/%s' % (flags, ref, config.get('git_prefix'), self.name, target.directory, self.name))
+            os.chdir('%s/src/%s' % (target.directory, self.name))
 
-        command('git checkout %s %s %s' % (flags, spec, redirect))
-        self.git_commit = command_and_read('git rev-parse --short=7 HEAD').readline().strip()
-        command('git submodule init --quiet')
-        command('git submodule update --quiet')
+            spec = self.specifier
+            if spec is None:
+                spec = 'master'
 
-        proj = '%s/src/%s' % (target.directory, self.name)
+            command('git checkout %s %s %s' % (flags, spec, redirect))
+            self.git_commit = command_and_read('git rev-parse --short=7 HEAD')[0].strip()
 
         self.cscript = {}
         exec(open('%s/cscript' % proj).read(), self.cscript)
 
+        if not built:
+            # cscript can include submodules = False to stop submodules being fetched
+            if (not 'submodules' in self.cscript or self.cscript['submodules'] == True) and os.path.exists('.gitmodules'):
+                command('git submodule --quiet init')
+                paths = command_and_read('git config --file .gitmodules --get-regexp path')
+                urls = command_and_read('git config --file .gitmodules --get-regexp url')
+                for path, url in zip(paths, urls):
+                    ref = ''
+                    if config.has('git_reference'):
+                        url = url.split(' ')[1]
+                        ref_path = os.path.join(config.get('git_reference'), os.path.basename(url))
+                        if os.path.exists(ref_path):
+                            ref = '--reference %s' % ref_path
+                    path = path.split(' ')[1]
+                    command('git submodule --quiet update %s %s' % (ref, path))
+
         if os.path.exists('%s/wscript' % proj):
             v = read_wscript_variable(proj, "VERSION");
             if v is not None:
-                self.version = Version(v)
+                try:
+                    self.version = Version(v)
+                except:
+                    tag = command_and_read('git -C %s describe --tags' % proj)[0][1:]
+                    self.version = Version.from_git_tag(tag)
 
         os.chdir(cwd)
 
@@ -741,47 +991,71 @@ class Tree(object):
         with TreeDirectory(self):
             return self.cscript[function](self.target, *args)
 
-    def build_dependencies(self, options=None):
+    def add_defaults(self, options):
+        """Add the defaults from self into a dict options"""
+        if 'option_defaults' in self.cscript:
+            from_cscript = self.cscript['option_defaults']
+            if isinstance(from_cscript, dict):
+                defaults_dict = from_cscript
+            else:
+                log_normal("Deprecated cscript option_defaults method; replace with a dict")
+                defaults_dict = from_cscript()
+            for k, v in defaults_dict.items():
+                if not k in options:
+                    options[k] = v
 
+    def dependencies(self, options):
+        """
+        yield details of the dependencies of this tree.  Each dependency is returned
+        as a tuple of (tree, options, parent_tree).  The 'options' parameter are the options that
+        we want to force for 'self'.
+        """
         if not 'dependencies' in self.cscript:
             return
 
-        if len(inspect.getargspec(self.cscript['dependencies']).args) == 2:
-            deps = self.call('dependencies', options)
+        if len(inspect.getfullargspec(self.cscript['dependencies']).args) == 2:
+            self_options = copy.copy(options)
+            self.add_defaults(self_options)
+            deps = self.call('dependencies', self_options)
         else:
-            log("Deprecated cscipt dependencies() method with no options parameter")
+            log_normal("Deprecated cscript dependencies() method with no options parameter")
             deps = self.call('dependencies')
 
+        # Loop over our immediate dependencies
         for d in deps:
             dep = globals.trees.get(d[0], d[1], self.target, self.name)
 
-            options = dict()
-            # Make the options to pass in from the option_defaults of the thing
-            # we are building and any options specified by the parent.
-            if 'option_defaults' in dep.cscript:
-                for k, v in dep.cscript['option_defaults']().items():
-                    options[k] = v
-
-            if len(d) > 2:
-                for k, v in d[2].items():
-                    options[k] = v
+            # deps only get their options from the parent's cscript
+            dep_options = d[2] if len(d) > 2 else {}
+            for i in dep.dependencies(dep_options):
+                yield i
+            yield (dep, dep_options, self)
 
-            msg = 'Building dependency %s %s of %s' % (d[0], d[1], self.name)
-            if len(options) > 0:
-                msg += ' with options %s' % options
-            log(msg)
+    def checkout_dependencies(self, options={}):
+        for i in self.dependencies(options):
+            pass
 
-            dep.build_dependencies(options)
-            dep.build(options)
+    def build_dependencies(self, options):
+        """
+        Called on the 'main' project tree (-p on the command line) to build all dependencies.
+        'options' will be the ones from the command line.
+        """
+        for i in self.dependencies(options):
+            i[0].build(i[1])
 
-    def build(self, options=None):
+    def build(self, options):
         if self.built:
             return
 
+        log_verbose("Building %s %s %s with %s" % (self.name, self.specifier, self.version, options))
+
         variables = copy.copy(self.target.variables)
 
+        options = copy.copy(options)
+        self.add_defaults(options)
+
         if not globals.dry_run:
-            if len(inspect.getargspec(self.cscript['build']).args) == 2:
+            if len(inspect.getfullargspec(self.cscript['build']).args) == 2:
                 self.call('build', options)
             else:
                 self.call('build')
@@ -789,6 +1063,7 @@ class Tree(object):
         self.target.variables = variables
         self.built = True
 
+
 #
 # Command-line parser
 #
@@ -797,45 +1072,75 @@ def main():
 
     commands = {
         "build": "build project",
-        "package": "package and build project",
-        "release": "release a project using its next version number (changing wscript and tagging)",
+        "package": "build and package the project",
+        "release": "release a project using its next version number (adding a tag)",
         "pot": "build the project's .pot files",
-        "changelog": "generate a simple HTML changelog",
         "manual": "build the project's manual",
         "doxygen": "build the project's Doxygen documentation",
         "latest": "print out the latest version",
-        "test": "run the project's unit tests",
-        "shell": "build the project then start a shell",
+        "test": "build the project and run its unit tests",
+        "shell": "start a shell in the project''s work directory",
         "checkout": "check out the project",
-        "revision": "print the head git revision number"
+        "revision": "print the head git revision number",
+        "dependencies" : "print details of the project's dependencies as a .dot file"
     }
 
-    one_of = "Command is one of:\n"
+    one_of = ""
     summary = ""
     for k, v in commands.items():
-        one_of += "\t%s\t%s\n" % (k, v)
+        one_of += "\t%s%s\n" % (k.ljust(20), v)
         summary += k + " "
 
     parser = argparse.ArgumentParser()
-    parser.add_argument('command', help=summary)
     parser.add_argument('-p', '--project', help='project name')
-    parser.add_argument('--minor', help='minor version number bump', action='store_true')
-    parser.add_argument('--micro', help='micro version number bump', action='store_true')
-    parser.add_argument('--major', help='major version to return with latest', type=int)
     parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
     parser.add_argument('-o', '--output', help='output directory', default='.')
     parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
-    parser.add_argument('-t', '--target', help='target')
+    parser.add_argument('-t', '--target', help='target', action='append')
+    parser.add_argument('--environment-version', help='version of environment to use')
     parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
     parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
     parser.add_argument('-w', '--work', help='override default work directory')
     parser.add_argument('-g', '--git-prefix', help='override configured git prefix')
-    parser.add_argument('--test', help="name of test to run (with `test'), defaults to all")
     parser.add_argument('-n', '--dry-run', help='run the process without building anything', action='store_true')
     parser.add_argument('-e', '--environment', help='pass the value of the named environment variable into the build', action='append')
     parser.add_argument('-m', '--mount', help='mount a given directory in the build environment', action='append')
+    parser.add_argument('--option', help='set an option for the build (use --option key:value)', action='append')
+    parser.add_argument('--ccache', help='use ccache', action='store_true')
+    parser.add_argument('--verbose', help='be verbose', action='store_true')
+
+    subparsers = parser.add_subparsers(help='command to run', dest='command')
+    parser_build = subparsers.add_parser("build", help="build project")
+    parser_package = subparsers.add_parser("package", help="build and package project")
+    parser_package.add_argument('--no-notarize', help='do not notarize .dmg packages', action='store_true')
+    parser_release = subparsers.add_parser("release", help="release a project using its next version number (adding a tag)")
+    parser_release.add_argument('--minor', help='minor version number bump', action='store_true')
+    parser_release.add_argument('--micro', help='micro version number bump', action='store_true')
+    parser_pot = subparsers.add_parser("pot", help="build the project's .pot files")
+    parser_manual = subparsers.add_parser("manual", help="build the project's manual")
+    parser_doxygen = subparsers.add_parser("doxygen", help="build the project's Doxygen documentation")
+    parser_latest = subparsers.add_parser("latest", help="print out the latest version")
+    parser_latest.add_argument('--latest-major', help='major version to return', type=int)
+    parser_latest.add_argument('--latest-minor', help='minor version to return', type=int)
+    parser_test = subparsers.add_parser("test", help="build the project and run its unit tests")
+    parser_test.add_argument('--no-implicit-build', help='do not build first', action='store_true')
+    parser_test.add_argument('--test', help="name of test to run, defaults to all")
+    parser_shell = subparsers.add_parser("shell", help="build the project then start a shell")
+    parser_checkout = subparsers.add_parser("checkout", help="check out the project")
+    parser_revision = subparsers.add_parser("revision", help="print the head git revision number")
+    parser_dependencies = subparsers.add_parser("dependencies", help="print details of the project's dependencies as a .dot file")
+
+    global args
     args = parser.parse_args()
 
+    # Check for incorrect multiple parameters
+    if args.target is not None:
+        if len(args.target) > 1:
+            parser.error('multiple -t options specified')
+            sys.exit(1)
+        else:
+            args.target = args.target[0]
+
     # Override configured stuff
     if args.git_prefix is not None:
         config.set('git_prefix', args.git_prefix)
@@ -851,45 +1156,52 @@ def main():
 
     if args.work is not None:
         args.work = os.path.abspath(args.work)
+        if not os.path.exists(args.work):
+            os.makedirs(args.work)
 
     if args.project is None and args.command != 'shell':
         raise Error('you must specify -p or --project')
 
     globals.quiet = args.quiet
-    globals.command = args.command
+    globals.verbose = args.verbose
     globals.dry_run = args.dry_run
 
-    if not globals.command in commands:
-        e = 'command must be one of:\n' + one_of
-        raise Error('command must be one of:\n%s' % one_of)
-
-    if globals.command == 'build':
+    if args.command == 'build':
         if args.target is None:
             raise Error('you must specify -t or --target')
 
         target = target_factory(args)
-        target.build(args.project, args.checkout)
+        target.build(args.project, args.checkout, get_command_line_options(args))
         if not args.keep:
             target.cleanup()
 
-    elif globals.command == 'package':
+    elif args.command == 'package':
         if args.target is None:
             raise Error('you must specify -t or --target')
 
-        target = target_factory(args)
+        target = None
+        try:
+            target = target_factory(args)
 
-        if target.platform == 'linux':
-            output_dir = os.path.join(args.output, '%s-%s-%d' % (target.distro, target.version, target.bits))
-        else:
-            output_dir = args.output
+            if target.platform == 'linux' and target.detail != "appimage":
+                if target.distro != 'arch':
+                    output_dir = os.path.join(args.output, '%s-%s-%d' % (target.distro, target.version, target.bits))
+                else:
+                    output_dir = os.path.join(args.output, '%s-%d' % (target.distro, target.bits))
+            else:
+                output_dir = args.output
 
-        makedirs(output_dir)
-        target.package(args.project, args.checkout, output_dir)
+            makedirs(output_dir)
+            target.package(args.project, args.checkout, output_dir, get_command_line_options(args), args.no_notarize)
+        except Error as e:
+            if target is not None and not args.keep:
+                target.cleanup()
+            raise
 
-        if not args.keep:
+        if target is not None and not args.keep:
             target.cleanup()
 
-    elif globals.command == 'release':
+    elif args.command == 'release':
         if args.minor is False and args.micro is False:
             raise Error('you must specify --minor or --micro')
 
@@ -904,22 +1216,12 @@ def main():
             version.bump_micro()
 
         with TreeDirectory(tree):
-            set_version_in_wscript(version)
-            append_version_to_changelog(version)
-            append_version_to_debian_changelog(version)
-
-            command('git commit -a -m "Bump version"')
             command('git tag -m "v%s" v%s' % (version, version))
-
-            version.to_devel()
-            set_version_in_wscript(version)
-            command('git commit -a -m "Bump version"')
-            command('git push')
             command('git push --tags')
 
         target.cleanup()
 
-    elif globals.command == 'pot':
+    elif args.command == 'pot':
         target = SourceTarget()
         tree = globals.trees.get(args.project, args.checkout, target)
 
@@ -929,53 +1231,7 @@ def main():
 
         target.cleanup()
 
-    elif globals.command == 'changelog':
-        target = SourceTarget()
-        tree = globals.trees.get(args.project, args.checkout, target)
-
-        with TreeDirectory(tree):
-            text = open('ChangeLog', 'r')
-
-        html = tempfile.NamedTemporaryFile()
-        versions = 8
-
-        last = None
-        changes = []
-
-        while True:
-            l = text.readline()
-            if l == '':
-                break
-
-            if len(l) > 0 and l[0] == "\t":
-                s = l.split()
-                if len(s) == 4 and s[1] == "Version" and s[3] == "released.":
-                    v = Version(s[2])
-                    if v.micro == 0:
-                        if last is not None and len(changes) > 0:
-                            print("<h2>Changes between version %s and %s</h2>" % (s[2], last), file=html)
-                            print("<ul>", file=html)
-                            for c in changes:
-                                print("<li>%s" % c, file=html)
-                            print("</ul>", file=html)
-                        last = s[2]
-                        changes = []
-                        versions -= 1
-                        if versions < 0:
-                            break
-                else:
-                    c = l.strip()
-                    if len(c) > 0:
-                        if c[0] == '*':
-                            changes.append(c[2:])
-                        else:
-                            changes[-1] += " " + c
-
-        copyfile(html.file, '%schangelog.html' % args.output)
-        html.close()
-        target.cleanup()
-
-    elif globals.command == 'manual':
+    elif args.command == 'manual':
         target = SourceTarget()
         tree = globals.trees.get(args.project, args.checkout, target)
 
@@ -988,7 +1244,7 @@ def main():
 
         target.cleanup()
 
-    elif globals.command == 'doxygen':
+    elif args.command == 'doxygen':
         target = SourceTarget()
         tree = globals.trees.get(args.project, args.checkout, target)
 
@@ -1001,15 +1257,17 @@ def main():
 
         target.cleanup()
 
-    elif globals.command == 'latest':
+    elif args.command == 'latest':
         target = SourceTarget()
         tree = globals.trees.get(args.project, args.checkout, target)
 
         with TreeDirectory(tree):
             f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
             latest = None
+            line = 0
             while latest is None:
-                t = f.readline()
+                t = f[line]
+                line += 1
                 m = re.compile(".*\((.*)\).*").match(t)
                 if m:
                     tags = m.group(1).split(', ')
@@ -1019,46 +1277,45 @@ def main():
                             t = s[1]
                         if len(t) > 0 and t[0] == 'v':
                             v = Version(t[1:])
-                            if args.major is None or v.major == args.major:
+                            if (args.latest_major is None or v.major == args.latest_major) and (args.latest_minor is None or v.minor == args.latest_minor):
                                 latest = v
 
         print(latest)
         target.cleanup()
 
-    elif globals.command == 'test':
+    elif args.command == 'test':
         if args.target is None:
             raise Error('you must specify -t or --target')
 
         target = None
         try:
             target = target_factory(args)
-            tree = globals.trees.get(args.project, args.checkout, target)
-            with TreeDirectory(tree):
-                target.test(tree, args.test)
-        except Error as e:
+            options = get_command_line_options(args)
+            if args.no_implicit_build:
+                globals.trees.add_built(args.project, args.checkout, target)
+            else:
+                target.build(args.project, args.checkout, options)
+            target.test(args.project, args.checkout, target, args.test, options)
+        finally:
             if target is not None and not args.keep:
                 target.cleanup()
-            raise
-
-        if target is not None and not args.keep:
-            target.cleanup()
 
-    elif globals.command == 'shell':
+    elif args.command == 'shell':
         if args.target is None:
             raise Error('you must specify -t or --target')
 
         target = target_factory(args)
         target.command('bash')
 
-    elif globals.command == 'revision':
+    elif args.command == 'revision':
 
         target = SourceTarget()
         tree = globals.trees.get(args.project, args.checkout, target)
         with TreeDirectory(tree):
-            print(command_and_read('git rev-parse HEAD').readline().strip()[:7])
+            print(command_and_read('git rev-parse HEAD')[0].strip()[:7])
         target.cleanup()
 
-    elif globals.command == 'checkout':
+    elif args.command == 'checkout':
 
         if args.output is None:
             raise Error('you must specify -o or --output')
@@ -1069,8 +1326,19 @@ def main():
             shutil.copytree('.', args.output)
         target.cleanup()
 
-    else:
-        raise Error('invalid command %s' % globals.command)
+    elif args.command == 'dependencies':
+        if args.target is None:
+            raise Error('you must specify -t or --target')
+        if args.checkout is None:
+            raise Error('you must specify -c or --checkout')
+
+        target = target_factory(args)
+        tree = globals.trees.get(args.project, args.checkout, target)
+        print("strict digraph {")
+        for d in list(tree.dependencies({})):
+            print("%s -> %s;" % (d[2].name.replace("-", "-"), d[0].name.replace("-", "_")))
+        print("}")
+
 
 try:
     main()