summaryrefslogtreecommitdiff
path: root/jfr_playoff/settings.py
blob: 7994bfcc310e37ea0b386fa3a7628a138031a001 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import glob
import json
import readline
import sys
import urllib


def complete_filename(text, state):
    return (glob.glob(text+'*')+[None])[state]


class PlayoffSettings(object):

    def __init__(self):
        self.settings = None
        self.interactive = False
        self.settings_file = None
        if len(sys.argv) > 1:
            self.settings_file = sys.argv[1].decode(
                sys.getfilesystemencoding())
        else:
            self.interactive = True

    def __merge_config(self, base_config,
                       new_config=None, remote_url=None,
                       overwrite=True):
        try:
            remote_file = urllib.urlopen(remote_url)
            print remote_file.info()
            print remote_file.read()
            remote_content = remote_file.read().decode('utf-8-sig')
            print remote_content
            remote_config = new_config if new_config is not None else json.loads(remote_content)
            for key, value in remote_config.iteritems():
                if (key not in base_config) or overwrite:
                    base_config[key] = value
        except Exception as e:
            print 'WARNING: unable to merge remote config: %s' % (str(e))
            if remote_url is not None:
                print 'Offending URL: %s' % (remote_url)
            raise
        return base_config

    def load(self):
        if self.settings_file is None:
            readline.set_completer_delims(' \t\n;')
            readline.parse_and_bind("tab: complete")
            readline.set_completer(complete_filename)
            self.settings_file = raw_input(
                'JSON settings file: ').decode(sys.stdin.encoding)

        if self.settings is None:
            self.settings = json.loads(
                open(unicode(self.settings_file)).read().decode('utf-8-sig'))
            if self.has_section('remotes'):
                remote_config = {}
                for remote in self.get('remotes'):
                    remote_config = self.__merge_config(
                        remote_config, remote_url=remote)
                self.settings = self.__merge_config(
                    self.settings, new_config=remote_config,
                    overwrite=False)

    def has_section(self, key):
        self.load()
        return key in self.settings

    def get(self, *keys):
        self.load()
        section = self.settings
        for key in keys:
            section = section[key]
        return section