options.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Copyright 2013 Google, Inc. All Rights Reserved.
  2. #
  3. # Google Author(s): Behdad Esfahbod, Roozbeh Pournader
  4. class Options(object):
  5. class UnknownOptionError(Exception):
  6. pass
  7. def __init__(self, **kwargs):
  8. self.verbose = False
  9. self.timing = False
  10. self.drop_tables = []
  11. self.set(**kwargs)
  12. def set(self, **kwargs):
  13. for k, v in kwargs.items():
  14. if not hasattr(self, k):
  15. raise self.UnknownOptionError("Unknown option '%s'" % k)
  16. setattr(self, k, v)
  17. def parse_opts(self, argv, ignore_unknown=[]):
  18. ret = []
  19. opts = {}
  20. for a in argv:
  21. orig_a = a
  22. if not a.startswith("--"):
  23. ret.append(a)
  24. continue
  25. a = a[2:]
  26. i = a.find("=")
  27. op = "="
  28. if i == -1:
  29. if a.startswith("no-"):
  30. k = a[3:]
  31. v = False
  32. else:
  33. k = a
  34. v = True
  35. else:
  36. k = a[:i]
  37. if k[-1] in "-+":
  38. op = k[-1] + "=" # Ops is '-=' or '+=' now.
  39. k = k[:-1]
  40. v = a[i + 1 :]
  41. ok = k
  42. k = k.replace("-", "_")
  43. if not hasattr(self, k):
  44. if ignore_unknown is True or ok in ignore_unknown:
  45. ret.append(orig_a)
  46. continue
  47. else:
  48. raise self.UnknownOptionError("Unknown option '%s'" % a)
  49. ov = getattr(self, k)
  50. if isinstance(ov, bool):
  51. v = bool(v)
  52. elif isinstance(ov, int):
  53. v = int(v)
  54. elif isinstance(ov, list):
  55. vv = v.split(",")
  56. if vv == [""]:
  57. vv = []
  58. vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
  59. if op == "=":
  60. v = vv
  61. elif op == "+=":
  62. v = ov
  63. v.extend(vv)
  64. elif op == "-=":
  65. v = ov
  66. for x in vv:
  67. if x in v:
  68. v.remove(x)
  69. else:
  70. assert 0
  71. opts[k] = v
  72. self.set(**opts)
  73. return ret