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
|
#!/usr/bin/env python
import base64
import mimetypes
import os.path
import re
import sys
ABSURL_RE = re.compile(r'''^(?:[a-z0-9+.-]+:|/)''')
def repl(func, base):
def g(m):
urlstr = m.group(1)
if urlstr[0] in ('"', "'"):
urlstr = urlstr[1:-1]
if ABSURL_RE.match(urlstr):
return m.group(0)
try:
return func(os.path.join(base, urlstr))
except FileNotFoundError:
return m.group(0)
return g
SCRIPT_RE = re.compile(r'''<script src=("[^"]+"|'[^']+')>\s*</script>''')
def scriptrepl(urlstr):
with open(urlstr, 'r') as f:
script = f.read()
if '</script>' in script:
raise Exception('</script> in script')
return f'<script>{script}</script>'
CSS_RE = re.compile(r'''<link rel="stylesheet" href=("[^"]+"|'[^']+')>''')
def cssrepl(urlstr):
with open(urlstr, 'r') as f:
return '<style>' + f.read() + '</style>'
URL_RE = re.compile(r'''\burl\(("[^"]+"|'[^']+'|[^)]+)\)''')
def urlrepl(urlstr):
with open(urlstr, 'rb') as f:
return ('url(data:' + mimetypes.guess_type(urlstr)[0] +
';base64,' + base64.b64encode(f.read()).decode('ascii') + ')')
if __name__ == '__main__':
mimetypes.add_type('font/woff2', '.woff2')
base = os.path.dirname(sys.argv[1])
with open(sys.argv[1], 'r') as f:
buf = f.read()
buf = SCRIPT_RE.sub(repl(scriptrepl, base), buf)
buf = CSS_RE.sub(repl(cssrepl, base), buf)
buf = URL_RE.sub(repl(urlrepl, base), buf)
sys.stdout.write(buf)
|