From 64bb16f5f70c6cc97cede6782e45583af9bdced3 Mon Sep 17 00:00:00 2001 From: Narayan Desai Date: Sat, 8 Mar 2008 18:42:00 +0000 Subject: implement support for long options git-svn-id: https://svn.mcs.anl.gov/repos/bcfg/trunk/bcfg2@4404 ce84e21b-d406-0410-9b95-82705330c041 --- src/lib/Options.py | 25 +++++++++++++++++++++---- testsuite/TestOptions.py | 10 ++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/lib/Options.py b/src/lib/Options.py index b25fb59fb..7d0ed557c 100644 --- a/src/lib/Options.py +++ b/src/lib/Options.py @@ -32,12 +32,17 @@ class Option(object): value = property(getValue) def __init__(self, desc, default, cmd=False, odesc=False, - env=False, cf=False, cook=False): + env=False, cf=False, cook=False, long_arg=False): self.desc = desc self.default = default self.cmd = cmd - if cmd and (cmd[0] != '-' or len(cmd) != 2): - raise OptionFailure("Poorly formed command %s" % cmd) + self.long = long_arg + if not self.long: + if cmd and (cmd[0] != '-' or len(cmd) != 2): + raise OptionFailure("Poorly formed command %s" % cmd) + else: + if cmd and (not cmd.startswith('--')): + raise OptionFailure("Poorly formed command %s" % cmd) self.odesc = odesc self.env = env self.cf = cf @@ -59,12 +64,20 @@ class Option(object): def buildGetopt(self): gstr = '' + if self.long: + return gstr if self.cmd: gstr = self.cmd[1] if self.odesc: gstr += ':' return gstr + def buildLongGetopt(self): + if self.odesc: + return self.cmd[2:]+'=' + else: + return self.cmd[2:] + def parse(self, opts, rawopts): if self.cmd and opts: # processing getopted data @@ -94,6 +107,9 @@ class OptionSet(dict): def buildGetopt(self): return ''.join([opt.buildGetopt() for opt in self.values()]) + def buildLongGetopt(self): + return [opt.buildLongGetopt() for opt in self.values() if opt.long] + def buildHelpMessage(self): return ''.join([opt.buildHelpMessage() for opt in self.values()]) @@ -109,7 +125,8 @@ class OptionSet(dict): ret = {} if do_getopt: try: - opts, args = getopt.getopt(argv, self.buildGetopt(), []) + opts, args = getopt.getopt(argv, self.buildGetopt(), + self.buildLongGetopt()) except getopt.GetoptError, err: self.helpExit(err) if '-h' in argv: diff --git a/testsuite/TestOptions.py b/testsuite/TestOptions.py index bf49c4326..8e2f9b91d 100644 --- a/testsuite/TestOptions.py +++ b/testsuite/TestOptions.py @@ -49,6 +49,16 @@ class TestOptionSet(object): res = os.buildGetopt() assert 'H:' in res and 'G' in res and len(res) == 3 + def test_buildLongGetopt(self): + opts = [('foo', Bcfg2.Options.Option('foo', 'test1', cmd='-G')), + ('bar', Bcfg2.Options.Option('foo', 'test2')), + ('baz', Bcfg2.Options.Option('foo', 'test1', cmd='--H', + odesc='1', long_arg=True))] + os = Bcfg2.Options.OptionSet(opts) + res = os.buildLongGetopt() + print res + assert 'H=' in res and len(res) == 1 + def test_parse(self): opts = [('foo', Bcfg2.Options.Option('foo', 'test1', cmd='-G')), ('bar', Bcfg2.Options.Option('foo', 'test2')), -- cgit v1.2.3-1-g7c22