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):
49 Store for Project objects which re-uses already-created objects
50 and checks for requests for different versions of the same thing.
56 def get(self, name, specifier, target):
57 for p in self.projects:
58 if p.name == name and p.specifier == specifier:
60 elif p.name == name and p.specifier != p.specifier:
61 raise Error('conflicting versions of %s requested (%s and %s)' % (name, specifier, p.specifier))
63 np = Project(name, specifier, target)
64 self.projects.append(np)
75 def __init__(self, key, default=None):
79 def offer(self, key, value):
83 class BoolOption(object):
84 def __init__(self, key):
88 def offer(self, key, value):
90 self.value = (value == 'yes' or value == '1' or value == 'true')
94 self.options = [ Option('linux_chroot_prefix'),
95 Option('windows_environment_prefix'),
96 Option('mingw_prefix'),
98 Option('osx_build_host'),
99 Option('osx_environment_prefix'),
100 Option('osx_sdk_prefix'),
102 Option('parallel', 4) ]
105 f = open('%s/.config/cdist' % os.path.expanduser('~'), 'r')
111 if len(l) > 0 and l[0] == '#':
114 s = l.strip().split()
116 for k in self.options:
122 for o in self.options:
126 raise Error('Required setting %s not found' % k)
135 if not globals.quiet:
136 print '\x1b[33m* %s\x1b[0m' % m
140 assert(len(s) == 1 or len(s) == 2)
142 return '%s:"\'%s\'"' % (s[0], s[1])
144 return '\"%s\"' % s[0]
147 log('copy %s -> %s' % (scp_escape(b), scp_escape(b)))
148 command('scp -r %s %s' % (scp_escape(a), scp_escape(b)))
151 log('copy %s -> %s' % (scp_escape(a), scp_escape(b)))
152 command('scp %s %s' % (scp_escape(a), scp_escape(b)))
155 if d.find(':') == -1:
159 command('ssh %s -- mkdir -p %s' % (s[0], s[1]))
167 shutil.rmtree(a, ignore_errors=True)
173 raise Error('command %s failed' % c)
175 def command_and_read(c):
177 p = subprocess.Popen(c.split(), stdout=subprocess.PIPE)
178 f = os.fdopen(os.dup(p.stdout.fileno()))
181 def read_wscript_variable(directory, variable):
182 f = open('%s/wscript' % directory, 'r')
189 if len(s) == 3 and s[0] == variable:
196 def set_version_in_wscript(version):
197 f = open('wscript', 'rw')
198 o = open('wscript.tmp', 'w')
205 if len(s) == 3 and s[0] == "VERSION":
206 print "Writing %s" % version
207 print >>o,"VERSION = '%s'" % version
213 os.rename('wscript.tmp', 'wscript')
215 def append_version_to_changelog(version):
217 f = open('ChangeLog', 'r')
219 log('Could not open ChangeLog')
225 f = open('ChangeLog', 'w')
226 now = datetime.datetime.now()
227 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))
230 def append_version_to_debian_changelog(version):
231 if not os.path.exists('debian'):
232 log('Could not find debian directory')
235 command('dch -b -v %s-1 "New upstream release."' % version)
237 def devel_to_git(project, filename):
238 if project.git_commit is not None:
239 filename = filename.replace('devel', '-%s' % project.git_commit)
242 class ProjectDirectory:
243 def __init__(self, target, project):
245 self.project = project
247 self.cwd = os.getcwd()
248 os.chdir('%s/src/%s' % (self.target.directory, self.project.name))
249 def __exit__(self, type, value, traceback):
257 def __init__(self, s):
260 if s.startswith("'"):
265 if s.endswith('devel'):
269 if s.endswith('pre'):
273 self.major = int(p[0])
274 self.minor = int(p[1])
276 self.micro = int(p[2])
280 def bump_minor(self):
284 def bump_micro(self):
290 def to_release(self):
294 s = '%d.%d.%d' % (self.major, self.minor, self.micro)
304 class Target(object):
306 platform -- platform string (e.g. 'windows', 'linux', 'osx')
307 directory -- directory to work in; if None we will use a temporary directory
308 Temporary directories will be removed after use; specified directories will not.
310 def __init__(self, platform, directory=None):
311 self.platform = platform
312 self.parallel = int(config.get('parallel'))
314 # self.directory is the working directory
315 if directory is None:
316 self.directory = tempfile.mkdtemp('', 'tmp', TEMPORARY_DIRECTORY)
319 self.directory = directory
322 # Environment variables that we will use when we call cscripts
326 def build_dependencies(self, project):
327 if 'dependencies' in project.cscript:
328 for d in project.cscript['dependencies'](self):
329 log('Building dependency %s %s of %s' % (d[0], d[1], project.name))
330 dep = projects.get(d[0], d[1], self)
331 self.build_dependencies(dep)
333 # Make the options to pass in from the option_defaults of the thing
334 # we are building and any options specified by the parent.
336 if 'option_defaults' in dep.cscript:
337 options = dep.cscript['option_defaults']()
339 for k, v in d[2].iteritems():
342 self.build(dep, options)
344 def build(self, project, options=None):
348 variables = copy.copy(self.variables)
350 if len(inspect.getargspec(project.cscript['build']).args) == 2:
351 project.call(self, 'build', options)
353 project.call(self, 'build')
355 self.variables = variables
358 def package(self, project):
359 self.build_dependencies(project)
361 return project.call(self, 'package', project.version)
363 def test(self, project):
364 self.build_dependencies(project)
366 return project.call(self, 'test')
369 self.variables[a] = b
372 del(self.variables[a])
375 return self.variables[a]
377 def append_with_space(self, k, v):
378 if not k in self.variables:
379 self.variables[k] = v
381 self.variables[k] = '%s %s' % (self.variables[k], v)
383 def variables_string(self, escaped_quotes=False):
385 for k, v in self.variables.iteritems():
387 v = v.replace('"', '\\"')
388 e += '%s=%s ' % (k, v)
393 rmtree(self.directory)
399 class WindowsTarget(Target):
400 def __init__(self, bits, directory=None):
401 super(WindowsTarget, self).__init__('windows', directory)
404 self.windows_prefix = '%s/%d' % (config.get('windows_environment_prefix'), self.bits)
405 if not os.path.exists(self.windows_prefix):
406 raise Error('windows prefix %s does not exist' % self.windows_prefix)
409 self.mingw_name = 'i686'
411 self.mingw_name = 'x86_64'
413 self.mingw_path = '%s/%d/bin' % (config.get('mingw_prefix'), self.bits)
414 self.mingw_prefixes = ['/%s/%d' % (config.get('mingw_prefix'), self.bits), '%s/%d/%s-w64-mingw32' % (config.get('mingw_prefix'), bits, self.mingw_name)]
416 self.set('PKG_CONFIG_LIBDIR', '%s/lib/pkgconfig' % self.windows_prefix)
417 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/bin/pkgconfig' % (self.directory, self.directory))
418 self.set('PATH', '%s/bin:%s:%s' % (self.windows_prefix, self.mingw_path, os.environ['PATH']))
419 self.set('CC', '%s-w64-mingw32-gcc' % self.mingw_name)
420 self.set('CXX', '%s-w64-mingw32-g++' % self.mingw_name)
421 self.set('LD', '%s-w64-mingw32-ld' % self.mingw_name)
422 self.set('RANLIB', '%s-w64-mingw32-ranlib' % self.mingw_name)
423 self.set('WINRC', '%s-w64-mingw32-windres' % self.mingw_name)
424 cxx = '-I%s/include -I%s/include' % (self.windows_prefix, self.directory)
425 link = '-L%s/lib -L%s/lib' % (self.windows_prefix, self.directory)
426 for p in self.mingw_prefixes:
427 cxx += ' -I%s/include' % p
428 link += ' -L%s/lib' % p
429 self.set('CXXFLAGS', '"%s"' % cxx)
430 self.set('CPPFLAGS', '')
431 self.set('LINKFLAGS', '"%s"' % link)
433 def command(self, c):
434 log('host -> %s' % c)
435 command('%s %s' % (self.variables_string(), c))
441 class LinuxTarget(Target):
442 def __init__(self, distro, version, bits, directory=None):
443 super(LinuxTarget, self).__init__('linux', directory)
445 self.version = version
447 # e.g. ubuntu-14.04-64
448 self.chroot = '%s-%s-%d' % (self.distro, self.version, self.bits)
449 # e.g. /home/carl/Environments/ubuntu-14.04-64
450 self.chroot_prefix = '%s/%s' % (config.get('linux_chroot_prefix'), self.chroot)
452 self.set('CXXFLAGS', '-I%s/include' % self.directory)
453 self.set('CPPFLAGS', '')
454 self.set('LINKFLAGS', '-L%s/lib' % self.directory)
455 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:/usr/local/lib/pkgconfig' % self.directory)
456 self.set('PATH', '%s:/usr/local/bin' % (os.environ['PATH']))
458 def command(self, c):
459 command('%s schroot -c %s -p -- %s' % (self.variables_string(), self.chroot, c))
465 class OSXTarget(Target):
466 def __init__(self, directory=None):
467 super(OSXTarget, self).__init__('osx', directory)
469 def command(self, c):
470 command('%s %s' % (self.variables_string(False), c))
473 class OSXSingleTarget(OSXTarget):
474 def __init__(self, bits, directory=None):
475 super(OSXSingleTarget, self).__init__(directory)
483 flags = '-isysroot %s/MacOSX%s.sdk -arch %s' % (config.get('osx_sdk_prefix'), config.get('osx_sdk'), arch)
484 enviro = '%s/%d' % (config.get('osx_environment_prefix'), bits)
486 # Environment variables
487 self.set('CFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
488 self.set('CPPFLAGS', '')
489 self.set('CXXFLAGS', '"-I%s/include -I%s/include %s"' % (self.directory, enviro, flags))
490 self.set('LDFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
491 self.set('LINKFLAGS', '"-L%s/lib -L%s/lib %s"' % (self.directory, enviro, flags))
492 self.set('PKG_CONFIG_PATH', '%s/lib/pkgconfig:%s/lib/pkgconfig:/usr/lib/pkgconfig' % (self.directory, enviro))
493 self.set('PATH', '$PATH:/usr/bin:/sbin:/usr/local/bin:%s/bin' % enviro)
494 self.set('MACOSX_DEPLOYMENT_TARGET', config.get('osx_sdk'))
496 def package(self, project):
497 raise Error('cannot package non-universal OS X versions')
500 class OSXUniversalTarget(OSXTarget):
501 def __init__(self, directory=None):
502 super(OSXUniversalTarget, self).__init__(directory)
504 self.parts.append(OSXSingleTarget(32, os.path.join(self.directory, '32')))
505 self.parts.append(OSXSingleTarget(64, os.path.join(self.directory, '64')))
507 def package(self, project):
509 p.build_dependencies(project)
512 project.call(self, 'package', project.version)
519 class SourceTarget(Target):
521 super(SourceTarget, self).__init__('source')
523 def command(self, c):
524 log('host -> %s' % c)
525 command('%s %s' % (self.variables_string(), c))
528 rmtree(self.directory)
530 def package(self, project):
531 with ProjectDirectory(self, project):
532 name = read_wscript_variable(os.getcwd(), 'APPNAME')
533 command('./waf dist')
534 return os.path.abspath('%s-%s.tar.bz2' % (name, project.version))
537 # @param s Target string:
539 # or ubuntu-version-{32,64}
540 # or debian-version-{32,64}
541 # or centos-version-{32,64}
544 # @param debug True to build with debugging symbols (where possible)
545 def target_factory(s, debug, work):
547 if s.startswith('windows-'):
548 target = WindowsTarget(int(s.split('-')[1]), work)
549 elif s.startswith('ubuntu-') or s.startswith('debian-') or s.startswith('centos-'):
552 print >>sys.stderr,"Bad Linux target name `%s'; must be something like ubuntu-12.04-32 (i.e. distro-version-bits)" % s
554 target = LinuxTarget(p[0], p[1], int(p[2]), work)
555 elif s.startswith('osx-'):
556 target = OSXSingleTarget(int(s.split('-')[1]), work)
558 if globals.command == 'build':
559 target = OSXSingleTarget(64, work)
561 target = OSXUniversalTarget(work)
563 target = SourceTarget()
565 if target is not None:
575 class Project(object):
576 """Description of a project. This class is never exposed to cscripts.
578 name -- name of git repository (without the .git)
579 specifier -- git tag or revision to use
580 target --- target object that we are using
581 version --- version from the wscript (if one is present)
582 git_commit -- git revision that is actually being used
583 built --- true if the project has been built yet in this run
586 def __init__(self, name, specifier, target):
588 self.specifier = specifier
590 self.git_commit = None
599 redirect = '>/dev/null'
600 command('git clone %s %s/%s.git %s/src/%s' % (flags, config.get('git_prefix'), self.name, target.directory, self.name))
601 os.chdir('%s/src/%s' % (target.directory, self.name))
603 spec = self.specifier
607 command('git checkout %s %s %s' % (flags, spec, redirect))
608 self.git_commit = command_and_read('git rev-parse --short=7 HEAD').readline().strip()
609 command('git submodule init --quiet')
610 command('git submodule update --quiet')
612 proj = '%s/src/%s' % (target.directory, self.name)
615 execfile('%s/cscript' % proj, self.cscript)
617 if os.path.exists('%s/wscript' % proj):
618 v = read_wscript_variable(proj, "VERSION");
620 self.version = Version(v)
624 def call(self, target, function, *args):
625 with ProjectDirectory(target, self):
626 return self.cscript[function](target, *args)
629 # Command-line parser
635 "build": "build project",
636 "package": "package and build project",
637 "release": "release a project using its next version number (changing wscript and tagging)",
638 "pot": "build the project's .pot files",
639 "changelog": "generate a simple HTML changelog",
640 "manual": "build the project's manual",
641 "doxygen": "build the project's Doxygen documentation",
642 "latest": "print out the latest version",
643 "test": "run the project's unit tests",
644 "shell": "build the project then start a shell in its chroot",
645 "revision": "print the head git revision number"
648 one_of = "Command is one of:\n"
650 for k, v in commands.iteritems():
651 one_of += "\t%s\t%s\n" % (k, v)
654 parser = argparse.ArgumentParser()
655 parser.add_argument('command', help=summary)
656 parser.add_argument('-p', '--project', help='project name')
657 parser.add_argument('--minor', help='minor version number bump', action='store_true')
658 parser.add_argument('--micro', help='micro version number bump', action='store_true')
659 parser.add_argument('--major', help='major version to return with latest', type=int)
660 parser.add_argument('-c', '--checkout', help='string to pass to git for checkout')
661 parser.add_argument('-o', '--output', help='output directory', default='.')
662 parser.add_argument('-q', '--quiet', help='be quiet', action='store_true')
663 parser.add_argument('-t', '--target', help='target')
664 parser.add_argument('-k', '--keep', help='keep working tree', action='store_true')
665 parser.add_argument('--debug', help='build with debugging symbols where possible', action='store_true')
666 parser.add_argument('-w', '--work', help='override default work directory')
667 args = parser.parse_args()
669 if args.output.find(':') == -1:
670 # This isn't of the form host:path so make it absolute
671 args.output = os.path.abspath(args.output) + '/'
673 if args.output[-1] != ':' and args.output[-1] != '/':
676 # Now, args.output is 'host:', 'host:path/' or 'path/'
678 if args.work is not None:
679 args.work = os.path.abspath(args.work)
681 if args.project is None and args.command != 'shell':
682 raise Error('you must specify -p or --project')
684 globals.quiet = args.quiet
685 globals.command = args.command
687 if not globals.command in commands:
688 e = 'command must be one of:\n' + one_of
689 raise Error('command must be one of:\n%s' % one_of)
691 if globals.command == 'build':
692 if args.target is None:
693 raise Error('you must specify -t or --target')
695 target = target_factory(args.target, args.debug, args.work)
696 project = projects.get(args.project, args.checkout, target)
697 target.build_dependencies(project)
698 target.build(project)
702 elif globals.command == 'package':
703 if args.target is None:
704 raise Error('you must specify -t or --target')
706 target = target_factory(args.target, args.debug, args.work)
707 project = projects.get(args.project, args.checkout, target)
709 packages = target.package(project)
710 if hasattr(packages, 'strip') or (not hasattr(packages, '__getitem__') and not hasattr(packages, '__iter__')):
711 packages = [packages]
713 if target.platform == 'linux':
714 out = '%s%s-%s-%d' % (args.output, target.distro, target.version, target.bits)
720 copyfile(p, '%s/%s' % (out, os.path.basename(devel_to_git(project, p))))
723 makedirs(args.output)
727 copyfile(p, '%s%s' % (args.output, os.path.basename(devel_to_git(project, p))))
732 elif globals.command == 'release':
733 if args.minor is False and args.micro is False:
734 raise Error('you must specify --minor or --micro')
736 target = SourceTarget()
737 project = projects.get(args.project, args.checkout, target)
739 version = project.version
746 set_version_in_wscript(version)
747 append_version_to_changelog(version)
748 append_version_to_debian_changelog(version)
750 command('git commit -a -m "Bump version"')
751 command('git tag -m "v%s" v%s' % (version, version))
754 set_version_in_wscript(version)
755 command('git commit -a -m "Bump version"')
757 command('git push --tags')
761 elif globals.command == 'pot':
762 target = SourceTarget()
763 project = projects.get(args.project, args.checkout, target)
765 pots = project.call(target, 'make_pot')
767 copyfile(p, '%s%s' % (args.output, os.path.basename(p)))
771 elif globals.command == 'changelog':
772 target = SourceTarget()
773 project = projects.get(args.project, args.checkout, target)
775 with ProjectDirectory(target, project):
776 text = open('ChangeLog', 'r')
778 html = tempfile.NamedTemporaryFile()
789 if len(l) > 0 and l[0] == "\t":
791 if len(s) == 4 and s[1] == "Version" and s[3] == "released.":
794 if last is not None and len(changes) > 0:
795 print >>html,"<h2>Changes between version %s and %s</h2>" % (s[2], last)
798 print >>html,"<li>%s" % c
809 changes.append(c[2:])
811 changes[-1] += " " + c
813 copyfile(html.file, '%schangelog.html' % args.output)
817 elif globals.command == 'manual':
818 target = SourceTarget()
819 project = projects.get(args.project, args.checkout, target)
821 outs = project.call(target, 'make_manual')
823 if os.path.isfile(o):
824 copyfile(o, '%s%s' % (args.output, os.path.basename(o)))
826 copytree(o, '%s%s' % (args.output, os.path.basename(o)))
830 elif globals.command == 'doxygen':
831 target = SourceTarget()
832 project = projects.get(args.project, args.checkout, target)
834 dirs = project.call(target, 'make_doxygen')
835 if hasattr(dirs, 'strip') or (not hasattr(dirs, '__getitem__') and not hasattr(dirs, '__iter__')):
839 copytree(d, '%s%s' % (args.output, 'doc'))
843 elif globals.command == 'latest':
844 target = SourceTarget()
845 project = projects.get(args.project, args.checkout, target)
847 with ProjectDirectory(target, project):
848 f = command_and_read('git log --tags --simplify-by-decoration --pretty="%d"')
850 while latest is None:
852 m = re.compile(".*\((.*)\).*").match(t)
854 tags = m.group(1).split(', ')
859 if len(t) > 0 and t[0] == 'v':
861 if args.major is None or v.major == args.major:
867 elif globals.command == 'test':
868 if args.target is None:
869 raise Error('you must specify -t or --target')
873 target = target_factory(args.target, args.debug, args.work)
874 project = projects.get(args.project, args.checkout, target)
875 with ProjectDirectory(target, project):
878 if target is not None:
882 if target is not None:
885 elif globals.command == 'shell':
886 if args.target is None:
887 raise Error('you must specify -t or --target')
889 target = target_factory(args.target, args.debug, args.work)
890 target.command('bash')
892 elif globals.command == 'revision':
894 target = SourceTarget()
895 project = projects.get(args.project, args.checkout, target)
896 with ProjectDirectory(target, project):
897 print command_and_read('git rev-parse HEAD').readline().strip()[:7]
901 raise Error('invalid command %s' % globals.command)
906 print >>sys.stderr,'cdist: %s' % str(e)