aboutsummaryrefslogtreecommitdiffstats
path: root/topple/topple.py
blob: 88a2bd00db4afd07eca0fd6f02a8a70fb59ab509 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
from __future__ import print_function

import ast
import os
import os.path
import sys

import pycommand


def get_setting_specs(module):
    sys.path.insert(0, os.getcwd())
    return __import__(module)


def write_settings(specs, out, values=None):
    values = values or {}

    print('# {file} file generated by topple'
          .format(file=specs.OUTPUT_FILE), file=out)

    for key, spec in specs.SETTINGS:
        value = values.get(key, spec[1])
        print(key, repr(value), sep=' = ', file=out)


def get_node_value(node):
    if isinstance(node, ast.Name):
        return ast.literal_eval(node.id)
    elif isinstance(node, ast.Str):
        return node.s
    elif isinstance(node, ast.Num):
        return node.n
    else:
        return node


def get_settings_from(filename):
    res = {}

    with open(filename, 'r') as f:
        tree = ast.parse('\n'.join(f.readlines()), filename)
        for node in ast.iter_child_nodes(tree):
            if isinstance(node, ast.Assign):
                for target in node.targets:
                    res[target.id] = get_node_value(node.value)
            else:
                print(node, node._fields)

    return res


class PreviewMixin(object):
    optionList = (
        ('preview', ('p', None, 'Print generated file to stdout')),
    )

    def __new__(cls, *args, **kwargs):
        cls.optionList = (cls.optionList or tuple()) + PreviewMixin.optionList
        instance = super(PreviewMixin, cls).__new__(cls, *args, **kwargs)
        return instance

    def write(self, output, specs, values=None):
        preview = self.flags['preview']

        if not preview:
            with open(output, 'w') as f:
                write_settings(specs, f, values)
        else:
            write_settings(specs, sys.stdout, values)


class Generate(pycommand.CommandBase, PreviewMixin):
    usagestr = 'usage: topple generate [--preview|-p]'

    def run(self):
        sys.path.insert(0, os.getcwd())

        specs = get_setting_specs(self.parentFlags['module'] or 'toppler')
        self.write(specs.OUTPUT_FILE, specs)


class Update(pycommand.CommandBase, PreviewMixin):
    usagestr = 'usage: topple update [--preview|-p]'

    def run(self):
        sys.path.insert(0, os.getcwd())
        filename = 'settings_local.py'
        res = get_settings_from(filename)
        specs = get_setting_specs(self.parentFlags['module'] or 'toppler')
        self.write(specs.OUTPUT_FILE, specs, res)


class Check(pycommand.CommandBase):
    usagestr = 'usage: topple check'

    def run(self):
        sys.path.insert(0, os.getcwd())
        filename = 'settings_local.py'
        res = get_settings_from(filename)
        specs = get_setting_specs(self.parentFlags['module'] or 'toppler')

        for key, spec in specs.SETTINGS:
            if key not in res:
                print('Missing setting:', key)
            elif not spec[0](res[key]):
                print('Value "%s" for %s does not pass predicate `%s\''
                      % (res[key], key, spec[0].func_name))


class Topple(pycommand.CommandBase):
    usagestr = 'usage: topple [--module=modulename|-m modulename] generate'
    description = (
        'Commands:\n'
        '  generate   Generate a new settings file.\n'
        '  update     Update an existing settings file.\n'
        '  check      Check the validity of an existing settings file.'
    )
    optionList = (('module', ('m', '<modulename>',
                              'Use specified python module.')),)

    def run(self):
        module = self.flags['module'] or 'toppler'

        if not os.path.exists(module + '.py'):
            print('No {module}.py module found!'.format(module=module))
            return 1
        if not self.args:
            print(self.usage)
            return 2

        if self.args[0] == 'generate':
            cmd = Generate(argv=self.args[1:])
        elif self.args[0] == 'update':
            cmd = Update(argv=self.args[1:])
        elif self.args[0] == 'check':
            cmd = Check(argv=self.args[1:])
        else:
            print('Undefined command: {cmd}'.format(cmd=self.args[0]))
            return 1

        cmd.registerParentFlag('module', self.flags['module'])

        if cmd.error:
            print('Error during {cmd}: {err}'.format(cmd=self.args[0],
                                                     err=cmd.error))
            return 1
        else:
            return cmd.run()