diff options
author | Alex Xu (Hello71) <alex_y_xu@yahoo.ca> | 2021-10-03 15:03:42 -0400 |
---|---|---|
committer | Alex Xu (Hello71) <alex_y_xu@yahoo.ca> | 2021-10-03 15:03:42 -0400 |
commit | 7dccf6e8684f767b6e377d627b36ccf493947f1e (patch) | |
tree | 4859d4e1a24ea2028de1366bc59cd28e6782a6d1 /inliner.py | |
download | alxu.ca-7dccf6e8684f767b6e377d627b36ccf493947f1e.tar.xz alxu.ca-7dccf6e8684f767b6e377d627b36ccf493947f1e.zip |
Initial commit
Diffstat (limited to 'inliner.py')
-rwxr-xr-x | inliner.py | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/inliner.py b/inliner.py new file mode 100755 index 0000000..b37c275 --- /dev/null +++ b/inliner.py @@ -0,0 +1,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) |