aboutsummaryrefslogtreecommitdiffstats
path: root/generate_auto_job
blob: 556b374c846181af64c68115e7e337608cbe3b7e (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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#!/usr/bin/env python3
import os
import sys
import argparse
import hashlib
import re
import yaml

whoami = os.path.basename(sys.argv[0])
BANNER = f'''//
// This file is automatically generated by {whoami}.
// Edits will be automatically overwritten if the build is
// run in maintainer mode.
//'''


def warn(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)


class Main:
    SOURCES = [whoami, 'job.yml', 'manual/cli.rst']
    DESTS = {
        'decl': 'libqpdf/qpdf/auto_job_decl.hh',
        'init': 'libqpdf/qpdf/auto_job_init.hh',
    }
    SUMS = 'job.sums'

    def main(self, args=sys.argv[1:], prog=whoami):
        options = self.parse_args(args, prog)
        self.top(options)

    def parse_args(self, args, prog):
        parser = argparse.ArgumentParser(
            prog=prog,
            description='Generate files for QPDFJob',
        )
        mxg = parser.add_mutually_exclusive_group(required=True)
        mxg.add_argument('--check',
                         help='update checksums if files are not up to date',
                         action='store_true', default=False)
        mxg.add_argument('--generate',
                         help='generate files from sources',
                         action='store_true', default=False)
        return parser.parse_args(args)

    def top(self, options):
        if options.check:
            self.check()
        elif options.generate:
            self.generate()
        else:
            exit(f'{whoami} unknown mode')

    def get_hashes(self):
        hashes = {}
        for i in sorted([*self.SOURCES, *self.DESTS.values()]):
            m = hashlib.sha256()
            try:
                with open(i, 'rb') as f:
                    m.update(f.read())
                hashes[i] = m.hexdigest()
            except FileNotFoundError:
                pass
        return hashes

    def check(self):
        hashes = self.get_hashes()
        match = False
        try:
            old_hashes = {}
            with open(self.SUMS, 'r') as f:
                for line in f.readlines():
                    m = re.match(r'^(\S+) (\S+)\s*$', line)
                    if m:
                        old_hashes[m.group(1)] = m.group(2)
            match = old_hashes == hashes
        except Exception:
            pass
        if not match:
            exit(f'{whoami}: auto job inputs have changed')

    def update_hashes(self):
        hashes = self.get_hashes()
        with open(self.SUMS, 'w') as f:
            print(f'# Generated by {whoami}', file=f)
            for k, v in hashes.items():
                print(f'{k} {v}', file=f)

    def generate_doc(self, df, f):
        st_top = 0
        st_topic = 1
        st_option = 2
        st_option_help = 3
        state = st_top

        indent = None
        topic = None
        option = None
        short_text = None
        long_text = None

        print('this->ap.addHelpFooter("For detailed help, visit'
              ' the qpdf manual: https://qpdf.readthedocs.io\\n");', file=f)

        def set_indent(x):
            nonlocal indent
            indent = ' ' * len(x)

        def append_long_text(line):
            nonlocal indent, long_text
            if line == '\n':
                long_text += '\n'
            elif line.startswith(indent):
                long_text += line[len(indent):]
            else:
                long_text = long_text.strip()
                if long_text != '':
                    long_text += '\n'
                return True
            return False

        lineno = 0
        for line in df.readlines():
            lineno += 1
            if state == st_top:
                m = re.match(r'^(\s*\.\. )help-topic (\S+): (.*)$', line)
                if m:
                    set_indent(m.group(1))
                    topic = m.group(2)
                    short_text = m.group(3)
                    long_text = ''
                    state = st_topic
                    continue
                m = re.match(r'^(\s*\.\. )qpdf:option:: (([^=\s]+)(=(\S+))?)$',
                             line)
                if m:
                    if topic is None:
                        raise Exception('option seen before topic')
                    set_indent(m.group(1))
                    option = m.group(3)
                    synopsis = m.group(2)
                    if synopsis.endswith('`'):
                        raise Exception(
                            f'stray ` at end of option line (line {lineno})')
                    if synopsis != option:
                        long_text = synopsis + '\n'
                    else:
                        long_text = ''
                    state = st_option
                    continue
            elif state == st_topic:
                if append_long_text(line):
                    print(f'this->ap.addHelpTopic("{topic}", "{short_text}",'
                          f' R"({long_text})");', file=f)
                    state = st_top
            elif state == st_option:
                if line == '\n' or line.startswith(indent):
                    m = re.match(r'^(\s*\.\. )help: (.*)$', line)
                    if m:
                        set_indent(m.group(1))
                        short_text = m.group(2)
                        state = st_option_help
                else:
                    state = st_top
            elif state == st_option_help:
                if append_long_text(line):
                    print(f'this->ap.addOptionHelp("{option}", "{topic}",'
                          f' "{short_text}", R"({long_text})");', file=f)
                    state = st_top

    def generate(self):
        warn(f'{whoami}: regenerating auto job files')

        with open('job.yml', 'r') as f:
            data = yaml.safe_load(f.read())
        self.validate(data)
        with open(self.DESTS['decl'], 'w') as f:
            print(BANNER, file=f)
            self.generate_decl(data, f)
        with open(self.DESTS['init'], 'w') as f:
            print(BANNER, file=f)
            self.generate_init(data, f)

        # Update hashes last to ensure that this will be rerun in the
        # event of a failure.
        self.update_hashes()
        # DON'T ADD CODE TO generate AFTER update_hashes

    def check_keys(self, what, d, exp):
        if not isinstance(d, dict):
            exit(f'{what} is not a dictionary')
        actual = set(d.keys())
        extra = actual - exp
        if extra:
            exit(f'{what}: unknown keys = {extra}')

    def validate(self, data):
        self.check_keys('top', data, set(['choices', 'options']))
        for o in data['options']:
            self.check_keys('top', o, set(
                ['table', 'prefix', 'bare', 'positional',
                 'optional_parameter', 'required_parameter',
                 'required_choices', 'optional_choices', 'from_table']))

    def to_identifier(self, label, prefix, const):
        identifier = re.sub(r'[^a-zA-Z0-9]', '_', label)
        if const:
            identifier = identifier.upper()
        else:
            identifier = identifier.lower()
            identifier = re.sub(r'(?:^|_)([a-z])',
                                lambda x: x.group(1).upper(),
                                identifier).replace('_', '')
        return prefix + identifier

    def generate_decl(self, data, f):
        for o in data['options']:
            table = o['table']
            if table in ('main', 'help'):
                continue
            i = self.to_identifier(table, 'O_', True)
            print(f'static constexpr char const* {i} = "{table}";', file=f)
        print('', file=f)
        for o in data['options']:
            table = o['table']
            prefix = 'arg' + o.get('prefix', '')
            if o.get('positional', False):
                print(f'void {prefix}Positional(char*);', file=f)
            for i in o.get('bare', []):
                identifier = self.to_identifier(i, prefix, False)
                print(f'void {identifier}();', file=f)
            for i in o.get('optional_parameter', []):
                identifier = self.to_identifier(i, prefix, False)
                print(f'void {identifier}(char *);', file=f)
            for i in o.get('required_parameter', {}):
                identifier = self.to_identifier(i, prefix, False)
                print(f'void {identifier}(char *);', file=f)
            for i in o.get('required_choices', {}):
                identifier = self.to_identifier(i, prefix, False)
                print(f'void {identifier}(char *);', file=f)
            for i in o.get('optional_choices', {}):
                identifier = self.to_identifier(i, prefix, False)
                print(f'void {identifier}(char *);', file=f)
            if table not in ('main', 'help'):
                identifier = self.to_identifier(table, 'argEnd', False)
                print(f'void {identifier}();', file=f)

    def generate_init(self, data, f):
        print('auto b = [this](void (ArgParser::*f)()) {', file=f)
        print('    return QPDFArgParser::bindBare(f, this);', file=f)
        print('};', file=f)
        print('auto p = [this](void (ArgParser::*f)(char *)) {', file=f)
        print('    return QPDFArgParser::bindParam(f, this);', file=f)
        print('};', file=f)
        print('', file=f)
        for k, v in data['choices'].items():
            print(f'char const* {k}_choices[] = {{', file=f, end='')
            for i in v:
                print(f'"{i}", ', file=f, end='')
            print('0};', file=f)
        print('', file=f)
        for o in data['options']:
            table = o['table']
            if table == 'main':
                print('this->ap.selectMainOptionTable();', file=f)
            elif table == 'help':
                print('this->ap.selectHelpOptionTable();', file=f)
            else:
                identifier = self.to_identifier(table, 'argEnd', False)
                print(f'this->ap.registerOptionTable("{table}",'
                      f' b(&ArgParser::{identifier}));', file=f)
            prefix = 'arg' + o.get('prefix', '')
            if o.get('positional', False):
                print('this->ap.addPositional('
                      f'p(&ArgParser::{prefix}Positional));', file=f)
            for i in o.get('bare', []):
                identifier = self.to_identifier(i, prefix, False)
                print(f'this->ap.addBare("{i}", '
                      f'b(&ArgParser::{identifier}));', file=f)
            for i in o.get('optional_parameter', []):
                identifier = self.to_identifier(i, prefix, False)
                print(f'this->ap.addOptionalParameter("{i}", '
                      f'p(&ArgParser::{identifier}));', file=f)
            for k, v in o.get('required_parameter', {}).items():
                identifier = self.to_identifier(k, prefix, False)
                print(f'this->ap.addRequiredParameter("{k}", '
                      f'p(&ArgParser::{identifier})'
                      f', "{v}");', file=f)
            for k, v in o.get('required_choices', {}).items():
                identifier = self.to_identifier(k, prefix, False)
                print(f'this->ap.addChoices("{k}", '
                      f'p(&ArgParser::{identifier})'
                      f', true, {v}_choices);', file=f)
            for k, v in o.get('optional_choices', {}).items():
                identifier = self.to_identifier(k, prefix, False)
                print(f'this->ap.addChoices("{k}", '
                      f'p(&ArgParser::{identifier})'
                      f', false, {v}_choices);', file=f)
        for o in data['options']:
            table = o['table']
            if 'from_table' not in o:
                continue
            if table == 'main':
                print('this->ap.selectMainOptionTable();', file=f)
            elif table == 'help':
                print('this->ap.selectHelpOptionTable();', file=f)
            else:
                print(f'this->ap.selectOptionTable("{table}");', file=f)
            ft = o['from_table']
            other_table = ft['table']
            for j in ft['options']:
                print('this->ap.copyFromOtherTable'
                      f'("{j}", "{other_table}");', file=f)
        with open('manual/cli.rst', 'r') as df:
            self.generate_doc(df, f)


if __name__ == '__main__':
    try:
        os.chdir(os.path.dirname(os.path.realpath(__file__)))
        Main().main()
    except KeyboardInterrupt:
        exit(130)