My static website generator using poole https://www.xythobuz.de
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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