~alexcleac/dotfiles unlisted

dotfiles/bin/rw.py -rwxr-xr-x 1.3 KiB
f52e5499Alex Cleac [newsboat] Improva download speed 2 months ago
                                                                                
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
#!/usr/bin/env python3
import fileinput
import re
import sys
import os
import importlib
import importlib.util

CALL_REGEX = re.compile(r'^(?P<offset>\s+)?(.+)?@call (?P<fname>[/\w\d]+\.py)(.+)?$')


def load_module(fname):
    spec = importlib.util.spec_from_file_location('external_script', fname)
    external_script = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(external_script)
    return external_script


def process_single_file(fname):
    with open(fname, 'r+') as file:
        contents = file.readlines()

        append_line = -1
        source_file = None
        indentation = ''
        for i, line in enumerate(contents):
            match = CALL_REGEX.match(line)
            if match is not None:
                source_file = match.group('fname')
                indentation = match.group('offset') or ''
                append_line = i
                break
        else:
            print('No src file found: exiting')
            sys.exit(1)

    i += 1
    script = load_module(source_file)
    to_insert = [indentation + x for x in script.program(filename=fname)]

    with open(fname, 'w') as file:
        file.write(''.join([
            *contents[:i],
            *to_insert,
            *contents[i:],
        ]))


if __name__ == '__main__':
    for fname in sys.argv[1:]:
        process_single_file(fname)