1# Copyright (c) 2012 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import getopt
6import sys
7
8from idl_log import ErrOut, InfoOut, WarnOut
9
10OptionMap = { }
11
12
13def GetOption(name):
14  if name not in OptionMap:
15    raise RuntimeError('Could not find option "%s".' % name)
16  return OptionMap[name].Get()
17
18class Option(object):
19  def __init__(self, name, desc, default = None, callfunc = None,
20               testfunc = None, cookie = None):
21
22    # Verify this option is not a duplicate
23    if name in OptionMap:
24      raise RuntimeError('Option "%s" already exists.' % name)
25    self.name = name
26    self.desc = desc
27    self.default = default
28    self.value = default
29    self.callfunc = callfunc
30    self.testfunc = testfunc
31    self.cookie = cookie
32    OptionMap[name] = self
33
34  def Set(self, value):
35    if self.testfunc:
36      if not self.testfunc(self, value): return False
37    # If this is a boolean option, set it to true
38    if self.default is None:
39      self.value = True
40    else:
41      self.value = value
42    if self.callfunc:
43      self.callfunc(self)
44    return True
45
46  def Get(self):
47    return self.value
48
49
50def DumpOption(option):
51  if len(option.name) > 1:
52    out = '  --%-15.15s\t%s' % (option.name, option.desc)
53  else:
54    out = '   -%-15.15s\t%s' % (option.name, option.desc)
55  if option.default:
56    out = '%s\n\t\t\t(Default: %s)\n' % (out, option.default)
57  InfoOut.Log(out)
58
59def DumpHelp(option=None):
60  InfoOut.Log('Usage:')
61  for opt in sorted(OptionMap.keys()):
62    DumpOption(OptionMap[opt])
63  sys.exit(0)
64
65#
66# Default IDL options
67#
68# -h : Help, prints options
69# --verbose : use verbose output
70# --test : test this module
71#
72Option('h', 'Help', callfunc=DumpHelp)
73Option('help', 'Help', callfunc=DumpHelp)
74Option('verbose', 'Verbose')
75Option('test', 'Test the IDL scripts')
76
77def ParseOptions(args):
78  short_opts= ""
79  long_opts = []
80
81  # Build short and long option lists
82  for name in sorted(OptionMap.keys()):
83    option = OptionMap[name]
84    if len(name) > 1:
85      if option.default is None:
86        long_opts.append('%s' % name)
87      else:
88        long_opts.append('%s=' % name)
89    else:
90      if option.default is None:
91        short_opts += name
92      else:
93        short_opts += '%s:' % name
94
95  try:
96    opts, filenames = getopt.getopt(args, short_opts, long_opts)
97
98    for opt, val in opts:
99      if len(opt) == 2: opt = opt[1:]
100      if opt[0:2] == '--': opt = opt[2:]
101      OptionMap[opt].Set(val)
102
103  except getopt.error, e:
104    ErrOut.Log('Illegal option: %s\n' % str(e))
105    DumpHelp()
106    sys.exit(-1)
107
108  return filenames
109