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
33 import multiprocessing
35 TEMPORARY_DIRECTORY = '/var/tmp'
37 class Error(Exception):
38 def __init__(self, value):
47 Store for Tree objects which re-uses already-created objects
48 and checks for requests for different versions of the same thing.
54 def get(self, name, specifier, target, required_by=None):
56 if t.name == name and t.specifier == specifier and t.target == target:
58 elif t.name == name and t.specifier != specifier:
59 a = specifier if specifier is not None else "[Any]"
60 if required_by is not None:
61 a += ' by %s' % required_by
62 b = t.specifier if t.specifier is not None else "[Any]"
63 if t.required_by is not None:
64 b += ' by %s' % t.required_by
65 raise Error('conflicting versions of %s required (%s versus %s)' % (name, a, b))
67 nt = Tree(name, specifier, target, required_by)
85 def __init__(self, key, default=None):
89 def offer(self, key, value):
93 class BoolOption(object):
94 def __init__(self, key):
98 def offer(self, key, value):
100 self.value = (value == 'yes' or value == '1' or value == 'true')
104 self.options = [ Option('mxe_prefix'),
105 Option('git_prefix'),
106 Option('osx_environment_prefix'),
107 Option('osx_sdk_prefix'),
110 Option('apple_password'),
111 BoolOption('docker_sudo'),
112 BoolOption('docker_no_user'),
113 Option('docker_hub_repository'),
114 Option('flatpak_state_dir'),
115 Option('parallel', multiprocessing.cpu_count()) ]
117 config_dir = '%s/.config' % os.path.expanduser('~')
118 if not os.path.exists(config_dir):
120 config_file = '%s/cdist' % config_dir
121 if not os.path.exists(config_file):
122 f = open(config_file, 'w')
123 for o in self.options:
124 print('# %s ' % o.key, file=f)
126 print('Template config file written to %s; please edit and try again.' % config_file, file=sys.stderr)
130 f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
136 if len(l) > 0 and l[0] == '#':
139 s = l.strip().split()
141 for k in self.options:
147 for o in self.options:
148 if o.key == k and o.value is not None:
153 for o in self.options:
156 raise Error('Required setting %s not found' % k)
160 for o in self.options:
164 if self.get('docker_sudo'):
176 if not globals.quiet:
177 print('\x1b[33m* %s\x1b[0m' % m)
179 def escape_spaces(s):
180 return s.replace(' ', '\\ ')
183 """Escape a host:filename string for use with an scp command"""
185 assert(len(s) == 1 or len(s) == 2)
187 return '%s:"\'%s\'"' % (s[0], s[1])
189 return '\"%s\"' % s[0]
192 return '\"%s\"' % n.substr(' ', '\\ ')
195 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
196 if b.startswith('s3://'):
197 command('s3cmd -P -r put "%s" "%s"' % (a, b))
199 command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
202 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
203 if b.startswith('s3://'):
204 command('s3cmd -P put "%s" "%s"' % (a, b))
210 temp_path = os.path.join(os.path.dirname(path), ".tmp." + os.path.basename(path))
211 command('scp %s %s' % (scp_escape(a), scp_escape(host + ":" + temp_path)))
212 command('ssh %s -- mv "%s" "%s"' % (host, escape_spaces(temp_path), escape_spaces(path)))
214 command('scp %s %s' % (scp_escape(a), scp_escape(b)))
218 Make directories either locally or on a remote host; remotely if
219 d includes a colon, otherwise locally.
221 if d.startswith('s3://'):
222 # No need to create folders on S3
225 if d.find(':') == -1:
233 command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
241 shutil.rmtree(a, ignore_errors=True)
247 raise Error('command %s failed' % c)
249 def command_and_read(c):
251 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
252 (out, err) = p.communicate()
253 if p.returncode != 0:
254 raise Error('command %s failed (%s)' % (c, err))
255 return out.splitlines()
257 def read_wscript_variable(directory, variable):
258 f = open('%s/wscript' % directory, 'r')
265 if len(s) == 3 and s[0] == variable:
272 def set_version_in_wscript(version):
273 f = open('wscript', 'rw')
274 o = open('wscript.tmp', 'w')
281 if len(s) == 3 and s[0] == "VERSION":
282 print("VERSION = '%s'" % version, file=o)
284 print(l, file=o, end="")
288 os.rename('wscript.tmp', 'wscript')
290 def append_version_to_changelog(version):
292 f = open('ChangeLog', 'r')
294 log('Could not open ChangeLog')
300 f = open('ChangeLog', 'w')
301 now = datetime.datetime.now()
302 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))
305 def append_version_to_debian_changelog(version):
306 if not os.path.exists('debian'):
307 log('Could not find debian directory')
310 command('dch -b -v %s-1 "New upstream release."' % version)
312 def devel_to_git(git_commit, filename):
313 if git_commit is not None:
314 filename = filename.replace('devel', '-%s' % git_commit)
317 def argument_options(args):
319 if args.option is not None:
320 for o in args.option:
323 raise Error("Bad option `%s'" % o)
334 def __init__(self, tree):
337 self.cwd = os.getcwd()
338 os.chdir('%s/src/%s' % (self.tree.target.directory, self.tree.name))
339 def __exit__(self, type, value, traceback):
347 def __init__(self, s):
350 if s.startswith("'"):
355 if s.endswith('devel'):
359 if s.endswith('pre'):
363 self.major = int(p[0])
364 self.minor = int(p[1])
366 self.micro = int(p[2])
371 def from_git_tag(cls, tag):
372 bits = tag.split('-')
374 if len(bits) > 1 and int(bits[1]) > 0:
378 def bump_minor(self):
382 def bump_micro(self):
388 def to_release(self):
392 s = '%d.%d.%d' % (self.major, self.minor, self.micro)
402 class Target(object):
404 Class representing the target that we are building for. This is exposed to cscripts,
405 though not all of it is guaranteed 'API'. cscripts may expect:
407 platform: platform string (e.g. 'windows', 'linux', 'osx')
408 parallel: number of parallel jobs to run
409 directory: directory to work in
410 variables: dict of environment variables
411 debug: True to build a debug version, otherwise False
412 ccache: True to use ccache, False to not
413 set(a, b): set the value of variable 'a' to 'b'
414 unset(a): unset the value of variable 'a'
415 command(c): run the command 'c' in the build environment
419 def __init__(self, platform, directory=None):
421 platform -- platform string (e.g. 'windows', 'linux', 'osx')
422 directory -- directory to work in; if None we will use a temporary directory
423 Temporary directories will be removed after use; specified directories will not.
425 self.platform = platform
426 self.parallel = int(config.get('parallel'))
428 # Environment variables that we will use when we call cscripts
432 # True to build our dependencies ourselves; False if this is taken care
433 # of in some other way
434 self.build_dependencies = True
436 if directory is None:
437 self.directory = tempfile.mkdtemp('', 'tmp', TEMPORARY_DIRECTORY)
439 self.set('CCACHE_BASEDIR', os.path.realpath(self.directory))
440 self.set('CCACHE_NOHASHDIR', '')
442 self.directory = directory
449 def package(self, project, checkout, output_dir, options):
450 tree = globals.trees.get(project, checkout, self)
451 if self.build_dependencies:
452 tree.build_dependencies(options)
454 if len(inspect.getargspec(tree.cscript['package']).args) == 3:
455 packages = tree.call('package', tree.version, options)
457 log("Deprecated cscript package() method with no options parameter")
458 packages = tree.call('package', tree.version)
460 if isinstance(packages, (str, unicode)):
461 copyfile(packages, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, packages))))
464 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
466 def build(self, project, checkout, options):
467 tree = globals.trees.get(project, checkout, self)
468 if self.build_dependencies:
469 tree.build_dependencies(options)
472 def test(self, tree, test, options):
473 """test is the test case to run, or None"""
474 if self.build_dependencies:
475 tree.build_dependencies(options)
477 return tree.call('test', test)
480 self.variables[a] = b
483 del(self.variables[a])
486 return self.variables[a]
488 def append(self, k, v, s):
489 if (not k in self.variables) or len(self.variables[k]) == 0:
490 self.variables[k] = '"%s"' % v
492 e = self.variables[k]
493 if e[0] == '"' and e[-1] == '"':
494 self.variables[k] = '"%s%s%s"' % (e[1:-1], s, v)
496 self.variables[k] = '"%s%s%s"' % (e, s, v)
498 def append_with_space(self, k, v):
499 return self.append(k, v, ' ')
501 def append_with_colon(self, k, v):
502 return self.append(k, v, ':')
504 def variables_string(self, escaped_quotes=False):
506 for k, v in self.variables.items():
508 v = v.replace('"', '\\"')
509 e += '%s=%s ' % (k, v)
514 rmtree(self.directory)
528 class DockerTarget(Target):
529 def __init__(self, platform, directory):
530 super(DockerTarget, self).__init__(platform, directory)
532 self.privileged = False
535 if config.get('docker_no_user'):
537 return '-u %s' % getpass.getuser()
540 opts = '-v %s:%s ' % (self.directory, self.directory)
541 for m in self.mounts:
542 opts += '-v %s:%s ' % (m, m)
544 opts += '--privileged=true '
546 opts += "-e CCACHE_DIR=/ccache --volumes-from ccache-%s" % self.image
549 if config.has('docker_hub_repository'):
550 tag = '%s:%s' % (config.get('docker_hub_repository'), tag)
552 self.container = command_and_read('%s run %s %s -itd %s /bin/bash' % (config.docker(), self._user_tag(), opts, tag))[0].strip()
554 def command(self, cmd):
555 dir = os.path.join(self.directory, os.path.relpath(os.getcwd(), self.directory))
556 interactive_flag = '-i ' if sys.stdin.isatty() else ''
557 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))
560 super(DockerTarget, self).cleanup()
561 command('%s kill %s' % (config.docker(), self.container))
564 self.mounts.append(m)
567 class FlatpakTarget(Target):
568 def __init__(self, project, checkout):
569 super(FlatpakTarget, self).__init__('flatpak')
570 self.build_dependencies = False
571 self.project = project
572 self.checkout = checkout
577 def command(self, cmd):
580 def checkout_dependencies(self):
581 tree = globals.trees.get(self.project, self.checkout, self)
582 return tree.checkout_dependencies()
587 def flatpak_builder(self):
588 b = 'flatpak-builder'
589 if config.has('flatpak_state_dir'):
590 b += ' --state-dir=%s' % config.get('flatpak_state_dir')
594 class WindowsTarget(DockerTarget):
596 This target exposes the following additional API:
598 version: Windows version ('xp' or None)
599 bits: bitness of Windows (32 or 64)
600 name: name of our target e.g. x86_64-w64-mingw32.shared
601 environment_prefix: path to Windows environment for the appropriate target (libraries and some tools)
602 tool_path: path to 32- and 64-bit tools
604 def __init__(self, windows_version, bits, directory, environment_version):
605 super(WindowsTarget, self).__init__('windows', directory)
606 self.version = windows_version
609 self.tool_path = '%s/usr/bin' % config.get('mxe_prefix')
611 self.name = 'i686-w64-mingw32.shared'
613 self.name = 'x86_64-w64-mingw32.shared'
614 self.environment_prefix = '%s/usr/%s' % (config.get('mxe_prefix'), self.name)
616 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.environment_prefix)
617 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
618 self.set('PATH', '%s/bin:%s:%s' % (self.environment_prefix, self.tool_path, os.environ['PATH']))
619 self.set('CC', '%s-gcc' % self.name)
620 self.set('CXX', '%s-g++' % self.name)
621 self.set('LD', '%s-ld' % self.name)
622 self.set('RANLIB', '%s-ranlib' % self.name)
623 self.set('WINRC', '%s-windres' % self.name)
624 cxx = '-I%s/include -I%s/include' % (self.environment_prefix, self.directory)
625 link = '-L%s/lib -L%s/lib' % (self.environment_prefix, self.directory)
626 self.set('CXXFLAGS', '"%s"' % cxx)
627 self.set('CPPFLAGS', '')
628 self.set('LINKFLAGS', '"%s"' % link)
629 self.set('LDFLAGS', '"%s"' % link)
631 self.image = 'windows'
632 if environment_version is not None:
633 self.image += '_%s' % environment_version
636 def library_prefix(self):
637 log('Deprecated property library_prefix: use environment_prefix')
638 return self.environment_prefix
641 def windows_prefix(self):
642 log('Deprecated property windows_prefix: use environment_prefix')
643 return self.environment_prefix
646 def mingw_prefixes(self):
647 log('Deprecated property mingw_prefixes: use environment_prefix')
648 return [self.environment_prefix]
651 def mingw_path(self):
652 log('Deprecated property mingw_path: use tool_path')
653 return self.tool_path
656 def mingw_name(self):
657 log('Deprecated property mingw_name: use name')
661 class LinuxTarget(DockerTarget):
663 Build for Linux in a docker container.
664 This target exposes the following additional API:
666 distro: distribution ('debian', 'ubuntu', 'centos' or 'fedora')
667 version: distribution version (e.g. '12.04', '8', '6.5')
668 bits: bitness of the distribution (32 or 64)
669 detail: None or 'appimage' if we are building for appimage
672 def __init__(self, distro, version, bits, directory=None):
673 super(LinuxTarget, self).__init__('linux', directory)
675 self.version = version
679 self.set('CXXFLAGS', '-I%s/include' % self.directory)
680 self.set('CPPFLAGS', '')
681 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
682 self.set('PKG_CONFIG_PATH',
683 '%s/lib/pkgconfig:%s/lib64/pkgconfig:/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig' % (self.directory, self.directory))
684 self.set('PATH', '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin')
686 if self.version is None:
687 self.image = '%s-%s' % (self.distro, self.bits)
689 self.image = '%s-%s-%s' % (self.distro, self.version, self.bits)
692 super(LinuxTarget, self).setup()
694 self.set('CC', '"ccache gcc"')
695 self.set('CXX', '"ccache g++"')
697 def test(self, tree, test, options):
698 self.append_with_colon('PATH', '%s/bin' % self.directory)
699 self.append_with_colon('LD_LIBRARY_PATH', '%s/lib' % self.directory)
700 super(LinuxTarget, self).test(tree, test, options)
703 class AppImageTarget(LinuxTarget):
704 def __init__(self, work):
705 super(AppImageTarget, self).__init__('ubuntu', '16.04', 64, work)
706 self.detail = 'appimage'
707 self.privileged = True
710 class OSXTarget(Target):
711 def __init__(self, directory=None):
712 super(OSXTarget, self).__init__('osx', directory)
713 self.sdk = config.get('osx_sdk')
714 self.sdk_prefix = config.get('osx_sdk_prefix')
715 self.environment_prefix = config.get('osx_environment_prefix')
716 self.apple_id = config.get('apple_id')
717 self.apple_password = config.get('apple_password')
719 def command(self, c):
720 command('%s %s' % (self.variables_string(False), c))
723 class OSXSingleTarget(OSXTarget):
724 def __init__(self, bits, directory=None):
725 super(OSXSingleTarget, self).__init__(directory)
733 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (self.sdk_prefix, self.sdk, arch)
734 enviro = '%s/%d' % (config.get('osx_environment_prefix'), bits)
736 # Environment variables
737 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
738 self.set('CPPFLAGS', '')
739 self.set('CXXFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
740 self.set('LDFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
741 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
742 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
743 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
744 self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
745 self.set('CCACHE_BASEDIR', self.directory)
747 @Target.ccache.setter
749 Target.ccache.fset(self, v)
751 self.set('CC', '"ccache gcc"')
752 self.set('CXX', '"ccache g++"')
755 class OSXUniversalTarget(OSXTarget):
756 def __init__(self, directory=None):
757 super(OSXUniversalTarget, self).__init__(directory)
760 def package(self, project, checkout, output_dir, options):
763 target = OSXSingleTarget(b, os.path.join(self.directory, '%d' % b))
764 target.ccache = self.ccache
765 tree = globals.trees.get(project, checkout, target)
766 tree.build_dependencies(options)
769 tree = globals.trees.get(project, checkout, self)
770 with TreeDirectory(tree):
771 if len(inspect.getargspec(tree.cscript['package']).args) == 3:
772 packages = tree.call('package', tree.version, options)
774 log("Deprecated cscript package() method with no options parameter")
775 packages = tree.call('package', tree.version)
777 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
779 class SourceTarget(Target):
780 """Build a source .tar.bz2"""
782 super(SourceTarget, self).__init__('source')
784 def command(self, c):
785 log('host -> %s' % c)
786 command('%s %s' % (self.variables_string(), c))
789 rmtree(self.directory)
791 def package(self, project, checkout, output_dir, options):
792 tree = globals.trees.get(project, checkout, self)
793 with TreeDirectory(tree):
794 name = read_wscript_variable(os.getcwd(), 'APPNAME')
795 command('./waf dist')
796 p = os.path.abspath('%s-%s.tar.bz2' % (name, tree.version))
797 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
799 # @param s Target string:
801 # or ubuntu-version-{32,64}
802 # or debian-version-{32,64}
803 # or centos-version-{32,64}
804 # or fedora-version-{32,64}
805 # or mageia-version-{32,64}
810 # @param debug True to build with debugging symbols (where possible)
811 def target_factory(args):
814 if s.startswith('windows-'):
817 target = WindowsTarget(None, int(x[1]), args.work, args.environment_version)
819 target = WindowsTarget(x[1], int(x[2]), args.work, args.environment_version)
821 raise Error("Bad Windows target name `%s'")
822 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-') or s.startswith('fedora-') or s.startswith('mageia-'):
825 raise Error("Bad Linux target name `%s'; must be something like ubuntu-16.04-32 (i.e. distro-version-bits)" % s)
826 target = LinuxTarget(p[0], p[1], int(p[2]), args.work)
827 elif s.startswith('arch-'):
830 raise Error("Bad Arch target name `%s'; must be arch-32 or arch-64")
831 target = LinuxTarget(p[0], None, int(p[1]), args.work)
832 elif s == 'raspbian':
833 target = LinuxTarget(s, None, None, args.work)
834 elif s.startswith('osx-'):
835 target = OSXSingleTarget(int(s.split('-')[1]), args.work)
837 if globals.command == 'build':
838 target = OSXSingleTarget(64, args.work)
840 target = OSXUniversalTarget(args.work)
842 target = SourceTarget()
844 target = FlatpakTarget(args.project, args.checkout)
845 elif s == 'appimage':
846 target = AppImageTarget(args.work)
849 raise Error("Bad target `%s'" % s)
851 target.debug = args.debug
852 target.ccache = args.ccache
854 if args.environment is not None:
855 for e in args.environment:
856 target.set(e, os.environ[e])
858 if args.mount is not None:
871 """Description of a tree, which is a checkout of a project,
872 possibly built. This class is never exposed to cscripts.
874 name -- name of git repository (without the .git)
875 specifier -- git tag or revision to use
876 target -- target object that we are using
877 version -- version from the wscript (if one is present)
878 git_commit -- git revision that is actually being used
879 built -- true if the tree has been built yet in this run
880 required_by -- name of the tree that requires this one
883 def __init__(self, name, specifier, target, required_by):
885 self.specifier = specifier
888 self.git_commit = None
890 self.required_by = required_by
898 redirect = '>/dev/null'
899 command('git clone %s %s/%s.git %s/src/%s' % (flags, config.get('git_prefix'), self.name, target.directory, self.name))
900 os.chdir('%s/src/%s' % (target.directory, self.name))
902 spec = self.specifier
906 command('git checkout %s %s %s' % (flags, spec, redirect))
907 self.git_commit = command_and_read('git rev-parse --short=7 HEAD')[0].strip()
909 proj = '%s/src/%s' % (target.directory, self.name)
912 exec(open('%s/cscript' % proj).read(), self.cscript)
914 # cscript can include submodules = False to stop submodules being fetched
915 if not 'submodules' in self.cscript or self.cscript['submodules'] == True:
916 command('git submodule init --quiet')
917 command('git submodule update --quiet')
919 if os.path.exists('%s/wscript' % proj):
920 v = read_wscript_variable(proj, "VERSION");
923 self.version = Version(v)
925 tag = subprocess.Popen(shlex.split('git -C %s describe --tags' % proj), stdout=subprocess.PIPE).communicate()[0][1:]
926 self.version = Version.from_git_tag(tag)
930 def call(self, function, *args):
931 with TreeDirectory(self):
932 return self.cscript[function](self.target, *args)
934 def add_defaults(self, options):
935 """Add the defaults from this into a dict options"""
936 if 'option_defaults' in self.cscript:
937 for k, v in self.cscript['option_defaults']().items():
941 def dependencies(self, options):
942 if not 'dependencies' in self.cscript:
945 if len(inspect.getargspec(self.cscript['dependencies']).args) == 2:
946 deps = self.call('dependencies', options)
948 log("Deprecated cscript dependencies() method with no options parameter")
949 deps = self.call('dependencies')
952 dep = globals.trees.get(d[0], d[1], self.target, self.name)
954 # Start with the options passed in
955 dep_options = copy.copy(options)
956 # Add things specified by the parent
958 for k, v in d[2].items():
959 if not k in dep_options:
961 # Then fill in the dependency's defaults
962 dep.add_defaults(dep_options)
964 for i in dep.dependencies(dep_options):
966 yield (dep, dep_options)
968 def checkout_dependencies(self, options={}):
969 for i in self.dependencies(options):
972 def build_dependencies(self, options):
973 for i in self.dependencies(options):
976 print('Building a dependency of %s %s %s with %s' % (self.name, self.specifier, self.version, options))
979 def build(self, options):
985 print("* Building %s %s %s with %s" % (self.name, self.specifier, self.version, options))
987 variables = copy.copy(self.target.variables)
989 # Start with the options passed in
990 options = copy.copy(options)
991 # Fill in the defaults
992 self.add_defaults(options)
994 if not globals.dry_run:
995 if len(inspect.getargspec(self.cscript['build']).args) == 2:
996 self.call('build', options)
1000 self.target.variables = variables
1004 # Command-line parser
1010 "build": "build project",
1011 "package": "package and build project",
1012 "release": "release a project using its next version number (changing wscript and tagging)",
1013 "pot": "build the project's .pot files",
1014 "changelog": "generate a simple HTML changelog",
1015 "manual": "build the project's manual",
1016 "doxygen": "build the project's Doxygen documentation",
1017 "latest": "print out the latest version",
1018 "test": "run the project's unit tests",
1019 "shell": "build the project then start a shell",
1020 "checkout": "check out the project",
1021 "revision": "print the head git revision number"
1024 one_of = "Command is one of:\n"
1026 for k, v in commands.items():
1027 one_of += "\t%s\t%s\n" % (k, v)
1030 parser = argparse.ArgumentParser()
1031 parser.add_argument('command', help=summary)
1032 parser.add_argument('-p', '--project', help='project name')
1033 parser.add_argument('--minor', help='minor version number bump', action='store_true')
1034 parser.add_argument('--micro', help='micro version number bump', action='store_true')
1035 parser.add_argument('--latest-major', help='major version to return with latest', type=int)
1036 parser.add_argument('--latest-minor', help='minor version to return with latest', type=int)
1037 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
1038 parser.add_argument('-o', '--output', help='output directory', default='.')
1039 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
1040 parser.add_argument('-t', '--target', help='target', action='append')
1041 parser.add_argument('--environment-version', help='version of environment to use')
1042 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
1043 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
1044 parser.add_argument('-w', '--work', help='override default work directory')
1045 parser.add_argument('-g', '--git-prefix', help='override configured git prefix')
1046 parser.add_argument('--test', help="name of test to run (with `test'), defaults to all")
1047 parser.add_argument('-n', '--dry-run', help='run the process without building anything', action='store_true')
1048 parser.add_argument('-e', '--environment', help='pass the value of the named environment variable into the build', action='append')
1049 parser.add_argument('-m', '--mount', help='mount a given directory in the build environment', action='append')
1050 parser.add_argument('--no-version-commit', help="use just tags for versioning, don't modify wscript, ChangeLog etc.", action='store_true')
1051 parser.add_argument('--option', help='set an option for the build (use --option key:value)', action='append')
1052 parser.add_argument('--ccache', help='use ccache', action='store_true')
1053 parser.add_argument('--verbose', help='be verbose', action='store_true')
1055 args = parser.parse_args()
1057 # Check for incorrect multiple parameters
1058 if args.target is not None:
1059 if len(args.target) > 1:
1060 parser.error('multiple -t options specified')
1063 args.target = args.target[0]
1065 # Override configured stuff
1066 if args.git_prefix is not None:
1067 config.set('git_prefix', args.git_prefix)
1069 if args.output.find(':') == -1:
1070 # This isn't of the form host:path so make it absolute
1071 args.output = os.path.abspath(args.output) + '/'
1073 if args.output[-1] != ':' and args.output[-1] != '/':
1076 # Now, args.output is 'host:', 'host:path/' or 'path/'
1078 if args.work is not None:
1079 args.work = os.path.abspath(args.work)
1081 if args.project is None and args.command != 'shell':
1082 raise Error('you must specify -p or --project')
1084 globals.quiet = args.quiet
1085 globals.command = args.command
1086 globals.dry_run = args.dry_run
1088 if not globals.command in commands:
1089 e = 'command must be one of:\n' + one_of
1090 raise Error('command must be one of:\n%s' % one_of)
1092 if globals.command == 'build':
1093 if args.target is None:
1094 raise Error('you must specify -t or --target')
1096 target = target_factory(args)
1097 target.build(args.project, args.checkout, argument_options(args))
1101 elif globals.command == 'package':
1102 if args.target is None:
1103 raise Error('you must specify -t or --target')
1107 target = target_factory(args)
1109 if target.platform == 'linux' and target.detail != "appimage":
1110 if target.distro != 'arch':
1111 output_dir = os.path.join(args.output, '%s-%s-%d' % (target.distro, target.version, target.bits))
1113 output_dir = os.path.join(args.output, '%s-%d' % (target.distro, target.bits))
1115 output_dir = args.output
1117 makedirs(output_dir)
1119 # Start with the options passed on the command line
1120 options = copy.copy(argument_options(args))
1121 # Fill in the defaults
1122 tree = globals.trees.get(args.project, args.checkout, target)
1123 tree.add_defaults(options)
1124 target.package(args.project, args.checkout, output_dir, options)
1126 if target is not None and not args.keep:
1130 if target is not None and not args.keep:
1133 elif globals.command == 'release':
1134 if args.minor is False and args.micro is False:
1135 raise Error('you must specify --minor or --micro')
1137 target = SourceTarget()
1138 tree = globals.trees.get(args.project, args.checkout, target)
1140 version = tree.version
1141 version.to_release()
1143 version.bump_minor()
1145 version.bump_micro()
1147 with TreeDirectory(tree):
1148 if not args.no_version_commit:
1149 set_version_in_wscript(version)
1150 append_version_to_changelog(version)
1151 append_version_to_debian_changelog(version)
1152 command('git commit -a -m "Bump version"')
1154 command('git tag -m "v%s" v%s' % (version, version))
1156 if not args.no_version_commit:
1158 set_version_in_wscript(version)
1159 command('git commit -a -m "Bump version"')
1162 command('git push --tags')
1166 elif globals.command == 'pot':
1167 target = SourceTarget()
1168 tree = globals.trees.get(args.project, args.checkout, target)
1170 pots = tree.call('make_pot')
1172 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
1176 elif globals.command == 'changelog':
1177 target = SourceTarget()
1178 tree = globals.trees.get(args.project, args.checkout, target)
1180 with TreeDirectory(tree):
1181 text = open('ChangeLog', 'r')
1183 html = tempfile.NamedTemporaryFile()
1194 if len(l) > 0 and l[0] == "\t":
1196 if len(s) == 4 and s[1] == "Version" and s[3] == "released.":
1199 if last is not None and len(changes) > 0:
1200 print("<h2>Changes between version %s and %s</h2>" % (s[2], last), file=html)
1201 print("<ul>", file=html)
1203 print("<li>%s" % c, file=html)
1204 print("</ul>", file=html)
1214 changes.append(c[2:])
1216 changes[-1] += " " + c
1218 copyfile(html.file, '%schangelog.html' % args.output)
1222 elif globals.command == 'manual':
1223 target = SourceTarget()
1224 tree = globals.trees.get(args.project, args.checkout, target)
1226 outs = tree.call('make_manual')
1228 if os.path.isfile(o):
1229 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
1231 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
1235 elif globals.command == 'doxygen':
1236 target = SourceTarget()
1237 tree = globals.trees.get(args.project, args.checkout, target)
1239 dirs = tree.call('make_doxygen')
1240 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
1244 copytree(d, args.output)
1248 elif globals.command == 'latest':
1249 target = SourceTarget()
1250 tree = globals.trees.get(args.project, args.checkout, target)
1252 with TreeDirectory(tree):
1253 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
1256 while latest is None:
1259 m = re.compile(".*\((.*)\).*").match(t)
1261 tags = m.group(1).split(', ')
1266 if len(t) > 0 and t[0] == 'v':
1268 if (args.latest_major is None or v.major == args.latest_major) and (args.latest_minor is None or v.minor == args.latest_minor):
1274 elif globals.command == 'test':
1275 if args.target is None:
1276 raise Error('you must specify -t or --target')
1280 target = target_factory(args)
1281 tree = globals.trees.get(args.project, args.checkout, target)
1282 with TreeDirectory(tree):
1283 target.test(tree, args.test, argument_options(args))
1285 if target is not None and not args.keep:
1289 if target is not None and not args.keep:
1292 elif globals.command == 'shell':
1293 if args.target is None:
1294 raise Error('you must specify -t or --target')
1296 target = target_factory(args)
1297 target.command('bash')
1299 elif globals.command == 'revision':
1301 target = SourceTarget()
1302 tree = globals.trees.get(args.project, args.checkout, target)
1303 with TreeDirectory(tree):
1304 print(command_and_read('git rev-parse HEAD')[0].strip()[:7])
1307 elif globals.command == 'checkout':
1309 if args.output is None:
1310 raise Error('you must specify -o or --output')
1312 target = SourceTarget()
1313 tree = globals.trees.get(args.project, args.checkout, target)
1314 with TreeDirectory(tree):
1315 shutil.copytree('.', args.output)
1319 raise Error('invalid command %s' % globals.command)
1324 print('cdist: %s' % str(e), file=sys.stderr)