OILS / doctools / html_head.py View on Github | oils.pub

99 lines, 60 significant
1#!/usr/bin/env python2
2"""html_head.py: Emit <html><head> boilerplate.
3
4And make sure it works on mobile!
5
6Note: this file is also run with python3, by the Soil CI, because outside
7containers we don't have python2.
8"""
9from __future__ import print_function
10
11import sys
12try:
13 import html
14except ImportError:
15 # only for cgi.escape -> html.escape
16 import cgi as html # type: ignore
17try:
18 import cStringIO
19except ImportError:
20 cStringIO = None
21 import io
22import optparse
23
24from doctools import doc_html
25
26
27# Python library. Also see doctools/doc_html.py.
28def Write(f, title, css_urls=None, js_urls=None):
29 css_urls = css_urls or []
30 js_urls = js_urls or []
31
32 # Note: do lang=en and charset=utf8 matter? I guess if goes to a different
33 # web server?
34 f.write('''\
35<!DOCTYPE html>
36<html>
37 <head>
38 <meta name="viewport" content="width=device-width, initial-scale=1">
39 <title>%s</title>
40''' % html.escape(title))
41
42 # Write CSS files first I guess?
43
44 for url in css_urls:
45 f.write(doc_html.CSS_FMT % html.escape(url))
46
47 for url in js_urls:
48 f.write(doc_html.JS_FMT % html.escape(url))
49
50 f.write('''\
51 </head>
52''')
53
54
55 # Not used now
56def HtmlHead(title, css_urls=None, js_urls=None):
57 if cStringIO:
58 f = cStringIO.StringIO()
59 else:
60 f = io.BytesIO()
61 Write(f, title, css_urls=css_urls, js_urls=js_urls)
62 return f.getvalue()
63
64
65def main(argv):
66 p = optparse.OptionParser('html_head.py FLAGS? CSS_JS*')
67 p.add_option('-t',
68 '--title',
69 dest='title',
70 default='',
71 help='The title of the web page')
72 opts, argv = p.parse_args(argv[1:])
73
74 # Make it easier to use from shell scripts
75 css_urls = []
76 js_urls = []
77 for arg in argv:
78 i = arg.rfind('?') # account for query param
79 if i != -1:
80 url = arg[:i]
81 else:
82 url = arg
83
84 if url.endswith('.js'):
85 js_urls.append(arg)
86 elif url.endswith('.css'):
87 css_urls.append(arg)
88 else:
89 raise RuntimeError("Expected URL with .js or .css, got %r" % arg)
90
91 Write(sys.stdout, opts.title, css_urls=css_urls, js_urls=js_urls)
92
93
94if __name__ == '__main__':
95 try:
96 main(sys.argv)
97 except RuntimeError as e:
98 print('FATAL: %s' % e, file=sys.stderr)
99 sys.exit(1)