Completed
Push — master ( 5ecf6e...2cfde1 )
by Andrii
11:27
created

Config.find()   B

Complexity

Conditions 5

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 5
c 2
b 0
f 1
dl 0
loc 17
rs 8.5454
1
#!/usr/bin/env python
2
3
import os
4
import sys
5
import json
6
import collections
7
8
from pprint import pprint
9
10
# http://stackoverflow.com/questions/10703858
11
def merge_dict(d1, d2):
12
    """
13
    Modifies d1 in-place to contain values from d2.  If any value
14
    in d1 is a dictionary (or dict-like), *and* the corresponding
15
    value in d2 is also a dictionary, then merge them in-place.
16
    """
17
    for k,v2 in d2.items():
18
        v1 = d1.get(k) # returns None if v1 has no value for this key
19
        if (isinstance(v1, collections.Mapping)
20
        and isinstance(v2, collections.Mapping)):
21
            merge_dict(v1, v2)
22
        else:
23
            d1[k] = v2
24
25
class Config(dict):
26
    def __init__(self, filename):
27
        with open(self.find(filename)) as file:
28
            self.merge(json.load(file))
29
30
    def merge(self, data):
31
        merge_dict(self, data)
32
33
    def find(self, filename):
34
        if os.path.isfile(filename):
35
            return filename
36
37
        command = sys.argv[0]
38
        if '/' != command[0]:
39
            command = os.path.normpath(os.path.join(os.getcwd(), command))
40
        path = os.path.join(os.path.dirname(os.path.dirname(command)), 'etc', filename)
41
        if os.path.isfile(path):
42
            return path
43
44
        ext = os.path.splitext(filename)[1]
45
46
        if not ext:
47
            return self.find(filename + '.json')
48
        else:
49
            return os.path.join('/etc/heppy', filename)
50