3 # Copyright (C) 2012-2022 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
29 from pathlib import Path
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, commit_ish, target, required_by=None):
59 if t.name == name and t.commit_ish == commit_ish and t.target == target:
61 elif t.name == name and t.commit_ish != commit_ish:
62 a = commit_ish if commit_ish is not None else "[Any]"
63 if required_by is not None:
64 a += ' by %s' % required_by
65 b = t.commit_ish if t.commit_ish 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, commit_ish, target, required_by)
74 def add_built(self, name, commit_ish, target):
75 self.trees.append(Tree(name, commit_ish, 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 in ['yes', '1', '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_intel_deployment'),
118 Option('osx_arm_deployment'),
119 Option('osx_old_deployment'),
120 Option('osx_keychain_file'),
121 Option('osx_keychain_password'),
123 Option('apple_password'),
124 BoolOption('docker_sudo'),
125 BoolOption('docker_no_user'),
126 Option('docker_hub_repository'),
127 Option('flatpak_state_dir'),
128 Option('parallel', multiprocessing.cpu_count()),
129 Option('temp', '/var/tmp')]
131 config_dir = '%s/.config' % os.path.expanduser('~')
132 if not os.path.exists(config_dir):
134 config_file = '%s/cdist' % config_dir
135 if not os.path.exists(config_file):
136 f = open(config_file, 'w')
137 for o in self.options:
138 print('# %s ' % o.key, file=f)
140 print('Template config file written to %s; please edit and try again.' % config_file, file=sys.stderr)
144 f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
150 if len(l) > 0 and l[0] == '#':
153 s = l.strip().split()
155 for k in self.options:
161 for o in self.options:
162 if o.key == k and o.value is not None:
167 for o in self.options:
170 raise Error('Required setting %s not found' % k)
174 for o in self.options:
178 if self.get('docker_sudo'):
190 if not globals.quiet:
191 print('\x1b[33m* %s\x1b[0m' % m)
195 print('\x1b[35m* %s\x1b[0m' % m)
197 def escape_spaces(s):
198 return s.replace(' ', '\\ ')
201 """Escape a host:filename string for use with an scp command"""
203 assert(len(s) == 1 or len(s) == 2)
205 return '%s:"\'%s\'"' % (s[0], s[1])
207 return '\"%s\"' % s[0]
210 return '\"%s\"' % n.substr(' ', '\\ ')
213 log_normal('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
214 if b.startswith('s3://'):
215 command('s3cmd -P -r put "%s" "%s"' % (a, b))
217 command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
220 log_normal('copy %s -> %s with cwd %s' % (scp_escape(a), scp_escape(b), os.getcwd()))
221 if b.startswith('s3://'):
222 command('s3cmd -P put "%s" "%s"' % (a, b))
228 temp_path = os.path.join(os.path.dirname(path), ".tmp." + os.path.basename(path))
229 command('scp %s %s' % (scp_escape(a), scp_escape(host + ":" + temp_path)))
230 command('ssh %s -- mv "%s" "%s"' % (host, escape_spaces(temp_path), escape_spaces(path)))
232 command('scp %s %s' % (scp_escape(a), scp_escape(b)))
236 Make directories either locally or on a remote host; remotely if
237 d includes a colon, otherwise locally.
239 if d.startswith('s3://'):
240 # No need to create folders on S3
243 if d.find(':') == -1:
251 command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
254 log_normal('remove %s' % a)
258 log_normal('remove %s' % a)
259 shutil.rmtree(a, ignore_errors=True)
264 r = subprocess.run(c, shell=True)
265 if r.returncode != 0:
266 raise Error('command %s failed (%d)' % (c, r.returncode))
267 except Exception as e:
268 raise Error('command %s failed (%s)' % (c, e))
270 def command_and_read(c):
272 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
273 (out, err) = p.communicate()
274 if p.returncode != 0:
275 raise Error('command %s failed (%s)' % (c, err))
276 return str(out, 'utf-8').splitlines()
278 def read_wscript_variable(directory, variable):
279 f = open('%s/wscript' % directory, 'r')
286 if len(s) == 3 and s[0] == variable:
294 def devel_to_git(git_commit, filename):
295 if git_commit is not None:
296 filename = filename.replace('devel', '-%s' % git_commit)
300 def get_command_line_options(args):
301 """Get the options specified by --option on the command line"""
303 if args.option is not None:
304 for o in args.option:
307 raise Error("Bad option `%s'" % o)
309 options[b[0]] = False
318 def __init__(self, tree):
321 self.cwd = os.getcwd()
322 os.chdir('%s/src/%s' % (self.tree.target.directory, self.tree.name))
323 def __exit__(self, type, value, traceback):
331 def __init__(self, s):
334 if s.startswith("'"):
339 if s.endswith('devel'):
343 if s.endswith('pre'):
347 self.major = int(p[0])
348 self.minor = int(p[1])
350 self.micro = int(p[2])
355 def from_git_tag(cls, tag):
356 bits = tag.split('-')
358 if len(bits) > 1 and int(bits[1]) > 0:
362 def bump_minor(self):
366 def bump_micro(self):
372 def to_release(self):
376 s = '%d.%d.%d' % (self.major, self.minor, self.micro)
386 class Target(object):
388 Class representing the target that we are building for. This is exposed to cscripts,
389 though not all of it is guaranteed 'API'. cscripts may expect:
391 platform: platform string (e.g. 'windows', 'linux', 'osx')
392 parallel: number of parallel jobs to run
393 directory: directory to work in
394 variables: dict of environment variables
395 debug: True to build a debug version, otherwise False
396 ccache: True to use ccache, False to not
397 set(a, b): set the value of variable 'a' to 'b'
398 unset(a): unset the value of variable 'a'
399 command(c): run the command 'c' in the build environment
403 def __init__(self, platform, directory=None):
405 platform -- platform string (e.g. 'windows', 'linux', 'osx')
406 directory -- directory to work in; if None we will use a temporary directory
407 Temporary directories will be removed after use; specified directories will not.
409 self.platform = platform
410 self.parallel = int(config.get('parallel'))
412 # Environment variables that we will use when we call cscripts
416 # True to build our dependencies ourselves; False if this is taken care
417 # of in some other way
418 self.build_dependencies = True
420 if directory is None:
421 self.directory = tempfile.mkdtemp('', 'tmp', config.get('temp'))
423 self.set('CCACHE_BASEDIR', os.path.realpath(self.directory))
424 self.set('CCACHE_NOHASHDIR', '')
426 self.directory = os.path.realpath(directory)
433 def _cscript_package(self, tree, options):
435 Call package() in the cscript and return what it returns, except that
436 anything not in a list will be put into one.
438 if len(inspect.getfullargspec(tree.cscript['package']).args) == 3:
439 packages = tree.call('package', tree.version, options)
441 log_normal("Deprecated cscript package() method with no options parameter")
442 packages = tree.call('package', tree.version)
444 return packages if isinstance(packages, list) else [packages]
446 def _copy_packages(self, tree, packages, output_dir):
448 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.commit, p))))
450 def package(self, project, checkout, output_dir, options, notarize):
451 tree = self.build(project, checkout, options, for_package=True)
452 tree.add_defaults(options)
453 p = self._cscript_package(tree, options)
454 self._copy_packages(tree, p, output_dir)
456 def build(self, project, checkout, options, for_package=False):
457 tree = globals.trees.get(project, checkout, self)
458 if self.build_dependencies:
459 tree.build_dependencies(options)
460 tree.build(options, for_package=for_package)
463 def test(self, project, checkout, target, test, options):
464 """test is the test case to run, or None"""
465 tree = globals.trees.get(project, checkout, target)
467 tree.add_defaults(options)
468 with TreeDirectory(tree):
469 if len(inspect.getfullargspec(tree.cscript['test']).args) == 3:
470 return tree.call('test', options, test)
472 log_normal('Deprecated cscript test() method with no options parameter')
473 return tree.call('test', test)
476 self.variables[a] = b
479 del(self.variables[a])
482 return self.variables[a]
484 def append(self, k, v, s):
485 if (not k in self.variables) or len(self.variables[k]) == 0:
486 self.variables[k] = '"%s"' % v
488 e = self.variables[k]
489 if e[0] == '"' and e[-1] == '"':
490 self.variables[k] = '"%s%s%s"' % (e[1:-1], s, v)
492 self.variables[k] = '"%s%s%s"' % (e, s, v)
494 def append_with_space(self, k, v):
495 return self.append(k, v, ' ')
497 def append_with_colon(self, k, v):
498 return self.append(k, v, ':')
500 def variables_string(self, escaped_quotes=False):
502 for k, v in self.variables.items():
504 v = v.replace('"', '\\"')
505 e += '%s=%s ' % (k, v)
510 rmtree(self.directory)
524 class DockerTarget(Target):
525 def __init__(self, platform, directory):
526 super(DockerTarget, self).__init__(platform, directory)
528 self.privileged = False
531 if config.get('docker_no_user'):
533 return '-u %s' % getpass.getuser()
535 def _mount_option(self, d):
536 return '-v %s:%s ' % (os.path.realpath(d), os.path.realpath(d))
539 opts = self._mount_option(self.directory)
540 for m in self.mounts:
541 opts += self._mount_option(m)
542 if config.has('git_reference'):
543 opts += self._mount_option(config.get('git_reference'))
545 opts += '--privileged=true '
547 opts += "-e CCACHE_DIR=/ccache/%s-%d --mount source=ccache,target=/ccache " % (self.image, os.getuid())
551 if config.has('docker_hub_repository'):
552 tag = '%s:%s' % (config.get('docker_hub_repository'), tag)
554 def signal_handler(signum, frame):
555 raise Error('Killed')
556 signal.signal(signal.SIGTERM, signal_handler)
558 self.container = command_and_read('%s run %s %s -itd %s /bin/bash' % (config.docker(), self._user_tag(), opts, tag))[0].strip()
560 def command(self, cmd):
561 dir = os.path.join(self.directory, os.path.relpath(os.getcwd(), self.directory))
562 interactive_flag = '-i ' if sys.stdin.isatty() else ''
563 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))
566 super(DockerTarget, self).cleanup()
567 command('%s kill %s' % (config.docker(), self.container))
570 self.mounts.append(m)
573 class FlatpakTarget(Target):
574 def __init__(self, project, checkout):
575 super(FlatpakTarget, self).__init__('flatpak')
576 self.build_dependencies = False
577 self.project = project
578 self.checkout = checkout
583 def command(self, cmd):
586 def checkout_dependencies(self):
587 tree = globals.trees.get(self.project, self.checkout, self)
588 return tree.checkout_dependencies()
593 def flatpak_builder(self):
594 b = 'flatpak-builder'
595 if config.has('flatpak_state_dir'):
596 b += ' --state-dir=%s' % config.get('flatpak_state_dir')
600 class WindowsDockerTarget(DockerTarget):
602 This target exposes the following additional API:
604 version: Windows version ('xp' or None)
605 bits: bitness of Windows (32 or 64)
606 name: name of our target e.g. x86_64-w64-mingw32.shared
607 environment_prefix: path to Windows environment for the appropriate target (libraries and some tools)
608 tool_path: path to 32- and 64-bit tools
610 def __init__(self, windows_version, bits, directory, environment_version):
611 super(WindowsDockerTarget, self).__init__('windows', directory)
612 self.version = windows_version
615 self.tool_path = '%s/usr/bin' % config.get('mxe_prefix')
617 self.name = 'i686-w64-mingw32.shared'
619 self.name = 'x86_64-w64-mingw32.shared'
620 self.environment_prefix = '%s/usr/%s' % (config.get('mxe_prefix'), self.name)
622 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.environment_prefix)
623 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
624 self.set('PATH', '%s/bin:%s:%s' % (self.environment_prefix, self.tool_path, os.environ['PATH']))
625 self.set('LD', '%s-ld' % self.name)
626 self.set('RANLIB', '%s-ranlib' % self.name)
627 self.set('WINRC', '%s-windres' % self.name)
628 cxx = '-I%s/include -I%s/include' % (self.environment_prefix, self.directory)
629 link = '-L%s/lib -L%s/lib' % (self.environment_prefix, self.directory)
630 self.set('CXXFLAGS', '"%s"' % cxx)
631 self.set('CPPFLAGS', '')
632 self.set('LINKFLAGS', '"%s"' % link)
633 self.set('LDFLAGS', '"%s"' % link)
635 self.image = 'windows'
636 if environment_version is not None:
637 self.image += '_%s' % environment_version
642 self.set('CC', '"ccache %s-gcc"' % self.name)
643 self.set('CXX', '"ccache %s-g++"' % self.name)
645 self.set('CC', '%s-gcc' % self.name)
646 self.set('CXX', '%s-g++' % self.name)
649 def library_prefix(self):
650 log_normal('Deprecated property library_prefix: use environment_prefix')
651 return self.environment_prefix
654 def windows_prefix(self):
655 log_normal('Deprecated property windows_prefix: use environment_prefix')
656 return self.environment_prefix
659 def mingw_prefixes(self):
660 log_normal('Deprecated property mingw_prefixes: use environment_prefix')
661 return [self.environment_prefix]
664 def mingw_path(self):
665 log_normal('Deprecated property mingw_path: use tool_path')
666 return self.tool_path
669 def mingw_name(self):
670 log_normal('Deprecated property mingw_name: use name')
674 class WindowsNativeTarget(Target):
676 This target exposes the following additional API:
678 version: Windows version ('xp' or None)
679 bits: bitness of Windows (32 or 64)
680 name: name of our target e.g. x86_64-w64-mingw32.shared
681 environment_prefix: path to Windows environment for the appropriate target (libraries and some tools)
683 def __init__(self, directory):
684 super().__init__('windows', directory)
688 self.environment_prefix = config.get('windows_native_environmnet_prefix')
690 self.set('PATH', '%s/bin:%s' % (self.environment_prefix, os.environ['PATH']))
692 def command(self, cmd):
696 class LinuxTarget(DockerTarget):
698 Build for Linux in a docker container.
699 This target exposes the following additional API:
701 distro: distribution ('debian', 'ubuntu', 'centos' or 'fedora')
702 version: distribution version (e.g. '12.04', '8', '6.5')
703 bits: bitness of the distribution (32 or 64)
704 detail: None or 'appimage' if we are building for appimage
707 def __init__(self, distro, version, bits, directory=None):
708 super(LinuxTarget, self).__init__('linux', directory)
710 self.version = version
714 self.set('CXXFLAGS', '-I%s/include' % self.directory)
715 self.set('CPPFLAGS', '')
716 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
717 self.set('PKG_CONFIG_PATH',
718 '%s/lib/pkgconfig:%s/lib64/pkgconfig:/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig' % (self.directory, self.directory))
719 self.set('PATH', '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin')
721 if self.version is None:
722 self.image = '%s-%s' % (self.distro, self.bits)
724 self.image = '%s-%s-%s' % (self.distro, self.version, self.bits)
727 super(LinuxTarget, self).setup()
729 self.set('CC', '"ccache gcc"')
730 self.set('CXX', '"ccache g++"')
732 def test(self, project, checkout, target, test, options):
733 self.append_with_colon('PATH', '%s/bin' % self.directory)
734 self.append_with_colon('LD_LIBRARY_PATH', '%s/lib' % self.directory)
735 super(LinuxTarget, self).test(project, checkout, target, test, options)
738 class AppImageTarget(LinuxTarget):
739 def __init__(self, work):
740 super(AppImageTarget, self).__init__('ubuntu', '18.04', 64, work)
741 self.detail = 'appimage'
742 self.privileged = True
745 def notarize_dmg(dmg, bundle_id):
747 ['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'],
751 def string_after(process, key):
752 lines = p.stdout.decode('utf-8').splitlines()
753 for i in range(0, len(lines)):
754 if lines[i].find(key) != -1:
755 return lines[i+1].strip().replace('<string>', '').replace('</string>', '')
757 request_uuid = string_after(p, "RequestUUID")
758 if request_uuid is None:
759 print("Looking for upload ID")
760 message = string_after(p, "message")
761 print("Looking in %s" % message)
763 m = re.match('.*The upload ID is ([0-9a-f\-]*)', message)
765 request_uuid = m.groups()[0]
766 if request_uuid is None:
767 print("Response: %s" % p)
768 raise Error('No RequestUUID found in response from Apple')
770 for i in range(0, 30):
771 print('%s: checking up on %s' % (datetime.datetime.now(), request_uuid))
772 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)
773 status = string_after(p, 'Status')
774 print('%s: got status %s' % (datetime.datetime.now(), status))
775 if status == 'invalid':
776 raise Error("Notarization failed")
777 elif status == 'success':
778 subprocess.run(['xcrun', 'stapler', 'staple', dmg])
780 elif status != "in progress":
781 print("Could not understand xcrun response")
785 raise Error("Notarization timed out")
788 class OSXTarget(Target):
789 def __init__(self, directory=None):
790 super(OSXTarget, self).__init__('osx', directory)
791 self.sdk_prefix = config.get('osx_sdk_prefix')
792 self.environment_prefix = config.get('osx_environment_prefix')
793 self.apple_id = config.get('apple_id')
794 self.apple_password = config.get('apple_password')
795 self.osx_keychain_file = config.get('osx_keychain_file')
796 self.osx_keychain_password = config.get('osx_keychain_password')
798 def command(self, c):
799 command('%s %s' % (self.variables_string(False), c))
801 def unlock_keychain(self):
802 self.command('security unlock-keychain -p %s %s' % (self.osx_keychain_password, self.osx_keychain_file))
804 def _copy_packages(self, tree, packages, output_dir):
806 dest = os.path.join(output_dir, os.path.basename(devel_to_git(tree.commit, p)))
808 if os.path.exists(p + ".id"):
809 copyfile(p + ".id", dest + ".id")
811 def _cscript_package_and_notarize(self, tree, options, notarize):
813 Call package() in the cscript and notarize the .dmgs that are returned, if notarize == True
815 p = self._cscript_package(tree, options)
817 if not isinstance(x, tuple):
818 raise Error('macOS packages must be returned from cscript as tuples of (dmg-filename, bundle-id)')
820 notarize_dmg(x[0], x[1])
822 with open(x[0] + '.id', 'w') as f:
824 return [x[0] for x in p]
827 class OSXSingleTarget(OSXTarget):
828 def __init__(self, arch, sdk, deployment, directory=None, can_notarize=True):
829 super(OSXSingleTarget, self).__init__(directory)
832 self.deployment = deployment
833 self.can_notarize = can_notarize
834 self.sub_targets = [self]
836 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (self.sdk_prefix, sdk, arch)
838 host_enviro = '%s/x86_64/%s' % (config.get('osx_environment_prefix'), deployment)
840 host_enviro = '%s/x86_64/10.10' % config.get('osx_environment_prefix')
841 target_enviro = '%s/%s/%s' % (config.get('osx_environment_prefix'), arch, deployment)
843 self.bin = '%s/bin' % target_enviro
845 # Environment variables
846 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, target_enviro, flags))
847 self.set('CPPFLAGS', '')
848 self.set('CXXFLAGS', '"-I%s/include -I%s/include -stdlib=libc++ %s"' % (self.directory, target_enviro, flags))
849 self.set('LDFLAGS', '"-L%s/lib -L%s/lib -stdlib=libc++ %s"' % (self.directory, target_enviro, flags))
850 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, target_enviro, flags))
851 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, target_enviro))
852 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % host_enviro)
853 self.set('MACOSX_DEPLOYMENT_TARGET', self.deployment)
854 self.set('CCACHE_BASEDIR', self.directory)
856 @Target.ccache.setter
858 Target.ccache.fset(self, v)
860 self.set('CC', '"ccache gcc"')
861 self.set('CXX', '"ccache g++"')
863 def package(self, project, checkout, output_dir, options, notarize):
864 tree = self.build(project, checkout, options, for_package=True)
865 tree.add_defaults(options)
866 self.unlock_keychain()
867 p = self._cscript_package_and_notarize(tree, options, self.can_notarize and notarize)
868 self._copy_packages(tree, p, output_dir)
871 class OSXUniversalTarget(OSXTarget):
872 def __init__(self, directory=None):
873 super(OSXUniversalTarget, self).__init__(directory)
874 self.sdk = config.get('osx_sdk')
875 self.sub_targets = []
876 for arch, deployment in (('x86_64', config.get('osx_intel_deployment')), ('arm64', config.get('osx_arm_deployment'))):
877 target = OSXSingleTarget(arch, self.sdk, deployment, os.path.join(self.directory, arch, deployment))
878 target.ccache = self.ccache
879 self.sub_targets.append(target)
881 def package(self, project, checkout, output_dir, options, notarize):
882 for target in self.sub_targets:
883 tree = globals.trees.get(project, checkout, target)
884 tree.build_dependencies(options)
885 tree.build(options, for_package=True)
887 self.unlock_keychain()
888 tree = globals.trees.get(project, checkout, self)
889 with TreeDirectory(tree):
890 p = self._cscript_package_and_notarize(tree, options, notarize)
891 self._copy_packages(tree, p, output_dir)
893 class SourceTarget(Target):
894 """Build a source .tar.bz2 and .zst"""
896 super(SourceTarget, self).__init__('source')
898 def command(self, c):
899 log_normal('host -> %s' % c)
900 command('%s %s' % (self.variables_string(), c))
903 rmtree(self.directory)
905 def package(self, project, checkout, output_dir, options, notarize):
906 tree = globals.trees.get(project, checkout, self)
907 with TreeDirectory(tree):
908 name = read_wscript_variable(os.getcwd(), 'APPNAME')
909 command('./waf dist')
910 bz2 = os.path.abspath('%s-%s.tar.bz2' % (name, tree.version))
911 copyfile(bz2, os.path.join(output_dir, os.path.basename(devel_to_git(tree.commit, bz2))))
912 command('tar xjf %s' % bz2)
913 command('tar --zstd -cf %s-%s.zst %s-%s' % (name, tree.version, name, tree.version))
914 zstd = os.path.abspath('%s-%s.zst' % (name, tree.version))
915 copyfile(zstd, os.path.join(output_dir, os.path.basename(devel_to_git(tree.commit, zstd))))
917 # @param s Target string:
919 # or ubuntu-version-{32,64}
920 # or debian-version-{32,64}
921 # or centos-version-{32,64}
922 # or fedora-version-{32,64}
923 # or mageia-version-{32,64}
928 def target_factory(args):
931 if s.startswith('windows-'):
933 if platform.system() == "Windows":
934 target = WindowsNativeTarget(args.work)
937 target = WindowsDockerTarget(None, int(x[1]), args.work, args.environment_version)
939 target = WindowsDockerTarget(x[1], int(x[2]), args.work, args.environment_version)
941 raise Error("Bad Windows target name `%s'")
942 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-') or s.startswith('fedora-') or s.startswith('mageia-'):
945 raise Error("Bad Linux target name `%s'; must be something like ubuntu-16.04-32 (i.e. distro-version-bits)" % s)
946 target = LinuxTarget(p[0], p[1], int(p[2]), args.work)
947 elif s.startswith('arch-'):
950 raise Error("Bad Arch target name `%s'; must be arch-32 or arch-64")
951 target = LinuxTarget(p[0], None, int(p[1]), args.work)
952 elif s == 'raspbian':
953 target = LinuxTarget(s, None, None, args.work)
955 target = OSXUniversalTarget(args.work)
956 elif s == 'osx-intel':
957 target = OSXSingleTarget('x86_64', config.get('osx_sdk'), config.get('osx_intel_deployment'), args.work)
959 target = OSXSingleTarget('x86_64', config.get('osx_sdk'), config.get('osx_old_deployment'), args.work, False)
961 target = SourceTarget()
963 target = FlatpakTarget(args.project, args.checkout)
964 elif s == 'appimage':
965 target = AppImageTarget(args.work)
968 raise Error("Bad target `%s'" % s)
970 target.debug = args.debug
971 target.ccache = args.ccache
973 if args.environment is not None:
974 for e in args.environment:
975 target.set(e, os.environ[e])
977 if args.mount is not None:
990 """Description of a tree, which is a checkout of a project,
991 possibly built. This class is never exposed to cscripts.
993 name -- name of git repository (without the .git)
994 commit_ish -- git tag or revision to use
995 target -- target object that we are using
996 version -- version from the wscript (if one is present)
997 commit -- git revision that is actually being used
998 built -- true if the tree has been built yet in this run
999 required_by -- name of the tree that requires this one
1002 def __init__(self, name, commit_ish, target, required_by, built=False):
1004 self.commit_ish = commit_ish
1005 self.target = target
1009 self.required_by = required_by
1012 proj = '%s/src/%s' % (target.directory, self.name)
1019 redirect = '>/dev/null'
1020 if config.has('git_reference'):
1021 ref = '--reference-if-able %s/%s.git' % (config.get('git_reference'), self.name)
1024 command('git -c protocol.file.allow=always clone %s %s %s/%s.git %s/src/%s' % (flags, ref, config.get('git_prefix'), self.name, target.directory, self.name))
1025 os.chdir('%s/src/%s' % (target.directory, self.name))
1027 if self.commit_ish is not None:
1028 command('git checkout %s %s %s' % (flags, self.commit_ish, redirect))
1029 self.commit = command_and_read('git rev-parse --short=7 HEAD')[0].strip()
1032 exec(open('%s/cscript' % proj).read(), self.cscript)
1035 # cscript can include submodules = False to stop submodules being fetched
1036 if (not 'submodules' in self.cscript or self.cscript['submodules'] == True) and os.path.exists('.gitmodules'):
1037 command('git submodule --quiet init')
1038 paths = command_and_read('git config --file .gitmodules --get-regexp path')
1039 urls = command_and_read('git config --file .gitmodules --get-regexp url')
1040 for path, url in zip(paths, urls):
1042 if config.has('git_reference'):
1043 url = url.split(' ')[1]
1044 ref_path = os.path.join(config.get('git_reference'), os.path.basename(url))
1045 if os.path.exists(ref_path):
1046 ref = '--reference %s' % ref_path
1047 path = path.split(' ')[1]
1048 command('git -c protocol.file.allow=always submodule --quiet update %s %s' % (ref, path))
1050 if os.path.exists('%s/wscript' % proj):
1051 v = read_wscript_variable(proj, "VERSION");
1054 self.version = Version(v)
1057 tag = command_and_read('git -C %s describe --match v* --tags' % proj)[0][1:]
1058 self.version = Version.from_git_tag(tag)
1060 # We'll leave version as None if we can't read it; maybe this is a bad idea
1061 # Should probably just install git on the Windows VM
1066 def call(self, function, *args):
1067 with TreeDirectory(self):
1068 return self.cscript[function](self.target, *args)
1070 def add_defaults(self, options):
1071 """Add the defaults from self into a dict options"""
1072 if 'option_defaults' in self.cscript:
1073 from_cscript = self.cscript['option_defaults']
1074 if isinstance(from_cscript, dict):
1075 defaults_dict = from_cscript
1077 log_normal("Deprecated cscript option_defaults method; replace with a dict")
1078 defaults_dict = from_cscript()
1079 for k, v in defaults_dict.items():
1080 if not k in options:
1083 def dependencies(self, options):
1085 yield details of the dependencies of this tree. Each dependency is returned
1086 as a tuple of (tree, options, parent_tree). The 'options' parameter are the options that
1087 we want to force for 'self'.
1089 if not 'dependencies' in self.cscript:
1092 if len(inspect.getfullargspec(self.cscript['dependencies']).args) == 2:
1093 self_options = copy.copy(options)
1094 self.add_defaults(self_options)
1095 deps = self.call('dependencies', self_options)
1097 log_normal("Deprecated cscript dependencies() method with no options parameter")
1098 deps = self.call('dependencies')
1100 # Loop over our immediate dependencies
1102 dep = globals.trees.get(d[0], d[1], self.target, self.name)
1104 # deps only get their options from the parent's cscript
1105 dep_options = d[2] if len(d) > 2 else {}
1106 for i in dep.dependencies(dep_options):
1108 yield (dep, dep_options, self)
1110 def checkout_dependencies(self, options={}):
1111 for i in self.dependencies(options):
1114 def build_dependencies(self, options):
1116 Called on the 'main' project tree (-p on the command line) to build all dependencies.
1117 'options' will be the ones from the command line.
1119 for i in self.dependencies(options):
1122 def build(self, options, for_package=False):
1126 log_verbose("Building %s %s %s with %s" % (self.name, self.commit_ish, self.version, options))
1128 variables = copy.copy(self.target.variables)
1130 options = copy.copy(options)
1131 self.add_defaults(options)
1133 if not globals.dry_run:
1134 num_args = len(inspect.getfullargspec(self.cscript['build']).args)
1136 self.call('build', options, for_package)
1138 self.call('build', options)
1142 self.target.variables = variables
1147 # Command-line parser
1153 "build": "build project",
1154 "package": "build and package the project",
1155 "release": "release a project using its next version number (adding a tag)",
1156 "pot": "build the project's .pot files",
1157 "manual": "build the project's manual",
1158 "doxygen": "build the project's Doxygen documentation",
1159 "latest": "print out the latest version",
1160 "test": "build the project and run its unit tests",
1161 "shell": "start a shell in the project''s work directory",
1162 "checkout": "check out the project",
1163 "revision": "print the head git revision number",
1164 "dependencies" : "print details of the project's dependencies as a .dot file"
1169 for k, v in commands.items():
1170 one_of += "\t%s%s\n" % (k.ljust(20), v)
1173 parser = argparse.ArgumentParser()
1174 parser.add_argument('-p', '--project', help='project name')
1175 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
1176 parser.add_argument('-o', '--output', help='output directory', default='.')
1177 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
1178 parser.add_argument('-t', '--target', help='target', action='append')
1179 parser.add_argument('--environment-version', help='version of environment to use')
1180 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
1181 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
1182 parser.add_argument('-w', '--work', help='override default work directory')
1183 parser.add_argument('-g', '--git-prefix', help='override configured git prefix')
1184 parser.add_argument('-n', '--dry-run', help='run the process without building anything', action='store_true')
1185 parser.add_argument('-e', '--environment', help='pass the value of the named environment variable into the build', action='append')
1186 parser.add_argument('-m', '--mount', help='mount a given directory in the build environment', action='append')
1187 parser.add_argument('--option', help='set an option for the build (use --option key:value)', action='append')
1188 parser.add_argument('--ccache', help='use ccache', action='store_true')
1189 parser.add_argument('--verbose', help='be verbose', action='store_true')
1191 subparsers = parser.add_subparsers(help='command to run', dest='command')
1192 parser_build = subparsers.add_parser("build", help="build project")
1193 parser_package = subparsers.add_parser("package", help="build and package project")
1194 parser_package.add_argument('--no-notarize', help='do not notarize .dmg packages', action='store_true')
1195 parser_release = subparsers.add_parser("release", help="release a project using its next version number (adding a tag)")
1196 parser_release.add_argument('--minor', help='minor version number bump', action='store_true')
1197 parser_release.add_argument('--micro', help='micro version number bump', action='store_true')
1198 parser_pot = subparsers.add_parser("pot", help="build the project's .pot files")
1199 parser_manual = subparsers.add_parser("manual", help="build the project's manual")
1200 parser_doxygen = subparsers.add_parser("doxygen", help="build the project's Doxygen documentation")
1201 parser_latest = subparsers.add_parser("latest", help="print out the latest version")
1202 parser_latest.add_argument('--major', help='major version to return', type=int)
1203 parser_latest.add_argument('--minor', help='minor version to return', type=int)
1204 parser_test = subparsers.add_parser("test", help="build the project and run its unit tests")
1205 parser_test.add_argument('--no-implicit-build', help='do not build first', action='store_true')
1206 parser_test.add_argument('--test', help="name of test to run, defaults to all")
1207 parser_shell = subparsers.add_parser("shell", help="build the project then start a shell")
1208 parser_checkout = subparsers.add_parser("checkout", help="check out the project")
1209 parser_revision = subparsers.add_parser("revision", help="print the head git revision number")
1210 parser_dependencies = subparsers.add_parser("dependencies", help="print details of the project's dependencies as a .dot file")
1211 parser_notarize = subparsers.add_parser("notarize", help="notarize .dmgs in a directory using *.dmg.id files")
1212 parser_notarize.add_argument('--dmgs', help='directory containing *.dmg and *.dmg.id')
1215 args = parser.parse_args()
1217 # Check for incorrect multiple parameters
1218 if args.target is not None:
1219 if len(args.target) > 1:
1220 parser.error('multiple -t options specified')
1223 args.target = args.target[0]
1225 # Override configured stuff
1226 if args.git_prefix is not None:
1227 config.set('git_prefix', args.git_prefix)
1229 if args.output.find(':') == -1:
1230 # This isn't of the form host:path so make it absolute
1231 args.output = os.path.abspath(args.output) + '/'
1233 if args.output[-1] != ':' and args.output[-1] != '/':
1236 # Now, args.output is 'host:', 'host:path/' or 'path/'
1238 if args.work is not None:
1239 args.work = os.path.abspath(args.work)
1240 if not os.path.exists(args.work):
1241 os.makedirs(args.work)
1243 if args.project is None and not args.command in ['shell', 'notarize']:
1244 raise Error('you must specify -p or --project')
1246 globals.quiet = args.quiet
1247 globals.verbose = args.verbose
1248 globals.dry_run = args.dry_run
1250 if args.command == 'build':
1251 if args.target is None:
1252 raise Error('you must specify -t or --target')
1254 target = target_factory(args)
1256 target.build(args.project, args.checkout, get_command_line_options(args))
1261 elif args.command == 'package':
1262 if args.target is None:
1263 raise Error('you must specify -t or --target')
1267 target = target_factory(args)
1269 if target.platform == 'linux' and target.detail != "appimage":
1270 if target.distro != 'arch':
1271 output_dir = os.path.join(args.output, '%s-%s-%d' % (target.distro, target.version, target.bits))
1273 output_dir = os.path.join(args.output, '%s-%d' % (target.distro, target.bits))
1275 output_dir = args.output
1277 makedirs(output_dir)
1278 target.package(args.project, args.checkout, output_dir, get_command_line_options(args), not args.no_notarize)
1280 if target is not None and not args.keep:
1283 elif args.command == 'release':
1284 if args.minor is False and args.micro is False:
1285 raise Error('you must specify --minor or --micro')
1287 target = SourceTarget()
1288 tree = globals.trees.get(args.project, args.checkout, target)
1290 version = tree.version
1291 version.to_release()
1293 version.bump_minor()
1295 version.bump_micro()
1297 with TreeDirectory(tree):
1298 command('git tag -m "v%s" v%s' % (version, version))
1299 command('git push --tags')
1303 elif args.command == 'pot':
1304 target = SourceTarget()
1305 tree = globals.trees.get(args.project, args.checkout, target)
1307 pots = tree.call('make_pot')
1309 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
1313 elif args.command == 'manual':
1314 target = SourceTarget()
1315 tree = globals.trees.get(args.project, args.checkout, target)
1316 tree.checkout_dependencies()
1318 outs = tree.call('make_manual')
1320 if os.path.isfile(o):
1321 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
1323 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
1327 elif args.command == 'doxygen':
1328 target = SourceTarget()
1329 tree = globals.trees.get(args.project, args.checkout, target)
1331 dirs = tree.call('make_doxygen')
1332 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
1336 copytree(d, args.output)
1340 elif args.command == 'latest':
1341 target = SourceTarget()
1342 tree = globals.trees.get(args.project, args.checkout, target)
1344 with TreeDirectory(tree):
1345 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
1348 while latest is None:
1351 m = re.compile(".*\((.*)\).*").match(t)
1353 tags = m.group(1).split(', ')
1358 if len(t) > 0 and t[0] == 'v':
1360 if (args.major is None or v.major == args.major) and (args.minor is None or v.minor == args.minor):
1366 elif args.command == 'test':
1367 if args.target is None:
1368 raise Error('you must specify -t or --target')
1372 target = target_factory(args)
1373 options = get_command_line_options(args)
1374 if args.no_implicit_build:
1375 globals.trees.add_built(args.project, args.checkout, target)
1377 target.build(args.project, args.checkout, options)
1378 target.test(args.project, args.checkout, target, args.test, options)
1380 if target is not None and not args.keep:
1383 elif args.command == 'shell':
1384 if args.target is None:
1385 raise Error('you must specify -t or --target')
1387 target = target_factory(args)
1388 target.command('bash')
1390 elif args.command == 'revision':
1392 target = SourceTarget()
1393 tree = globals.trees.get(args.project, args.checkout, target)
1394 with TreeDirectory(tree):
1395 print(command_and_read('git rev-parse HEAD')[0].strip()[:7])
1398 elif args.command == 'checkout':
1400 if args.output is None:
1401 raise Error('you must specify -o or --output')
1403 target = SourceTarget()
1404 tree = globals.trees.get(args.project, args.checkout, target)
1405 with TreeDirectory(tree):
1406 shutil.copytree('.', args.output)
1409 elif args.command == 'dependencies':
1410 if args.target is None:
1411 raise Error('you must specify -t or --target')
1412 if args.checkout is None:
1413 raise Error('you must specify -c or --checkout')
1415 target = target_factory(args)
1416 tree = globals.trees.get(args.project, args.checkout, target)
1417 print("strict digraph {")
1418 for d in list(tree.dependencies({})):
1419 print("%s -> %s;" % (d[2].name.replace("-", "-"), d[0].name.replace("-", "_")))
1422 elif args.command == 'notarize':
1423 if args.dmgs is None:
1424 raise Error('you must specify ---dmgs')
1426 for dmg in Path(args.dmgs).glob('*.dmg'):
1429 with open(str(dmg) + '.id') as f:
1430 id = f.readline().strip()
1432 raise Error('could not find ID file for %s' % dmg)
1433 notarize_dmg(dmg, id)
1438 print('cdist: %s' % str(e), file=sys.stderr)