summaryrefslogtreecommitdiffstats
path: root/nbb/nbblib/__init__.in
blob: ed2174388a5c4096c0d0584691221d188bce80e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
"""\
nbb (ndim's branch builder) %(PACKAGE_VERSION)s
Build, install given branch of source code into a branch specific place
Copyright (C) 2007, 2008 Hans Ulrich Niedermann <hun@n-dimensional.de>
License conditions TBA

Usage: %(prog)s <to-be-determined>

Features:
 * supports git branches (TBD: git config)
 * supports bzr branches (requires useful branch nick, TBD: bzr config)
 * does out-of-source-tree builds (in-source-tree-builds unsupported)
 * direct support for automake/autoconf based build systems
 * TBD: supports execution of user commands in source, build, install dirs

TODO:
 * VCS config support ('git config', etc.)
 * Build system support: automake/autoconf, cmake
 * Design nice user interface. Requirements:
   * print top_srcdir, builddir, installdir
   * start subshell in top_srcdir, builddir, installdir
   * run 'autoreconf' type step
   * run 'configure' type step
   * run 'make' type step
   * run 'make install' type step
   * run custom (make) commands
 * Bash syntax completion for that user interface.
 * Man page or something similar.

Command line interface (TBD):

  Run default build commands:
    $ %(prog)s [general options] init [command specific options]
    $ %(prog)s [general options] configure [command specific options]
    $ %(prog)s [general options] build [command specific options]
    $ %(prog)s [general options] install [command specific options]

  Run cleanup commands:
    TBD

  Get/set config:
    $ %(prog)s [general options] config srcdir
    $ %(prog)s [general options] config builddir [<builddir>]
    $ %(prog)s [general options] config installdir [<installdir>]

  Start an interactive shell in either of the three directories:
    $ %(prog)s [general options] src-sh [command specific options]
    $ %(prog)s [general options] build-sh [command specific options]
    $ %(prog)s [general options] install-sh [command specific options]

  Run command in builddir:
    $ %(prog)s [general options] run <command> [<param>...]
    $ %(prog)s [general options] run [command specific options... <-->] <cmd>...

  (Not sure about these)
  Run a non-interactive shell command in either of the three directories:
    $ %(prog)s [general options] src-sh [command specific options] <command>...
    $ %(prog)s [general options] build-sh [command specific options] <command>...
    $ %(prog)s [general options] install-sh [command specific options] <cmd...>

Global options:

  -h --help          Print this help text
  -V --version       Print program version number

  -n --dry-run       Do not actually execute any commands

  -b --build-system  Force buildsystem detection (%(buildsystems)s)
  -v --vcs           Force VCS detection (%(vcssystems)s)
"""

import sys
import os
import getopt

import subprocess
import urlparse


# Used to make sure nbb_lib and nbb fit together
PACKAGE_VERSION = "@PACKAGE_VERSION@"

GIT_CONFIG_PREFIX = 'nbb'


########################################################################
# Utility functions
########################################################################


def adjust_doc(doc):
    """Remove common whitespace at beginning of doc string lines"""
    if not doc: return doc
    i = 0
    for i in range(len(doc)):
        if doc[i] not in " \t":
            break
    prefix = doc[:i]
    rest_doc = doc[i:]
    almost_doc = rest_doc.replace("\n%s" % prefix, "\n")
    i = -1
    while almost_doc[i] == '\n':
        i = i - 1
    return almost_doc[:i]


def prog_stdout(call_list):
    """Run program and return stdout (similar to shell backticks)"""
    p = subprocess.Popen(call_list,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    stdout, stderr = p.communicate(input=None)
    return stdout.strip()


def prog_retstd(call_list):
    """Run program and return stdout (similar to shell backticks)"""
    p = subprocess.Popen(call_list,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    stdout, stderr = p.communicate(input=None)
    return (p.returncode, stdout.strip(), stderr.strip())


class ProgramRunError(Exception):
    """A program run returns a retcode != 0"""
    def __init__(self, call_list, retcode, cwd=None):
        self.call_list = call_list
        self.retcode = retcode
        if cwd:
            self.cwd = cwd
        else:
            self.cwd = os.getcwd()
    def __str__(self):
        return ("Error running program (%s, retcode=%d, cwd=%s)"
                % (repr(self.call_list),
                   self.retcode,
                   repr(self.cwd)))


def prog_run(call_list, context):
    """Run program showing its output. Raise exception if retcode != 0."""
    print "RUN:", call_list
    print "  in", os.getcwd()
    if context.dry_run:
        return None
    p = subprocess.Popen(call_list)
    stdout, stderr = p.communicate(input=None)
    if p.returncode != 0:
        raise ProgramRunError(call_list, p.returncode, os.getcwd())
    return p.returncode


class AbstractConfig(object):
    """Return static config until we implement real config reading"""

    def __init__(self, srcdir, nick):
        super(AbstractConfig, self).__init__()
        self._srcdir = srcdir
        self._nick = nick

    def get_srcdir(self):
        return os.path.join(self._srcdir)
    srcdir = property(get_srcdir)

    def get_builddir(self):
        return os.path.join(self._srcdir, "_build", self._nick)
    builddir = property(get_builddir)

    def get_installdir(self):
        return os.path.join(self._srcdir, "_install", self._nick)
    installdir = property(get_installdir)


class CommandLineError(Exception):
    def __init__(self, message, *args):
        super(CommandLineError, self).__init__()
        if args:
            self.msg = message % args
        else:
            self.msg = message
    def __str__(self):
        return "Command line error: %s" % self.msg


class DuplicatePluginName(Exception):
    pass


class PluginDict(object):
    """Helper for GenericPluginMeta class

    Behaves basically like a standard dict, but fails when asked
    to update an existing value.
    """
    def __init__(self):
        self.dict = {}
    def __getitem__(self, *args):
        return self.dict.__getitem__(*args)
    def __setitem__(self, key, value):
        if self.dict.has_key(key):
            raise DuplicatePluginName()
        else:
            self.dict[key] = value
    def items(self): return self.dict.items()
    def keys(self): return self.dict.keys()
    def values(self): return self.dict.values()
    def __iter__(self): return self.dict.__iter__()
    def __str__(self): return self.dict.__str__()
    def __repr__(self): return self.dict.__repr__()
    def __len__(self): return self.dict.__len__()
    def has_key(self, key): return self.dict.has_key(key)


########################################################################
# Generic plugin system
########################################################################
# Plugin architecture (metaclass tricks) by Marty Alchin from
# http://gulopine.gamemusic.org/2008/jan/10/simple-plugin-framework/
# Slightly modified go store plugins as dict.
########################################################################

class GenericPluginMeta(type):
    def __init__(cls, name, bases, attrs):
        if not hasattr(cls, 'plugins'):
            # This branch only executes when processing the mount point itself.
            # So, since this is a new plugin type, not an implementation, this
            # class shouldn't be registered as a plugin. Instead, it sets up a
            # list where plugins can be registered later.
            cls.plugins = PluginDict()
        elif hasattr(cls, 'name'):
            # This must be a plugin implementation, which should be registered.
            # Simply appending it to the list is all that's needed to keep
            # track of it later.
            cls.plugins[cls.name] = cls
        else:
            # This must be an abstract subclass of plugins.
            pass


########################################################################
# VCS Source Tree plugin system
########################################################################

class NotAVCSourceTree(Exception):
    pass


class AmbigousVCSource(Exception):
    def __init__(self, srcdir, matches):
        super(AmbigousVCSource, self).__init__()
        self.srcdir = srcdir
        self.matches = matches
    def __str__(self):
        fmt = "  %-9s %-15s %s"
        def strmatch(m):
            return fmt % (m.name, m.branch_name(), m.tree_root())
        alist = [fmt % ('VCS Type', 'Branch Name', 'Source tree root')] + map(strmatch, self.matches)
        return ("More than one source tree VCS type detected for '%s':\n#%s"
                % (self.srcdir, '\n '.join(alist)))


class VCSourceTree(object):
    """
    Mount point for plugins which refer to actions that can be performed.

    Plugins implementing this reference should provide the following
    interface:

    name  attribute
        The text to be displayed, describing the version control system
    __init__  function
        Must raise NotAVCSourceTree() if it is not a VCS source tree
    """
    __metaclass__ = GenericPluginMeta

    def __init__(self, context):
        super(VCSourceTree, self).__init__()
        self.context = context

    @classmethod
    def detect(cls, srcdir, context):
        """Detect VCS tree type and return object representing it"""
        if len(VCSourceTree.plugins) < 1:
            raise "No VC source tree classes registered"
        matches = PluginDict()
        for key, klass in VCSourceTree.plugins.items():
            try:
                t = klass(srcdir, context)
                if t.tree_root() == srcdir:
                    matches[key] = t
            except NotAVCSourceTree, e:
                pass
        if len(matches) > 1:
            raise AmbigousVCSource(srcdir, matches.values())
        elif len(matches) < 1:
            raise NotAVCSourceTree(srcdir)
        return matches[matches.keys()[0]]

    def get_config(self):
        """Get configuration object which determines builddir etc"""
        return AbstractConfig(self.tree_root(), self.branch_name())
    config = property(get_config)

    def tree_root(self):
        """Get absolute path to source tree root"""
        raise NotImplementedError()

    def branch_name(self):
        """Return name identifying the branch"""
        raise NotImplementedError()

    def __str__(self):
        return repr(self)

    def __repr__(self):
        return "<%s(%s, %s)>" % (self.__class__.__name__,
                                 repr(self.tree_root()),
                                 repr(self.branch_name()))


########################################################################
# Command plugin system
########################################################################

class Command(object):
    """
    Mount point for plugins which refer to commands that can be performed.

    Plugins implementing this reference should provide the following
    interface:

    name  attribute
        The text to be displayed, describing the version control system
    summary attribute
        Short (less than 50 chars) command summary line
    usage attribute
        Usage string (defaults to '')

    validate_args(*args, **kwargs)  function
        Must raise CommandLineError() if it encounters invalid arguments in cmdargs
    run() function
        Actually run the function

    FFF(*args, **kwargs)
        *args are the arguments from the command line
        **kwargs are additional parameters from within the program
    """
    __metaclass__ = GenericPluginMeta

    usage = ''

    def __init__(self, *args, **kwargs):
        self.validate_args(*args, **kwargs)
        self.args = args
        self.kwargs = kwargs
        self.context = kwargs['context']

    def run(self):
        """Run the command"""
        raise NotImplementedError()

    def validate_args(self, *args, **kwargs):
        """Validate command line arguments"""
        print "Command: ", self.name
        print "*args:   ", args
        print "**kwargs:", kwargs
	if len(args) > 0:
            raise CommandLineError("'%s' command takes no parameters", self.name)

    def __str__(self):
        return "Command(%s, %s)" % (self.cmd_name, self.cmdargs)


class HelpCommand(Command):
    """\
    If the optional <command> is given, print the help for <command>.
    Else, print a list of commands and general help.
    """

    name = 'help'
    summary = 'print help text'
    usage = '[<command>]'

    def validate_args(self, *args, **kwargs):
        if len(args) == 1 and args[0] not in Command.plugins.keys():
            raise CommandLineError("'%s' is an invalid command name", args[0])
        elif len(args) > 1:
            raise CommandLineError("'%s' command only takes one optional parameter", self.name)

    def _print_command_list(self):
        print "List of commands:"
        keys = Command.plugins.keys()
        keys.sort()
        for k in keys:
           print "\t%-15s\t%s" % (k, Command.plugins[k].summary)

    def _print_command_help(self, cmd):
        """print help for command cmd"""
        c = Command.plugins[cmd]
        print "Purpose:", c.summary
        if c.usage:
            print "Usage:  ", outdict['prog'], cmd, c.usage
        else:
            print "Usage:  ", outdict['prog'], cmd
        if hasattr(c, '__doc__'):
            if c.__doc__:
                print
                print adjust_doc(c.__doc__)

    def run(self):
        if len(self.args) == 0:
            self._print_command_list()
        elif len(self.args) == 1:
            self._print_command_help(self.args[0])
        else:
            assert(False)


class GitConfig(AbstractConfig):
    """"""

    def __init__(self, *args, **kwargs):
        super(GitConfig, self).__init__(*args, **kwargs)

    def _itemname(self, item): return '.'.join((GIT_CONFIG_PREFIX, item, ))
    def _myreldir(self, rdir):
        return os.path.join(self._srcdir, rdir, self._nick)

    def get_builddir(self):
        ret, stdout, stderr = prog_retstd(['git', 'config', self._itemname('builddir')])
        assert(stderr == "")
	if ret == 0 and stdout:
            return self._myreldir(stdout)
        else:
            return super(GitConfig, self).get_builddir()

    def set_builddir(self, value):
        ret, stdout, stderr = prog_retstd(['git', 'config', self._itemname('builddir'), value])
        assert(ret == 0 and stdout == "" and stderr == "")

    builddir = property(get_builddir, set_builddir)

    def get_installdir(self):
        ret, stdout, stderr = prog_retstd(['git', 'config', self._itemname('installdir')])
        assert(stderr == "")
	if ret == 0 and stdout:
            return self._myreldir(stdout)
        else:
            return super(GitConfig, self).get_installdir()

    def set_installdir(self, value):
        ret, stdout, stderr = prog_retstd(['git', 'config', self._itemname('installdir'), value])
        assert(ret == 0 and stdout == "" and stderr == "")

    installdir = property(get_installdir, set_installdir)


class InternalConfigCommand(Command):
    name = 'internal-config'
    summary = 'print internal program configuration'
    def run(self):
        print "Source tree types:",  ", ".join(VCSourceTree.plugins.keys())
        print "Build system types:", ", ".join(BSSourceTree.plugins.keys())
        print "Commands:",           ", ".join(Command.plugins.keys())


class SourceClassCommand(Command):
    """Base class for commands acting on source trees"""
    def __init__(self, *args, **kwargs):
        super(SourceClassCommand, self).__init__(*args, **kwargs)
        context = kwargs['context']
        srcdir = os.getcwd()
        absdir = os.path.abspath(srcdir)
        self.vcs_sourcetree = VCSourceTree.detect(absdir, context)
        if context.verbose:
            print "vcs_sourcetree", str(self.vcs_sourcetree)
        assert(self.vcs_sourcetree)
        cfg = self.vcs_sourcetree.config
        self.bs_sourcetree = BSSourceTree.detect(self.vcs_sourcetree, context)
        if context.verbose:
            print "bs_sourcetree", str(self.bs_sourcetree)
            print "CONFIG", cfg
            print " ", "srcdir", cfg.srcdir
            print " ", "builddir", cfg.builddir
            print " ", "installdir", cfg.installdir


class BuildTestCommand(SourceClassCommand):
    name = 'build-test'
    summary = 'simple build test'
    def run(self):
        self.bs_sourcetree.init()
        self.bs_sourcetree.configure()
        self.bs_sourcetree.build()
        self.bs_sourcetree.install()


class ConfigCommand(SourceClassCommand):
    name = 'config'
    summary = 'set/get config values'
    usage = '(srcdir|builddir|installdir)'

    def validate_args(self, *args, **kwargs):
        items = ('srcdir', 'builddir', 'installdir', )
        if len(args) == 0:
            raise CommandLineError("'%s' requires at least one parameter (%s)", self.name,
                                   ', '.join(items))
        elif len(args) == 1 and args[0] in items:
            pass
        elif len(args) == 2 and args[0] in items:
            if args[0] in ('srcdir', ):
                raise CommandLineError("'%s' command cannot change 'srcdir'", self.name)
            else:
                pass
        else:
            raise CommandLineError("'%s' requires less or different parameters", self.name)

    def run(self):
        git_get_items = ('builddir', 'installdir', 'srcdir')
        git_set_items = ('builddir', 'installdir', )
        if len(self.args) == 1:
            if self.args[0] in git_get_items:
                print getattr(self.vcs_sourcetree.config, self.args[0])
            else:
                assert(False)
        elif len(self.args) == 2:
            if self.args[0] == 'builddir':
                self.vcs_sourcetree.config.builddir = self.args[1]
            elif self.args[0] == 'installdir':
                self.vcs_sourcetree.config.installdir = self.args[1]
            else:
                assert(False)
        else:
            assert(False)


########################################################################
# VCS Source Tree plugins
########################################################################

class GitSourceTree(VCSourceTree):

    name = 'git'

    def __init__(self, srcdir, context):
        super(GitSourceTree, self).__init__(context)
        os.chdir(srcdir)
        if "true" != prog_stdout(["git", "rev-parse",
                                  "--is-inside-work-tree"]):
            raise NotAVCSourceTree()
        reldir = prog_stdout(["git", "rev-parse", "--show-cdup"])
        if reldir:
            os.chdir(reldir)
        self.__tree_root = os.getcwd()

    def get_config(self):
        return GitConfig(self.tree_root(), self.branch_name())
    config = property(get_config)

    def tree_root(self):
        return self.__tree_root

    def branch_name(self):
        bname = prog_stdout(["git", "symbolic-ref", "HEAD"])
        refs,heads,branch = bname.split('/')
        assert(refs=='refs' and heads=='heads')
        return branch


class BzrSourceTree(VCSourceTree):

    name = 'bzr'

    def __init__(self, srcdir, context):
        super(BzrSourceTree, self).__init__(context)
        try:
            import bzrlib.workingtree
            wt,b = bzrlib.workingtree.WorkingTree.open_containing(srcdir)
        except bzrlib.errors.NotBranchError:
            raise NotAVCSourceTree()
        except ImportError:
            raise NotAVCSourceTree()
        self.wt = wt
        #print "wt:", wt
        #print "wt:", dir(wt)
        #print "wt.branch:", wt.branch
        #print "wt.branch:", dir(wt.branch)
        #print "wt.branch.nick:", wt.branch.nick
        #print "wt.branch.abspath:", wt.branch.abspath
        #print "wt.branch.base:", wt.branch.base
        #print "wt.branch.basis_tree:", wt.branch.basis_tree()

    def tree_root(self):
        proto,host,path,some,thing = urlparse.urlsplit(self.wt.branch.base)
        assert(proto == "file" and host == "")
        assert(some == "" and thing == "")
        return os.path.abspath(path)

    def branch_name(self):
        return self.wt.branch.nick


########################################################################
# Buildsystem Source Tree plugins
########################################################################

class NotABSSourceTree(Exception):
    def __init__(self, vcs_tree):
        super(NotABSSourceTree, self).__init__()
        self.vcs_tree = vcs_tree
    def __str__(self):
        return "Source tree build system type for '%s' not detected" % (self.vcs_tree,)


class AmbigousBSSource(Exception):
    def __init__(self, srcdir, matches):
        super(AmbigousBSSource, self).__init__()
        self.srcdir = srcdir
        self.matches = matches
    def __str__(self):
        fmt = "  %-9s %s"
        def strmatch(m):
            return fmt % (m.name, m.tree_root())
        alist = [fmt % ('VCS Type', 'Source tree root')] + map(strmatch, self.matches)
        return ("More than one source tree VCS type detected for '%s':\n#%s"
                % (self.srcdir, '\n '.join(alist)))


class BSSourceTree(object):
    __metaclass__ = GenericPluginMeta

    def __init__(self, context):
        super(BSSourceTree, self).__init__()
        self.context = context

    @classmethod
    def detect(cls, vcs_tree, context):
        """Find BS tree type and return it"""
        if len(BSSourceTree.plugins) < 1:
            raise "No BS source tree classes registered"
        matches = PluginDict()
        for key, klass in BSSourceTree.plugins.items():
            try:
                t = klass(vcs_tree, context)
                if t.tree_root() == vcs_tree.tree_root():
                    matches[key] = t
            except NotABSSourceTree, e:
                pass
        if len(matches) > 1:
            raise ("More than one source tree BS type detected for '%s': %s"
                   % (vcs_tree, ", ".join(map(lambda x:str(x), matches))))
        elif len(matches) < 1:
            raise NotABSSourceTree(vcs_tree)
        return matches[matches.keys()[0]]

    def __str__(self):
        return "BS-Source-Tree(%s, %s)" % (self.name,
                                           repr(self.tree_root()))

    # Abstract methods
    def tree_root(self): raise NotImplementedError()
    def init(self): raise NotImplementedError()
    def configure(self): raise NotImplementedError()
    def build(self): raise NotImplementedError()
    def install(self): raise NotImplementedError()


class AutomakeSourceTree(BSSourceTree):
    name = 'automake'
    def __init__(self, vcs_tree, context):
        super(AutomakeSourceTree, self).__init__(context)
        srcdir = vcs_tree.tree_root()
        self.config = vcs_tree.config
        flag = False
        for f in [ os.path.join(srcdir, 'configure.ac'),
                   os.path.join(srcdir, 'configure.in'),
                   ]:
            if os.path.exists(f):
                flag = True
                break
        if not flag:
            raise NotABSSourceTree(vcs_tree)

    def tree_root(self):
        return self.config.srcdir

    def init(self):
        """'autoreconf'"""
        prog_run(["autoreconf", "-v", "-i", "-s", self.config.srcdir], self.context)

    def configure(self):
        """'configure --prefix'"""
        builddir = self.config.builddir
        if not os.path.exists(builddir): os.makedirs(builddir)
        os.chdir(builddir)
        prog_run(["%s/configure" % self.config.srcdir,
                  "--prefix=%s" % self.config.installdir
                  ], self.context)

    def build(self):
        """'make'"""
        os.chdir(self.config.builddir)
        prog_run(["make", ], self.context)

    def install(self):
        """'make install'"""
        os.chdir(self.config.builddir)
        prog_run(["make", "install", "INSTALL=/usr/bin/install -p"], self.context)


########################################################################
# Commands
########################################################################

class NBB_Command(object):
    def __init__(self, cmd, cmdargs, context):
        if Command.plugins.has_key(cmd):
            try:
                c = Command.plugins[cmd](*cmdargs, **{'context':context})
                c.run()
            except CommandLineError, e:
                print "%(prog)s: Fatal:" % (outdict), e
                sys.exit(2)
            except ProgramRunError, e:
                print "%(prog)s: Fatal:" % (outdict), e
                print "Program aborted."
        else:
            print "Fatal: Unknown command '%s'" % cmd
	    raise NotImplementedError()
        return


########################################################################
# Main program
########################################################################


outdict = {}
outdict['vcssystems']   = ", ".join(VCSourceTree.plugins.keys())
outdict['buildsystems'] = ", ".join(BSSourceTree.plugins.keys())
outdict['PACKAGE_VERSION'] = PACKAGE_VERSION

def print_help():
    print __doc__ % outdict,


class Property(object):
    def __init__(self, **kwargs):
        if kwargs.has_key('default'):
            self.default = kwargs['default']
    def __get__(self, instance, owner):
        if hasattr(self, 'value'):
            return self.value
        elif hasattr(self, 'default'):
            return self.default
        else:
            return None
    def __set__(self, instance, value):
        if hasattr(self, 'value'):
            raise "Property cannot be set more than once"
        elif not self.isvalid(value):
            raise "Property cannot be set to invalid value '%s'" % value
        else:
            self.value = value
    def __str__(self):
        if hasattr(self, 'value'):
            return self.value
        else:
            return '<undefined property>'
    def isvalid(self, value):
        return True


class VCSProperty(Property):
    def isvalid(self, value):
        return (value in VCSourceTree.plugins.keys())


class BSProperty(Property):
    def isvalid(self, value):
        return (value in BSSourceTree.plugins.keys())


class BoolProperty(Property):
    def __init__(self, default=False):
        super(BoolProperty, self).__init__(default=default)
    def isvalid(self, value):
        return (value in (True, False))

class DryRunProperty(BoolProperty):
    def __init__(self):
        super(DryRunProperty, self).__init__(default=False)


class Context(object):
    vcs = VCSProperty()
    bs = BSProperty()
    dry_run = DryRunProperty()
    verbose = BoolProperty()

def main(argv):

    prog = argv[0]
    idx = prog.rfind('/')
    if idx >= 0:
        prog = prog[idx+1:]
    outdict['prog'] = prog

    if len(argv) < 2:
        print "Fatal: %(prog)s requires some arguments" % outdict
        return 2

    i = 1
    ctx = Context()
    while i<len(argv):
        if argv[i][0] != '-':
            break
        if argv[i] in ('-h', '--help'):
            print_help()
            return
        elif argv[i] in ('-V', '--version'):
            print "%(prog)s (ndim's branch builder) %(PACKAGE_VERSION)s" % outdict
            return
        elif argv[i] in ('-n', '--dry-run'):
            ctx.dry_run = True
        elif argv[i] in ('-b', '--build-system'):
            i = i + 1
            assert(i<len(argv))
            ctx.bs = argv[i]
        elif argv[i][:6] == '--build-system=':
            ctx.bs = argv[i][6:]
        elif argv[i] in ('-v', '--vcs'):
            i = i + 1
            assert(i<len(argv))
            ctx.vcs = argv[i]
        elif argv[i][:6] == '--vcs=':
            ctx.vcs = argv[i][6:]
        elif argv[i] in ('--verbose', ):
            ctx.verbose = True
        # print "", i, argv[i]
        i = i + 1
    cmd = argv[i]
    cmdargs = argv[i+1:]
    nbb = NBB_Command(cmd, cmdargs, context=ctx)


if __name__ == '__main__':
    raise "This is not a library"

# vim: syntax=python
# Local Variables:
# mode: python
# End: