3 # Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 from __future__ import print_function
27 import multiprocessing
38 TEMPORARY_DIRECTORY = '/var/tmp'
40 class Error(Exception):
41 def __init__(self, value):
50 Store for Tree objects which re-uses already-created objects
51 and checks for requests for different versions of the same thing.
57 def get(self, name, specifier, target, required_by=None):
59 if t.name == name and t.specifier == specifier and t.target == target:
61 elif t.name == name and t.specifier != specifier:
62 a = specifier if specifier is not None else "[Any]"
63 if required_by is not None:
64 a += ' by %s' % required_by
65 b = t.specifier if t.specifier is not None else "[Any]"
66 if t.required_by is not None:
67 b += ' by %s' % t.required_by
68 raise Error('conflicting versions of %s required (%s versus %s)' % (name, a, b))
70 nt = Tree(name, specifier, target, required_by)
74 def add_built(self, name, specifier, target):
75 self.trees.append(Tree(name, specifier, target, None, built=True))
92 def __init__(self, key, default=None):
96 def offer(self, key, value):
100 class BoolOption(object):
101 def __init__(self, key):
105 def offer(self, key, value):
107 self.value = (value == 'yes' or value == '1' or value == 'true')
111 self.options = [ Option('mxe_prefix'),
112 Option('git_prefix'),
113 Option('git_reference'),
114 Option('osx_environment_prefix'),
115 Option('osx_sdk_prefix'),
117 Option('osx_keychain_file'),
118 Option('osx_keychain_password'),
120 Option('apple_password'),
121 BoolOption('docker_sudo'),
122 BoolOption('docker_no_user'),
123 Option('docker_hub_repository'),
124 Option('flatpak_state_dir'),
125 Option('parallel', multiprocessing.cpu_count()) ]
127 config_dir = '%s/.config' % os.path.expanduser('~')
128 if not os.path.exists(config_dir):
130 config_file = '%s/cdist' % config_dir
131 if not os.path.exists(config_file):
132 f = open(config_file, 'w')
133 for o in self.options:
134 print('# %s ' % o.key, file=f)
136 print('Template config file written to %s; please edit and try again.' % config_file, file=sys.stderr)
140 f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
146 if len(l) > 0 and l[0] == '#':
149 s = l.strip().split()
151 for k in self.options:
157 for o in self.options:
158 if o.key == k and o.value is not None:
163 for o in self.options:
166 raise Error('Required setting %s not found' % k)
170 for o in self.options:
174 if self.get('docker_sudo'):
186 if not globals.quiet:
187 print('\x1b[33m* %s\x1b[0m' % m)
191 print('\x1b[35m* %s\x1b[0m' % m)
193 def escape_spaces(s):
194 return s.replace(' ', '\\ ')
197 """Escape a host:filename string for use with an scp command"""
199 assert(len(s) == 1 or len(s) == 2)
201 return '%s:"\'%s\'"' % (s[0], s[1])
203 return '\"%s\"' % s[0]
206 return '\"%s\"' % n.substr(' ', '\\ ')
209 log_normal('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
210 if b.startswith('s3://'):
211 command('s3cmd -P -r put "%s" "%s"' % (a, b))
213 command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
216 log_normal('copy %s -> %s with cwd %s' % (scp_escape(a), scp_escape(b), os.getcwd()))
217 if b.startswith('s3://'):
218 command('s3cmd -P put "%s" "%s"' % (a, b))
224 temp_path = os.path.join(os.path.dirname(path), ".tmp." + os.path.basename(path))
225 command('scp %s %s' % (scp_escape(a), scp_escape(host + ":" + temp_path)))
226 command('ssh %s -- mv "%s" "%s"' % (host, escape_spaces(temp_path), escape_spaces(path)))
228 command('scp %s %s' % (scp_escape(a), scp_escape(b)))
232 Make directories either locally or on a remote host; remotely if
233 d includes a colon, otherwise locally.
235 if d.startswith('s3://'):
236 # No need to create folders on S3
239 if d.find(':') == -1:
247 command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
250 log_normal('remove %s' % a)
254 log_normal('remove %s' % a)
255 shutil.rmtree(a, ignore_errors=True)
260 r = subprocess.run(c, shell=True)
261 if r.returncode != 0:
262 raise Error('command %s failed (%d)' % (c, r.returncode))
263 except Exception as e:
264 raise Error('command %s failed (%s)' % (c, e))
266 def command_and_read(c):
268 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
269 (out, err) = p.communicate()
270 if p.returncode != 0:
271 raise Error('command %s failed (%s)' % (c, err))
272 return str(out, 'utf-8').splitlines()
274 def read_wscript_variable(directory, variable):
275 f = open('%s/wscript' % directory, 'r')
282 if len(s) == 3 and s[0] == variable:
290 def devel_to_git(git_commit, filename):
291 if git_commit is not None:
292 filename = filename.replace('devel', '-%s' % git_commit)
296 def get_command_line_options(args):
297 """Get the options specified by --option on the command line"""
299 if args.option is not None:
300 for o in args.option:
303 raise Error("Bad option `%s'" % o)
305 options[b[0]] = False
314 def __init__(self, tree):
317 self.cwd = os.getcwd()
318 os.chdir('%s/src/%s' % (self.tree.target.directory, self.tree.name))
319 def __exit__(self, type, value, traceback):
327 def __init__(self, s):
330 if s.startswith("'"):
335 if s.endswith('devel'):
339 if s.endswith('pre'):
343 self.major = int(p[0])
344 self.minor = int(p[1])
346 self.micro = int(p[2])
351 def from_git_tag(cls, tag):
352 bits = tag.split('-')
354 if len(bits) > 1 and int(bits[1]) > 0:
358 def bump_minor(self):
362 def bump_micro(self):
368 def to_release(self):
372 s = '%d.%d.%d' % (self.major, self.minor, self.micro)
382 class Target(object):
384 Class representing the target that we are building for. This is exposed to cscripts,
385 though not all of it is guaranteed 'API'. cscripts may expect:
387 platform: platform string (e.g. 'windows', 'linux', 'osx')
388 parallel: number of parallel jobs to run
389 directory: directory to work in
390 variables: dict of environment variables
391 debug: True to build a debug version, otherwise False
392 ccache: True to use ccache, False to not
393 set(a, b): set the value of variable 'a' to 'b'
394 unset(a): unset the value of variable 'a'
395 command(c): run the command 'c' in the build environment
399 def __init__(self, platform, directory=None):
401 platform -- platform string (e.g. 'windows', 'linux', 'osx')
402 directory -- directory to work in; if None we will use a temporary directory
403 Temporary directories will be removed after use; specified directories will not.
405 self.platform = platform
406 self.parallel = int(config.get('parallel'))
408 # Environment variables that we will use when we call cscripts
412 # True to build our dependencies ourselves; False if this is taken care
413 # of in some other way
414 self.build_dependencies = True
416 if directory is None:
417 self.directory = tempfile.mkdtemp('', 'tmp', TEMPORARY_DIRECTORY)
419 self.set('CCACHE_BASEDIR', os.path.realpath(self.directory))
420 self.set('CCACHE_NOHASHDIR', '')
422 self.directory = os.path.realpath(directory)
429 def _build_packages(self, tree, options):
430 if len(inspect.getfullargspec(tree.cscript['package']).args) == 3:
431 packages = tree.call('package', tree.version, options)
433 log_normal("Deprecated cscript package() method with no options parameter")
434 packages = tree.call('package', tree.version)
436 return packages if isinstance(packages, list) else [packages]
438 def _copy_packages(self, tree, packages, output_dir):
440 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
442 def package(self, project, checkout, output_dir, options, no_notarize):
443 tree = self.build(project, checkout, options)
444 tree.add_defaults(options)
445 p = self._build_packages(tree, options)
446 self._copy_packages(tree, p, output_dir)
448 def build(self, project, checkout, options):
449 tree = globals.trees.get(project, checkout, self)
450 if self.build_dependencies:
451 tree.build_dependencies(options)
455 def test(self, project, checkout, target, test, options):
456 """test is the test case to run, or None"""
457 tree = globals.trees.get(project, checkout, target)
459 tree.add_defaults(options)
460 with TreeDirectory(tree):
461 if len(inspect.getfullargspec(tree.cscript['test']).args) == 3:
462 return tree.call('test', options, test)
464 log_normal('Deprecated cscript test() method with no options parameter')
465 return tree.call('test', test)
468 self.variables[a] = b
471 del(self.variables[a])
474 return self.variables[a]
476 def append(self, k, v, s):
477 if (not k in self.variables) or len(self.variables[k]) == 0:
478 self.variables[k] = '"%s"' % v
480 e = self.variables[k]
481 if e[0] == '"' and e[-1] == '"':
482 self.variables[k] = '"%s%s%s"' % (e[1:-1], s, v)
484 self.variables[k] = '"%s%s%s"' % (e, s, v)
486 def append_with_space(self, k, v):
487 return self.append(k, v, ' ')
489 def append_with_colon(self, k, v):
490 return self.append(k, v, ':')
492 def variables_string(self, escaped_quotes=False):
494 for k, v in self.variables.items():
496 v = v.replace('"', '\\"')
497 e += '%s=%s ' % (k, v)
502 rmtree(self.directory)
516 class DockerTarget(Target):
517 def __init__(self, platform, directory):
518 super(DockerTarget, self).__init__(platform, directory)
520 self.privileged = False
523 if config.get('docker_no_user'):
525 return '-u %s' % getpass.getuser()
527 def _mount_option(self, d):
528 return '-v %s:%s ' % (os.path.realpath(d), os.path.realpath(d))
531 opts = self._mount_option(self.directory)
532 for m in self.mounts:
533 opts += self._mount_option(m)
534 if config.has('git_reference'):
535 opts += self._mount_option(config.get('git_reference'))
537 opts += '--privileged=true '
539 opts += "-e CCACHE_DIR=/ccache/%s-%d --mount source=ccache,target=/ccache" % (self.image, os.getuid())
542 if config.has('docker_hub_repository'):
543 tag = '%s:%s' % (config.get('docker_hub_repository'), tag)
545 self.container = command_and_read('%s run %s %s -itd %s /bin/bash' % (config.docker(), self._user_tag(), opts, tag))[0].strip()
547 def command(self, cmd):
548 dir = os.path.join(self.directory, os.path.relpath(os.getcwd(), self.directory))
549 interactive_flag = '-i ' if sys.stdin.isatty() else ''
550 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))
553 super(DockerTarget, self).cleanup()
554 command('%s kill %s' % (config.docker(), self.container))
557 self.mounts.append(m)
560 class FlatpakTarget(Target):
561 def __init__(self, project, checkout):
562 super(FlatpakTarget, self).__init__('flatpak')
563 self.build_dependencies = False
564 self.project = project
565 self.checkout = checkout
570 def command(self, cmd):
573 def checkout_dependencies(self):
574 tree = globals.trees.get(self.project, self.checkout, self)
575 return tree.checkout_dependencies()
580 def flatpak_builder(self):
581 b = 'flatpak-builder'
582 if config.has('flatpak_state_dir'):
583 b += ' --state-dir=%s' % config.get('flatpak_state_dir')
587 class WindowsDockerTarget(DockerTarget):
589 This target exposes the following additional API:
591 version: Windows version ('xp' or None)
592 bits: bitness of Windows (32 or 64)
593 name: name of our target e.g. x86_64-w64-mingw32.shared
594 environment_prefix: path to Windows environment for the appropriate target (libraries and some tools)
595 tool_path: path to 32- and 64-bit tools
597 def __init__(self, windows_version, bits, directory, environment_version):
598 super(WindowsDockerTarget, self).__init__('windows', directory)
599 self.version = windows_version
602 self.tool_path = '%s/usr/bin' % config.get('mxe_prefix')
604 self.name = 'i686-w64-mingw32.shared'
606 self.name = 'x86_64-w64-mingw32.shared'
607 self.environment_prefix = '%s/usr/%s' % (config.get('mxe_prefix'), self.name)
609 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.environment_prefix)
610 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
611 self.set('PATH', '%s/bin:%s:%s' % (self.environment_prefix, self.tool_path, os.environ['PATH']))
612 self.set('LD', '%s-ld' % self.name)
613 self.set('RANLIB', '%s-ranlib' % self.name)
614 self.set('WINRC', '%s-windres' % self.name)
615 cxx = '-I%s/include -I%s/include' % (self.environment_prefix, self.directory)
616 link = '-L%s/lib -L%s/lib' % (self.environment_prefix, self.directory)
617 self.set('CXXFLAGS', '"%s"' % cxx)
618 self.set('CPPFLAGS', '')
619 self.set('LINKFLAGS', '"%s"' % link)
620 self.set('LDFLAGS', '"%s"' % link)
622 self.image = 'windows'
623 if environment_version is not None:
624 self.image += '_%s' % environment_version
629 self.set('CC', '"ccache %s-gcc"' % self.name)
630 self.set('CXX', '"ccache %s-g++"' % self.name)
632 self.set('CC', '%s-gcc' % self.name)
633 self.set('CXX', '%s-g++' % self.name)
636 def library_prefix(self):
637 log_normal('Deprecated property library_prefix: use environment_prefix')
638 return self.environment_prefix
641 def windows_prefix(self):
642 log_normal('Deprecated property windows_prefix: use environment_prefix')
643 return self.environment_prefix
646 def mingw_prefixes(self):
647 log_normal('Deprecated property mingw_prefixes: use environment_prefix')
648 return [self.environment_prefix]
651 def mingw_path(self):
652 log_normal('Deprecated property mingw_path: use tool_path')
653 return self.tool_path
656 def mingw_name(self):
657 log_normal('Deprecated property mingw_name: use name')
661 class WindowsNativeTarget(Target):
663 This target exposes the following additional API:
665 version: Windows version ('xp' or None)
666 bits: bitness of Windows (32 or 64)
667 name: name of our target e.g. x86_64-w64-mingw32.shared
668 environment_prefix: path to Windows environment for the appropriate target (libraries and some tools)
670 def __init__(self, directory):
671 super().__init__('windows', directory)
675 self.environment_prefix = config.get('windows_native_environmnet_prefix')
677 self.set('PATH', '%s/bin:%s' % (self.environment_prefix, os.environ['PATH']))
679 def command(self, cmd):
683 class LinuxTarget(DockerTarget):
685 Build for Linux in a docker container.
686 This target exposes the following additional API:
688 distro: distribution ('debian', 'ubuntu', 'centos' or 'fedora')
689 version: distribution version (e.g. '12.04', '8', '6.5')
690 bits: bitness of the distribution (32 or 64)
691 detail: None or 'appimage' if we are building for appimage
694 def __init__(self, distro, version, bits, directory=None):
695 super(LinuxTarget, self).__init__('linux', directory)
697 self.version = version
701 self.set('CXXFLAGS', '-I%s/include' % self.directory)
702 self.set('CPPFLAGS', '')
703 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
704 self.set('PKG_CONFIG_PATH',
705 '%s/lib/pkgconfig:%s/lib64/pkgconfig:/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig' % (self.directory, self.directory))
706 self.set('PATH', '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin')
708 if self.version is None:
709 self.image = '%s-%s' % (self.distro, self.bits)
711 self.image = '%s-%s-%s' % (self.distro, self.version, self.bits)
714 super(LinuxTarget, self).setup()
716 self.set('CC', '"ccache gcc"')
717 self.set('CXX', '"ccache g++"')
719 def test(self, project, checkout, target, test, options):
720 self.append_with_colon('PATH', '%s/bin' % self.directory)
721 self.append_with_colon('LD_LIBRARY_PATH', '%s/lib' % self.directory)
722 super(LinuxTarget, self).test(project, checkout, target, test, options)
725 class AppImageTarget(LinuxTarget):
726 def __init__(self, work):
727 super(AppImageTarget, self).__init__('ubuntu', '18.04', 64, work)
728 self.detail = 'appimage'
729 self.privileged = True
732 def notarize(dmg, bundle_id):
734 ['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'],
738 def string_after(process, key):
739 lines = p.stdout.decode('utf-8').splitlines()
740 for i in range(0, len(lines)):
741 if lines[i].find(key) != -1:
742 return lines[i+1].strip().replace('<string>', '').replace('</string>', '')
744 request_uuid = string_after(p, "RequestUUID")
745 if request_uuid is None:
746 raise Error('No RequestUUID found in response from Apple')
748 for i in range(0, 30):
749 print('Checking up on %s' % request_uuid)
750 p = subprocess.run(['xcrun', 'altool', '--notarization-info', request_uuid, '-u', config.get('apple_id'), '-p', config.get('apple_password'), '--output-format', 'xml'], capture_output=True)
751 status = string_after(p, 'Status')
752 print('Got %s' % status)
753 if status == 'invalid':
754 raise Error("Notarization failed")
755 elif status == 'success':
756 subprocess.run(['xcrun', 'stapler', 'staple', dmg])
759 print("Could not understand xcrun response")
763 raise Error("Notarization timed out")
766 class OSXTarget(Target):
767 def __init__(self, directory=None):
768 super(OSXTarget, self).__init__('osx', directory)
769 self.sdk = config.get('osx_sdk')
770 self.sdk_prefix = config.get('osx_sdk_prefix')
771 self.environment_prefix = config.get('osx_environment_prefix')
772 self.apple_id = config.get('apple_id')
773 self.apple_password = config.get('apple_password')
774 self.osx_keychain_file = config.get('osx_keychain_file')
775 self.osx_keychain_password = config.get('osx_keychain_password')
777 def command(self, c):
778 command('%s %s' % (self.variables_string(False), c))
780 def build(self, *a, **k):
781 self.command('security unlock-keychain -p %s %s' % (self.osx_keychain_password, self.osx_keychain_file))
782 return super().build(*a, **k)
785 class OSXSingleTarget(OSXTarget):
786 def __init__(self, bits, directory=None):
787 super(OSXSingleTarget, self).__init__(directory)
795 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (self.sdk_prefix, self.sdk, arch)
796 enviro = '%s/%d' % (config.get('osx_environment_prefix'), bits)
798 # Environment variables
799 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
800 self.set('CPPFLAGS', '')
801 self.set('CXXFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
802 self.set('LDFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
803 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
804 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
805 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
806 self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
807 self.set('CCACHE_BASEDIR', self.directory)
809 @Target.ccache.setter
811 Target.ccache.fset(self, v)
813 self.set('CC', '"ccache gcc"')
814 self.set('CXX', '"ccache g++"')
816 def package(self, project, checkout, output_dir, options, no_notarize):
817 tree = self.build(project, checkout, options)
818 tree.add_defaults(options)
819 p = self._build_packages(tree, options)
821 if not isinstance(x, tuple):
822 raise Error('macOS packages must be returned from cscript as tuples of (dmg-filename, bundle-id)')
825 self._copy_packages(tree, [x[0] for x in p], output_dir)
828 class OSXUniversalTarget(OSXTarget):
829 def __init__(self, directory=None):
830 super(OSXUniversalTarget, self).__init__(directory)
833 def package(self, project, checkout, output_dir, options, no_notarize):
836 target = OSXSingleTarget(b, os.path.join(self.directory, '%d' % b))
837 target.ccache = self.ccache
838 tree = globals.trees.get(project, checkout, target)
839 tree.build_dependencies(options)
842 tree = globals.trees.get(project, checkout, self)
843 with TreeDirectory(tree):
844 if len(inspect.getfullargspec(tree.cscript['package']).args) == 3:
845 packages = tree.call('package', tree.version, options)
847 log_normal("Deprecated cscript package() method with no options parameter")
848 packages = tree.call('package', tree.version)
850 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
852 class SourceTarget(Target):
853 """Build a source .tar.bz2"""
855 super(SourceTarget, self).__init__('source')
857 def command(self, c):
858 log_normal('host -> %s' % c)
859 command('%s %s' % (self.variables_string(), c))
862 rmtree(self.directory)
864 def package(self, project, checkout, output_dir, options, no_notarize):
865 tree = globals.trees.get(project, checkout, self)
866 with TreeDirectory(tree):
867 name = read_wscript_variable(os.getcwd(), 'APPNAME')
868 command('./waf dist')
869 p = os.path.abspath('%s-%s.tar.bz2' % (name, tree.version))
870 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
872 # @param s Target string:
874 # or ubuntu-version-{32,64}
875 # or debian-version-{32,64}
876 # or centos-version-{32,64}
877 # or fedora-version-{32,64}
878 # or mageia-version-{32,64}
883 # @param debug True to build with debugging symbols (where possible)
884 def target_factory(args):
887 if s.startswith('windows-'):
889 if platform.system() == "Windows":
890 target = WindowsNativeTarget(args.work)
893 target = WindowsDockerTarget(None, int(x[1]), args.work, args.environment_version)
895 target = WindowsDockerTarget(x[1], int(x[2]), args.work, args.environment_version)
897 raise Error("Bad Windows target name `%s'")
898 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-') or s.startswith('fedora-') or s.startswith('mageia-'):
901 raise Error("Bad Linux target name `%s'; must be something like ubuntu-16.04-32 (i.e. distro-version-bits)" % s)
902 target = LinuxTarget(p[0], p[1], int(p[2]), args.work)
903 elif s.startswith('arch-'):
906 raise Error("Bad Arch target name `%s'; must be arch-32 or arch-64")
907 target = LinuxTarget(p[0], None, int(p[1]), args.work)
908 elif s == 'raspbian':
909 target = LinuxTarget(s, None, None, args.work)
910 elif s.startswith('osx-'):
911 target = OSXSingleTarget(int(s.split('-')[1]), args.work)
913 if args.command == 'build':
914 target = OSXSingleTarget(64, args.work)
916 target = OSXUniversalTarget(args.work)
918 target = SourceTarget()
920 target = FlatpakTarget(args.project, args.checkout)
921 elif s == 'appimage':
922 target = AppImageTarget(args.work)
925 raise Error("Bad target `%s'" % s)
927 target.debug = args.debug
928 target.ccache = args.ccache
930 if args.environment is not None:
931 for e in args.environment:
932 target.set(e, os.environ[e])
934 if args.mount is not None:
947 """Description of a tree, which is a checkout of a project,
948 possibly built. This class is never exposed to cscripts.
950 name -- name of git repository (without the .git)
951 specifier -- git tag or revision to use
952 target -- target object that we are using
953 version -- version from the wscript (if one is present)
954 git_commit -- git revision that is actually being used
955 built -- true if the tree has been built yet in this run
956 required_by -- name of the tree that requires this one
959 def __init__(self, name, specifier, target, required_by, built=False):
961 self.specifier = specifier
964 self.git_commit = None
966 self.required_by = required_by
969 proj = '%s/src/%s' % (target.directory, self.name)
976 redirect = '>/dev/null'
977 if config.has('git_reference'):
978 ref = '--reference-if-able %s/%s.git' % (config.get('git_reference'), self.name)
981 command('git clone %s %s %s/%s.git %s/src/%s' % (flags, ref, config.get('git_prefix'), self.name, target.directory, self.name))
982 os.chdir('%s/src/%s' % (target.directory, self.name))
984 spec = self.specifier
988 command('git checkout %s %s %s' % (flags, spec, redirect))
989 self.git_commit = command_and_read('git rev-parse --short=7 HEAD')[0].strip()
992 exec(open('%s/cscript' % proj).read(), self.cscript)
995 # cscript can include submodules = False to stop submodules being fetched
996 if (not 'submodules' in self.cscript or self.cscript['submodules'] == True) and os.path.exists('.gitmodules'):
997 command('git submodule --quiet init')
998 paths = command_and_read('git config --file .gitmodules --get-regexp path')
999 urls = command_and_read('git config --file .gitmodules --get-regexp url')
1000 for path, url in zip(paths, urls):
1002 if config.has('git_reference'):
1003 url = url.split(' ')[1]
1004 ref_path = os.path.join(config.get('git_reference'), os.path.basename(url))
1005 if os.path.exists(ref_path):
1006 ref = '--reference %s' % ref_path
1007 path = path.split(' ')[1]
1008 command('git submodule --quiet update %s %s' % (ref, path))
1010 if os.path.exists('%s/wscript' % proj):
1011 v = read_wscript_variable(proj, "VERSION");
1014 self.version = Version(v)
1017 tag = command_and_read('git -C %s describe --tags' % proj)[0][1:]
1018 self.version = Version.from_git_tag(tag)
1020 # We'll leave version as None if we can't read it; maybe this is a bad idea
1021 # Should probably just install git on the Windows VM
1026 def call(self, function, *args):
1027 with TreeDirectory(self):
1028 return self.cscript[function](self.target, *args)
1030 def add_defaults(self, options):
1031 """Add the defaults from self into a dict options"""
1032 if 'option_defaults' in self.cscript:
1033 from_cscript = self.cscript['option_defaults']
1034 if isinstance(from_cscript, dict):
1035 defaults_dict = from_cscript
1037 log_normal("Deprecated cscript option_defaults method; replace with a dict")
1038 defaults_dict = from_cscript()
1039 for k, v in defaults_dict.items():
1040 if not k in options:
1043 def dependencies(self, options):
1045 yield details of the dependencies of this tree. Each dependency is returned
1046 as a tuple of (tree, options, parent_tree). The 'options' parameter are the options that
1047 we want to force for 'self'.
1049 if not 'dependencies' in self.cscript:
1052 if len(inspect.getfullargspec(self.cscript['dependencies']).args) == 2:
1053 self_options = copy.copy(options)
1054 self.add_defaults(self_options)
1055 deps = self.call('dependencies', self_options)
1057 log_normal("Deprecated cscript dependencies() method with no options parameter")
1058 deps = self.call('dependencies')
1060 # Loop over our immediate dependencies
1062 dep = globals.trees.get(d[0], d[1], self.target, self.name)
1064 # deps only get their options from the parent's cscript
1065 dep_options = d[2] if len(d) > 2 else {}
1066 for i in dep.dependencies(dep_options):
1068 yield (dep, dep_options, self)
1070 def checkout_dependencies(self, options={}):
1071 for i in self.dependencies(options):
1074 def build_dependencies(self, options):
1076 Called on the 'main' project tree (-p on the command line) to build all dependencies.
1077 'options' will be the ones from the command line.
1079 for i in self.dependencies(options):
1082 def build(self, options):
1086 log_verbose("Building %s %s %s with %s" % (self.name, self.specifier, self.version, options))
1088 variables = copy.copy(self.target.variables)
1090 options = copy.copy(options)
1091 self.add_defaults(options)
1093 if not globals.dry_run:
1094 if len(inspect.getfullargspec(self.cscript['build']).args) == 2:
1095 self.call('build', options)
1099 self.target.variables = variables
1104 # Command-line parser
1110 "build": "build project",
1111 "package": "build and package the project",
1112 "release": "release a project using its next version number (adding a tag)",
1113 "pot": "build the project's .pot files",
1114 "manual": "build the project's manual",
1115 "doxygen": "build the project's Doxygen documentation",
1116 "latest": "print out the latest version",
1117 "test": "build the project and run its unit tests",
1118 "shell": "start a shell in the project''s work directory",
1119 "checkout": "check out the project",
1120 "revision": "print the head git revision number",
1121 "dependencies" : "print details of the project's dependencies as a .dot file"
1126 for k, v in commands.items():
1127 one_of += "\t%s%s\n" % (k.ljust(20), v)
1130 parser = argparse.ArgumentParser()
1131 parser.add_argument('-p', '--project', help='project name')
1132 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
1133 parser.add_argument('-o', '--output', help='output directory', default='.')
1134 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
1135 parser.add_argument('-t', '--target', help='target', action='append')
1136 parser.add_argument('--environment-version', help='version of environment to use')
1137 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
1138 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
1139 parser.add_argument('-w', '--work', help='override default work directory')
1140 parser.add_argument('-g', '--git-prefix', help='override configured git prefix')
1141 parser.add_argument('-n', '--dry-run', help='run the process without building anything', action='store_true')
1142 parser.add_argument('-e', '--environment', help='pass the value of the named environment variable into the build', action='append')
1143 parser.add_argument('-m', '--mount', help='mount a given directory in the build environment', action='append')
1144 parser.add_argument('--option', help='set an option for the build (use --option key:value)', action='append')
1145 parser.add_argument('--ccache', help='use ccache', action='store_true')
1146 parser.add_argument('--verbose', help='be verbose', action='store_true')
1148 subparsers = parser.add_subparsers(help='command to run', dest='command')
1149 parser_build = subparsers.add_parser("build", help="build project")
1150 parser_package = subparsers.add_parser("package", help="build and package project")
1151 parser_package.add_argument('--no-notarize', help='do not notarize .dmg packages', action='store_true')
1152 parser_release = subparsers.add_parser("release", help="release a project using its next version number (adding a tag)")
1153 parser_release.add_argument('--minor', help='minor version number bump', action='store_true')
1154 parser_release.add_argument('--micro', help='micro version number bump', action='store_true')
1155 parser_pot = subparsers.add_parser("pot", help="build the project's .pot files")
1156 parser_manual = subparsers.add_parser("manual", help="build the project's manual")
1157 parser_doxygen = subparsers.add_parser("doxygen", help="build the project's Doxygen documentation")
1158 parser_latest = subparsers.add_parser("latest", help="print out the latest version")
1159 parser_latest.add_argument('--major', help='major version to return', type=int)
1160 parser_latest.add_argument('--minor', help='minor version to return', type=int)
1161 parser_test = subparsers.add_parser("test", help="build the project and run its unit tests")
1162 parser_test.add_argument('--no-implicit-build', help='do not build first', action='store_true')
1163 parser_test.add_argument('--test', help="name of test to run, defaults to all")
1164 parser_shell = subparsers.add_parser("shell", help="build the project then start a shell")
1165 parser_checkout = subparsers.add_parser("checkout", help="check out the project")
1166 parser_revision = subparsers.add_parser("revision", help="print the head git revision number")
1167 parser_dependencies = subparsers.add_parser("dependencies", help="print details of the project's dependencies as a .dot file")
1170 args = parser.parse_args()
1172 # Check for incorrect multiple parameters
1173 if args.target is not None:
1174 if len(args.target) > 1:
1175 parser.error('multiple -t options specified')
1178 args.target = args.target[0]
1180 # Override configured stuff
1181 if args.git_prefix is not None:
1182 config.set('git_prefix', args.git_prefix)
1184 if args.output.find(':') == -1:
1185 # This isn't of the form host:path so make it absolute
1186 args.output = os.path.abspath(args.output) + '/'
1188 if args.output[-1] != ':' and args.output[-1] != '/':
1191 # Now, args.output is 'host:', 'host:path/' or 'path/'
1193 if args.work is not None:
1194 args.work = os.path.abspath(args.work)
1195 if not os.path.exists(args.work):
1196 os.makedirs(args.work)
1198 if args.project is None and args.command != 'shell':
1199 raise Error('you must specify -p or --project')
1201 globals.quiet = args.quiet
1202 globals.verbose = args.verbose
1203 globals.dry_run = args.dry_run
1205 if args.command == 'build':
1206 if args.target is None:
1207 raise Error('you must specify -t or --target')
1209 target = target_factory(args)
1210 target.build(args.project, args.checkout, get_command_line_options(args))
1214 elif args.command == 'package':
1215 if args.target is None:
1216 raise Error('you must specify -t or --target')
1220 target = target_factory(args)
1222 if target.platform == 'linux' and target.detail != "appimage":
1223 if target.distro != 'arch':
1224 output_dir = os.path.join(args.output, '%s-%s-%d' % (target.distro, target.version, target.bits))
1226 output_dir = os.path.join(args.output, '%s-%d' % (target.distro, target.bits))
1228 output_dir = args.output
1230 makedirs(output_dir)
1231 target.package(args.project, args.checkout, output_dir, get_command_line_options(args), args.no_notarize)
1233 if target is not None and not args.keep:
1237 if target is not None and not args.keep:
1240 elif args.command == 'release':
1241 if args.minor is False and args.micro is False:
1242 raise Error('you must specify --minor or --micro')
1244 target = SourceTarget()
1245 tree = globals.trees.get(args.project, args.checkout, target)
1247 version = tree.version
1248 version.to_release()
1250 version.bump_minor()
1252 version.bump_micro()
1254 with TreeDirectory(tree):
1255 command('git tag -m "v%s" v%s' % (version, version))
1256 command('git push --tags')
1260 elif args.command == 'pot':
1261 target = SourceTarget()
1262 tree = globals.trees.get(args.project, args.checkout, target)
1264 pots = tree.call('make_pot')
1266 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
1270 elif args.command == 'manual':
1271 target = SourceTarget()
1272 tree = globals.trees.get(args.project, args.checkout, target)
1274 outs = tree.call('make_manual')
1276 if os.path.isfile(o):
1277 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
1279 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
1283 elif args.command == 'doxygen':
1284 target = SourceTarget()
1285 tree = globals.trees.get(args.project, args.checkout, target)
1287 dirs = tree.call('make_doxygen')
1288 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
1292 copytree(d, args.output)
1296 elif args.command == 'latest':
1297 target = SourceTarget()
1298 tree = globals.trees.get(args.project, args.checkout, target)
1300 with TreeDirectory(tree):
1301 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
1304 while latest is None:
1307 m = re.compile(".*\((.*)\).*").match(t)
1309 tags = m.group(1).split(', ')
1314 if len(t) > 0 and t[0] == 'v':
1316 if (args.major is None or v.major == args.major) and (args.minor is None or v.minor == args.minor):
1322 elif args.command == 'test':
1323 if args.target is None:
1324 raise Error('you must specify -t or --target')
1328 target = target_factory(args)
1329 options = get_command_line_options(args)
1330 if args.no_implicit_build:
1331 globals.trees.add_built(args.project, args.checkout, target)
1333 target.build(args.project, args.checkout, options)
1334 target.test(args.project, args.checkout, target, args.test, options)
1336 if target is not None and not args.keep:
1339 elif args.command == 'shell':
1340 if args.target is None:
1341 raise Error('you must specify -t or --target')
1343 target = target_factory(args)
1344 target.command('bash')
1346 elif args.command == 'revision':
1348 target = SourceTarget()
1349 tree = globals.trees.get(args.project, args.checkout, target)
1350 with TreeDirectory(tree):
1351 print(command_and_read('git rev-parse HEAD')[0].strip()[:7])
1354 elif args.command == 'checkout':
1356 if args.output is None:
1357 raise Error('you must specify -o or --output')
1359 target = SourceTarget()
1360 tree = globals.trees.get(args.project, args.checkout, target)
1361 with TreeDirectory(tree):
1362 shutil.copytree('.', args.output)
1365 elif args.command == 'dependencies':
1366 if args.target is None:
1367 raise Error('you must specify -t or --target')
1368 if args.checkout is None:
1369 raise Error('you must specify -c or --checkout')
1371 target = target_factory(args)
1372 tree = globals.trees.get(args.project, args.checkout, target)
1373 print("strict digraph {")
1374 for d in list(tree.dependencies({})):
1375 print("%s -> %s;" % (d[2].name.replace("-", "-"), d[0].name.replace("-", "_")))
1382 print('cdist: %s' % str(e), file=sys.stderr)