3 # Copyright (C) 2012-2015 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.
31 TEMPORARY_DIRECTORY = '/var/tmp'
33 class Error(Exception):
34 def __init__(self, value):
43 Store for Tree objects which re-uses already-created objects
44 and checks for requests for different versions of the same thing.
50 def get(self, name, specifier, target):
52 if t.name == name and t.specifier == specifier and t.target == target:
54 elif t.name == name and t.specifier != specifier:
55 raise Error('conflicting versions of %s requested (%s and %s)' % (name, specifier, t.specifier))
57 nt = Tree(name, specifier, target)
74 def __init__(self, key, default=None):
78 def offer(self, key, value):
82 class BoolOption(object):
83 def __init__(self, key):
87 def offer(self, key, value):
89 self.value = (value == 'yes' or value == '1' or value == 'true')
93 self.options = [ Option('linux_chroot_prefix'),
94 Option('windows_environment_prefix'),
95 Option('mingw_prefix'),
97 Option('osx_build_host'),
98 Option('osx_environment_prefix'),
99 Option('osx_sdk_prefix'),
101 Option('parallel', 4) ]
104 f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
110 if len(l) > 0 and l[0] == '#':
113 s = l.strip().split()
115 for k in self.options:
121 for o in self.options:
125 raise Error('Required setting %s not found' % k)
128 for o in self.options:
138 if not globals.quiet:
139 print('\x1b[33m* %s\x1b[0m' % m)
143 assert(len(s) == 1 or len(s) == 2)
145 return '%s:"\'%s\'"' % (s[0], s[1])
147 return '\"%s\"' % s[0]
150 log('copy %s -> %s' % (scp_escape(b), scp_escape(b)))
151 command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
154 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
155 command('scp %s %s' % (scp_escape(a), scp_escape(b)))
158 if d.find(':') == -1:
162 command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
170 shutil.rmtree(a, ignore_errors=True)
176 raise Error('command %s failed' % c)
178 def command_and_read(c):
180 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE)
181 f = os.fdopen(os.dup(p.stdout.fileno()))
184 def read_wscript_variable(directory, variable):
185 f = open('%s/wscript' % directory, 'r')
192 if len(s) == 3 and s[0] == variable:
199 def set_version_in_wscript(version):
200 f = open('wscript', 'rw')
201 o = open('wscript.tmp', 'w')
208 if len(s) == 3 and s[0] == "VERSION":
209 print("Writing %s" % version)
210 print("VERSION = '%s'" % version, file=o)
212 print(l, file=o, end="")
216 os.rename('wscript.tmp', 'wscript')
218 def append_version_to_changelog(version):
220 f = open('ChangeLog', 'r')
222 log('Could not open ChangeLog')
228 f = open('ChangeLog', 'w')
229 now = datetime.datetime.now()
230 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))
233 def append_version_to_debian_changelog(version):
234 if not os.path.exists('debian'):
235 log('Could not find debian directory')
238 command('dch -b -v %s-1 "New upstream release."' % version)
240 def devel_to_git(git_commit, filename):
241 if git_commit is not None:
242 filename = filename.replace('devel', '-%s' % git_commit)
246 def __init__(self, tree):
249 self.cwd = os.getcwd()
250 os.chdir('%s/src/%s' % (self.tree.target.directory, self.tree.name))
251 def __exit__(self, type, value, traceback):
259 def __init__(self, s):
262 if s.startswith("'"):
267 if s.endswith('devel'):
271 if s.endswith('pre'):
275 self.major = int(p[0])
276 self.minor = int(p[1])
278 self.micro = int(p[2])
282 def bump_minor(self):
286 def bump_micro(self):
292 def to_release(self):
296 s = '%d.%d.%d' % (self.major, self.minor, self.micro)
306 class Target(object):
308 platform -- platform string (e.g. 'windows', 'linux', 'osx')
309 directory -- directory to work in; if None we will use a temporary directory
310 Temporary directories will be removed after use; specified directories will not.
312 def __init__(self, platform, directory=None):
313 self.platform = platform
314 self.parallel = int(config.get('parallel'))
316 # self.directory is the working directory
317 if directory is None:
318 self.directory = tempfile.mkdtemp('', 'tmp', TEMPORARY_DIRECTORY)
321 self.directory = directory
324 # Environment variables that we will use when we call cscripts
328 def package(self, project, checkout):
329 tree = globals.trees.get(project, checkout, self)
330 tree.build_dependencies()
332 return tree.call('package', tree.version), tree.git_commit
334 def test(self, tree):
335 tree.build_dependencies()
337 return tree.call('test')
340 self.variables[a] = b
343 del(self.variables[a])
346 return self.variables[a]
348 def append_with_space(self, k, v):
349 if (not k in self.variables) or len(self.variables[k]) == 0:
350 self.variables[k] = '"%s"' % v
352 e = self.variables[k]
353 if e[0] == '"' and e[-1] == '"':
354 self.variables[k] = '"%s %s"' % (e[1:-1], v)
356 self.variables[k] = '"%s %s"' % (e, v)
358 def variables_string(self, escaped_quotes=False):
360 for k, v in self.variables.items():
362 v = v.replace('"', '\\"')
363 e += '%s=%s ' % (k, v)
368 rmtree(self.directory)
374 class WindowsTarget(Target):
375 def __init__(self, bits, directory=None):
376 super(WindowsTarget, self).__init__('windows', directory)
379 self.windows_prefix = '%s/%d' % (config.get('windows_environment_prefix'), self.bits)
380 if not os.path.exists(self.windows_prefix):
381 raise Error('windows prefix %s does not exist' % self.windows_prefix)
384 self.mingw_name = 'i686'
386 self.mingw_name = 'x86_64'
388 self.mingw_path = '%s/%d/bin' % (config.get('mingw_prefix'), self.bits)
389 self.mingw_prefixes = ['/%s/%d' % (config.get('mingw_prefix'), self.bits), '%s/%d/%s-w64-mingw32' % (config.get('mingw_prefix'), bits, self.mingw_name)]
391 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.windows_prefix)
392 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
393 self.set('PATH', '%s/bin:%s:%s' % (self.windows_prefix, self.mingw_path, os.environ['PATH']))
394 self.set('CC', '%s-w64-mingw32-gcc' % self.mingw_name)
395 self.set('CXX', '%s-w64-mingw32-g++' % self.mingw_name)
396 self.set('LD', '%s-w64-mingw32-ld' % self.mingw_name)
397 self.set('RANLIB', '%s-w64-mingw32-ranlib' % self.mingw_name)
398 self.set('WINRC', '%s-w64-mingw32-windres' % self.mingw_name)
399 cxx = '-I%s/include -I%s/include' % (self.windows_prefix, self.directory)
400 link = '-L%s/lib -L%s/lib' % (self.windows_prefix, self.directory)
401 for p in self.mingw_prefixes:
402 cxx += ' -I%s/include' % p
403 link += ' -L%s/lib' % p
404 self.set('CXXFLAGS', '"%s"' % cxx)
405 self.set('CPPFLAGS', '')
406 self.set('LINKFLAGS', '"%s"' % link)
407 self.set('LDFLAGS', '"%s"' % link)
409 def command(self, c):
410 log('host -> %s' % c)
411 command('%s %s' % (self.variables_string(), c))
413 class LinuxTarget(Target):
414 """Parent for Linux targets"""
415 def __init__(self, distro, version, bits, directory=None):
416 super(LinuxTarget, self).__init__('linux', directory)
418 self.version = version
421 self.set('CXXFLAGS', '-I%s/include' % self.directory)
422 self.set('CPPFLAGS', '')
423 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
424 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:/usr/local/lib/pkgconfig' % self.directory)
425 self.set('PATH', '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin')
427 class ChrootTarget(LinuxTarget):
428 """Build in a chroot"""
429 def __init__(self, distro, version, bits, directory=None):
430 super(ChrootTarget, self).__init__(distro, version, bits, directory)
431 # e.g. ubuntu-14.04-64
432 if self.version is not None and self.bits is not None:
433 self.chroot = '%s-%s-%d' % (self.distro, self.version, self.bits)
435 self.chroot = self.distro
436 # e.g. /home/carl/Environments/ubuntu-14.04-64
437 self.chroot_prefix = '%s/%s' % (config.get('linux_chroot_prefix'), self.chroot)
439 def command(self, c):
440 command('%s schroot -c %s -p -- %s' % (self.variables_string(), self.chroot, c))
443 class HostTarget(LinuxTarget):
444 """Build directly on the host"""
445 def __init__(self, distro, version, bits, directory=None):
446 super(HostTarget, self).__init__(distro, version, bits, directory)
448 def command(self, c):
449 command('%s %s' % (self.variables_string(), c))
455 class OSXTarget(Target):
456 def __init__(self, directory=None):
457 super(OSXTarget, self).__init__('osx', directory)
458 self.sdk = config.get('osx_sdk')
459 self.sdk_prefix = config.get('osx_sdk_prefix')
461 def command(self, c):
462 command('%s %s' % (self.variables_string(False), c))
465 class OSXSingleTarget(OSXTarget):
466 def __init__(self, bits, directory=None):
467 super(OSXSingleTarget, self).__init__(directory)
475 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (self.sdk_prefix, self.sdk, arch)
476 enviro = '%s/%d' % (config.get('osx_environment_prefix'), bits)
478 # Environment variables
479 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
480 self.set('CPPFLAGS', '')
481 self.set('CXXFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
482 self.set('LDFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
483 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
484 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
485 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
486 self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
488 def package(self, project, checkout):
489 raise Error('cannot package non-universal OS X versions')
492 class OSXUniversalTarget(OSXTarget):
493 def __init__(self, directory=None):
494 super(OSXUniversalTarget, self).__init__(directory)
496 def package(self, project, checkout):
499 target = OSXSingleTarget(b, os.path.join(self.directory, '%d' % b))
500 tree = globals.trees.get(project, checkout, target)
501 tree.build_dependencies()
504 tree = globals.trees.get(project, checkout, self)
505 with TreeDirectory(tree):
506 return tree.call('package', tree.version), tree.git_commit
508 class SourceTarget(Target):
509 """Build a source .tar.bz2"""
511 super(SourceTarget, self).__init__('source')
513 def command(self, c):
514 log('host -> %s' % c)
515 command('%s %s' % (self.variables_string(), c))
518 rmtree(self.directory)
520 def package(self, project, checkout):
521 tree = globals.trees.get(project, checkout, self)
522 with TreeDirectory(tree):
523 name = read_wscript_variable(os.getcwd(), 'APPNAME')
524 command('./waf dist')
525 return os.path.abspath('%s-%s.tar.bz2' % (name, tree.version)), tree.git_commit
528 # @param s Target string:
530 # or ubuntu-version-{32,64}
531 # or debian-version-{32,64}
532 # or centos-version-{32,64}
535 # @param debug True to build with debugging symbols (where possible)
536 def target_factory(s, debug, work):
538 if s.startswith('windows-'):
539 target = WindowsTarget(int(s.split('-')[1]), work)
540 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-'):
543 raise Error("Bad Linux target name `%s'; must be something like ubuntu-12.04-32 (i.e. distro-version-bits)" % s)
544 target = ChrootTarget(p[0], p[1], int(p[2]), work)
545 elif s.startswith('arch-'):
548 raise Error("Bad Arch target name `%s'; must be arch-32 or arch-64")
549 target = ChrootTarget(p[0], None, p[1], work)
550 elif s == 'raspbian':
551 target = ChrootTarget(s, None, None, work)
554 f = open('/etc/fedora-release', 'r')
555 l = f.readline().strip().split()
556 if command_and_read('uname -m').read().strip() == 'x86_64':
560 target = HostTarget("fedora", l[2], bits, work)
561 except Exception as e:
562 raise Error("could not identify distribution for `host' target (%s)" % e)
563 elif s.startswith('osx-'):
564 target = OSXSingleTarget(int(s.split('-')[1]), work)
566 if globals.command == 'build':
567 target = OSXSingleTarget(64, work)
569 target = OSXUniversalTarget(work)
571 target = SourceTarget()
574 raise Error("Bad target `%s'" % s)
585 """Description of a tree, which is a checkout of a project,
586 possibly built. This class is never exposed to cscripts.
588 name -- name of git repository (without the .git)
589 specifier -- git tag or revision to use
590 target --- target object that we are using
591 version --- version from the wscript (if one is present)
592 git_commit -- git revision that is actually being used
593 built --- true if the tree has been built yet in this run
596 def __init__(self, name, specifier, target):
598 self.specifier = specifier
601 self.git_commit = None
610 redirect = '>/dev/null'
611 command('git clone %s %s/%s.git %s/src/%s' % (flags, config.get('git_prefix'), self.name, target.directory, self.name))
612 os.chdir('%s/src/%s' % (target.directory, self.name))
614 spec = self.specifier
618 command('git checkout %s %s %s' % (flags, spec, redirect))
619 self.git_commit = command_and_read('git rev-parse --short=7 HEAD').readline().strip()
620 command('git submodule init --quiet')
621 command('git submodule update --quiet')
623 proj = '%s/src/%s' % (target.directory, self.name)
626 execfile('%s/cscript' % proj, self.cscript)
628 if os.path.exists('%s/wscript' % proj):
629 v = read_wscript_variable(proj, "VERSION");
631 self.version = Version(v)
635 def call(self, function, *args):
636 with TreeDirectory(self):
637 return self.cscript[function](self.target, *args)
639 def build_dependencies(self):
640 if 'dependencies' in self.cscript:
641 for d in self.cscript['dependencies'](self.target):
642 log('Building dependency %s %s of %s' % (d[0], d[1], self.name))
643 dep = globals.trees.get(d[0], d[1], self.target)
644 dep.build_dependencies()
646 # Make the options to pass in from the option_defaults of the thing
647 # we are building and any options specified by the parent.
649 if 'option_defaults' in dep.cscript:
650 options = dep.cscript['option_defaults']()
652 for k, v in d[2].items():
657 def build(self, options=None):
661 variables = copy.copy(self.target.variables)
663 if len(inspect.getargspec(self.cscript['build']).args) == 2:
664 self.call('build', options)
668 self.target.variables = variables
672 # Command-line parser
678 "build": "build project",
679 "package": "package and build project",
680 "release": "release a project using its next version number (changing wscript and tagging)",
681 "pot": "build the project's .pot files",
682 "changelog": "generate a simple HTML changelog",
683 "manual": "build the project's manual",
684 "doxygen": "build the project's Doxygen documentation",
685 "latest": "print out the latest version",
686 "test": "run the project's unit tests",
687 "shell": "build the project then start a shell in its chroot",
688 "checkout": "check out the project",
689 "revision": "print the head git revision number"
692 one_of = "Command is one of:\n"
694 for k, v in commands.items():
695 one_of += "\t%s\t%s\n" % (k, v)
698 parser = argparse.ArgumentParser()
699 parser.add_argument('command', help=summary)
700 parser.add_argument('-p', '--project', help='project name')
701 parser.add_argument('--minor', help='minor version number bump', action='store_true')
702 parser.add_argument('--micro', help='micro version number bump', action='store_true')
703 parser.add_argument('--major', help='major version to return with latest', type=int)
704 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
705 parser.add_argument('-o', '--output', help='output directory', default='.')
706 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
707 parser.add_argument('-t', '--target', help='target')
708 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
709 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
710 parser.add_argument('-w', '--work', help='override default work directory')
711 parser.add_argument('-g', '--git-prefix', help='override configured git prefix')
712 args = parser.parse_args()
714 # Override configured stuff
715 if args.git_prefix is not None:
716 config.set('git_prefix', args.git_prefix)
718 if args.output.find(':') == -1:
719 # This isn't of the form host:path so make it absolute
720 args.output = os.path.abspath(args.output) + '/'
722 if args.output[-1] != ':' and args.output[-1] != '/':
725 # Now, args.output is 'host:', 'host:path/' or 'path/'
727 if args.work is not None:
728 args.work = os.path.abspath(args.work)
730 if args.project is None and args.command != 'shell':
731 raise Error('you must specify -p or --project')
733 globals.quiet = args.quiet
734 globals.command = args.command
736 if not globals.command in commands:
737 e = 'command must be one of:\n' + one_of
738 raise Error('command must be one of:\n%s' % one_of)
740 if globals.command == 'build':
741 if args.target is None:
742 raise Error('you must specify -t or --target')
744 target = target_factory(args.target, args.debug, args.work)
745 tree = globals.trees.get(args.project, args.checkout, target)
746 tree.build_dependencies()
751 elif globals.command == 'package':
752 if args.target is None:
753 raise Error('you must specify -t or --target')
755 target = target_factory(args.target, args.debug, args.work)
756 packages, git_commit = target.package(args.project, args.checkout)
757 if hasattr(packages, 'strip') or (not hasattr(packages, '__getitem__') and not hasattr(packages, '__iter__')):
758 packages = [packages]
760 if target.platform == 'linux':
761 out = '%s%s-%s-%d' % (args.output, target.distro, target.version, target.bits)
767 copyfile(p, '%s/%s' % (out, os.path.basename(devel_to_git(git_commit, p))))
770 makedirs(args.output)
774 copyfile(p, '%s%s' % (args.output, os.path.basename(devel_to_git(git_commit, p))))
779 elif globals.command == 'release':
780 if args.minor is False and args.micro is False:
781 raise Error('you must specify --minor or --micro')
783 target = SourceTarget()
784 tree = globals.trees.get(args.project, args.checkout, target)
786 version = tree.version
793 set_version_in_wscript(version)
794 append_version_to_changelog(version)
795 append_version_to_debian_changelog(version)
797 command('git commit -a -m "Bump version"')
798 command('git tag -m "v%s" v%s' % (version, version))
801 set_version_in_wscript(version)
802 command('git commit -a -m "Bump version"')
804 command('git push --tags')
808 elif globals.command == 'pot':
809 target = SourceTarget()
810 tree = globals.trees.get(args.project, args.checkout, target)
812 pots = tree.call('make_pot')
814 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
818 elif globals.command == 'changelog':
819 target = SourceTarget()
820 tree = globals.trees.get(args.project, args.checkout, target)
822 with TreeDirectory(tree):
823 text = open('ChangeLog', 'r')
825 html = tempfile.NamedTemporaryFile()
836 if len(l) > 0 and l[0] == "\t":
838 if len(s) == 4 and s[1] == "Version" and s[3] == "released.":
841 if last is not None and len(changes) > 0:
842 print("<h2>Changes between version %s and %s</h2>" % (s[2], last), file=html)
843 print("<ul>", file=html)
845 print("<li>%s" % c, file=html)
846 print("</ul>", file=html)
856 changes.append(c[2:])
858 changes[-1] += " " + c
860 copyfile(html.file, '%schangelog.html' % args.output)
864 elif globals.command == 'manual':
865 target = SourceTarget()
866 tree = globals.trees.get(args.project, args.checkout, target)
868 outs = tree.call('make_manual')
870 if os.path.isfile(o):
871 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
873 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
877 elif globals.command == 'doxygen':
878 target = SourceTarget()
879 tree = globals.trees.get(args.project, args.checkout, target)
881 dirs = tree.call('make_doxygen')
882 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
886 copytree(d, args.output)
890 elif globals.command == 'latest':
891 target = SourceTarget()
892 tree = globals.trees.get(args.project, args.checkout, target)
894 with TreeDirectory(tree):
895 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
897 while latest is None:
899 m = re.compile(".*\((.*)\).*").match(t)
901 tags = m.group(1).split(', ')
906 if len(t) > 0 and t[0] == 'v':
908 if args.major is None or v.major == args.major:
914 elif globals.command == 'test':
915 if args.target is None:
916 raise Error('you must specify -t or --target')
920 target = target_factory(args.target, args.debug, args.work)
921 tree = globals.trees.get(args.project, args.checkout, target)
922 with TreeDirectory(tree):
925 if target is not None:
929 if target is not None:
932 elif globals.command == 'shell':
933 if args.target is None:
934 raise Error('you must specify -t or --target')
936 target = target_factory(args.target, args.debug, args.work)
937 target.command('bash')
939 elif globals.command == 'revision':
941 target = SourceTarget()
942 tree = globals.trees.get(args.project, args.checkout, target)
943 with TreeDirectory(tree):
944 print(command_and_read('git rev-parse HEAD').readline().strip()[:7])
947 elif globals.command == 'checkout':
949 if args.output is None:
950 raise Error('you must specify -o or --output')
952 target = SourceTarget()
953 tree = globals.trees.get(args.project, args.checkout, target)
954 with TreeDirectory(tree):
955 shutil.copytree('.', args.output)
959 raise Error('invalid command %s' % globals.command)
964 print('cdist: %s' % str(e), file=sys.stderr)