Make config.py more versatile
[git-stats.git] / src / git_stats / config.py
blobe64d3015d002780db06124ffc56de95665e0b43a
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 read(path, convert_camel_case=True):
45 """Reads in the specified file
47 Understands 'True', 'False', 'None' and integer values.
48 All camelCase keys are converted to dashed_form.
49 The file is expected to have the following format:
51 [GitStats]\n
52 [key = value\n]*
53 <any unindented or empty line>
56 Args:
57 path: The location of the file to read in
59 Returns: A dictionary with the key:value pairs specified in the file.
60 """
62 config = {}
64 file = open(path)
65 lines = file.readlines()
67 # Find our verse
68 try:
69 pos = lines.index("[GitStats]\n")
70 except ValueError:
71 return config
73 # Kick off the header
74 pos += 1
75 lines = lines[pos:]
77 for line in lines:
78 # Remove spaces and newlines
79 stripline = line.lstrip().rstrip()
81 if stripline == line.rstrip() or not stripline:
82 break
84 # Extract the key:value pair
85 splitline = stripline.split(' = ')
86 key = splitline[0].rstrip()
87 value = splitline[1].lstrip()
89 # Try to convert to a number
90 try:
91 intval = int(value)
92 value = intval
93 except ValueError:
94 pass
96 if value == "False":
97 value = False
99 if value == "True":
100 value = True
102 if value == "None":
103 value = None
105 if convert_camel_case and key.lower() != key:
106 res = ""
108 for c in key:
109 if c.isupper():
110 res += '_'
112 res += c.lower()
114 key = res
116 config[key] = value
118 return config
120 if __name__ == '__main__':
121 result = readAll()
123 print("convert_camel_case is ON:")
124 for key, value in result.iteritems():
125 print(str(key) + ": " + str(value))
127 result = readAll(False)
129 print("")
130 print("convertCamelCase is OFF:")
131 for key, value in result.iteritems():
132 print(str(key) + ": " + str(value))