#!/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'''''')
def scriptrepl(urlstr):
with open(urlstr, 'r') as f:
script = f.read()
if '' in script:
raise Exception(' in script')
return f''
CSS_RE = re.compile(r'''''')
def cssrepl(urlstr):
with open(urlstr, 'r') as f:
return ''
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)