summaryrefslogtreecommitdiff
path: root/inliner.py
diff options
context:
space:
mode:
Diffstat (limited to 'inliner.py')
-rwxr-xr-xinliner.py50
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)