gitstats: Refactored bug.py to use a Memory and Options class
[git-stats.git] / src / git_stats / parse.py
blobe56c000363b03e3cea11a26b800aece2122238ae
1 #!/usr/bin/env python
3 import copy
5 from git import Repo
6 from optparse import OptionParser, Option, OptionValueError
8 def _check_file(option, opt, value):
9 """Checks whether value is a valid file and returns it
10 """
12 return check_file(value)
15 def check_file(value, relative=False):
16 """Check whether value is a valid file and returns it
17 """
19 git = Repo(".").git
21 file = git.ls_files("--full-name", "--", value, with_keep_cwd=relative)
23 if not file:
24 raise OptionValueError("Unknown file '" + value + "'")
26 splitfile = file.split('\n')
28 if len(splitfile) > 1:
29 raise OptionValueError("Please specify only one file, '" + value + "' matches more than one file")
31 return splitfile[0]
33 def _check_commit(option, opt, value):
34 """Checks whether value is a valid rev and returns its hash
35 """
37 git = Repo(".").git
38 rev = git.rev_parse("--verify", value, with_exceptions=False)
40 if not rev:
41 raise OptionValueError("Unknown commit '" + value + "'")
43 return rev
45 def _check_bool(option, opt, value):
46 """Checks whether a value is a boolean and returns it's value
48 Understands about 'True', 'False', and 'None.
49 """
51 if value== "True":
52 return True
54 if value == "False":
55 return False
57 if value == "None":
58 return None
60 raise OptionValueError("Not a boolean: '" + value + "'")
62 class GitOption(Option):
63 """This parser understands a new type, "commit"
64 """
66 TYPES = Option.TYPES + ("commit",) + ("file",) + ("bool",)
67 TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
68 TYPE_CHECKER["commit"] = _check_commit
69 TYPE_CHECKER["file"] = _check_file
70 TYPE_CHECKER["bool"] = _check_bool
72 def isUnique(options, atLeastOne=False):
73 """Checks if a list of options is unique
75 Args:
76 options: The list of options to check
77 atLeastOne: If set, when no optiosn are set, return False
78 """
80 unique = False
82 for option in options:
83 if option:
84 # If we already found one, it's not unique for sure
85 if unique:
86 return False
87 else:
88 unique = True
90 # If there is only one, it's unique
91 if unique:
92 return True
94 # None found, so unique only if we don't require at least one
95 return not atLeastOne