3 # Copyright (C) 2012-2014 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'
39 class Error(Exception):
40 def __init__(self, value):
52 def __init__(self, key, default=None):
56 def offer(self, key, value):
60 class BoolOption(object):
61 def __init__(self, key):
65 def offer(self, key, value):
67 self.value = (value == 'yes' or value == '1' or value == 'true')
71 self.options = [ Option('linux_chroot_prefix'),
72 Option('windows_environment_prefix'),
73 Option('mingw_prefix'),
75 Option('osx_build_host'),
76 Option('osx_environment_prefix'),
77 Option('osx_sdk_prefix'),
79 Option('parallel', 4) ]
82 f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
88 if len(l) > 0 and l[0] == '#':
93 for k in self.options:
99 for o in self.options:
103 raise Error('Required setting %s not found' % k)
112 if not globals.quiet:
113 print '\x1b[33m* %s\x1b[0m' % m
117 assert(len(s) == 1 or len(s) == 2)
119 s[1] = '"\'%s\'"' % s[1]
120 return '%s:%s' % (s[0], s[1])
125 log('copy %s -> %s' % (a, b))
126 os.system('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
129 log('copy %s -> %s' % (a, b))
130 os.system('scp %s %s' % (scp_escape(a), scp_escape(b)))
138 shutil.rmtree(a, ignore_errors=True)
140 def command(c, can_fail=False):
143 if (r >> 8) and not can_fail:
144 raise Error('command %s failed' % c)
146 def command_and_read(c):
148 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE)
149 f = os.fdopen(os.dup(p.stdout.fileno()))
152 def read_wscript_variable(directory, variable):
153 f = open('%s/wscript' % directory, 'r')
160 if len(s) == 3 and s[0] == variable:
172 def __init__(self, s):
175 if s.startswith("'"):
180 if s.endswith('devel'):
184 if s.endswith('pre'):
188 self.major = int(p[0])
189 self.minor = int(p[1])
191 self.micro = int(p[2])
195 def bump_minor(self):
199 def bump_micro(self):
205 def to_release(self):
209 s = '%d.%d.%d' % (self.major, self.minor, self.micro)
219 class Target(object):
220 # @param directory directory to work in; if None we will use a temporary directory
221 # Temporary directories will be removed after use; specified directories will not
222 def __init__(self, platform, directory=None):
223 self.platform = platform
224 self.parallel = int(config.get('parallel'))
226 if directory is None:
227 self.directory = tempfile.mkdtemp('', 'tmp', TEMPORARY_DIRECTORY)
230 self.directory = directory
233 # Environment variables that we will use when we call cscripts
237 def build_dependencies(self, project):
239 if 'dependencies' in project.cscript:
240 for d in project.cscript['dependencies'](self):
241 log('Building dependency %s %s of %s' % (d[0], d[1], project.name))
242 dep = Project(d[0], '.', d[1])
244 self.build_dependencies(dep)
246 # Make the options to pass in from the option_defaults of the thing
247 # we are building and any options specified by the parent.
249 if 'option_defaults' in dep.cscript:
250 options = dep.cscript['option_defaults']()
252 for k, v in d[2].iteritems():
255 self.build(dep, options)
259 def build(self, project, options=None):
260 variables = copy.copy(self.variables)
261 if len(inspect.getargspec(project.cscript['build']).args) == 2:
262 project.cscript['build'](self, options)
264 project.cscript['build'](self)
265 self.variables = variables
267 def package(self, project):
268 project.checkout(self)
269 self.build_dependencies(project)
271 return project.cscript['package'](self, project.version)
273 def test(self, project):
274 project.checkout(self)
275 self.build_dependencies(project)
277 project.cscript['test'](self)
280 self.variables[a] = b
283 del(self.variables[a])
286 return self.variables[a]
288 def append_with_space(self, k, v):
289 if not k in self.variables:
290 self.variables[k] = v
292 self.variables[k] = '%s %s' % (self.variables[k], v)
294 def variables_string(self, escaped_quotes=False):
296 for k, v in self.variables.iteritems():
298 v = v.replace('"', '\\"')
299 e += '%s=%s ' % (k, v)
304 rmtree(self.directory)
310 class WindowsTarget(Target):
311 def __init__(self, bits, directory=None):
312 super(WindowsTarget, self).__init__('windows', directory)
315 self.windows_prefix = '%s/%d' % (config.get('windows_environment_prefix'), self.bits)
316 if not os.path.exists(self.windows_prefix):
317 raise Error('windows prefix %s does not exist' % self.windows_prefix)
320 self.mingw_name = 'i686'
322 self.mingw_name = 'x86_64'
324 mingw_path = '%s/%d/bin' % (config.get('mingw_prefix'), self.bits)
325 self.mingw_prefixes = ['/%s/%d' % (config.get('mingw_prefix'), self.bits), '%s/%d/%s-w64-mingw32' % (config.get('mingw_prefix'), bits, self.mingw_name)]
327 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.windows_prefix)
328 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
329 self.set('PATH', '%s/bin:%s:%s' % (self.windows_prefix, mingw_path, os.environ['PATH']))
330 self.set('CC', '%s-w64-mingw32-gcc' % self.mingw_name)
331 self.set('CXX', '%s-w64-mingw32-g++' % self.mingw_name)
332 self.set('LD', '%s-w64-mingw32-ld' % self.mingw_name)
333 self.set('RANLIB', '%s-w64-mingw32-ranlib' % self.mingw_name)
334 self.set('WINRC', '%s-w64-mingw32-windres' % self.mingw_name)
335 cxx = '-I%s/include -I%s/include' % (self.windows_prefix, self.directory)
336 link = '-L%s/lib -L%s/lib' % (self.windows_prefix, self.directory)
337 for p in self.mingw_prefixes:
338 cxx += ' -I%s/include' % p
339 link += ' -L%s/lib' % p
340 self.set('CXXFLAGS', '"%s"' % cxx)
341 self.set('CPPFLAGS', '')
342 self.set('LINKFLAGS', '"%s"' % link)
344 def command(self, c):
345 log('host -> %s' % c)
346 command('%s %s' % (self.variables_string(), c))
352 class LinuxTarget(Target):
353 def __init__(self, distro, version, bits, directory=None):
354 super(LinuxTarget, self).__init__('linux', directory)
356 self.version = version
358 # e.g. ubuntu-14.04-64
359 self.chroot = '%s-%s-%d' % (self.distro, self.version, self.bits)
360 # e.g. /home/carl/Environments/ubuntu-14.04-64
361 self.chroot_prefix = '%s/%s' % (config.get('linux_chroot_prefix'), self.chroot)
363 self.set('CXXFLAGS', '-I%s/include' % self.directory)
364 self.set('CPPFLAGS', '')
365 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
366 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:/usr/local/lib/pkgconfig' % self.directory)
367 self.set('PATH', '%s:/usr/local/bin' % (os.environ['PATH']))
369 def command(self, c):
370 command('%s schroot -c %s -p -- %s' % (self.variables_string(), self.chroot, c))
376 class OSXTarget(Target):
377 def __init__(self, directory=None):
378 super(OSXTarget, self).__init__('osx', directory)
380 def command(self, c):
381 command('%s %s' % (self.variables_string(False), c))
384 class OSXSingleTarget(OSXTarget):
385 def __init__(self, bits, directory=None):
386 super(OSXSingleTarget, self).__init__(directory)
394 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (config.get('osx_sdk_prefix'), config.get('osx_sdk'), arch)
395 enviro = '%s/%d' % (config.get('osx_environment_prefix'), bits)
397 # Environment variables
398 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
399 self.set('CPPFLAGS', '')
400 self.set('CXXFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
401 self.set('LDFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
402 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
403 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
404 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
405 self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
407 def package(self, project):
408 raise Error('cannot package non-universal OS X versions')
411 class OSXUniversalTarget(OSXTarget):
412 def __init__(self, directory=None):
413 super(OSXUniversalTarget, self).__init__(directory)
415 self.parts.append(OSXSingleTarget(32, os.path.join(self.directory, '32')))
416 self.parts.append(OSXSingleTarget(64, os.path.join(self.directory, '64')))
418 def package(self, project):
421 p.build_dependencies(project)
424 return project.cscript['package'](self, project.version)
431 class SourceTarget(Target):
433 super(SourceTarget, self).__init__('source')
435 def command(self, c):
436 log('host -> %s' % c)
437 command('%s %s' % (self.variables_string(), c))
440 rmtree(self.directory)
442 def package(self, project):
443 project.checkout(self)
444 name = read_wscript_variable(os.getcwd(), 'APPNAME')
445 command('./waf dist')
446 return os.path.abspath('%s-%s.tar.bz2' % (name, project.version))
449 # @param s Target string:
451 # or ubuntu-version-{32,64}
452 # or debian-version-{32,64}
453 # or centos-version-{32,64}
456 # @param debug True to build with debugging symbols (where possible)
457 def target_factory(s, debug, work):
459 if s.startswith('windows-'):
460 target = WindowsTarget(int(s.split('-')[1]), work)
461 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-'):
464 print >>sys.stderr,"Bad Linux target name `%s'; must be something like ubuntu-12.04-32 (i.e. distro-version-bits)" % s
466 target = LinuxTarget(p[0], p[1], int(p[2]), work)
467 elif s.startswith('osx-'):
468 target = OSXSingleTarget(int(s.split('-')[1]), work)
470 if globals.command == 'build':
471 target = OSXSingleTarget(64, work)
473 target = OSXUniversalTarget(work)
475 target = SourceTarget()
477 if target is not None:
487 class Project(object):
488 def __init__(self, name, directory, specifier=None):
490 self.directory = directory
492 self.specifier = specifier
493 self.git_commit = None
494 if self.specifier is None:
495 self.specifier = 'master'
497 def checkout(self, target):
502 redirect = '>/dev/null'
503 command('git clone %s %s/%s.git %s/src/%s' % (flags, config.get('git_prefix'), self.name, target.directory, self.name))
504 os.chdir('%s/src/%s' % (target.directory, self.name))
505 command('git checkout %s %s %s' % (flags, self.specifier, redirect))
506 self.git_commit = command_and_read('git rev-parse --short=7 HEAD').readline().strip()
507 command('git submodule init --quiet')
508 command('git submodule update --quiet')
509 os.chdir(self.directory)
511 proj = '%s/src/%s/%s' % (target.directory, self.name, self.directory)
513 self.read_cscript('%s/cscript' % proj)
515 if os.path.exists('%s/wscript' % proj):
516 v = read_wscript_variable(proj, "VERSION");
518 self.version = Version(v)
520 def read_cscript(self, s):
522 execfile(s, self.cscript)
524 def set_version_in_wscript(version):
525 f = open('wscript', 'rw')
526 o = open('wscript.tmp', 'w')
533 if len(s) == 3 and s[0] == "VERSION":
534 print "Writing %s" % version
535 print >>o,"VERSION = '%s'" % version
541 os.rename('wscript.tmp', 'wscript')
543 def append_version_to_changelog(version):
545 f = open('ChangeLog', 'r')
547 log('Could not open ChangeLog')
553 f = open('ChangeLog', 'w')
554 now = datetime.datetime.now()
555 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))
558 def append_version_to_debian_changelog(version):
559 if not os.path.exists('debian'):
560 log('Could not find debian directory')
563 command('dch -b -v %s-1 "New upstream release."' % version)
565 def devel_to_git(project, filename):
566 if project.git_commit is not None:
567 filename = filename.replace('devel', '-%s' % project.git_commit)
572 # Command-line parser
578 "build": "build project",
579 "package": "package and build project",
580 "release": "release a project using its next version number (changing wscript and tagging)",
581 "pot": "build the project's .pot files",
582 "changelog": "generate a simple HTML changelog",
583 "manual": "build the project's manual",
584 "doxygen": "build the project's Doxygen documentation",
585 "latest": "print out the latest version",
586 "test": "run the project's unit tests",
587 "shell": "build the project then start a shell in its chroot",
588 "revision": "print the head git revision number"
591 one_of = "Command is one of:\n"
593 for k, v in commands.iteritems():
594 one_of += "\t%s\t%s\n" % (k, v)
597 parser = argparse.ArgumentParser()
598 parser.add_argument('command', help=summary)
599 parser.add_argument('-p', '--project', help='project name')
600 parser.add_argument('-d', '--directory', help='directory within project repo', default='.')
601 parser.add_argument('--minor', help='minor version number bump', action='store_true')
602 parser.add_argument('--micro', help='micro version number bump', action='store_true')
603 parser.add_argument('--major', help='major version to return with latest', type=int)
604 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
605 parser.add_argument('-o', '--output', help='output directory', default='.')
606 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
607 parser.add_argument('-t', '--target', help='target')
608 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
609 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
610 parser.add_argument('-w', '--work', help='override default work directory')
611 args = parser.parse_args()
613 if args.output.find(':') == -1:
614 # This isn't of the form host:path so make it absolute
615 args.output = os.path.abspath(args.output) + '/'
617 # Now, args.output is 'host:' or 'path/'
619 if args.work is not None:
620 args.work = os.path.abspath(args.work)
622 if args.project is None and args.command != 'shell':
623 raise Error('you must specify -p or --project')
625 globals.quiet = args.quiet
626 globals.command = args.command
628 project = Project(args.project, args.directory, args.checkout)
630 if not globals.command in commands:
631 e = 'command must be one of:\n' + one_of
632 raise Error('command must be one of:\n%s' % one_of)
634 if globals.command == 'build':
635 if args.target is None:
636 raise Error('you must specify -t or --target')
638 target = target_factory(args.target, args.debug, args.work)
639 project.checkout(target)
640 target.build_dependencies(project)
641 target.build(project)
645 elif globals.command == 'package':
646 if args.target is None:
647 raise Error('you must specify -t or --target')
649 target = target_factory(args.target, args.debug, args.work)
651 packages = target.package(project)
652 if hasattr(packages, 'strip') or (not hasattr(packages, '__getitem__') and not hasattr(packages, '__iter__')):
653 packages = [packages]
655 if target.platform == 'linux':
656 out = '%s%s-%s-%d' % (args.output, target.distro, target.version, target.bits)
662 copyfile(p, '%s/%s' % (out, os.path.basename(devel_to_git(project, p))))
665 copyfile(p, '%s%s' % (args.output, os.path.basename(devel_to_git(project, p))))
670 elif globals.command == 'release':
671 if args.minor is False and args.micro is False:
672 raise Error('you must specify --minor or --micro')
674 target = SourceTarget()
675 project.checkout(target)
677 version = project.version
684 set_version_in_wscript(version)
685 append_version_to_changelog(version)
686 append_version_to_debian_changelog(version)
688 command('git commit -a -m "Bump version"')
689 command('git tag -m "v%s" v%s' % (version, version))
692 set_version_in_wscript(version)
693 command('git commit -a -m "Bump version"')
695 command('git push --tags')
699 elif globals.command == 'pot':
700 target = SourceTarget()
701 project.checkout(target)
703 pots = project.cscript['make_pot'](target)
705 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
709 elif globals.command == 'changelog':
710 target = SourceTarget()
711 project.checkout(target)
713 text = open('ChangeLog', 'r')
714 html = tempfile.NamedTemporaryFile()
725 if len(l) > 0 and l[0] == "\t":
727 if len(s) == 4 and s[1] == "Version" and s[3] == "released.":
730 if last is not None and len(changes) > 0:
731 print >>html,"<h2>Changes between version %s and %s</h2>" % (s[2], last)
734 print >>html,"<li>%s" % c
745 changes.append(c[2:])
747 changes[-1] += " " + c
749 copyfile(html.file, '%schangelog.html' % args.output)
753 elif globals.command == 'manual':
754 target = SourceTarget()
755 project.checkout(target)
757 outs = project.cscript['make_manual'](target)
759 if os.path.isfile(o):
760 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
762 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
766 elif globals.command == 'doxygen':
767 target = SourceTarget()
768 project.checkout(target)
770 dirs = project.cscript['make_doxygen'](target)
771 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
775 copytree(d, '%s%s' % (args.output, 'doc'))
779 elif globals.command == 'latest':
780 target = SourceTarget()
781 project.checkout(target)
783 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
785 while latest is None:
787 m = re.compile(".*\((.*)\).*").match(t)
789 tags = m.group(1).split(', ')
794 if len(t) > 0 and t[0] == 'v':
796 if args.major is None or v.major == args.major:
802 elif globals.command == 'test':
803 if args.target is None:
804 raise Error('you must specify -t or --target')
808 target = target_factory(args.target, args.debug, args.work)
811 if target is not None:
815 if target is not None:
818 elif globals.command == 'shell':
819 if args.target is None:
820 raise Error('you must specify -t or --target')
822 target = target_factory(args.target, args.debug, args.work)
823 target.command('bash')
825 elif globals.command == 'revision':
827 target = SourceTarget()
828 project.checkout(target)
829 print command_and_read('git rev-parse HEAD').readline().strip()[:7]
833 raise Error('invalid command %s' % globals.command)
838 print >>sys.stderr,'cdist: %s' % str(e)