aboutsummaryrefslogtreecommitdiff
path: root/dodo.py
blob: fb63007acd01961bbc12be9a22251b339d4b5bf5 (plain) (blame)
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import sys
import os
import shutil
import json
import yaml
import subprocess
from pathlib import Path
from doit.action import CmdAction


sys.path += ['src_py']
os.environ['PYTHONPATH'] = os.path.abspath('src_py')

DOIT_CONFIG = {
    'backend': 'sqlite3',
    'default_tasks': ['dist_build'],
    'verbosity': 2}


# ######################## utility functions #################################

def mkdir_p(*paths):
    for path in paths:
        os.makedirs(str(Path(path)), exist_ok=True)


def rm_rf(*paths):
    for path in paths:
        p = Path(path)
        if not p.exists():
            continue
        if p.is_dir():
            shutil.rmtree(str(p), ignore_errors=True)
        else:
            p.unlink()


def cp_r(src, dest):
    src = Path(src)
    dest = Path(dest)
    if src.is_dir():
        shutil.copytree(str(src), str(dest))
    else:
        shutil.copy2(str(src), str(dest))


# ########################## global tasks ####################################

def task_clean_all():
    """Clean all"""

    return {'actions': [(rm_rf, ['build', 'dist'])],
            'task_dep': ['pyhatter_clean',
                         'jshatter_clean',
                         'dist_clean']}


def task_gen_all():
    """Generate all"""

    return {'actions': None,
            'task_dep': ['pyhatter_gen',
                         'jshatter_gen']}


def task_check_all():
    """Check all"""

    return {'actions': None,
            'task_dep': ['pyhatter_check']}


# ############################ dist tasks #####################################

def task_dist_clean():
    """Distribution - clean"""

    return {'actions': [(rm_rf, ['dist'])]}


def task_dist_build():
    """Distribution - build (DEFAULT)"""

    def generate_setup_py():
        with open('dist/setup.py', 'w', encoding='utf-8') as f:
            f.write('\n')

    return {'actions': [(rm_rf, ['dist']),
                        (cp_r, ['build/pyhatter', 'dist']),
                        (cp_r, ['build/jshatter', 'dist/hatter/web']),
                        generate_setup_py],
            'task_dep': [
                'gen_all',
                'pyhatter_build',
                'jshatter_build']}


# ########################## pyhatter tasks ###################################

def task_pyhatter_clean():
    """PyHatter - clean"""

    return {'actions': [(rm_rf, ['build/pyhatter',
                                 'src_py/hatter/json_validator.py'])]}


def task_pyhatter_build():
    """PyHatter - build"""

    generated_files = {Path('src_py/hatter/json_validator.py')}

    def compile(src_path, dst_path):
        mkdir_p(dst_path.parent)
        # if src_path.suffix == '.py':
        #     py_compile.compile(src_path, dst_path.with_suffix('.pyc'),
        #                        doraise=True)
        # else:
        #     cp_r(src_path, dst_path)
        cp_r(src_path, dst_path)

    def create_subtask(src_path):
        dst_path = Path('build/pyhatter') / src_path.relative_to('src_py')
        return {'name': str(src_path),
                'actions': [(compile, [src_path, dst_path])],
                'file_dep': [src_path],
                'targets': [dst_path]}

    for src_path in generated_files:
        yield create_subtask(src_path)

    for dirpath, dirnames, filenames in os.walk('src_py'):
        if '__pycache__' in dirnames:
            dirnames.remove('__pycache__')
        for i in filenames:
            src_path = Path(dirpath) / i
            if src_path not in generated_files:
                yield create_subtask(src_path)


def task_pyhatter_check():
    """PyHatter - run flake8"""

    return {'actions': [CmdAction('python -m flake8 .', cwd='src_py')]}


def task_pyhatter_gen():
    """PyHatter - generate additional python modules"""

    return {'actions': None,
            'task_dep': ['pyhatter_gen_json_validator']}


def task_pyhatter_gen_json_validator():
    """PyHatter - generate json validator"""

    schema_files = list(Path('schemas_json').glob('**/*.yaml'))
    output_file = Path('src_py/hatter/json_validator.py')

    def parse_schemas():
        schemas = {}
        for schema_file in schema_files:
            with open(schema_file, encoding='utf-8') as f:
                data = yaml.safe_load(f)
                if data['id'] in schemas:
                    raise Exception("duplicate schema id " + data['id'])
                schemas[data['id']] = data
        return schemas

    def generate_output():
        schemas = parse_schemas()
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(
                '# pylint: skip-file\n'
                'import jsonschema\n\n\n'
                '_schemas = ' + repr(schemas) + '  # NOQA\n\n\n'
                'def validate(data, schema_id):\n'
                '    """ Validate data with JSON schema\n\n'
                '    Args:\n'
                '       data: validated data\n'
                '       schema_id (str): JSON schema identificator\n\n'
                '    Raises:\n'
                '       Exception: validation fails\n\n'
                '    """\n'
                '    base_uri = schema_id.split("#")[0] + "#"\n'
                '    fragment = schema_id.split("#")[1] if "#" in schema_id else ""\n'  # NOQA
                '    resolver = jsonschema.RefResolver(\n'
                '        base_uri=base_uri,\n'
                '        referrer=_schemas[base_uri],\n'
                '        handlers={"hat": lambda x: _schemas[x + "#"]})\n'
                '    jsonschema.validate(\n'
                '        instance=data,\n'
                '        schema=resolver.resolve_fragment(resolver.referrer, fragment),\n'  # NOQA
                '        resolver=resolver)\n')

    return {'actions': [generate_output],
            'file_dep': schema_files,
            'targets': [output_file]}


# ########################## jshatter tasks ###################################

def task_jshatter_clean():
    """JsHatter - clean"""

    return {'actions': [(rm_rf, ['build/jshatter',
                                 'src_js/hatter/validator.js'])]}


def task_jshatter_install_deps():
    """JsHatter - install dependencies"""

    def patch():
        subprocess.Popen(['patch', '-r', '/dev/null', '--forward', '-p0',
                          '-i', 'node_modules.patch'],
                         stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL).wait()

    return {'actions': ['yarn install',
                        patch]}


def task_jshatter_remove_deps():
    """JsHatter - remove dependencies"""

    return {'actions': [(rm_rf, ['node_modules', 'yarn.lock'])]}


def task_jshatter_gen():
    """JsHatter - generate additional JavaScript modules"""

    return {'actions': None,
            'task_dep': ['jshatter_gen_validator']}


def task_jshatter_gen_validator():
    """JsHatter - generate json validator"""

    schema_files = list(Path('schemas_json').glob('**/*.yaml'))
    output_file = Path('src_js/hatter/validator.js')

    def parse_schemas():
        for schema_file in schema_files:
            with open(schema_file, encoding='utf-8') as f:
                yield yaml.safe_load(f)

    def generate_output():
        schemas_json = json.dumps(list(parse_schemas()), indent=4)
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(
                'import tv4 from "tv4";\n\n\n' +
                schemas_json + '.forEach(i => tv4.addSchema(i.id, i));\n\n\n' +
                'export function validate(data, schemaId) {\n' +
                '    return tv4.validate(data, tv4.getSchema(schemaId));\n' +
                '}\n')

    return {'actions': [generate_output],
            'file_dep': schema_files,
            'targets': [output_file]}


def task_jshatter_build():
    """JsHatter - build"""

    return {'actions': ['yarn run build'],
            'task_dep': ['jshatter_install_deps', 'jshatter_gen']}


def task_jshatter_watch():
    """JsHatter - build on change"""

    return {'actions': ['yarn run watch'],
            'task_dep': ['jshatter_install_deps', 'jshatter_gen']}