3 # Copyright (C) 2012-2019 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()) ]
118 f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
124 if len(l) > 0 and l[0] == '#':
127 s = l.strip().split()
129 for k in self.options:
135 for o in self.options:
136 if o.key == k and o.value is not None:
141 for o in self.options:
144 raise Error('Required setting %s not found' % k)
148 for o in self.options:
152 if self.get('docker_sudo'):
164 if not globals.quiet:
165 print('\x1b[33m* %s\x1b[0m' % m)
167 def escape_spaces(s):
168 return s.replace(' ', '\\ ')
171 """Escape a host:filename string for use with an scp command"""
173 assert(len(s) == 1 or len(s) == 2)
175 return '%s:"\'%s\'"' % (s[0], s[1])
177 return '\"%s\"' % s[0]
180 return '\"%s\"' % n.substr(' ', '\\ ')
183 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
184 if b.startswith('s3://'):
185 command('s3cmd -P -r put "%s" "%s"' % (a, b))
187 command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
190 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
191 if b.startswith('s3://'):
192 command('s3cmd -P put "%s" "%s"' % (a, b))
198 temp_path = os.path.join(os.path.dirname(path), ".tmp." + os.path.basename(path))
199 command('scp %s %s' % (scp_escape(a), scp_escape(host + ":" + temp_path)))
200 command('ssh %s -- mv "%s" "%s"' % (host, escape_spaces(temp_path), escape_spaces(path)))
202 command('scp %s %s' % (scp_escape(a), scp_escape(b)))
206 Make directories either locally or on a remote host; remotely if
207 d includes a colon, otherwise locally.
209 if d.startswith('s3://'):
210 # No need to create folders on S3
213 if d.find(':') == -1:
221 command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
229 shutil.rmtree(a, ignore_errors=True)
235 raise Error('command %s failed' % c)
237 def command_and_read(c):
239 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
240 (out, err) = p.communicate()
241 if p.returncode != 0:
242 raise Error('command %s failed (%s)' % (c, err))
243 return out.splitlines()
245 def read_wscript_variable(directory, variable):
246 f = open('%s/wscript' % directory, 'r')
253 if len(s) == 3 and s[0] == variable:
260 def set_version_in_wscript(version):
261 f = open('wscript', 'rw')
262 o = open('wscript.tmp', 'w')
269 if len(s) == 3 and s[0] == "VERSION":
270 print("VERSION = '%s'" % version, file=o)
272 print(l, file=o, end="")
276 os.rename('wscript.tmp', 'wscript')
278 def append_version_to_changelog(version):
280 f = open('ChangeLog', 'r')
282 log('Could not open ChangeLog')
288 f = open('ChangeLog', 'w')
289 now = datetime.datetime.now()
290 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))
293 def append_version_to_debian_changelog(version):
294 if not os.path.exists('debian'):
295 log('Could not find debian directory')
298 command('dch -b -v %s-1 "New upstream release."' % version)
300 def devel_to_git(git_commit, filename):
301 if git_commit is not None:
302 filename = filename.replace('devel', '-%s' % git_commit)
305 def argument_options(args):
307 if args.option is not None:
308 for o in args.option:
311 raise Error("Bad option `%s'" % o)
322 def __init__(self, tree):
325 self.cwd = os.getcwd()
326 os.chdir('%s/src/%s' % (self.tree.target.directory, self.tree.name))
327 def __exit__(self, type, value, traceback):
335 def __init__(self, s):
338 if s.startswith("'"):
343 if s.endswith('devel'):
347 if s.endswith('pre'):
351 self.major = int(p[0])
352 self.minor = int(p[1])
354 self.micro = int(p[2])
359 def from_git_tag(cls, tag):
360 bits = tag.split('-')
362 if len(bits) > 1 and int(bits[1]) > 0:
366 def bump_minor(self):
370 def bump_micro(self):
376 def to_release(self):
380 s = '%d.%d.%d' % (self.major, self.minor, self.micro)
390 class Target(object):
392 Class representing the target that we are building for. This is exposed to cscripts,
393 though not all of it is guaranteed 'API'. cscripts may expect:
395 platform: platform string (e.g. 'windows', 'linux', 'osx')
396 parallel: number of parallel jobs to run
397 directory: directory to work in
398 variables: dict of environment variables
399 debug: True to build a debug version, otherwise False
400 ccache: True to use ccache, False to not
401 set(a, b): set the value of variable 'a' to 'b'
402 unset(a): unset the value of variable 'a'
403 command(c): run the command 'c' in the build environment
407 def __init__(self, platform, directory=None):
409 platform -- platform string (e.g. 'windows', 'linux', 'osx')
410 directory -- directory to work in; if None we will use a temporary directory
411 Temporary directories will be removed after use; specified directories will not.
413 self.platform = platform
414 self.parallel = int(config.get('parallel'))
416 # Environment variables that we will use when we call cscripts
420 # True to build our dependencies ourselves; False if this is taken care
421 # of in some other way
422 self.build_dependencies = True
424 if directory is None:
425 self.directory = tempfile.mkdtemp('', 'tmp', TEMPORARY_DIRECTORY)
427 self.set('CCACHE_BASEDIR', os.path.realpath(self.directory))
428 self.set('CCACHE_NOHASHDIR', '')
430 self.directory = directory
437 def package(self, project, checkout, output_dir, options):
438 tree = globals.trees.get(project, checkout, self)
439 if self.build_dependencies:
440 tree.build_dependencies(options)
442 if len(inspect.getargspec(tree.cscript['package']).args) == 3:
443 packages = tree.call('package', tree.version, options)
445 log("Deprecated cscript package() method with no options parameter")
446 packages = tree.call('package', tree.version)
448 if isinstance(packages, (str, unicode)):
449 copyfile(packages, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, packages))))
452 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
454 def build(self, project, checkout, options):
455 tree = globals.trees.get(project, checkout, self)
456 if self.build_dependencies:
457 tree.build_dependencies(options)
460 def test(self, tree, test, options):
461 """test is the test case to run, or None"""
462 if self.build_dependencies:
463 tree.build_dependencies(options)
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, version):
518 super(DockerTarget, self).__init__(platform, directory)
519 self.version = version
521 self.privileged = False
524 if config.get('docker_no_user'):
526 return '-u %s' % getpass.getuser()
529 opts = '-v %s:%s ' % (self.directory, self.directory)
530 for m in self.mounts:
531 opts += '-v %s:%s ' % (m, m)
533 opts += '--privileged=true '
535 opts += "-e CCACHE_DIR=/ccache --volumes-from ccache-%s" % self.image
538 if config.has('docker_hub_repository'):
539 tag = '%s:%s' % (config.get('docker_hub_repository'), tag)
541 self.container = command_and_read('%s run %s %s -itd %s /bin/bash' % (config.docker(), self._user_tag(), opts, tag))[0].strip()
543 def command(self, cmd):
544 dir = os.path.join(self.directory, os.path.relpath(os.getcwd(), self.directory))
545 command('%s exec %s -t %s /bin/bash -c \'export %s; cd %s; %s\'' % (config.docker(), self._user_tag(), self.container, self.variables_string(), dir, cmd))
548 super(DockerTarget, self).cleanup()
549 command('%s kill %s' % (config.docker(), self.container))
552 self.mounts.append(m)
555 class FlatpakTarget(Target):
556 def __init__(self, project, checkout):
557 super(FlatpakTarget, self).__init__('flatpak')
558 self.build_dependencies = False
559 self.project = project
560 self.checkout = checkout
565 def command(self, cmd):
568 def checkout_dependencies(self):
569 tree = globals.trees.get(self.project, self.checkout, self)
570 return tree.checkout_dependencies()
575 def flatpak_builder(self):
576 b = 'flatpak-builder'
577 if config.has('flatpak_state_dir'):
578 b += ' --state-dir=%s' % config.get('flatpak_state_dir')
582 class WindowsTarget(DockerTarget):
584 This target exposes the following additional API:
586 version: Windows version ('xp' or None)
587 bits: bitness of Windows (32 or 64)
588 name: name of our target e.g. x86_64-w64-mingw32.shared
589 environment_prefix: path to Windows environment for the appropriate target (libraries and some tools)
590 tool_path: path to 32- and 64-bit tools
592 def __init__(self, version, bits, directory=None):
593 super(WindowsTarget, self).__init__('windows', directory, version)
596 self.tool_path = '%s/usr/bin' % config.get('mxe_prefix')
598 self.name = 'i686-w64-mingw32.shared'
600 self.name = 'x86_64-w64-mingw32.shared'
601 self.environment_prefix = '%s/usr/%s' % (config.get('mxe_prefix'), self.name)
603 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.environment_prefix)
604 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
605 self.set('PATH', '%s/bin:%s:%s' % (self.environment_prefix, self.tool_path, os.environ['PATH']))
606 self.set('CC', '%s-gcc' % self.name)
607 self.set('CXX', '%s-g++' % self.name)
608 self.set('LD', '%s-ld' % self.name)
609 self.set('RANLIB', '%s-ranlib' % self.name)
610 self.set('WINRC', '%s-windres' % self.name)
611 cxx = '-I%s/include -I%s/include' % (self.environment_prefix, self.directory)
612 link = '-L%s/lib -L%s/lib' % (self.environment_prefix, self.directory)
613 self.set('CXXFLAGS', '"%s"' % cxx)
614 self.set('CPPFLAGS', '')
615 self.set('LINKFLAGS', '"%s"' % link)
616 self.set('LDFLAGS', '"%s"' % link)
618 self.image = 'windows'
621 def library_prefix(self):
622 log('Deprecated property library_prefix: use environment_prefix')
623 return self.environment_prefix
626 def windows_prefix(self):
627 log('Deprecated property windows_prefix: use environment_prefix')
628 return self.environment_prefix
631 def mingw_prefixes(self):
632 log('Deprecated property mingw_prefixes: use environment_prefix')
633 return [self.environment_prefix]
636 def mingw_path(self):
637 log('Deprecated property mingw_path: use tool_path')
638 return self.tool_path
641 def mingw_name(self):
642 log('Deprecated property mingw_name: use name')
646 class LinuxTarget(DockerTarget):
648 Build for Linux in a docker container.
649 This target exposes the following additional API:
651 distro: distribution ('debian', 'ubuntu', 'centos' or 'fedora')
652 version: distribution version (e.g. '12.04', '8', '6.5')
653 bits: bitness of the distribution (32 or 64)
654 detail: None or 'appimage' if we are building for appimage
657 def __init__(self, distro, version, bits, directory=None):
658 super(LinuxTarget, self).__init__('linux', directory, version)
663 self.set('CXXFLAGS', '-I%s/include' % self.directory)
664 self.set('CPPFLAGS', '')
665 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
666 self.set('PKG_CONFIG_PATH',
667 '%s/lib/pkgconfig:%s/lib64/pkgconfig:/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig' % (self.directory, self.directory))
668 self.set('PATH', '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin')
670 if self.version is None:
671 self.image = '%s-%s' % (self.distro, self.bits)
673 self.image = '%s-%s-%s' % (self.distro, self.version, self.bits)
676 super(LinuxTarget, self).setup()
678 self.set('CC', '"ccache gcc"')
679 self.set('CXX', '"ccache g++"')
681 def test(self, tree, test, options):
682 self.append_with_colon('PATH', '%s/bin' % self.directory)
683 self.append_with_colon('LD_LIBRARY_PATH', '%s/lib' % self.directory)
684 super(LinuxTarget, self).test(tree, test, options)
687 class AppImageTarget(LinuxTarget):
688 def __init__(self, work):
689 super(AppImageTarget, self).__init__('ubuntu', '16.04', 64, work)
690 self.detail = 'appimage'
691 self.privileged = True
694 class OSXTarget(Target):
695 def __init__(self, directory=None):
696 super(OSXTarget, self).__init__('osx', directory)
697 self.sdk = config.get('osx_sdk')
698 self.sdk_prefix = config.get('osx_sdk_prefix')
699 self.environment_prefix = config.get('osx_environment_prefix')
700 self.apple_id = config.get('apple_id')
701 self.apple_password = config.get('apple_password')
703 def command(self, c):
704 command('%s %s' % (self.variables_string(False), c))
707 class OSXSingleTarget(OSXTarget):
708 def __init__(self, bits, directory=None):
709 super(OSXSingleTarget, self).__init__(directory)
717 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (self.sdk_prefix, self.sdk, arch)
718 enviro = '%s/%d' % (config.get('osx_environment_prefix'), bits)
720 # Environment variables
721 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
722 self.set('CPPFLAGS', '')
723 self.set('CXXFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
724 self.set('LDFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
725 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
726 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
727 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
728 self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
729 self.set('CCACHE_BASEDIR', self.directory)
731 @Target.ccache.setter
733 Target.ccache.fset(self, v)
735 self.set('CC', '"ccache gcc"')
736 self.set('CXX', '"ccache g++"')
739 class OSXUniversalTarget(OSXTarget):
740 def __init__(self, directory=None):
741 super(OSXUniversalTarget, self).__init__(directory)
744 def package(self, project, checkout, output_dir, options):
747 target = OSXSingleTarget(b, os.path.join(self.directory, '%d' % b))
748 target.ccache = self.ccache
749 tree = globals.trees.get(project, checkout, target)
750 tree.build_dependencies(options)
753 tree = globals.trees.get(project, checkout, self)
754 with TreeDirectory(tree):
755 if len(inspect.getargspec(tree.cscript['package']).args) == 3:
756 packages = tree.call('package', tree.version, options)
758 log("Deprecated cscript package() method with no options parameter")
759 packages = tree.call('package', tree.version)
761 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
763 class SourceTarget(Target):
764 """Build a source .tar.bz2"""
766 super(SourceTarget, self).__init__('source')
768 def command(self, c):
769 log('host -> %s' % c)
770 command('%s %s' % (self.variables_string(), c))
773 rmtree(self.directory)
775 def package(self, project, checkout, output_dir, options):
776 tree = globals.trees.get(project, checkout, self)
777 with TreeDirectory(tree):
778 name = read_wscript_variable(os.getcwd(), 'APPNAME')
779 command('./waf dist')
780 p = os.path.abspath('%s-%s.tar.bz2' % (name, tree.version))
781 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
783 # @param s Target string:
785 # or ubuntu-version-{32,64}
786 # or debian-version-{32,64}
787 # or centos-version-{32,64}
788 # or fedora-version-{32,64}
789 # or mageia-version-{32,64}
794 # @param debug True to build with debugging symbols (where possible)
795 def target_factory(args):
798 if s.startswith('windows-'):
801 target = WindowsTarget(None, int(x[1]), args.work)
803 target = WindowsTarget(x[1], int(x[2]), args.work)
805 raise Error("Bad Windows target name `%s'")
806 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-') or s.startswith('fedora-') or s.startswith('mageia-'):
809 raise Error("Bad Linux target name `%s'; must be something like ubuntu-16.04-32 (i.e. distro-version-bits)" % s)
810 target = LinuxTarget(p[0], p[1], int(p[2]), args.work)
811 elif s.startswith('arch-'):
814 raise Error("Bad Arch target name `%s'; must be arch-32 or arch-64")
815 target = LinuxTarget(p[0], None, int(p[1]), args.work)
816 elif s == 'raspbian':
817 target = LinuxTarget(s, None, None, args.work)
818 elif s.startswith('osx-'):
819 target = OSXSingleTarget(int(s.split('-')[1]), args.work)
821 if globals.command == 'build':
822 target = OSXSingleTarget(64, args.work)
824 target = OSXUniversalTarget(args.work)
826 target = SourceTarget()
828 target = FlatpakTarget(args.project, args.checkout)
829 elif s == 'appimage':
830 target = AppImageTarget(args.work)
833 raise Error("Bad target `%s'" % s)
835 target.debug = args.debug
836 target.ccache = args.ccache
838 if args.environment is not None:
839 for e in args.environment:
840 target.set(e, os.environ[e])
842 if args.mount is not None:
855 """Description of a tree, which is a checkout of a project,
856 possibly built. This class is never exposed to cscripts.
858 name -- name of git repository (without the .git)
859 specifier -- git tag or revision to use
860 target -- target object that we are using
861 version -- version from the wscript (if one is present)
862 git_commit -- git revision that is actually being used
863 built -- true if the tree has been built yet in this run
864 required_by -- name of the tree that requires this one
867 def __init__(self, name, specifier, target, required_by):
869 self.specifier = specifier
872 self.git_commit = None
874 self.required_by = required_by
882 redirect = '>/dev/null'
883 command('git clone %s %s/%s.git %s/src/%s' % (flags, config.get('git_prefix'), self.name, target.directory, self.name))
884 os.chdir('%s/src/%s' % (target.directory, self.name))
886 spec = self.specifier
890 command('git checkout %s %s %s' % (flags, spec, redirect))
891 self.git_commit = command_and_read('git rev-parse --short=7 HEAD')[0].strip()
893 proj = '%s/src/%s' % (target.directory, self.name)
896 exec(open('%s/cscript' % proj).read(), self.cscript)
898 # cscript can include submodules = False to stop submodules being fetched
899 if not 'submodules' in self.cscript or self.cscript['submodules'] == True:
900 command('git submodule init --quiet')
901 command('git submodule update --quiet')
903 if os.path.exists('%s/wscript' % proj):
904 v = read_wscript_variable(proj, "VERSION");
907 self.version = Version(v)
909 tag = subprocess.Popen(shlex.split('git -C %s describe --tags' % proj), stdout=subprocess.PIPE).communicate()[0][1:]
910 self.version = Version.from_git_tag(tag)
914 def call(self, function, *args):
915 with TreeDirectory(self):
916 return self.cscript[function](self.target, *args)
918 def add_defaults(self, options):
919 """Add the defaults from this into a dict options"""
920 if 'option_defaults' in self.cscript:
921 for k, v in self.cscript['option_defaults']().items():
925 def dependencies(self, options):
926 if not 'dependencies' in self.cscript:
929 if len(inspect.getargspec(self.cscript['dependencies']).args) == 2:
930 deps = self.call('dependencies', options)
932 log("Deprecated cscript dependencies() method with no options parameter")
933 deps = self.call('dependencies')
936 dep = globals.trees.get(d[0], d[1], self.target, self.name)
938 # Start with the options passed in
939 dep_options = copy.copy(options)
940 # Add things specified by the parent
942 for k, v in d[2].items():
943 if not k in dep_options:
945 # Then fill in the dependency's defaults
946 dep.add_defaults(dep_options)
948 for i in dep.dependencies(dep_options):
950 yield (dep, dep_options)
952 def checkout_dependencies(self, options={}):
953 for i in self.dependencies(options):
956 def build_dependencies(self, options):
957 for i in self.dependencies(options):
960 def build(self, options):
964 variables = copy.copy(self.target.variables)
966 # Start with the options passed in
967 options = copy.copy(options)
968 # Fill in the defaults
969 self.add_defaults(options)
971 if not globals.dry_run:
972 if len(inspect.getargspec(self.cscript['build']).args) == 2:
973 self.call('build', options)
977 self.target.variables = variables
981 # Command-line parser
987 "build": "build project",
988 "package": "package and build project",
989 "release": "release a project using its next version number (changing wscript and tagging)",
990 "pot": "build the project's .pot files",
991 "changelog": "generate a simple HTML changelog",
992 "manual": "build the project's manual",
993 "doxygen": "build the project's Doxygen documentation",
994 "latest": "print out the latest version",
995 "test": "run the project's unit tests",
996 "shell": "build the project then start a shell",
997 "checkout": "check out the project",
998 "revision": "print the head git revision number"
1001 one_of = "Command is one of:\n"
1003 for k, v in commands.items():
1004 one_of += "\t%s\t%s\n" % (k, v)
1007 parser = argparse.ArgumentParser()
1008 parser.add_argument('command', help=summary)
1009 parser.add_argument('-p', '--project', help='project name')
1010 parser.add_argument('--minor', help='minor version number bump', action='store_true')
1011 parser.add_argument('--micro', help='micro version number bump', action='store_true')
1012 parser.add_argument('--latest-major', help='major version to return with latest', type=int)
1013 parser.add_argument('--latest-minor', help='minor version to return with latest', type=int)
1014 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
1015 parser.add_argument('-o', '--output', help='output directory', default='.')
1016 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
1017 parser.add_argument('-t', '--target', help='target')
1018 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
1019 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
1020 parser.add_argument('-w', '--work', help='override default work directory')
1021 parser.add_argument('-g', '--git-prefix', help='override configured git prefix')
1022 parser.add_argument('--test', help="name of test to run (with `test'), defaults to all")
1023 parser.add_argument('-n', '--dry-run', help='run the process without building anything', action='store_true')
1024 parser.add_argument('-e', '--environment', help='pass the value of the named environment variable into the build', action='append')
1025 parser.add_argument('-m', '--mount', help='mount a given directory in the build environment', action='append')
1026 parser.add_argument('--no-version-commit', help="use just tags for versioning, don't modify wscript, ChangeLog etc.", action='store_true')
1027 parser.add_argument('--option', help='set an option for the build (use --option key:value)', action='append')
1028 parser.add_argument('--ccache', help='use ccache', action='store_true')
1029 args = parser.parse_args()
1031 # Override configured stuff
1032 if args.git_prefix is not None:
1033 config.set('git_prefix', args.git_prefix)
1035 if args.output.find(':') == -1:
1036 # This isn't of the form host:path so make it absolute
1037 args.output = os.path.abspath(args.output) + '/'
1039 if args.output[-1] != ':' and args.output[-1] != '/':
1042 # Now, args.output is 'host:', 'host:path/' or 'path/'
1044 if args.work is not None:
1045 args.work = os.path.abspath(args.work)
1047 if args.project is None and args.command != 'shell':
1048 raise Error('you must specify -p or --project')
1050 globals.quiet = args.quiet
1051 globals.command = args.command
1052 globals.dry_run = args.dry_run
1054 if not globals.command in commands:
1055 e = 'command must be one of:\n' + one_of
1056 raise Error('command must be one of:\n%s' % one_of)
1058 if globals.command == 'build':
1059 if args.target is None:
1060 raise Error('you must specify -t or --target')
1062 target = target_factory(args)
1063 target.build(args.project, args.checkout, argument_options(args))
1067 elif globals.command == 'package':
1068 if args.target is None:
1069 raise Error('you must specify -t or --target')
1073 target = target_factory(args)
1075 if target.platform == 'linux' and target.detail != "appimage":
1076 if target.distro != 'arch':
1077 output_dir = os.path.join(args.output, '%s-%s-%d' % (target.distro, target.version, target.bits))
1079 output_dir = os.path.join(args.output, '%s-%d' % (target.distro, target.bits))
1081 output_dir = args.output
1083 makedirs(output_dir)
1085 # Start with the options passed on the command line
1086 options = copy.copy(argument_options(args))
1087 # Fill in the defaults
1088 tree = globals.trees.get(args.project, args.checkout, target)
1089 tree.add_defaults(options)
1090 target.package(args.project, args.checkout, output_dir, options)
1092 if target is not None and not args.keep:
1096 if target is not None and not args.keep:
1099 elif globals.command == 'release':
1100 if args.minor is False and args.micro is False:
1101 raise Error('you must specify --minor or --micro')
1103 target = SourceTarget()
1104 tree = globals.trees.get(args.project, args.checkout, target)
1106 version = tree.version
1107 version.to_release()
1109 version.bump_minor()
1111 version.bump_micro()
1113 with TreeDirectory(tree):
1114 if not args.no_version_commit:
1115 set_version_in_wscript(version)
1116 append_version_to_changelog(version)
1117 append_version_to_debian_changelog(version)
1118 command('git commit -a -m "Bump version"')
1120 command('git tag -m "v%s" v%s' % (version, version))
1122 if not args.no_version_commit:
1124 set_version_in_wscript(version)
1125 command('git commit -a -m "Bump version"')
1128 command('git push --tags')
1132 elif globals.command == 'pot':
1133 target = SourceTarget()
1134 tree = globals.trees.get(args.project, args.checkout, target)
1136 pots = tree.call('make_pot')
1138 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
1142 elif globals.command == 'changelog':
1143 target = SourceTarget()
1144 tree = globals.trees.get(args.project, args.checkout, target)
1146 with TreeDirectory(tree):
1147 text = open('ChangeLog', 'r')
1149 html = tempfile.NamedTemporaryFile()
1160 if len(l) > 0 and l[0] == "\t":
1162 if len(s) == 4 and s[1] == "Version" and s[3] == "released.":
1165 if last is not None and len(changes) > 0:
1166 print("<h2>Changes between version %s and %s</h2>" % (s[2], last), file=html)
1167 print("<ul>", file=html)
1169 print("<li>%s" % c, file=html)
1170 print("</ul>", file=html)
1180 changes.append(c[2:])
1182 changes[-1] += " " + c
1184 copyfile(html.file, '%schangelog.html' % args.output)
1188 elif globals.command == 'manual':
1189 target = SourceTarget()
1190 tree = globals.trees.get(args.project, args.checkout, target)
1192 outs = tree.call('make_manual')
1194 if os.path.isfile(o):
1195 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
1197 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
1201 elif globals.command == 'doxygen':
1202 target = SourceTarget()
1203 tree = globals.trees.get(args.project, args.checkout, target)
1205 dirs = tree.call('make_doxygen')
1206 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
1210 copytree(d, args.output)
1214 elif globals.command == 'latest':
1215 target = SourceTarget()
1216 tree = globals.trees.get(args.project, args.checkout, target)
1218 with TreeDirectory(tree):
1219 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
1222 while latest is None:
1225 m = re.compile(".*\((.*)\).*").match(t)
1227 tags = m.group(1).split(', ')
1232 if len(t) > 0 and t[0] == 'v':
1234 if (args.latest_major is None or v.major == args.latest_major) and (args.latest_minor is None or v.minor == args.latest_minor):
1240 elif globals.command == 'test':
1241 if args.target is None:
1242 raise Error('you must specify -t or --target')
1246 target = target_factory(args)
1247 tree = globals.trees.get(args.project, args.checkout, target)
1248 with TreeDirectory(tree):
1249 target.test(tree, args.test, argument_options(args))
1251 if target is not None and not args.keep:
1255 if target is not None and not args.keep:
1258 elif globals.command == 'shell':
1259 if args.target is None:
1260 raise Error('you must specify -t or --target')
1262 target = target_factory(args)
1263 target.command('bash')
1265 elif globals.command == 'revision':
1267 target = SourceTarget()
1268 tree = globals.trees.get(args.project, args.checkout, target)
1269 with TreeDirectory(tree):
1270 print(command_and_read('git rev-parse HEAD')[0].strip()[:7])
1273 elif globals.command == 'checkout':
1275 if args.output is None:
1276 raise Error('you must specify -o or --output')
1278 target = SourceTarget()
1279 tree = globals.trees.get(args.project, args.checkout, target)
1280 with TreeDirectory(tree):
1281 shutil.copytree('.', args.output)
1285 raise Error('invalid command %s' % globals.command)
1290 print('cdist: %s' % str(e), file=sys.stderr)