Completed
Push — master ( fca8f9...aaddef )
by Andrii
04:19
created

Config.findFile()   B

Complexity

Conditions 6

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
dl 0
loc 21
rs 7.8867
1
#!/usr/bin/env python
2
3
import os
4
import sys
5
import json
6
import collections
7
8
# http://stackoverflow.com/questions/10703858
9
def merge_dict(d1, d2):
10
    """
11
    Modifies d1 in-place to contain values from d2.  If any value
12
    in d1 is a dictionary (or dict-like), *and* the corresponding
13
    value in d2 is also a dictionary, then merge them in-place.
14
    """
15
    for k,v2 in d2.items():
16
        v1 = d1.get(k) # returns None if v1 has no value for this key
17
        if (isinstance(v1, collections.Mapping)
18
        and isinstance(v2, collections.Mapping)):
19
            merge_dict(v1, v2)
20
        else:
21
            d1[k] = v2
22
23
class Config(dict):
24
    def __init__(self, filename):
25
        self.path = self.findFile(filename)
26
        with open(self.path) as file:
27
            self.merge(json.load(file))
28
29
    def merge(self, data):
30
        merge_dict(self, data)
31
32
    @classmethod
33
    def findFile(cls, 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
        if ':' in filename:
45
            return cls.findFile(filename.split(':', 1)[0])
46
47
        ext = os.path.splitext(filename)[1]
48
49
        if ext != '.json':
50
            return cls.findFile(filename + '.json')
51
        else:
52
            return os.path.join('/etc/heppy', filename)
53
54