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 = '/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)
134 if not globals.quiet:
135 print '\x1b[33m* %s\x1b[0m' % m
139 assert(len(s) == 1 or len(s) == 2)
141 return '%s:"\'%s\'"' % (s[0], s[1])
143 return '\"%s\"' % s[0]
146 log('copy %s -> %s' % (scp_escape(b), scp_escape(b)))
147 command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
150 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
151 command('scp %s %s' % (scp_escape(a), scp_escape(b)))
154 if d.find(':') == -1:
158 command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
166 shutil.rmtree(a, ignore_errors=True)
172 raise Error('command %s failed' % c)
174 def command_and_read(c):
176 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE)
177 f = os.fdopen(os.dup(p.stdout.fileno()))
180 def read_wscript_variable(directory, variable):
181 f = open('%s/wscript' % directory, 'r')
188 if len(s) == 3 and s[0] == variable:
195 def set_version_in_wscript(version):
196 f = open('wscript', 'rw')
197 o = open('wscript.tmp', 'w')
204 if len(s) == 3 and s[0] == "VERSION":
205 print "Writing %s" % version
206 print >>o,"VERSION = '%s'" % version
212 os.rename('wscript.tmp', 'wscript')
214 def append_version_to_changelog(version):
216 f = open('ChangeLog', 'r')
218 log('Could not open ChangeLog')
224 f = open('ChangeLog', 'w')
225 now = datetime.datetime.now()
226 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))
229 def append_version_to_debian_changelog(version):
230 if not os.path.exists('debian'):
231 log('Could not find debian directory')
234 command('dch -b -v %s-1 "New upstream release."' % version)
236 def devel_to_git(git_commit, filename):
237 if git_commit is not None:
238 filename = filename.replace('devel', '-%s' % git_commit)
242 def __init__(self, tree):
245 self.cwd = os.getcwd()
246 os.chdir('%s/src/%s' % (self.tree.target.directory, self.tree.name))
247 def __exit__(self, type, value, traceback):
255 def __init__(self, s):
258 if s.startswith("'"):
263 if s.endswith('devel'):
267 if s.endswith('pre'):
271 self.major = int(p[0])
272 self.minor = int(p[1])
274 self.micro = int(p[2])
278 def bump_minor(self):
282 def bump_micro(self):
288 def to_release(self):
292 s = '%d.%d.%d' % (self.major, self.minor, self.micro)
302 class Target(object):
304 platform -- platform string (e.g. 'windows', 'linux', 'osx')
305 directory -- directory to work in; if None we will use a temporary directory
306 Temporary directories will be removed after use; specified directories will not.
308 def __init__(self, platform, directory=None):
309 self.platform = platform
310 self.parallel = int(config.get('parallel'))
312 # self.directory is the working directory
313 if directory is None:
314 self.directory = tempfile.mkdtemp('', 'tmp', TEMPORARY_DIRECTORY)
317 self.directory = directory
320 # Environment variables that we will use when we call cscripts
324 def package(self, project, checkout):
325 tree = globals.trees.get(project, checkout, self)
326 tree.build_dependencies()
328 return tree.call('package', tree.version), tree.git_commit
330 def test(self, tree):
331 tree.build_dependencies()
333 return tree.call('test')
336 self.variables[a] = b
339 del(self.variables[a])
342 return self.variables[a]
344 def append_with_space(self, k, v):
345 if not k in self.variables:
346 self.variables[k] = v
348 self.variables[k] = '%s %s' % (self.variables[k], v)
350 def variables_string(self, escaped_quotes=False):
352 for k, v in self.variables.iteritems():
354 v = v.replace('"', '\\"')
355 e += '%s=%s ' % (k, v)
360 rmtree(self.directory)
366 class WindowsTarget(Target):
367 def __init__(self, bits, directory=None):
368 super(WindowsTarget, self).__init__('windows', directory)
371 self.windows_prefix = '%s/%d' % (config.get('windows_environment_prefix'), self.bits)
372 if not os.path.exists(self.windows_prefix):
373 raise Error('windows prefix %s does not exist' % self.windows_prefix)
376 self.mingw_name = 'i686'
378 self.mingw_name = 'x86_64'
380 self.mingw_path = '%s/%d/bin' % (config.get('mingw_prefix'), self.bits)
381 self.mingw_prefixes = ['/%s/%d' % (config.get('mingw_prefix'), self.bits), '%s/%d/%s-w64-mingw32' % (config.get('mingw_prefix'), bits, self.mingw_name)]
383 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.windows_prefix)
384 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
385 self.set('PATH', '%s/bin:%s:%s' % (self.windows_prefix, self.mingw_path, os.environ['PATH']))
386 self.set('CC', '%s-w64-mingw32-gcc' % self.mingw_name)
387 self.set('CXX', '%s-w64-mingw32-g++' % self.mingw_name)
388 self.set('LD', '%s-w64-mingw32-ld' % self.mingw_name)
389 self.set('RANLIB', '%s-w64-mingw32-ranlib' % self.mingw_name)
390 self.set('WINRC', '%s-w64-mingw32-windres' % self.mingw_name)
391 cxx = '-I%s/include -I%s/include' % (self.windows_prefix, self.directory)
392 link = '-L%s/lib -L%s/lib' % (self.windows_prefix, self.directory)
393 for p in self.mingw_prefixes:
394 cxx += ' -I%s/include' % p
395 link += ' -L%s/lib' % p
396 self.set('CXXFLAGS', '"%s"' % cxx)
397 self.set('CPPFLAGS', '')
398 self.set('LINKFLAGS', '"%s"' % link)
400 def command(self, c):
401 log('host -> %s' % c)
402 command('%s %s' % (self.variables_string(), c))
408 class LinuxTarget(Target):
409 def __init__(self, distro, version, bits, directory=None):
410 super(LinuxTarget, self).__init__('linux', directory)
412 self.version = version
414 # e.g. ubuntu-14.04-64
415 self.chroot = '%s-%s-%d' % (self.distro, self.version, self.bits)
416 # e.g. /home/carl/Environments/ubuntu-14.04-64
417 self.chroot_prefix = '%s/%s' % (config.get('linux_chroot_prefix'), self.chroot)
419 self.set('CXXFLAGS', '-I%s/include' % self.directory)
420 self.set('CPPFLAGS', '')
421 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
422 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:/usr/local/lib/pkgconfig' % self.directory)
423 self.set('PATH', '%s:/usr/local/bin' % (os.environ['PATH']))
425 def command(self, c):
426 command('%s schroot -c %s -p -- %s' % (self.variables_string(), self.chroot, c))
432 class OSXTarget(Target):
433 def __init__(self, directory=None):
434 super(OSXTarget, self).__init__('osx', directory)
436 def command(self, c):
437 command('%s %s' % (self.variables_string(False), c))
440 class OSXSingleTarget(OSXTarget):
441 def __init__(self, bits, directory=None):
442 super(OSXSingleTarget, self).__init__(directory)
450 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (config.get('osx_sdk_prefix'), config.get('osx_sdk'), arch)
451 enviro = '%s/%d' % (config.get('osx_environment_prefix'), bits)
453 # Environment variables
454 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
455 self.set('CPPFLAGS', '')
456 self.set('CXXFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
457 self.set('LDFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
458 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
459 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
460 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
461 self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
463 def package(self, project, checkout):
464 raise Error('cannot package non-universal OS X versions')
467 class OSXUniversalTarget(OSXTarget):
468 def __init__(self, directory=None):
469 super(OSXUniversalTarget, self).__init__(directory)
471 def package(self, project, checkout):
474 target = OSXSingleTarget(b, os.path.join(self.directory, '%d' % b))
475 tree = globals.trees.get(project, checkout, target)
476 tree.build_dependencies()
479 tree = globals.trees.get(project, checkout, self)
480 with TreeDirectory(tree):
481 return tree.call('package', tree.version), tree.git_commit
487 class SourceTarget(Target):
489 super(SourceTarget, self).__init__('source')
491 def command(self, c):
492 log('host -> %s' % c)
493 command('%s %s' % (self.variables_string(), c))
496 rmtree(self.directory)
498 def package(self, project, checkout):
499 tree = globals.trees.get(project, checkout, self)
500 with TreeDirectory(tree):
501 name = read_wscript_variable(os.getcwd(), 'APPNAME')
502 command('./waf dist')
503 return os.path.abspath('%s-%s.tar.bz2' % (name, tree.version)), tree.git_commit
506 # @param s Target string:
508 # or ubuntu-version-{32,64}
509 # or debian-version-{32,64}
510 # or centos-version-{32,64}
513 # @param debug True to build with debugging symbols (where possible)
514 def target_factory(s, debug, work):
516 if s.startswith('windows-'):
517 target = WindowsTarget(int(s.split('-')[1]), work)
518 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-'):
521 print >>sys.stderr,"Bad Linux target name `%s'; must be something like ubuntu-12.04-32 (i.e. distro-version-bits)" % s
523 target = LinuxTarget(p[0], p[1], int(p[2]), work)
524 elif s == 'raspbian':
525 target = LinuxTarget(s, '', 32, work)
526 elif s.startswith('osx-'):
527 target = OSXSingleTarget(int(s.split('-')[1]), work)
529 if globals.command == 'build':
530 target = OSXSingleTarget(64, work)
532 target = OSXUniversalTarget(work)
534 target = SourceTarget()
536 if target is not None:
547 """Description of a tree, which is a checkout of a project,
548 possibly built. This class is never exposed to cscripts.
550 name -- name of git repository (without the .git)
551 specifier -- git tag or revision to use
552 target --- target object that we are using
553 version --- version from the wscript (if one is present)
554 git_commit -- git revision that is actually being used
555 built --- true if the tree has been built yet in this run
558 def __init__(self, name, specifier, target):
560 self.specifier = specifier
563 self.git_commit = None
572 redirect = '>/dev/null'
573 command('git clone %s %s/%s.git %s/src/%s' % (flags, config.get('git_prefix'), self.name, target.directory, self.name))
574 os.chdir('%s/src/%s' % (target.directory, self.name))
576 spec = self.specifier
580 command('git checkout %s %s %s' % (flags, spec, redirect))
581 self.git_commit = command_and_read('git rev-parse --short=7 HEAD').readline().strip()
582 command('git submodule init --quiet')
583 command('git submodule update --quiet')
585 proj = '%s/src/%s' % (target.directory, self.name)
588 execfile('%s/cscript' % proj, self.cscript)
590 if os.path.exists('%s/wscript' % proj):
591 v = read_wscript_variable(proj, "VERSION");
593 self.version = Version(v)
597 def call(self, function, *args):
598 with TreeDirectory(self):
599 return self.cscript[function](self.target, *args)
601 def build_dependencies(self):
602 if 'dependencies' in self.cscript:
603 for d in self.cscript['dependencies'](self.target):
604 log('Building dependency %s %s of %s' % (d[0], d[1], self.name))
605 dep = globals.trees.get(d[0], d[1], self.target)
606 dep.build_dependencies()
608 # Make the options to pass in from the option_defaults of the thing
609 # we are building and any options specified by the parent.
611 if 'option_defaults' in dep.cscript:
612 options = dep.cscript['option_defaults']()
614 for k, v in d[2].iteritems():
619 def build(self, options=None):
623 variables = copy.copy(self.target.variables)
625 if len(inspect.getargspec(self.cscript['build']).args) == 2:
626 self.call('build', options)
630 self.target.variables = variables
634 # Command-line parser
640 "build": "build project",
641 "package": "package and build project",
642 "release": "release a project using its next version number (changing wscript and tagging)",
643 "pot": "build the project's .pot files",
644 "changelog": "generate a simple HTML changelog",
645 "manual": "build the project's manual",
646 "doxygen": "build the project's Doxygen documentation",
647 "latest": "print out the latest version",
648 "test": "run the project's unit tests",
649 "shell": "build the project then start a shell in its chroot",
650 "checkout": "check out the project",
651 "revision": "print the head git revision number"
654 one_of = "Command is one of:\n"
656 for k, v in commands.iteritems():
657 one_of += "\t%s\t%s\n" % (k, v)
660 parser = argparse.ArgumentParser()
661 parser.add_argument('command', help=summary)
662 parser.add_argument('-p', '--project', help='project name')
663 parser.add_argument('--minor', help='minor version number bump', action='store_true')
664 parser.add_argument('--micro', help='micro version number bump', action='store_true')
665 parser.add_argument('--major', help='major version to return with latest', type=int)
666 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
667 parser.add_argument('-o', '--output', help='output directory', default='.')
668 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
669 parser.add_argument('-t', '--target', help='target')
670 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
671 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
672 parser.add_argument('-w', '--work', help='override default work directory')
673 args = parser.parse_args()
675 if args.output.find(':') == -1:
676 # This isn't of the form host:path so make it absolute
677 args.output = os.path.abspath(args.output) + '/'
679 if args.output[-1] != ':' and args.output[-1] != '/':
682 # Now, args.output is 'host:', 'host:path/' or 'path/'
684 if args.work is not None:
685 args.work = os.path.abspath(args.work)
687 if args.project is None and args.command != 'shell':
688 raise Error('you must specify -p or --project')
690 globals.quiet = args.quiet
691 globals.command = args.command
693 if not globals.command in commands:
694 e = 'command must be one of:\n' + one_of
695 raise Error('command must be one of:\n%s' % one_of)
697 if globals.command == 'build':
698 if args.target is None:
699 raise Error('you must specify -t or --target')
701 target = target_factory(args.target, args.debug, args.work)
702 tree = globals.trees.get(args.project, args.checkout, target)
703 tree.build_dependencies()
708 elif globals.command == 'package':
709 if args.target is None:
710 raise Error('you must specify -t or --target')
712 target = target_factory(args.target, args.debug, args.work)
713 packages, git_commit = target.package(args.project, args.checkout)
714 if hasattr(packages, 'strip') or (not hasattr(packages, '__getitem__') and not hasattr(packages, '__iter__')):
715 packages = [packages]
717 if target.platform == 'linux':
718 out = '%s%s-%s-%d' % (args.output, target.distro, target.version, target.bits)
724 copyfile(p, '%s/%s' % (out, os.path.basename(devel_to_git(git_commit, p))))
727 makedirs(args.output)
731 copyfile(p, '%s%s' % (args.output, os.path.basename(devel_to_git(git_commit, p))))
736 elif globals.command == 'release':
737 if args.minor is False and args.micro is False:
738 raise Error('you must specify --minor or --micro')
740 target = SourceTarget()
741 tree = globals.trees.get(args.project, args.checkout, target)
743 version = tree.version
750 set_version_in_wscript(version)
751 append_version_to_changelog(version)
752 append_version_to_debian_changelog(version)
754 command('git commit -a -m "Bump version"')
755 command('git tag -m "v%s" v%s' % (version, version))
758 set_version_in_wscript(version)
759 command('git commit -a -m "Bump version"')
761 command('git push --tags')
765 elif globals.command == 'pot':
766 target = SourceTarget()
767 tree = globals.trees.get(args.project, args.checkout, target)
769 pots = tree.call('make_pot')
771 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
775 elif globals.command == 'changelog':
776 target = SourceTarget()
777 tree = globals.trees.get(args.project, args.checkout, target)
779 with TreeDirectory(tree):
780 text = open('ChangeLog', 'r')
782 html = tempfile.NamedTemporaryFile()
793 if len(l) > 0 and l[0] == "\t":
795 if len(s) == 4 and s[1] == "Version" and s[3] == "released.":
798 if last is not None and len(changes) > 0:
799 print >>html,"<h2>Changes between version %s and %s</h2>" % (s[2], last)
802 print >>html,"<li>%s" % c
813 changes.append(c[2:])
815 changes[-1] += " " + c
817 copyfile(html.file, '%schangelog.html' % args.output)
821 elif globals.command == 'manual':
822 target = SourceTarget()
823 tree = globals.trees.get(args.project, args.checkout, target)
825 outs = tree.call('make_manual')
827 if os.path.isfile(o):
828 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
830 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
834 elif globals.command == 'doxygen':
835 target = SourceTarget()
836 tree = globals.trees.get(args.project, args.checkout, target)
838 dirs = tree.call('make_doxygen')
839 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
843 copytree(d, '%s%s' % (args.output, 'doc'))
847 elif globals.command == 'latest':
848 target = SourceTarget()
849 tree = globals.trees.get(args.project, args.checkout, target)
851 with TreeDirectory(tree):
852 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
854 while latest is None:
856 m = re.compile(".*\((.*)\).*").match(t)
858 tags = m.group(1).split(', ')
863 if len(t) > 0 and t[0] == 'v':
865 if args.major is None or v.major == args.major:
871 elif globals.command == 'test':
872 if args.target is None:
873 raise Error('you must specify -t or --target')
877 target = target_factory(args.target, args.debug, args.work)
878 tree = globals.trees.get(args.project, args.checkout, target)
879 with TreeDirectory(tree):
882 if target is not None:
886 if target is not None:
889 elif globals.command == 'shell':
890 if args.target is None:
891 raise Error('you must specify -t or --target')
893 target = target_factory(args.target, args.debug, args.work)
894 target.command('bash')
896 elif globals.command == 'revision':
898 target = SourceTarget()
899 tree = globals.trees.get(args.project, args.checkout, target)
900 with TreeDirectory(tree):
901 print command_and_read('git rev-parse HEAD').readline().strip()[:7]
904 elif globals.command == 'checkout':
906 if args.output is None:
907 raise Error('you must specify -o or --output')
909 target = SourceTarget()
910 tree = globals.trees.get(args.project, args.checkout, target)
911 with TreeDirectory(tree):
912 shutil.copytree('.', args.output)
916 raise Error('invalid command %s' % globals.command)
921 print >>sys.stderr,'cdist: %s' % str(e)