| 1 |
from __future__ import absolute_import |
| 2 |
|
| 3 |
from docstructure import SITE_STRUCTURE, HREF_MAP, BASENAME_MAP |
| 4 |
from lxml.etree import (parse, fromstring, ElementTree, |
| 5 |
Element, SubElement, XPath, XML) |
| 6 |
import glob |
| 7 |
import hashlib |
| 8 |
import os |
| 9 |
import re |
| 10 |
import sys |
| 11 |
import copy |
| 12 |
import shutil |
| 13 |
import textwrap |
| 14 |
import subprocess |
| 15 |
|
| 16 |
from io import open as open_file |
| 17 |
|
| 18 |
RST2HTML_OPTIONS = " ".join([ |
| 19 |
'--no-toc-backlinks', |
| 20 |
'--strip-comments', |
| 21 |
'--language en', |
| 22 |
'--date', |
| 23 |
]) |
| 24 |
|
| 25 |
XHTML_NS = 'http://www.w3.org/1999/xhtml' |
| 26 |
htmlnsmap = {"h": XHTML_NS} |
| 27 |
|
| 28 |
find_head = XPath("/h:html/h:head[1]", namespaces=htmlnsmap) |
| 29 |
find_body = XPath("/h:html/h:body[1]", namespaces=htmlnsmap) |
| 30 |
find_title = XPath("/h:html/h:head/h:title/text()", namespaces=htmlnsmap) |
| 31 |
find_title_tag = XPath("/h:html/h:head/h:title", namespaces=htmlnsmap) |
| 32 |
find_headings = XPath("//h:h1[not(@class)]//text()", namespaces=htmlnsmap) |
| 33 |
find_heading_tag = XPath("//h:h1[@class = 'title'][1]", namespaces=htmlnsmap) |
| 34 |
find_menu = XPath("//h:ul[@id=$name]", namespaces=htmlnsmap) |
| 35 |
find_page_end = XPath("/h:html/h:body/h:div[last()]", namespaces=htmlnsmap) |
| 36 |
|
| 37 |
find_words = re.compile(r'(\w+)').findall |
| 38 |
replace_invalid = re.compile(r'[-_/.\s\\]').sub |
| 39 |
|
| 40 |
|
| 41 |
def make_menu_section_head(section, menuroot): |
| 42 |
section_id = section + '-section' |
| 43 |
section_head = menuroot.xpath("//ul[@id=$section]/li", section=section_id) |
| 44 |
if not section_head: |
| 45 |
ul = SubElement(menuroot, "ul", id=section_id) |
| 46 |
section_head = SubElement(ul, "li") |
| 47 |
title = SubElement(section_head, "span", {"class":"section title"}) |
| 48 |
title.text = section |
| 49 |
else: |
| 50 |
section_head = section_head[0] |
| 51 |
return section_head |
| 52 |
|
| 53 |
|
| 54 |
def build_menu(tree, basename, section_head): |
| 55 |
page_title = find_title(tree) |
| 56 |
if page_title: |
| 57 |
page_title = page_title[0] |
| 58 |
else: |
| 59 |
page_title = replace_invalid('', basename.capitalize()) |
| 60 |
build_menu_entry(page_title, basename+".html", section_head, |
| 61 |
headings=find_headings(tree)) |
| 62 |
|
| 63 |
|
| 64 |
def build_menu_entry(page_title, url, section_head, headings=None): |
| 65 |
page_id = replace_invalid(' ', os.path.splitext(url)[0]) + '-menu' |
| 66 |
ul = SubElement(section_head, "ul", {"class":"menu foreign", "id":page_id}) |
| 67 |
|
| 68 |
title = SubElement(ul, "li", {"class":"menu title"}) |
| 69 |
a = SubElement(title, "a", href=url) |
| 70 |
a.text = page_title |
| 71 |
|
| 72 |
if headings: |
| 73 |
subul = SubElement(title, "ul", {"class":"submenu"}) |
| 74 |
for heading in headings: |
| 75 |
li = SubElement(subul, "li", {"class":"menu item"}) |
| 76 |
try: |
| 77 |
ref = heading.getparent().getparent().get('id') |
| 78 |
except AttributeError: |
| 79 |
ref = None |
| 80 |
if ref is None: |
| 81 |
ref = '-'.join(find_words(replace_invalid(' ', heading.lower()))) |
| 82 |
a = SubElement(li, "a", href=url+'#'+ref) |
| 83 |
a.text = heading |
| 84 |
|
| 85 |
|
| 86 |
def merge_menu(tree, menu, name): |
| 87 |
menu_root = copy.deepcopy(menu) |
| 88 |
tree.getroot()[1][0].insert(0, menu_root) # html->body->div[class=document] |
| 89 |
for el in menu_root.iter(): |
| 90 |
tag = el.tag |
| 91 |
if tag[0] != '{': |
| 92 |
el.tag = "{http://www.w3.org/1999/xhtml}" + tag |
| 93 |
current_menu = find_menu( |
| 94 |
menu_root, name=replace_invalid(' ', name) + '-menu') |
| 95 |
if not current_menu: |
| 96 |
current_menu = find_menu( |
| 97 |
menu_root, name=replace_invalid('-', name) + '-menu') |
| 98 |
if current_menu: |
| 99 |
for submenu in current_menu: |
| 100 |
submenu.set("class", submenu.get("class", ""). |
| 101 |
replace("foreign", "current")) |
| 102 |
return tree |
| 103 |
|
| 104 |
|
| 105 |
def inject_flatter_button(tree): |
| 106 |
head = tree.xpath('h:head[1]', namespaces=htmlnsmap)[0] |
| 107 |
script = SubElement(head, '{%s}script' % XHTML_NS, type='text/javascript') |
| 108 |
script.text = """ |
| 109 |
(function() { |
| 110 |
var s = document.createElement('script'); |
| 111 |
var t = document.getElementsByTagName('script')[0]; |
| 112 |
s.type = 'text/javascript'; |
| 113 |
s.async = true; |
| 114 |
s.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto'; |
| 115 |
t.parentNode.insertBefore(s, t); |
| 116 |
})(); |
| 117 |
""" |
| 118 |
script.tail = '\n' |
| 119 |
intro_div = tree.xpath('h:body//h:div[@id = "introduction"][1]', namespaces=htmlnsmap)[0] |
| 120 |
intro_div.insert(-1, XML( |
| 121 |
'<p style="text-align: center;">Like working with lxml? ' |
| 122 |
'Happy about the time that it just saved you? <br />' |
| 123 |
'Show your appreciation with <a href="http://flattr.com/thing/268156/lxml-The-Python-XML-Toolkit">Flattr</a>.<br />' |
| 124 |
'<a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="https://lxml.de/"></a>' |
| 125 |
'</p>' |
| 126 |
)) |
| 127 |
|
| 128 |
|
| 129 |
def inject_donate_buttons(lxml_path, rst2html_script, tree): |
| 130 |
command = ([sys.executable, rst2html_script] |
| 131 |
+ RST2HTML_OPTIONS.split() + [os.path.join(lxml_path, 'README.rst')]) |
| 132 |
rst2html = subprocess.Popen(command, stdout=subprocess.PIPE) |
| 133 |
stdout, _ = rst2html.communicate() |
| 134 |
readme = fromstring(stdout) |
| 135 |
|
| 136 |
intro_div = tree.xpath('h:body//h:div[@id = "introduction"][1]', |
| 137 |
namespaces=htmlnsmap)[0] |
| 138 |
support_div = readme.xpath('h:body//h:div[@id = "support-the-project"][1]', |
| 139 |
namespaces=htmlnsmap)[0] |
| 140 |
intro_div.append(support_div) |
| 141 |
|
| 142 |
finance_div = readme.xpath('h:body//h:div[@id = "project-income-report"][1]', |
| 143 |
namespaces=htmlnsmap)[0] |
| 144 |
legal = readme.xpath('h:body//h:div[@id = "legal-notice-for-donations"][1]', |
| 145 |
namespaces=htmlnsmap)[0] |
| 146 |
last_div = tree.xpath('h:body//h:div//h:div', namespaces=htmlnsmap)[-1] |
| 147 |
last_div.addnext(finance_div) |
| 148 |
finance_div.addnext(legal) |
| 149 |
|
| 150 |
|
| 151 |
def inject_banner(parent): |
| 152 |
banner = parent.makeelement('div', {'class': 'banner'}) |
| 153 |
parent.insert(0, banner) |
| 154 |
|
| 155 |
banner_image = SubElement(banner, 'div', {'class': "banner_image"}) |
| 156 |
SubElement(banner_image, 'img', src="python-xml-title.png") |
| 157 |
|
| 158 |
banner_text = SubElement(banner, 'div', {'class': "banner_link"}) |
| 159 |
banner_link = SubElement(banner_text, 'a', href="index.html#support-the-project") |
| 160 |
banner_link.text = "Like the tool? " |
| 161 |
SubElement(banner_link, 'br', {'class': "first"}).tail = "Help making it better! " |
| 162 |
SubElement(banner_link, 'br', {'class': "second"}).tail = "Your donation helps!" |
| 163 |
|
| 164 |
|
| 165 |
def rest2html(script, source_path, dest_path, stylesheet_url): |
| 166 |
command = ('%s %s %s --stylesheet=%s --link-stylesheet %s > %s' % |
| 167 |
(sys.executable, script, RST2HTML_OPTIONS, |
| 168 |
stylesheet_url, source_path, dest_path)) |
| 169 |
subprocess.call(command, shell=True) |
| 170 |
|
| 171 |
|
| 172 |
def convert_changelog(lxml_path, changelog_file_path, rst2html_script, stylesheet_url): |
| 173 |
f = open_file(os.path.join(lxml_path, 'CHANGES.txt'), 'r', encoding='utf-8') |
| 174 |
try: |
| 175 |
content = f.read() |
| 176 |
finally: |
| 177 |
f.close() |
| 178 |
|
| 179 |
links = dict(LP='`%s <https://bugs.launchpad.net/lxml/+bug/%s>`_', |
| 180 |
GH='`%s <https://github.com/lxml/lxml/issues/%s>`_') |
| 181 |
replace_tracker_links = re.compile('((LP|GH)#([0-9]+))').sub |
| 182 |
def insert_link(match): |
| 183 |
text, ref_type, ref_id = match.groups() |
| 184 |
return links[ref_type] % (text, ref_id) |
| 185 |
content = replace_tracker_links(insert_link, content) |
| 186 |
|
| 187 |
command = [sys.executable, rst2html_script] + RST2HTML_OPTIONS.split() + [ |
| 188 |
'--link-stylesheet', '--stylesheet', stylesheet_url ] |
| 189 |
out_file = open(changelog_file_path, 'wb') |
| 190 |
try: |
| 191 |
rst2html = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=out_file) |
| 192 |
rst2html.communicate(content.encode('utf8')) |
| 193 |
finally: |
| 194 |
out_file.close() |
| 195 |
|
| 196 |
|
| 197 |
def publish(dirname, lxml_path, release, with_donations=True): |
| 198 |
if not os.path.exists(dirname): |
| 199 |
os.mkdir(dirname) |
| 200 |
|
| 201 |
doc_dir = os.path.join(lxml_path, 'doc') |
| 202 |
script = os.path.join(doc_dir, 'rest2html.py') |
| 203 |
pubkey = os.path.join(doc_dir, 'pubkey.asc') |
| 204 |
stylesheet_file = 'style.css' |
| 205 |
|
| 206 |
shutil.copy(pubkey, dirname) |
| 207 |
# FIXME: find a way to make hashed filenames work both locally and in the versioned directories. |
| 208 |
stylesheet_url = stylesheet_file |
| 209 |
""" |
| 210 |
style_file_pattern = "style_%s.css" |
| 211 |
for old_stylesheet in glob.iglob(os.path.join(dirname, style_file_pattern % "*")): |
| 212 |
os.unlink(old_stylesheet) |
| 213 |
with open(os.path.join(dirname, stylesheet_file), 'rb') as f: |
| 214 |
css = f.read() |
| 215 |
checksum = hashlib.sha256(css).hexdigest()[:32] |
| 216 |
|
| 217 |
stylesheet_url = style_file_pattern % checksum |
| 218 |
with open(os.path.join(dirname, stylesheet_url), 'wb') as out: |
| 219 |
out.write(css) |
| 220 |
""" |
| 221 |
|
| 222 |
href_map = HREF_MAP.copy() |
| 223 |
changelog_basename = 'changes-%s' % release |
| 224 |
href_map['Release Changelog'] = changelog_basename + '.html' |
| 225 |
|
| 226 |
menu_js = textwrap.dedent(''' |
| 227 |
function trigger_menu(event) { |
| 228 |
var sidemenu = document.getElementById("sidemenu"); |
| 229 |
var classes = sidemenu.getAttribute("class"); |
| 230 |
classes = (classes.indexOf(" visible") === -1) ? classes + " visible" : classes.replace(" visible", ""); |
| 231 |
sidemenu.setAttribute("class", classes); |
| 232 |
event.preventDefault(); |
| 233 |
event.stopPropagation(); |
| 234 |
} |
| 235 |
function hide_menu() { |
| 236 |
var sidemenu = document.getElementById("sidemenu"); |
| 237 |
var classes = sidemenu.getAttribute("class"); |
| 238 |
if (classes.indexOf(" visible") !== -1) { |
| 239 |
sidemenu.setAttribute("class", classes.replace(" visible", "")); |
| 240 |
} |
| 241 |
} |
| 242 |
''') |
| 243 |
|
| 244 |
trees = {} |
| 245 |
menu = Element("div", {'class': 'sidemenu', 'id': 'sidemenu'}) |
| 246 |
SubElement(menu, 'div', {'class': 'menutrigger', 'onclick': 'trigger_menu(event)'}).text = "Menu" |
| 247 |
menu_div = SubElement(menu, 'div', {'class': 'menu'}) |
| 248 |
if with_donations: |
| 249 |
inject_banner(menu_div) |
| 250 |
|
| 251 |
# build HTML pages and parse them back |
| 252 |
for section, text_files in SITE_STRUCTURE: |
| 253 |
section_head = make_menu_section_head(section, menu_div) |
| 254 |
for filename in text_files: |
| 255 |
if filename.startswith('@'): |
| 256 |
# special menu entry |
| 257 |
page_title = filename[1:] |
| 258 |
url = href_map[page_title] |
| 259 |
build_menu_entry(page_title, url, section_head) |
| 260 |
else: |
| 261 |
path = os.path.join(doc_dir, filename) |
| 262 |
basename = os.path.splitext(os.path.basename(filename))[0] |
| 263 |
basename = BASENAME_MAP.get(basename, basename) |
| 264 |
outname = basename + '.html' |
| 265 |
outpath = os.path.join(dirname, outname) |
| 266 |
|
| 267 |
rest2html(script, path, outpath, stylesheet_url) |
| 268 |
tree = parse(outpath) |
| 269 |
|
| 270 |
if with_donations: |
| 271 |
page_div = tree.getroot()[1][0] # html->body->div[class=document] |
| 272 |
inject_banner(page_div) |
| 273 |
|
| 274 |
if filename == 'main.txt': |
| 275 |
# inject donation buttons |
| 276 |
#inject_flatter_button(tree) |
| 277 |
inject_donate_buttons(lxml_path, script, tree) |
| 278 |
|
| 279 |
trees[filename] = (tree, basename, outpath) |
| 280 |
build_menu(tree, basename, section_head) |
| 281 |
|
| 282 |
# also convert CHANGES.txt |
| 283 |
changelog_path = os.path.join(dirname, f'changes-{release}.html') |
| 284 |
convert_changelog(lxml_path, changelog_path, script, stylesheet_url) |
| 285 |
trees[f'changelog'] = (parse(changelog_path), 'changelog', changelog_path) |
| 286 |
|
| 287 |
# generate sitemap from menu |
| 288 |
sitemap = XML(textwrap.dedent('''\ |
| 289 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| 290 |
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> |
| 291 |
<head> |
| 292 |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> |
| 293 |
<title>Sitemap of lxml.de - Processing XML and HTML with Python</title> |
| 294 |
<meta content="lxml - the most feature-rich and easy-to-use library for processing XML and HTML in the Python language" |
| 295 |
name="description" /> |
| 296 |
<meta content="Python XML, XML, XML processing, HTML, lxml, simple XML, ElementTree, etree, lxml.etree, objectify, XML parsing, XML validation, XPath, XSLT" |
| 297 |
name="keywords" /> |
| 298 |
</head> |
| 299 |
<body> |
| 300 |
<h1>Sitemap of lxml.de - Processing XML and HTML with Python</h1> |
| 301 |
</body> |
| 302 |
</html> |
| 303 |
''')) |
| 304 |
sitemap_menu = copy.deepcopy(menu) |
| 305 |
SubElement(SubElement(sitemap_menu[-1], 'li'), 'a', href='https://lxml.de/files/').text = 'Download files' |
| 306 |
sitemap[-1].append(sitemap_menu) # append to body |
| 307 |
ElementTree(sitemap).write(os.path.join(dirname, 'sitemap.html')) |
| 308 |
|
| 309 |
# integrate sitemap into the menu |
| 310 |
SubElement(SubElement(menu_div[-1], 'li'), 'a', href='/sitemap.html').text = 'Sitemap' |
| 311 |
|
| 312 |
# integrate menu into web pages |
| 313 |
for tree, basename, outpath in trees.values(): |
| 314 |
head = find_head(tree)[0] |
| 315 |
SubElement(head, 'script', type='text/javascript').text = menu_js |
| 316 |
SubElement(head, 'meta', name='viewport', content="width=device-width, initial-scale=1") |
| 317 |
find_body(tree)[0].set('onclick', 'hide_menu()') |
| 318 |
|
| 319 |
new_tree = merge_menu(tree, menu, basename) |
| 320 |
title = find_title_tag(new_tree) |
| 321 |
if title and title[0].text == 'lxml': |
| 322 |
title[0].text = "lxml - Processing XML and HTML with Python" |
| 323 |
heading = find_heading_tag(new_tree) |
| 324 |
if heading: |
| 325 |
heading[0].text = "lxml - XML and HTML with Python" |
| 326 |
new_tree.write(outpath) |
| 327 |
|
| 328 |
|
| 329 |
if __name__ == '__main__': |
| 330 |
no_donations = '--no-donations' in sys.argv[1:] |
| 331 |
if no_donations: |
| 332 |
sys.argv.remove('--no-donations') |
| 333 |
publish(sys.argv[1], sys.argv[2], sys.argv[3], with_donations=not no_donations) |