#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # Converts from the source markup format to HTML for the web version. import sys reload(sys) sys.setdefaultencoding('utf8') import glob import os import re import subprocess import sys import time from datetime import datetime import markdown import smartypants # Assumes cwd is root project dir. GREEN = '\033[32m' RED = '\033[31m' DEFAULT = '\033[0m' PINK = '\033[91m' YELLOW = '\033[33m' CHAPTERS = [ "致谢", "序", "架构,性能和游戏", "重访设计模式", "命令模式", "享元模式", "观察者模式", "原型模式", "单例模式", "状态模式", "序列模式", "双缓冲模式", "游戏循环", "更新方法", "行为模式", "字节码", "子类沙箱", "类型对象", "解耦模式", "组件模式", "事件队列", "服务定位器", "优化模式", "数据局部性", "脏标识模式", "对象池模式", "空间分区" ] CHAPTERS_HTML = [ "Acknowledgements", "Introduction", "Architecture, Performance, and Games", "Design Patterns Revisited", "Command", "Flyweight", "Observer", "Prototype", "Singleton", "State", "Sequencing Patterns", "Double Buffer", "Game Loop", "Update Method", "Behavioral Patterns", "Bytecode", "Subclass Sandbox", "Type Object", "Decoupling Patterns", "Component", "Event Queue", "Service Locator", "Optimization Patterns", "Data Locality", "Dirty Flag", "Object Pool", "Spatial Partition" ] # URLs for hyperlinks to chapters. Note that the order is significant here. # The index in this list + 1 is the chapter's number in the table of contents. CHAPTER_HREFS = [ "acknowledgements.html", "introduction.html", "architecture-performance-and-games.html", "command.html", "flyweight.html", "observer.html", "prototype.html", "singleton.html", "state.html", "double-buffer.html", "game-loop.html", "update-method.html", "bytecode.html", "subclass-sandbox.html", "type-object.html", "component.html", "event-queue.html", "service-locator.html", "data-locality.html", "dirty-flag.html", "object-pool.html", "spatial-partition.html" ] num_chapters = 0 empty_chapters = 0 total_words = 0 extension = "html" def output_path(pattern): return extension + "/" + pattern + "." + extension def cpp_path(pattern): return 'code/cpp/' + pattern + '.h' def pretty(text): '''Use nicer HTML entities and special characters.''' text = text.replace(" -- ", " — ") text = text.replace("à", "à") text = text.replace("ï", "ï") text = text.replace("ø", "ø") text = text.replace("æ", "æ") return text def format_file(path, nav, skip_up_to_date): basename = os.path.basename(path) basename = basename.split('.')[0] # See if the HTML is up to date. sourcemod = os.path.getmtime(path) sourcemod = max(sourcemod, os.path.getmtime('asset/template.html')) if os.path.exists(cpp_path(basename)): sourcemod = max(sourcemod, os.path.getmtime(cpp_path(basename))) destmod = 0 if os.path.exists(output_path(basename)): destmod = max(destmod, os.path.getmtime(output_path(basename))) if skip_up_to_date and sourcemod < destmod: return title = '' title_html = '' section = '' isoutline = False navigation = [] # Read the markdown file and preprocess it. contents = '' with open(path, 'r') as input: # Read each line, preprocessing the special codes. for line in input: stripped = line.lstrip() indentation = line[:len(line) - len(stripped)] if stripped.startswith('^'): command,_,args = stripped.rstrip('\n').lstrip('^').partition(' ') args = args.strip() if command == 'title': title = args title_html = title # Remove any discretionary hyphens from the title. title = title.replace('', '') elif command == 'section': section = args elif command == 'code': contents = contents + include_code(basename, args, indentation) elif command == 'outline': isoutline = True else: print "UNKNOWN COMMAND:", command, args elif extension != "xml" and stripped.startswith('#'): # Build the page navigation from the headers. index = stripped.find(" ") headertype = stripped[:index] header = pretty(stripped[index:].strip()) anchor = header.lower().replace(' ', '-') anchor = anchor.translate(None, '.?!:/"') # Add an anchor to the header. contents += indentation + headertype contents += '' + header + '\n' # Build the navigation. if len(headertype) == 2: navigation.append((len(headertype), header, anchor)) else: contents += pretty(line) modified = datetime.fromtimestamp(os.path.getmtime(path)) mod_str = modified.strftime('%B %d, %Y') with open("asset/template." + extension) as f: template = f.read() # Write the output. with open(output_path(basename), 'w') as out: title_text = title section_header = "" if section != "": title_text = title + " · " + section section_href = section.lower().replace(" ", "-") section_header = '{}'.format( section_href, section) prev_link, next_link = make_prev_next(title) contents = contents.replace('
", "\n") html = html.replace("", "\n") html = html.replace("", "\n") html = html.replace("", "\n") html = html.replace("", "\n") html = html.replace("", "\n") html = html.replace("", "\n") html = html.replace("", "\n") html = html.replace("", "\n") # TODO: Non-breaking spaces in... sections.
return html
result = ""
for chunk in chunks:
if chunk == "":
in_code = True
result += chunk
elif chunk == "":
in_code = False
result += chunk
else:
if in_code:
result += clean_up_code_xml(chunk)
else:
result += clean_up_xhtml(chunk)
return result
def title_to_file(title):
"""Given a title like "Event Queue", converts it to the corresponding file
name like "event-queue"."""
return (title.lower()
.replace(" ", "-")
.replace(",", ""))
def make_prev_next(title):
"""Generate the links that thread through the chapters."""
chapter_index = CHAPTERS.index(title)
prev_link = ""
next_link = ""
if chapter_index > 0:
prev_href = title_to_file(CHAPTERS_HTML[chapter_index - 1])
prev_link = '← 上一章'.format(
prev_href, CHAPTERS_HTML[chapter_index - 1])
if chapter_index < len(CHAPTERS_HTML) - 1:
next_href = title_to_file(CHAPTERS_HTML[chapter_index + 1])
next_link = '下一章 →'.format(
next_href, CHAPTERS_HTML[chapter_index + 1])
return (prev_link, next_link)
def navigation_to_html(chapter, headers):
nav = ''
# Section headers start two levels deep.
currentdepth = 1
for depth, header, anchor in headers:
if currentdepth == depth:
nav += '