OILS / doctools / html_head.py View on Github | oilshell.org

98 lines, 58 significant
1#!/usr/bin/env python2
2"""
3html_head.py: Emit <html><head> boilerplate.
4
5And make sure it works on mobile!
6
7Note: this file is also run with python3, by the Soil CI, because outside
8containers we don't have python2.
9"""
10from __future__ import print_function
11
12import sys
13try:
14 import html
15except ImportError:
16 import cgi as html # only for cgi.escape -> html.escape
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(
68 '-t', '--title', dest='title', default='',
69 help='The title of the web page')
70 opts, argv = p.parse_args(argv[1:])
71
72 # Make it easier to use from shell scripts
73 css_urls = []
74 js_urls = []
75 for arg in argv:
76 i = arg.rfind('?') # account for query param
77 if i != -1:
78 url = arg[:i]
79 else:
80 url = arg
81
82 if url.endswith('.js'):
83 js_urls.append(arg)
84 elif url.endswith('.css'):
85 css_urls.append(arg)
86 else:
87 raise RuntimeError("Expected URL with .js or .css, got %r" % arg)
88
89 Write(sys.stdout, opts.title, css_urls=css_urls, js_urls=js_urls)
90
91
92
93if __name__ == '__main__':
94 try:
95 main(sys.argv)
96 except RuntimeError as e:
97 print('FATAL: %s' % e, file=sys.stderr)
98 sys.exit(1)