Completed
Push — master ( 66ee29...ce8105 )
by Andrii
15:26
created

Config   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 20
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 3 2
A find() 0 12 4
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
        return os.path.join('/etc/heppy', filename)
45