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'),
109 BoolOption('docker_sudo'),
110 BoolOption('docker_no_user'),
111 Option('docker_hub_repository'),
112 Option('flatpak_state_dir'),
113 Option('parallel', multiprocessing.cpu_count()) ]
116 f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
122 if len(l) > 0 and l[0] == '#':
125 s = l.strip().split()
127 for k in self.options:
133 for o in self.options:
134 if o.key == k and o.value is not None:
139 for o in self.options:
142 raise Error('Required setting %s not found' % k)
146 for o in self.options:
150 if self.get('docker_sudo'):
162 if not globals.quiet:
163 print('\x1b[33m* %s\x1b[0m' % m)
165 def escape_spaces(s):
166 return s.replace(' ', '\\ ')
169 """Escape a host:filename string for use with an scp command"""
171 assert(len(s) == 1 or len(s) == 2)
173 return '%s:"\'%s\'"' % (s[0], s[1])
175 return '\"%s\"' % s[0]
178 return '\"%s\"' % n.substr(' ', '\\ ')
181 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
182 if b.startswith('s3://'):
183 command('s3cmd -P -r put "%s" "%s"' % (a, b))
185 command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
188 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
189 if b.startswith('s3://'):
190 command('s3cmd -P put "%s" "%s"' % (a, b))
196 temp_path = os.path.join(os.path.dirname(path), ".tmp." + os.path.basename(path))
197 command('scp %s %s' % (scp_escape(a), scp_escape(host + ":" + temp_path)))
198 command('ssh %s -- mv "%s" "%s"' % (host, escape_spaces(temp_path), escape_spaces(path)))
200 command('scp %s %s' % (scp_escape(a), scp_escape(b)))
204 Make directories either locally or on a remote host; remotely if
205 d includes a colon, otherwise locally.
207 if d.startswith('s3://'):
208 # No need to create folders on S3
211 if d.find(':') == -1:
219 command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
227 shutil.rmtree(a, ignore_errors=True)
233 raise Error('command %s failed' % c)
235 def command_and_read(c):
237 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE)
238 f = os.fdopen(os.dup(p.stdout.fileno()))
241 def read_wscript_variable(directory, variable):
242 f = open('%s/wscript' % directory, 'r')
249 if len(s) == 3 and s[0] == variable:
256 def set_version_in_wscript(version):
257 f = open('wscript', 'rw')
258 o = open('wscript.tmp', 'w')
265 if len(s) == 3 and s[0] == "VERSION":
266 print("VERSION = '%s'" % version, file=o)
268 print(l, file=o, end="")
272 os.rename('wscript.tmp', 'wscript')
274 def append_version_to_changelog(version):
276 f = open('ChangeLog', 'r')
278 log('Could not open ChangeLog')
284 f = open('ChangeLog', 'w')
285 now = datetime.datetime.now()
286 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))
289 def append_version_to_debian_changelog(version):
290 if not os.path.exists('debian'):
291 log('Could not find debian directory')
294 command('dch -b -v %s-1 "New upstream release."' % version)
296 def devel_to_git(git_commit, filename):
297 if git_commit is not None:
298 filename = filename.replace('devel', '-%s' % git_commit)
301 def argument_options(args):
303 if args.option is not None:
304 for o in args.option:
307 raise Error("Bad option `%s'" % o)
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', TEMPORARY_DIRECTORY)
423 self.set('CCACHE_BASEDIR', os.path.realpath(self.directory))
424 self.set('CCACHE_NOHASHDIR', '')
426 self.directory = directory
433 def package(self, project, checkout, output_dir, options):
434 tree = globals.trees.get(project, checkout, self)
435 if self.build_dependencies:
436 tree.build_dependencies(options)
438 if len(inspect.getargspec(tree.cscript['package']).args) == 3:
439 packages = tree.call('package', tree.version, options)
441 log("Deprecated cscript package() method with no options parameter")
442 packages = tree.call('package', tree.version)
444 if isinstance(packages, (str, unicode)):
445 copyfile(packages, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, packages))))
448 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
450 def build(self, project, checkout, options):
451 tree = globals.trees.get(project, checkout, self)
452 if self.build_dependencies:
453 tree.build_dependencies(options)
456 def test(self, tree, test, options):
457 """test is the test case to run, or None"""
458 if self.build_dependencies:
459 tree.build_dependencies(options)
461 return tree.call('test', test)
464 self.variables[a] = b
467 del(self.variables[a])
470 return self.variables[a]
472 def append(self, k, v, s):
473 if (not k in self.variables) or len(self.variables[k]) == 0:
474 self.variables[k] = '"%s"' % v
476 e = self.variables[k]
477 if e[0] == '"' and e[-1] == '"':
478 self.variables[k] = '"%s%s%s"' % (e[1:-1], s, v)
480 self.variables[k] = '"%s%s%s"' % (e, s, v)
482 def append_with_space(self, k, v):
483 return self.append(k, v, ' ')
485 def append_with_colon(self, k, v):
486 return self.append(k, v, ':')
488 def variables_string(self, escaped_quotes=False):
490 for k, v in self.variables.items():
492 v = v.replace('"', '\\"')
493 e += '%s=%s ' % (k, v)
498 rmtree(self.directory)
512 class DockerTarget(Target):
513 def __init__(self, platform, directory, version):
514 super(DockerTarget, self).__init__(platform, directory)
515 self.version = version
517 self.privileged = False
520 if config.get('docker_no_user'):
522 return '-u %s' % getpass.getuser()
525 opts = '-v %s:%s ' % (self.directory, self.directory)
526 for m in self.mounts:
527 opts += '-v %s:%s ' % (m, m)
529 opts += '--privileged=true '
531 opts += "-e CCACHE_DIR=/ccache --volumes-from ccache-%s" % self.image
534 if config.has('docker_hub_repository'):
535 tag = '%s:%s' % (config.get('docker_hub_repository'), tag)
537 self.container = command_and_read('%s run %s %s -itd %s /bin/bash' % (config.docker(), self._user_tag(), opts, tag)).read().strip()
539 def command(self, cmd):
540 dir = os.path.join(self.directory, os.path.relpath(os.getcwd(), self.directory))
541 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))
544 super(DockerTarget, self).cleanup()
545 command('%s kill %s' % (config.docker(), self.container))
548 self.mounts.append(m)
551 class FlatpakTarget(Target):
552 def __init__(self, project, checkout):
553 super(FlatpakTarget, self).__init__('flatpak')
554 self.build_dependencies = False
555 self.project = project
556 self.checkout = checkout
561 def command(self, cmd):
564 def checkout_dependencies(self):
565 tree = globals.trees.get(self.project, self.checkout, self)
566 return tree.checkout_dependencies()
571 def flatpak_builder(self):
572 b = 'flatpak-builder'
573 if config.has('flatpak_state_dir'):
574 b += ' --state-dir=%s' % config.get('flatpak_state_dir')
578 class WindowsTarget(DockerTarget):
580 This target exposes the following additional API:
582 version: Windows version ('xp' or None)
583 bits: bitness of Windows (32 or 64)
584 name: name of our target e.g. x86_64-w64-mingw32.shared
585 environment_prefix: path to Windows environment for the appropriate target (libraries and some tools)
586 tool_path: path to 32- and 64-bit tools
588 def __init__(self, version, bits, directory=None):
589 super(WindowsTarget, self).__init__('windows', directory, version)
592 self.tool_path = '%s/usr/bin' % config.get('mxe_prefix')
594 self.name = 'i686-w64-mingw32.shared'
596 self.name = 'x86_64-w64-mingw32.shared'
597 self.environment_prefix = '%s/usr/%s' % (config.get('mxe_prefix'), self.name)
599 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.environment_prefix)
600 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
601 self.set('PATH', '%s/bin:%s:%s' % (self.environment_prefix, self.tool_path, os.environ['PATH']))
602 self.set('CC', '%s-gcc' % self.name)
603 self.set('CXX', '%s-g++' % self.name)
604 self.set('LD', '%s-ld' % self.name)
605 self.set('RANLIB', '%s-ranlib' % self.name)
606 self.set('WINRC', '%s-windres' % self.name)
607 cxx = '-I%s/include -I%s/include' % (self.environment_prefix, self.directory)
608 link = '-L%s/lib -L%s/lib' % (self.environment_prefix, self.directory)
609 self.set('CXXFLAGS', '"%s"' % cxx)
610 self.set('CPPFLAGS', '')
611 self.set('LINKFLAGS', '"%s"' % link)
612 self.set('LDFLAGS', '"%s"' % link)
614 self.image = 'windows'
617 def library_prefix(self):
618 log('Deprecated property library_prefix: use environment_prefix')
619 return self.environment_prefix
622 def windows_prefix(self):
623 log('Deprecated property windows_prefix: use environment_prefix')
624 return self.environment_prefix
627 def mingw_prefixes(self):
628 log('Deprecated property mingw_prefixes: use environment_prefix')
629 return [self.environment_prefix]
632 def mingw_path(self):
633 log('Deprecated property mingw_path: use tool_path')
634 return self.tool_path
637 def mingw_name(self):
638 log('Deprecated property mingw_name: use name')
642 class LinuxTarget(DockerTarget):
644 Build for Linux in a docker container.
645 This target exposes the following additional API:
647 distro: distribution ('debian', 'ubuntu', 'centos' or 'fedora')
648 version: distribution version (e.g. '12.04', '8', '6.5')
649 bits: bitness of the distribution (32 or 64)
650 detail: None or 'appimage' if we are building for appimage
653 def __init__(self, distro, version, bits, directory=None):
654 super(LinuxTarget, self).__init__('linux', directory, version)
659 self.set('CXXFLAGS', '-I%s/include' % self.directory)
660 self.set('CPPFLAGS', '')
661 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
662 self.set('PKG_CONFIG_PATH',
663 '%s/lib/pkgconfig:%s/lib64/pkgconfig:/usr/local/lib64/pkgconfig:/usr/local/lib/pkgconfig' % (self.directory, self.directory))
664 self.set('PATH', '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin')
666 if self.version is None:
667 self.image = '%s-%s' % (self.distro, self.bits)
669 self.image = '%s-%s-%s' % (self.distro, self.version, self.bits)
672 super(LinuxTarget, self).setup()
674 self.set('CC', '"ccache gcc"')
675 self.set('CXX', '"ccache g++"')
677 def test(self, tree, test, options):
678 self.append_with_colon('PATH', '%s/bin' % self.directory)
679 self.append_with_colon('LD_LIBRARY_PATH', '%s/lib' % self.directory)
680 super(LinuxTarget, self).test(tree, test, options)
683 class AppImageTarget(LinuxTarget):
684 def __init__(self, work):
685 super(AppImageTarget, self).__init__('ubuntu', '16.04', 64, work)
686 self.detail = 'appimage'
687 self.privileged = True
690 class OSXTarget(Target):
691 def __init__(self, directory=None):
692 super(OSXTarget, self).__init__('osx', directory)
693 self.sdk = config.get('osx_sdk')
694 self.sdk_prefix = config.get('osx_sdk_prefix')
695 self.environment_prefix = config.get('osx_environment_prefix')
697 def command(self, c):
698 command('%s %s' % (self.variables_string(False), c))
701 class OSXSingleTarget(OSXTarget):
702 def __init__(self, bits, directory=None):
703 super(OSXSingleTarget, self).__init__(directory)
711 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (self.sdk_prefix, self.sdk, arch)
712 enviro = '%s/%d' % (config.get('osx_environment_prefix'), bits)
714 # Environment variables
715 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
716 self.set('CPPFLAGS', '')
717 self.set('CXXFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
718 self.set('LDFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
719 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
720 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
721 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
722 self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
724 def package(self, project, checkout, output_dir, options):
725 raise Error('cannot package non-universal OS X versions')
727 @Target.ccache.setter
729 Target.ccache.fset(self, v)
731 self.set('CC', '"ccache gcc"')
732 self.set('CXX', '"ccache g++"')
735 class OSXUniversalTarget(OSXTarget):
736 def __init__(self, directory=None):
737 super(OSXUniversalTarget, self).__init__(directory)
739 def package(self, project, checkout, output_dir, options):
742 target = OSXSingleTarget(b, os.path.join(self.directory, '%d' % b))
743 target.ccache = self.ccache
744 tree = globals.trees.get(project, checkout, target)
745 tree.build_dependencies(options)
748 tree = globals.trees.get(project, checkout, self)
749 with TreeDirectory(tree):
750 if len(inspect.getargspec(tree.cscript['package']).args) == 3:
751 packages = tree.call('package', tree.version, options)
753 log("Deprecated cscript package() method with no options parameter")
754 packages = tree.call('package', tree.version)
756 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
758 class SourceTarget(Target):
759 """Build a source .tar.bz2"""
761 super(SourceTarget, self).__init__('source')
763 def command(self, c):
764 log('host -> %s' % c)
765 command('%s %s' % (self.variables_string(), c))
768 rmtree(self.directory)
770 def package(self, project, checkout, output_dir, options):
771 tree = globals.trees.get(project, checkout, self)
772 with TreeDirectory(tree):
773 name = read_wscript_variable(os.getcwd(), 'APPNAME')
774 command('./waf dist')
775 p = os.path.abspath('%s-%s.tar.bz2' % (name, tree.version))
776 copyfile(p, os.path.join(output_dir, os.path.basename(devel_to_git(tree.git_commit, p))))
778 # @param s Target string:
780 # or ubuntu-version-{32,64}
781 # or debian-version-{32,64}
782 # or centos-version-{32,64}
783 # or fedora-version-{32,64}
784 # or mageia-version-{32,64}
789 # @param debug True to build with debugging symbols (where possible)
790 def target_factory(args):
793 if s.startswith('windows-'):
796 target = WindowsTarget(None, int(x[1]), args.work)
798 target = WindowsTarget(x[1], int(x[2]), args.work)
800 raise Error("Bad Windows target name `%s'")
801 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-') or s.startswith('fedora-') or s.startswith('mageia-'):
804 raise Error("Bad Linux target name `%s'; must be something like ubuntu-16.04-32 (i.e. distro-version-bits)" % s)
805 target = LinuxTarget(p[0], p[1], int(p[2]), args.work)
806 elif s.startswith('arch-'):
809 raise Error("Bad Arch target name `%s'; must be arch-32 or arch-64")
810 target = LinuxTarget(p[0], None, int(p[1]), args.work)
811 elif s == 'raspbian':
812 target = LinuxTarget(s, None, None, args.work)
813 elif s.startswith('osx-'):
814 target = OSXSingleTarget(int(s.split('-')[1]), args.work)
816 if globals.command == 'build':
817 target = OSXSingleTarget(64, args.work)
819 target = OSXUniversalTarget(args.work)
821 target = SourceTarget()
823 target = FlatpakTarget(args.project, args.checkout)
824 elif s == 'appimage':
825 target = AppImageTarget(args.work)
828 raise Error("Bad target `%s'" % s)
830 target.debug = args.debug
831 target.ccache = args.ccache
833 if args.environment is not None:
834 for e in args.environment:
835 target.set(e, os.environ[e])
837 if args.mount is not None:
850 """Description of a tree, which is a checkout of a project,
851 possibly built. This class is never exposed to cscripts.
853 name -- name of git repository (without the .git)
854 specifier -- git tag or revision to use
855 target -- target object that we are using
856 version -- version from the wscript (if one is present)
857 git_commit -- git revision that is actually being used
858 built -- true if the tree has been built yet in this run
859 required_by -- name of the tree that requires this one
862 def __init__(self, name, specifier, target, required_by):
864 self.specifier = specifier
867 self.git_commit = None
869 self.required_by = required_by
877 redirect = '>/dev/null'
878 command('git clone %s %s/%s.git %s/src/%s' % (flags, config.get('git_prefix'), self.name, target.directory, self.name))
879 os.chdir('%s/src/%s' % (target.directory, self.name))
881 spec = self.specifier
885 command('git checkout %s %s %s' % (flags, spec, redirect))
886 self.git_commit = command_and_read('git rev-parse --short=7 HEAD').readline().strip()
887 command('git submodule init --quiet')
888 command('git submodule update --quiet')
890 proj = '%s/src/%s' % (target.directory, self.name)
893 exec(open('%s/cscript' % proj).read(), self.cscript)
895 if os.path.exists('%s/wscript' % proj):
896 v = read_wscript_variable(proj, "VERSION");
899 self.version = Version(v)
901 tag = subprocess.Popen(shlex.split('git -C %s describe --tags' % proj), stdout=subprocess.PIPE).communicate()[0][1:]
902 self.version = Version.from_git_tag(tag)
906 def call(self, function, *args):
907 with TreeDirectory(self):
908 return self.cscript[function](self.target, *args)
910 def add_defaults(self, options):
911 """Add the defaults from this into a dict options"""
912 if 'option_defaults' in self.cscript:
913 for k, v in self.cscript['option_defaults']().items():
917 def dependencies(self, options):
918 if not 'dependencies' in self.cscript:
921 if len(inspect.getargspec(self.cscript['dependencies']).args) == 2:
922 deps = self.call('dependencies', options)
924 log("Deprecated cscript dependencies() method with no options parameter")
925 deps = self.call('dependencies')
928 dep = globals.trees.get(d[0], d[1], self.target, self.name)
930 # Start with the options passed in
931 dep_options = copy.copy(options)
932 # Add things specified by the parent
934 for k, v in d[2].items():
935 if not k in dep_options:
937 # Then fill in the dependency's defaults
938 dep.add_defaults(dep_options)
940 for i in dep.dependencies(dep_options):
942 yield (dep, dep_options)
944 def checkout_dependencies(self, options={}):
945 for i in self.dependencies(options):
948 def build_dependencies(self, options):
949 for i in self.dependencies(options):
952 def build(self, options):
956 variables = copy.copy(self.target.variables)
958 # Start with the options passed in
959 options = copy.copy(options)
960 # Fill in the defaults
961 self.add_defaults(options)
963 if not globals.dry_run:
964 if len(inspect.getargspec(self.cscript['build']).args) == 2:
965 self.call('build', options)
969 self.target.variables = variables
973 # Command-line parser
979 "build": "build project",
980 "package": "package and build project",
981 "release": "release a project using its next version number (changing wscript and tagging)",
982 "pot": "build the project's .pot files",
983 "changelog": "generate a simple HTML changelog",
984 "manual": "build the project's manual",
985 "doxygen": "build the project's Doxygen documentation",
986 "latest": "print out the latest version",
987 "test": "run the project's unit tests",
988 "shell": "build the project then start a shell",
989 "checkout": "check out the project",
990 "revision": "print the head git revision number"
993 one_of = "Command is one of:\n"
995 for k, v in commands.items():
996 one_of += "\t%s\t%s\n" % (k, v)
999 parser = argparse.ArgumentParser()
1000 parser.add_argument('command', help=summary)
1001 parser.add_argument('-p', '--project', help='project name')
1002 parser.add_argument('--minor', help='minor version number bump', action='store_true')
1003 parser.add_argument('--micro', help='micro version number bump', action='store_true')
1004 parser.add_argument('--latest-major', help='major version to return with latest', type=int)
1005 parser.add_argument('--latest-minor', help='minor version to return with latest', type=int)
1006 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
1007 parser.add_argument('-o', '--output', help='output directory', default='.')
1008 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
1009 parser.add_argument('-t', '--target', help='target')
1010 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
1011 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
1012 parser.add_argument('-w', '--work', help='override default work directory')
1013 parser.add_argument('-g', '--git-prefix', help='override configured git prefix')
1014 parser.add_argument('--test', help="name of test to run (with `test'), defaults to all")
1015 parser.add_argument('-n', '--dry-run', help='run the process without building anything', action='store_true')
1016 parser.add_argument('-e', '--environment', help='pass the value of the named environment variable into the build', action='append')
1017 parser.add_argument('-m', '--mount', help='mount a given directory in the build environment', action='append')
1018 parser.add_argument('--no-version-commit', help="use just tags for versioning, don't modify wscript, ChangeLog etc.", action='store_true')
1019 parser.add_argument('--option', help='set an option for the build (use --option key:value)', action='append')
1020 parser.add_argument('--ccache', help='use ccache', action='store_true')
1021 args = parser.parse_args()
1023 # Override configured stuff
1024 if args.git_prefix is not None:
1025 config.set('git_prefix', args.git_prefix)
1027 if args.output.find(':') == -1:
1028 # This isn't of the form host:path so make it absolute
1029 args.output = os.path.abspath(args.output) + '/'
1031 if args.output[-1] != ':' and args.output[-1] != '/':
1034 # Now, args.output is 'host:', 'host:path/' or 'path/'
1036 if args.work is not None:
1037 args.work = os.path.abspath(args.work)
1039 if args.project is None and args.command != 'shell':
1040 raise Error('you must specify -p or --project')
1042 globals.quiet = args.quiet
1043 globals.command = args.command
1044 globals.dry_run = args.dry_run
1046 if not globals.command in commands:
1047 e = 'command must be one of:\n' + one_of
1048 raise Error('command must be one of:\n%s' % one_of)
1050 if globals.command == 'build':
1051 if args.target is None:
1052 raise Error('you must specify -t or --target')
1054 target = target_factory(args)
1055 target.build(args.project, args.checkout, argument_options(args))
1059 elif globals.command == 'package':
1060 if args.target is None:
1061 raise Error('you must specify -t or --target')
1065 target = target_factory(args)
1067 if target.platform == 'linux' and target.detail != "appimage":
1068 if target.distro != 'arch':
1069 output_dir = os.path.join(args.output, '%s-%s-%d' % (target.distro, target.version, target.bits))
1071 output_dir = os.path.join(args.output, '%s-%d' % (target.distro, target.bits))
1073 output_dir = args.output
1075 makedirs(output_dir)
1077 # Start with the options passed on the command line
1078 options = copy.copy(argument_options(args))
1079 # Fill in the defaults
1080 tree = globals.trees.get(args.project, args.checkout, target)
1081 tree.add_defaults(options)
1082 target.package(args.project, args.checkout, output_dir, options)
1084 if target is not None and not args.keep:
1088 if target is not None and not args.keep:
1091 elif globals.command == 'release':
1092 if args.minor is False and args.micro is False:
1093 raise Error('you must specify --minor or --micro')
1095 target = SourceTarget()
1096 tree = globals.trees.get(args.project, args.checkout, target)
1098 version = tree.version
1099 version.to_release()
1101 version.bump_minor()
1103 version.bump_micro()
1105 with TreeDirectory(tree):
1106 if not args.no_version_commit:
1107 set_version_in_wscript(version)
1108 append_version_to_changelog(version)
1109 append_version_to_debian_changelog(version)
1110 command('git commit -a -m "Bump version"')
1112 command('git tag -m "v%s" v%s' % (version, version))
1114 if not args.no_version_commit:
1116 set_version_in_wscript(version)
1117 command('git commit -a -m "Bump version"')
1120 command('git push --tags')
1124 elif globals.command == 'pot':
1125 target = SourceTarget()
1126 tree = globals.trees.get(args.project, args.checkout, target)
1128 pots = tree.call('make_pot')
1130 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
1134 elif globals.command == 'changelog':
1135 target = SourceTarget()
1136 tree = globals.trees.get(args.project, args.checkout, target)
1138 with TreeDirectory(tree):
1139 text = open('ChangeLog', 'r')
1141 html = tempfile.NamedTemporaryFile()
1152 if len(l) > 0 and l[0] == "\t":
1154 if len(s) == 4 and s[1] == "Version" and s[3] == "released.":
1157 if last is not None and len(changes) > 0:
1158 print("<h2>Changes between version %s and %s</h2>" % (s[2], last), file=html)
1159 print("<ul>", file=html)
1161 print("<li>%s" % c, file=html)
1162 print("</ul>", file=html)
1172 changes.append(c[2:])
1174 changes[-1] += " " + c
1176 copyfile(html.file, '%schangelog.html' % args.output)
1180 elif globals.command == 'manual':
1181 target = SourceTarget()
1182 tree = globals.trees.get(args.project, args.checkout, target)
1184 outs = tree.call('make_manual')
1186 if os.path.isfile(o):
1187 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
1189 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
1193 elif globals.command == 'doxygen':
1194 target = SourceTarget()
1195 tree = globals.trees.get(args.project, args.checkout, target)
1197 dirs = tree.call('make_doxygen')
1198 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
1202 copytree(d, args.output)
1206 elif globals.command == 'latest':
1207 target = SourceTarget()
1208 tree = globals.trees.get(args.project, args.checkout, target)
1210 with TreeDirectory(tree):
1211 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
1213 while latest is None:
1215 m = re.compile(".*\((.*)\).*").match(t)
1217 tags = m.group(1).split(', ')
1222 if len(t) > 0 and t[0] == 'v':
1224 if (args.latest_major is None or v.major == args.latest_major) and (args.latest_minor is None or v.minor == args.latest_minor):
1230 elif globals.command == 'test':
1231 if args.target is None:
1232 raise Error('you must specify -t or --target')
1236 target = target_factory(args)
1237 tree = globals.trees.get(args.project, args.checkout, target)
1238 with TreeDirectory(tree):
1239 target.test(tree, args.test, argument_options(args))
1241 if target is not None and not args.keep:
1245 if target is not None and not args.keep:
1248 elif globals.command == 'shell':
1249 if args.target is None:
1250 raise Error('you must specify -t or --target')
1252 target = target_factory(args)
1253 target.command('bash')
1255 elif globals.command == 'revision':
1257 target = SourceTarget()
1258 tree = globals.trees.get(args.project, args.checkout, target)
1259 with TreeDirectory(tree):
1260 print(command_and_read('git rev-parse HEAD').readline().strip()[:7])
1263 elif globals.command == 'checkout':
1265 if args.output is None:
1266 raise Error('you must specify -o or --output')
1268 target = SourceTarget()
1269 tree = globals.trees.get(args.project, args.checkout, target)
1270 with TreeDirectory(tree):
1271 shutil.copytree('.', args.output)
1275 raise Error('invalid command %s' % globals.command)
1280 print('cdist: %s' % str(e), file=sys.stderr)