-
Notifications
You must be signed in to change notification settings - Fork 6
/
build_plugin.py
executable file
·234 lines (185 loc) · 7.48 KB
/
build_plugin.py
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
#!/usr/bin/env python3
"""Utility to build iitc plugin for given source file name."""
import base64
import re
import sys
from functools import partial
from importlib import import_module
from mimetypes import guess_type
from pathlib import Path
import settings
def get_module(name):
sys.path.insert(0, '') # temporary include cwd in modules search paths
module = import_module(name)
sys.path.pop(0)
return module
def fill_meta(source, plugin_name, dist_path):
meta = ['// ==UserScript==']
keys = set()
def append_line(key, value):
if key not in keys:
meta.append(f'// @{key:<14} {value}')
is_main = False
for line in source.splitlines():
text = line.lstrip()
rem = text[:2]
if rem != '//':
raise UserWarning(f'{plugin_name}: wrong line in metablock: {line}')
text = text[2:].strip()
try:
key, value = text.split(None, 1)
except ValueError:
if text == '==UserScript==':
raise UserWarning(f'{plugin_name}: wrong metablock detected')
else:
key = key[1:]
keys.add(key)
if key == 'version':
if not re.match(r'^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$', value):
print(f'{plugin_name}: wrong version format: {value}') # expected: major.minor.patch
elif settings.version_timestamp: # append timestamp only for well-formed version
line = line.replace(value, '{ver}.{.build_timestamp}'.format(settings, ver=value))
elif key == 'name':
if value == 'IITC: Ingress intel map total conversion':
is_main = True
else:
line = line.replace(value, 'IITC plugin: ' + value)
meta.append(line)
append_line('id', plugin_name)
append_line('namespace', settings.namespace)
if settings.url_dist_base:
path = [settings.url_dist_base]
if dist_path:
path.append(dist_path)
path.append(plugin_name)
path = '/'.join(path)
if settings.update_file in {'.user.js', '.meta.js'}:
append_line('updateURL', path + settings.update_file)
append_line('downloadURL', path + '.user.js')
if keys.isdisjoint({'match', 'include'}):
append_line('match', settings.match)
append_line('grant', 'none')
meta.append('// ==/UserScript==\n')
return '\n'.join(meta), is_main
def multi_line(text):
return ('\n' + text).replace('\\', r'\\').replace('\n', '\\\n').replace("'", r"\'")
def log_dependency(filename, deps_list=None):
if deps_list is not None:
deps_list.append(filename)
def readtext(filename):
log_dependency(filename)
return filename.read_text(encoding='utf-8-sig')
def readbytes(filename):
log_dependency(filename)
return filename.read_bytes()
def load_image(filename):
mtype, _ = guess_type(str(filename)) # todo: after Python 3.8 mimetypes accepts PathLike too
assert mtype, f'Failed to guess mimetype: {filename}'
return 'data:{};base64,{}'.format(
mtype,
base64.b64encode(readbytes(filename)).decode('utf8'),
)
def wrap_iife(filename):
return """
// *** module: {.name} ***
(function () {{
var log = ulog('{.stem}');
{content}
}})();
""".format(filename, filename, content=readtext(filename))
def bundle_code(_, path=None):
files = (path / 'code').glob('*.js')
return '\n'.join(map(wrap_iife, sorted(files)))
def imgrepl(match, path=None):
fullname = path / match.group('filename')
return load_image(fullname)
def expand_template(match, path=None):
quote = "'%s'"
kw, filename = match.groups()
if not filename:
return quote % getattr(settings, kw)
fullname = path / filename
if kw == 'include_raw':
return """// *** included: {filename} ***
{content}
""".format(filename=filename, content=readtext(fullname))
elif kw == 'include_string':
return quote % multi_line(readtext(fullname))
elif kw == 'include_img':
return quote % load_image(fullname)
elif kw == 'include_css':
pattern = r'(?<=url\()["\']?(?P<filename>[^)#]+?)["\']?(?=\))'
css = re.sub(pattern, partial(imgrepl, path=fullname.parent), readtext(fullname))
return quote % multi_line(css)
def process_file(source, out_dir, dist_path=None, deps_list=None):
"""Generate .user.js (and optionally .meta.js) from given source file.
Resulted file(s) put into out_dir (if specified, otherwise - use current).
dist_path component is for adding to @downloadURL/@updateURL.
"""
global log_dependency
log_dependency = partial(log_dependency, deps_list=deps_list)
try:
meta, script = readtext(source).split('\n\n', 1)
except ValueError:
raise Exception(f'{source}: wrong input: empty line expected after metablock')
plugin_name = source.stem
meta, is_main = fill_meta(meta, plugin_name, dist_path)
settings.plugin_id = plugin_name
if not settings.version_timestamp and settings.ignore_semver:
try:
old_meta, _ = (out_dir / (plugin_name + '.user.js')).read_text().split('\n\n', 1)
if old_meta + '\n' == meta:
return False
except:
pass
path = source.parent # used as root for all (relative) paths
script = re.sub(r"'@bundle_code@';", partial(bundle_code, path=path), script)
try:
script_before_wrapper, script = script.split('\n/*wrapped-from-here*/\n', 1)
except ValueError:
script_before_wrapper = ''
wrapper = get_module(settings.plugin_wrapper)
template = r"'@(\w+)(?::([\w./-]+))?@'" # to find '@keyword[:path]@' patterns
repl = partial(expand_template, path=path)
data = [
meta,
script_before_wrapper,
re.sub(template, repl, wrapper.start),
re.sub(template, repl, script),
wrapper.setup if not is_main else '', # it's for plugins only
wrapper.end,
]
(out_dir / (plugin_name + '.user.js')).write_text(''.join(data), encoding='utf8')
if settings.url_dist_base and settings.update_file == '.meta.js':
(out_dir / (plugin_name + '.meta.js')).write_text(meta, encoding='utf8')
return True
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('build', type=str, nargs='?',
help='Specify build name')
parser.add_argument('sources', type=Path, nargs='+',
help='Specify source file name')
parser.add_argument('--out-dir', type=Path, nargs='?',
help='Specify out directory')
args = parser.parse_args()
try:
settings.load(args.build)
except ValueError as err:
parser.error(err)
args.out_dir = args.out_dir or Path(settings.build_target_dir)
if not args.out_dir.is_dir():
parser.error('Out directory not found: {.out_dir}'.format(args))
for source in args.sources:
if not source.is_file():
parser.error('Source file not found: {}'.format(source))
target = args.out_dir / (source.stem + '.user.js')
if target.is_file() and target.samefile(source):
parser.error('Target cannot be same as source: {}'.format(source))
try:
if process_file(source, args.out_dir):
print('new/changed:', target)
else:
print('unchanged: ', target)
except UserWarning as err:
parser.error(err)