My static website generator using poole https://www.xythobuz.de
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

poole.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # =============================================================================
  4. #
  5. # Poole - A damn simple static website generator.
  6. # Copyright (C) 2012 Oben Sonne <obensonne@googlemail.com>
  7. #
  8. # This file is part of Poole.
  9. #
  10. # Poole is free software: you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation, either version 3 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # Poole is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License
  21. # along with Poole. If not, see <http://www.gnu.org/licenses/>.
  22. #
  23. # =============================================================================
  24. from __future__ import with_statement
  25. from __future__ import print_function
  26. import codecs
  27. import glob
  28. import optparse
  29. import os
  30. from os.path import join as opj
  31. from os.path import exists as opx
  32. import re
  33. import shutil
  34. import sys
  35. import traceback
  36. try:
  37. import markdown
  38. except ImportError:
  39. print("abort : need python-markdown, get it from "
  40. "http://www.freewisdom.org/projects/python-markdown/Installation")
  41. sys.exit(1)
  42. # =============================================================================
  43. # Python 2/3 hacks
  44. # =============================================================================
  45. PY3 = sys.version_info[0] == 3
  46. if PY3:
  47. import builtins
  48. exec_ = getattr(builtins, "exec")
  49. import importlib.util
  50. import importlib.machinery
  51. def imp_load_source(modname, filename):
  52. loader = importlib.machinery.SourceFileLoader(modname, filename)
  53. spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
  54. module = importlib.util.module_from_spec(spec)
  55. # The module is always executed and not cached in sys.modules.
  56. # Uncomment the following line to cache the module.
  57. # sys.modules[module.__name__] = module
  58. loader.exec_module(module)
  59. return module
  60. import urllib
  61. def urlparse_urljoin(a, b):
  62. return urllib.parse.urljoin(a, b)
  63. from io import StringIO
  64. from http.server import HTTPServer, SimpleHTTPRequestHandler
  65. else:
  66. import tempfile
  67. from StringIO import StringIO
  68. from SimpleHTTPServer import SimpleHTTPRequestHandler
  69. from BaseHTTPServer import HTTPServer
  70. def exec_(code, envdic):
  71. with tempfile.NamedTemporaryFile() as tf:
  72. tf.write('# -*- coding: utf-8 -*-\n')
  73. tf.write(code.encode('utf-8'))
  74. tf.flush()
  75. execfile(tf.name, envdic)
  76. import imp
  77. def imp_load_source(module_name, module_path):
  78. return imp.load_source(module_name, module_path)
  79. import urlparse
  80. def urlparse_urljoin(a, b):
  81. return urlparse.urljoin(a, b)
  82. # =============================================================================
  83. # init site
  84. # =============================================================================
  85. EXAMPLE_FILES = {
  86. "page.html": """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  87. <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  88. <head>
  89. <meta http-equiv="Content-Type" content="text/html; charset={{ htmlspecialchars(__encoding__) }}" />
  90. <title>poole - {{ htmlspecialchars(page["title"]) }}</title>
  91. <meta name="description" content="{{ htmlspecialchars(page.get("description", "a poole site")) }}" />
  92. <meta name="keywords" content="{{ htmlspecialchars(page.get("keywords", "poole")) }}" />
  93. <link rel="stylesheet" type="text/css" href="poole.css" />
  94. </head>
  95. <body>
  96. <div id="box">
  97. <div id="header">
  98. <h1>a poole site</h1>
  99. <h2>{{ htmlspecialchars(page["title"]) }}</h2>
  100. </div>
  101. <div id="menu">
  102. <!--%
  103. mpages = [p for p in pages if "menu-position" in p]
  104. mpages.sort(key=lambda p: int(p["menu-position"]))
  105. entry = '<span class="%s"><a href="%s">%s</a></span>'
  106. for p in mpages:
  107. style = p["title"] == page["title"] and "current" or ""
  108. print(entry % (style, htmlspecialchars(p["url"]), htmlspecialchars(p["title"])))
  109. %-->
  110. </div>
  111. <div id="content">{{ __content__ }}</div>
  112. </div>
  113. <div id="footer">
  114. Built with <a href="http://bitbucket.org/obensonne/poole">Poole</a>
  115. &middot;
  116. Licensed as <a href="http://creativecommons.org/licenses/by-sa/3.0">CC-SA</a>
  117. &middot;
  118. <a href="http://validator.w3.org/check?uri=referer">Validate me</a>
  119. </div>
  120. </body>
  121. </html>
  122. """,
  123. # -----------------------------------------------------------------------------
  124. opj("input", "index.md"): """
  125. title: home
  126. menu-position: 0
  127. ---
  128. ## Welcome to Poole
  129. In Poole you write your pages in [markdown][md]. It's easier to write
  130. markdown than HTML.
  131. Poole is made for simple websites you just want to get done, without installing
  132. a bunch of requirements and without learning a template engine.
  133. In a build, Poole copies every file from the *input* directory to the *output*
  134. directory. During that process every markdown file (ending with *md*, *mkd*,
  135. *mdown* or *markdown*) is converted to HTML using the project's `page.html`
  136. as a skeleton.
  137. [md]: http://daringfireball.net/projects/markdown/
  138. """,
  139. # -----------------------------------------------------------------------------
  140. opj("input", "logic.md"): """
  141. menu-position: 4
  142. ---
  143. Poole has basic support for content generation using Python code inlined in
  144. page files. This is everything but a clear separation of logic and content but
  145. for simple sites this is just a pragmatic way to get things done fast.
  146. For instance the menu on this page is generated by some inlined Python code in
  147. the project's `page.html` file.
  148. Just ignore this feature if you don't need it :)
  149. Content generation by inlined Python code is good to add some zest to your
  150. site. If you use it a lot, you better go with more sophisticated site
  151. generators like [Hyde](http://ringce.com/hyde).
  152. """,
  153. # -----------------------------------------------------------------------------
  154. opj("input", "layout.md"): """
  155. menu-position: 3
  156. ---
  157. Every page of a poole site is based on *one global template file*, `page.html`.
  158. All you need to adjust the site layout is to
  159. * edit the page template `page.html` and
  160. * extend or edit the style file `input/poole.css`.
  161. """,
  162. opj("input", "blog.md"): """
  163. menu-position: 10
  164. ---
  165. Poole has basic blog support. If an input page's file name has a structure like
  166. `page-title.YYYY-MM-DD.post-title.md`, e.g. `blog.2010-02-27.read_this.md`,
  167. Poole recognizes the date and post title and sets them as attributes of the
  168. page. These attributes can then be used to generate a list of blog posts:
  169. <!--%
  170. from datetime import datetime
  171. posts = [p for p in pages if "post" in p] # get all blog post pages
  172. posts.sort(key=lambda p: p.get("date"), reverse=True) # sort post pages by date
  173. for p in posts:
  174. date = datetime.strptime(p.date, "%Y-%m-%d").strftime("%B %d, %Y")
  175. print " * **[%s](%s)** - %s" % (p.post, p.url, date) # markdown list item
  176. %-->
  177. Have a look into `input/blog.md` to see how it works. Feel free to adjust it
  178. to your needs.
  179. """,
  180. # -----------------------------------------------------------------------------
  181. opj("input", "blog.2010-02-22.Doctors_in_my_penguin.md") : """
  182. ---
  183. ## {{ page["post"] }}
  184. *Posted at
  185. <!--%
  186. from datetime import datetime
  187. print datetime.strptime(page["date"], "%Y-%m-%d").strftime("%B %d, %Y")
  188. %-->*
  189. There is a bank in my eel, your argument is invalid.
  190. More nonsense at <http://automeme.net/>.
  191. """,
  192. # -----------------------------------------------------------------------------
  193. opj("input", "blog.2010-03-01.I_ate_all the pokemans.md"): """
  194. ## {{ page["post"] }}
  195. *Posted at <!--{ page["date"] }-->.*
  196. What *are* interior crocodile alligators? We just don't know.
  197. More nonsense at <http://automeme.net/>.
  198. """,
  199. # -----------------------------------------------------------------------------
  200. opj("input", "poole.css"): """
  201. body {
  202. font-family: sans;
  203. width: 800px;
  204. margin: 1em auto;
  205. color: #2e3436;
  206. }
  207. div#box {
  208. border: solid #2e3436 1px;
  209. }
  210. div#header, div#menu, div#content, div#footer {
  211. padding: 1em;
  212. }
  213. div#menu {
  214. background-color: #2e3436;
  215. padding: 0.6em 0 0.6em 0;
  216. }
  217. #menu span {
  218. background-color: #2e3436;
  219. font-weight: bold;
  220. padding: 0.6em;
  221. }
  222. #menu span.current {
  223. background-color: #555753;
  224. }
  225. #menu a {
  226. color: #fefefc;
  227. text-decoration: none;
  228. }
  229. div#footer {
  230. color: gray;
  231. text-align: center;
  232. font-size: small;
  233. }
  234. div#footer a {
  235. color: gray;
  236. text-decoration: none;
  237. }
  238. pre {
  239. border: dotted black 1px;
  240. background: #eeeeec;
  241. font-size: small;
  242. padding: 1em;
  243. }
  244. """
  245. }
  246. def init(project):
  247. """Initialize a site project."""
  248. if not opx(project):
  249. os.makedirs(project)
  250. if os.listdir(project):
  251. print("abort : project dir %s is not empty" % project)
  252. sys.exit(1)
  253. os.mkdir(opj(project, "input"))
  254. os.mkdir(opj(project, "output"))
  255. for fname, content in EXAMPLE_FILES.items():
  256. with open(opj(project, fname), 'w') as fp:
  257. fp.write(content)
  258. print("success: initialized project")
  259. # =============================================================================
  260. # build site
  261. # =============================================================================
  262. MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
  263. class Page(dict):
  264. """Abstraction of a source page."""
  265. _template = None # template dictionary
  266. _opts = None # command line options
  267. _pstrip = None # path prefix to strip from (non-virtual) page file names
  268. _re_eom = re.compile(r'^---+ *\r?\n?$')
  269. _re_vardef = re.compile(r'^([^\n:=]+?)[:=]((?:.|\n )*)', re.MULTILINE)
  270. _sec_macros = "macros"
  271. _modmacs = None
  272. def __init__(self, fname, virtual=None, **attrs):
  273. """Create a new page.
  274. Page content is read from `fname`, except when `virtual` is given (a
  275. string representing the raw content of a virtual page).
  276. The filename refers to the page source file. For virtual pages, this
  277. *must* be relative to a projects input directory.
  278. Virtual pages may contain page attribute definitions similar to real
  279. pages. However, it probably is easier to provide the attributes
  280. directly. This may be done using arbitrary keyword arguments.
  281. """
  282. super(Page, self).__init__()
  283. self.update(self._template)
  284. self.update(attrs)
  285. self._virtual = virtual is not None
  286. fname = opj(self._pstrip, fname) if virtual else fname
  287. self["fname"] = fname
  288. self["url"] = re.sub(MKD_PATT, ".html", fname)
  289. self["url"] = self["url"][len(self._pstrip):].lstrip(os.path.sep)
  290. self["url"] = self["url"].replace(os.path.sep, "/")
  291. if virtual:
  292. self.raw = virtual
  293. else:
  294. with codecs.open(fname, 'r', self._opts.input_enc) as fp:
  295. self.raw = fp.readlines()
  296. # split raw content into macro definitions and real content
  297. vardefs = ""
  298. self.source = ""
  299. for line in self.raw:
  300. if not vardefs and self._re_eom.match(line):
  301. vardefs = self.source
  302. self.source = "" # only macro defs until here, reset source
  303. else:
  304. self.source += line
  305. for key, val in self._re_vardef.findall(vardefs):
  306. key = key.strip()
  307. val = val.strip()
  308. val = re.sub(r' *\n +', ' ', val) # clean out line continuation
  309. self[key] = val
  310. basename = os.path.basename(fname)
  311. fpatt = r'(.+?)(?:\.([0-9]+-[0-9]+-[0-9]+)(?:\.(.*))?)?%s' % MKD_PATT
  312. title, date, post = re.match(fpatt, basename).groups()
  313. title = title.replace("_", " ")
  314. post = post and post.replace("_", " ") or None
  315. self["title"] = self.get("title", title)
  316. if date and "date" not in self: self["date"] = date
  317. if post and "post" not in self: self["post"] = post
  318. self.html = ""
  319. def __getattr__(self, name):
  320. """Attribute-style access to dictionary items."""
  321. try:
  322. return self[name]
  323. except KeyError:
  324. raise AttributeError(name)
  325. def __str__(self):
  326. """Page representation by file name."""
  327. return ('%s (virtual)' % self.fname) if self._virtual else self.fname
  328. # -----------------------------------------------------------------------------
  329. def build(project, opts):
  330. """Build a site project."""
  331. # -------------------------------------------------------------------------
  332. # utilities
  333. # -------------------------------------------------------------------------
  334. def abort_iex(page, itype, inline, exc):
  335. """Abort because of an exception in inlined Python code."""
  336. print("abort : Python %s in %s failed" % (itype, page))
  337. print((" %s raising the exception " % itype).center(79, "-"))
  338. print(inline.encode('utf-8'))
  339. print(" exception ".center(79, "-"))
  340. print(exc)
  341. sys.exit(1)
  342. # -------------------------------------------------------------------------
  343. # regex patterns and replacements
  344. # -------------------------------------------------------------------------
  345. regx_escp = re.compile(r'\\((?:(?:&lt;|<)!--|{)(?:{|%))') # escaped code
  346. repl_escp = r'\1'
  347. regx_rurl = re.compile(r'(?<=(?:(?:\n| )src|href)=")([^#/&%].*?)(?=")')
  348. repl_rurl = lambda m: urlparse_urljoin(opts.base_url, m.group(1))
  349. regx_eval = re.compile(r'(?<!\\)(?:(?:<!--|{){)(.*?)(?:}(?:-->|}))', re.S)
  350. def repl_eval(m):
  351. """Replace a Python expression block by its evaluation."""
  352. expr = m.group(1)
  353. try:
  354. repl = eval(expr, macros.copy())
  355. except:
  356. abort_iex(page, "expression", expr, traceback.format_exc())
  357. else:
  358. if PY3:
  359. if not isinstance(repl, str):
  360. repl = str(repl)
  361. else:
  362. if not isinstance(repl, basestring): # e.g. numbers
  363. repl = unicode(repl)
  364. elif not isinstance(repl, unicode):
  365. repl = repl.decode("utf-8")
  366. return repl
  367. regx_exec = re.compile(r'(?<!\\)(?:(?:<!--|{)%)(.*?)(?:%(?:-->|}))', re.S)
  368. def repl_exec(m):
  369. """Replace a block of Python statements by their standard output."""
  370. stmt = m.group(1).replace("\r\n", "\n")
  371. # base indentation
  372. ind_lvl = len(re.findall(r'^(?: *\n)*( *)', stmt, re.MULTILINE)[0])
  373. ind_rex = re.compile(r'^ {0,%d}' % ind_lvl, re.MULTILINE)
  374. stmt = ind_rex.sub('', stmt)
  375. # execute
  376. sys.stdout = StringIO()
  377. try:
  378. exec_(stmt, macros.copy())
  379. except:
  380. sys.stdout = sys.__stdout__
  381. abort_iex(page, "statements", stmt, traceback.format_exc())
  382. else:
  383. repl = sys.stdout.getvalue()[:-1] # remove last line break
  384. sys.stdout = sys.__stdout__
  385. if not PY3:
  386. if not isinstance(repl, unicode):
  387. repl = repl.decode(opts.input_enc)
  388. return repl
  389. # -------------------------------------------------------------------------
  390. # preparations
  391. # -------------------------------------------------------------------------
  392. dir_in = opj(project, "input")
  393. dir_out = opj(project, "output")
  394. page_html = opj(project, "page.html")
  395. # check required files and folders
  396. for pelem in (page_html, dir_in, dir_out):
  397. if not opx(pelem):
  398. print("abort : %s does not exist, looks like project has not been "
  399. "initialized" % pelem)
  400. sys.exit(1)
  401. # prepare output directory
  402. for fod in glob.glob(opj(dir_out, "*")):
  403. if os.path.isdir(fod):
  404. shutil.rmtree(fod)
  405. else:
  406. os.remove(fod)
  407. if not opx(dir_out):
  408. os.mkdir(dir_out)
  409. # macro module
  410. fname = opj(opts.project, "macros.py")
  411. macros = imp_load_source("macros", fname).__dict__ if opx(fname) else {}
  412. macros["__encoding__"] = opts.output_enc
  413. macros["options"] = opts
  414. macros["project"] = project
  415. macros["input"] = dir_in
  416. macros["output"] = dir_out
  417. # "builtin" functions for use in macros and templates
  418. macros["htmlspecialchars"] = htmlspecialchars
  419. macros["Page"] = Page
  420. # -------------------------------------------------------------------------
  421. # process input files
  422. # -------------------------------------------------------------------------
  423. Page._template = macros.get("page", {})
  424. Page._opts = opts
  425. Page._pstrip = dir_in
  426. pages = []
  427. custom_converter = macros.get('converter', {})
  428. for cwd, dirs, files in os.walk(dir_in if PY3 else dir_in.decode(opts.filename_enc)):
  429. cwd_site = cwd[len(dir_in):].lstrip(os.path.sep)
  430. for sdir in dirs[:]:
  431. if re.search(opts.ignore, opj(cwd_site, sdir)):
  432. dirs.remove(sdir)
  433. else:
  434. os.mkdir(opj(dir_out, cwd_site, sdir))
  435. for f in files:
  436. if re.search(opts.ignore, opj(cwd_site, f)):
  437. pass
  438. elif re.search(MKD_PATT, f):
  439. page = Page(opj(cwd, f))
  440. pages.append(page)
  441. foo = opj(cwd, f)
  442. bar = opj(dir_out, f)
  443. print('info : copy %s' % bar)
  444. shutil.copyfile(foo, bar)
  445. else:
  446. # either use a custom converter or do a plain copy
  447. for patt, (func, ext) in custom_converter.items():
  448. if re.search(patt, f):
  449. f_src = opj(cwd, f)
  450. f_dst = opj(dir_out, cwd_site, f)
  451. f_dst = '%s.%s' % (os.path.splitext(f_dst)[0], ext)
  452. print('info : convert %s (%s)' % (f_src, func.__name__))
  453. func(f_src, f_dst)
  454. break
  455. else:
  456. src = opj(cwd, f)
  457. try:
  458. shutil.copy(src, opj(dir_out, cwd_site))
  459. except OSError:
  460. # some filesystems like FAT won't allow shutil.copy
  461. shutil.copyfile(src, opj(dir_out, cwd_site, f))
  462. pages.sort(key=lambda p: int(p.get("sval", "0")))
  463. macros["pages"] = pages
  464. # -------------------------------------------------------------------------
  465. # run pre-convert hooks in macro module (named 'once' before)
  466. # -------------------------------------------------------------------------
  467. hooks = [a for a in macros if re.match(r'hook_preconvert_|once_', a)]
  468. for fn in sorted(hooks):
  469. macros[fn]()
  470. # -------------------------------------------------------------------------
  471. # convert pages (markdown to HTML)
  472. # -------------------------------------------------------------------------
  473. for page in pages:
  474. print("info : convert %s" % page)
  475. # replace expressions and statements in page source
  476. macros["page"] = page
  477. out = regx_eval.sub(repl_eval, page.source)
  478. out = regx_exec.sub(repl_exec, out)
  479. # convert to HTML
  480. page.html = markdown.Markdown(extensions=opts.md_ext).convert(out)
  481. # -------------------------------------------------------------------------
  482. # run post-convert hooks in macro module
  483. # -------------------------------------------------------------------------
  484. hooks = [a for a in macros if a.startswith("hook_postconvert_")]
  485. for fn in sorted(hooks):
  486. macros[fn]()
  487. # -------------------------------------------------------------------------
  488. # render complete HTML pages
  489. # -------------------------------------------------------------------------
  490. with codecs.open(opj(project, "page.html"), 'r', opts.input_enc) as fp:
  491. skeleton = fp.read()
  492. for page in pages:
  493. print("info : render %s" % page.url)
  494. # replace expressions and statements in page.html
  495. macros["page"] = page
  496. macros["__content__"] = page.html
  497. out = regx_eval.sub(repl_eval, skeleton)
  498. out = regx_exec.sub(repl_exec, out)
  499. # un-escape escaped python code blocks
  500. out = regx_escp.sub(repl_escp, out)
  501. # make relative links absolute
  502. out = regx_rurl.sub(repl_rurl, out)
  503. # write HTML page
  504. fname = page.fname.replace(dir_in, dir_out)
  505. fname = re.sub(MKD_PATT, ".html", fname)
  506. with codecs.open(fname, 'w', opts.output_enc) as fp:
  507. fp.write(out)
  508. # -------------------------------------------------------------------------
  509. # remove empty subfolders
  510. # -------------------------------------------------------------------------
  511. removeEmptyFolders(dir_out)
  512. print("success: built project")
  513. def removeEmptyFolders(path):
  514. # remove empty subfolders
  515. files = os.listdir(path)
  516. if len(files):
  517. for f in files:
  518. fullpath = os.path.join(path, f)
  519. if os.path.isdir(fullpath):
  520. removeEmptyFolders(fullpath)
  521. # Dirty OS X Hack
  522. try:
  523. os.remove(os.path.join(path, ".DS_Store"))
  524. except OSError as ex:
  525. pass
  526. # if folder empty, delete it
  527. files = os.listdir(path)
  528. if len(files) == 0:
  529. print("info : removing empty folder: ", path)
  530. os.rmdir(path)
  531. # =============================================================================
  532. # serve site
  533. # =============================================================================
  534. def serve(project, port):
  535. """Temporary serve a site project."""
  536. root = opj(project, "output")
  537. if not os.listdir(project):
  538. print("abort : output dir is empty (build project first!)")
  539. sys.exit(1)
  540. os.chdir(root)
  541. server = HTTPServer(('', port), SimpleHTTPRequestHandler)
  542. server.serve_forever()
  543. # =============================================================================
  544. # options
  545. # =============================================================================
  546. def options():
  547. """Parse and validate command line arguments."""
  548. usage = ("Usage: %prog --init [path/to/project]\n"
  549. " %prog --build [OPTIONS] [path/to/project]\n"
  550. " %prog --serve [OPTIONS] [path/to/project]\n"
  551. "\n"
  552. " Project path is optional, '.' is used as default.")
  553. op = optparse.OptionParser(usage=usage)
  554. op.add_option("-i" , "--init", action="store_true", default=False,
  555. help="init project")
  556. op.add_option("-b" , "--build", action="store_true", default=False,
  557. help="build project")
  558. op.add_option("-s" , "--serve", action="store_true", default=False,
  559. help="serve project")
  560. og = optparse.OptionGroup(op, "Build options")
  561. og.add_option("", "--base-url", default="/", metavar="URL",
  562. help="base url for relative links (default: /)")
  563. og.add_option("" , "--ignore", default=r"^\.|~$", metavar="REGEX",
  564. help="input files to ignore (default: '^\\.|~$')")
  565. og.add_option("" , "--md-ext", default=[], metavar="EXT",
  566. action="append", help="enable a markdown extension")
  567. og.add_option("", "--input-enc", default="utf-8", metavar="ENC",
  568. help="encoding of input pages (default: utf-8)")
  569. og.add_option("", "--output-enc", default="utf-8", metavar="ENC",
  570. help="encoding of output pages (default: utf-8)")
  571. og.add_option("", "--filename-enc", default="utf-8", metavar="ENC",
  572. help="encoding of file names (default: utf-8)")
  573. op.add_option_group(og)
  574. og = optparse.OptionGroup(op, "Serve options")
  575. og.add_option("" , "--port", default=8080,
  576. metavar="PORT", type="int",
  577. help="port for serving (default: 8080)")
  578. op.add_option_group(og)
  579. opts, args = op.parse_args()
  580. if opts.init + opts.build + opts.serve < 1:
  581. op.print_help()
  582. op.exit()
  583. opts.project = args and args[0] or "."
  584. return opts
  585. # =============================================================================
  586. # template helper functions
  587. # =============================================================================
  588. def htmlspecialchars(s):
  589. """
  590. Replace the characters that are special within HTML (&, <, > and ")
  591. with their equivalent character entity (e.g., &amp;). This should be
  592. called whenever an arbitrary string is inserted into HTML (so in most
  593. places where you use {{ variable }} in your templates).
  594. Note that " is not special in most HTML, only within attributes.
  595. However, since escaping it does not hurt within normal HTML, it is
  596. just escaped unconditionally.
  597. """
  598. escape = {
  599. "&": "&amp;",
  600. '"': "&quot;",
  601. ">": "&gt;",
  602. "<": "&lt;",
  603. }
  604. # Look up the translation for every character in s (defaulting to
  605. # the character itself if no translation is available).
  606. return ''.join([escape.get(c,c) for c in s])
  607. # =============================================================================
  608. # main
  609. # =============================================================================
  610. def main():
  611. opts = options()
  612. if opts.init:
  613. init(opts.project)
  614. if opts.build:
  615. build(opts.project, opts)
  616. if opts.serve:
  617. serve(opts.project, opts.port)
  618. if __name__ == '__main__':
  619. main()