gitstats: Teach config.py to read multiple verses
[git-stats.git] / src / git_stats / config.py
blob75724dc5496a6e6cfb2cfd2937cf23472aab3ce6
1 #!/usr/bin/env python
4 import os
6 from git import Repo
8 def readAll(convert_camel_case=True):
9 """Reads all config files and returns the result
11 When a value is read in multiple times the one read in
12 the last is used. The following files are tried in the
13 listed order:
14 ~/.gitconfig
15 .git/config
16 config
17 """
19 paths = []
21 path = "~/.gitconfig"
22 path = os.path.expanduser(path)
23 paths.append(path)
25 repo = Repo(".")
26 path = os.path.join(repo.wd, '.git', 'config')
27 paths.append(path)
29 paths.append("config")
31 result = {}
33 for path in paths:
34 if not os.path.isfile(path):
35 continue
37 config = read(path, convert_camel_case)
39 for key, value in config.iteritems():
40 result[key] = value
42 return result
44 def _readVerse(verse, config, convert_camel_case):
45 """Reads in a verse from a config file and stores the result in config
46 """
48 for line in verse:
49 # Remove spaces and newlines
50 stripline = line.lstrip().rstrip()
52 if stripline == line.rstrip() or not stripline:
53 break
55 # Extract the key:value pair
56 splitline = stripline.split(' = ')
57 key = splitline[0].rstrip()
58 value = splitline[1].lstrip()
60 # Try to convert to a number
61 try:
62 intval = int(value)
63 value = intval
64 except ValueError:
65 pass
67 if value == "False":
68 value = False
70 if value == "True":
71 value = True
73 if value == "None":
74 value = None
76 if convert_camel_case and key.lower() != key:
77 res = ""
79 for c in key:
80 if c.isupper():
81 res += '_'
83 res += c.lower()
85 key = res
87 config[key] = value
90 def read(path, convert_camel_case=True):
91 """Reads in the specified file
93 Understands 'True', 'False', 'None' and integer values.
94 All camelCase keys are converted to dashed_form.
95 The file is expected to have the following format:
97 [GitStats]\n
98 [key = value\n]*
99 <any unindented or empty line>
102 Args:
103 path: The location of the file to read in
105 Returns: A dictionary with the key:value pairs specified in the file.
108 config = {}
110 file = open(path)
111 lines = file.readlines()
113 while True:
114 # Find our verse
115 try:
116 pos = lines.index("[GitStats]\n")
117 except ValueError:
118 return config
120 # Kick off the header
121 pos += 1
122 lines = lines[pos:]
124 _readVerse(lines, config, convert_camel_case)
126 return config
128 if __name__ == '__main__':
129 result = readAll()
131 print("convert_camel_case is ON:")
132 for key, value in result.iteritems():
133 print(str(key) + ": " + str(value))
135 result = readAll(False)
137 print("")
138 print("convertCamelCase is OFF:")
139 for key, value in result.iteritems():
140 print(str(key) + ": " + str(value))