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

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