Commits

Fredrik Håård  committed 798bd19

Apparantly had forgotten to add the code to the repo...

  • Participants
  • Parent commits 225dff5

Comments (0)

Files changed (1)

+# -*- encoding: utf-8 -*-
+from string import Template
+from datetime import datetime
+import os, os.path, sys, shutil, re
+from docutils.core import publish_parts
+from hgapi import hgapi
+
+CSS_NAME = "blaag.css"
+CSS_URL = '/blaag.css'
+CSS_PATH = 'css'
+ENTRIES_PATH = 'entries'
+HTML_PATH = 'html'
+BASE = '/'
+TITLE = u'Fredrik Håård\'s Blaag'
+DISQUS_NAME = 'devrantblaag'
+
+defaults = {'disqus_name': DISQUS_NAME, 
+            'css': CSS_URL, 
+            'page_title': TITLE,
+            'blaag_title': TITLE}
+
+page_tpl = Template(open("templates/pagetemplate.html").read().decode("utf-8"))
+blaag_tpl = Template(open("templates/blaag_template.html").read().decode("utf-8"))
+comments_full_tpl = Template(open("templates/comments_full.html").read().decode("utf-8"))
+comments_short_tpl = Template(open("templates/comments_short.html").read().decode("utf-8"))
+menu_link_tpl = Template(open("templates/menu_link.html").read().decode("utf-8"))
+timestamp_tpl = Template(open("templates/timestamp.html").read().decode("utf-8"))
+created_tpl = Template(open("templates/created.html").read().decode("utf-8"))
+modified_tpl = Template(open("templates/modified.html").read().decode("utf-8"))
+
+
+def get_data(entry):
+    """Parse the rst in the string entry and return the parts dict"""
+    return publish_parts(entry, writer_name="html")
+
+def get_entries():
+    """Get the filenames of all entries, sorted using [].sort()"""
+    entries = [x for x in os.listdir(ENTRIES_PATH) if x.endswith(".rst")]
+    entries.sort()
+    return entries
+
+def get_data_entries(entries):
+    """Read and parse entries, return document parts as generated by docutils"""
+    data = []
+    for entry in entries:
+        with open(os.path.join(ENTRIES_PATH, entry)) as source:
+            parts = get_data(source.read().decode("utf-8"))
+            parts.update(get_entry_dates(entry))
+            data.append(parts)
+    return data
+
+def identifier(parts):
+    """Create a identifier from doc title, replacing special chars with dash (-)"""
+    return re.sub("[^\w]", "-", parts["title"]).strip("-")
+    
+def url(parts):
+    """Create a url from a document"""
+    return BASE + identifier(parts)
+
+def setup_target_folder():
+    """Create target folder if it does not exist, and copy CSS files there"""
+    if not os.path.exists(HTML_PATH):
+        os.mkdir(HTML_PATH)
+    shutil.copy(os.path.join(CSS_PATH, CSS_NAME), HTML_PATH)
+    shutil.copy(os.path.join(CSS_PATH, "html4css1.css"), HTML_PATH)
+
+def hgdate_to_utc(hgdate_string):
+    """Convert a hgdate format string to unix time UTC"""
+    return sum([int(i) for i in hgdate_string.split()])
+
+def get_entry_dates(entry):
+    """Get (creation, last modification) as unix time UTC"""
+    repo = hgapi.Repo(ENTRIES_PATH)
+    times = repo.hg_log(template='{date|hgdate}', filespec=entry).split("\n")
+    created = hgdate_to_utc(times[-1])
+    modified = hgdate_to_utc(times[0])
+    return {'created': created, 'modified': modified}
+
+def get_timestamp(created, modified):
+    """Return html for the timestamp portion of a post"""
+    cr_str, mod_str = [datetime.fromtimestamp(ts).strftime("%y%m%d %H:%M") 
+                       for ts in created, modified]
+    ts_str = created_tpl.substitute(timestamp=cr_str)
+    if cr_str != mod_str:
+        ts_str += modified_tpl.substitute(timestamp=mod_str)
+    return timestamp_tpl.substitute(timestamps = ts_str)
+
+def generate_blaag(entries, overwrite):
+    """Generate html from blaag entries. If overwrite is set to true, 
+    overwrite existing entries"""
+    setup_target_folder()
+    data = get_data_entries(entries)
+    links = "<br/>".join([menu_link_tpl.substitute(link=url(parts), 
+                                                   title=parts['title']) 
+                          for parts in data])
+    main = []
+    
+    for parts in data: 
+        parts.update(defaults)
+        parts.update({'timestamp': get_timestamp(parts['created'], parts['modified'])})
+        htmltitle = identifier(parts)
+        target_path = os.path.join(HTML_PATH, htmltitle)
+        if os.path.exists(target_path):
+            if not overwrite:
+                print("Skipping existing: %s" % (target_path,))
+                continue
+        else:
+            os.mkdir(target_path)
+        with open(os.path.join(HTML_PATH, htmltitle, "index.html"), "w") as target:
+            #Write page for post
+
+            fullcomments = comments_full_tpl.substitute(parts, threadid=htmltitle)
+            blaag_html = blaag_tpl.substitute(parts, comments=fullcomments)
+            target.write(page_tpl.substitute(parts, title=parts['title'], 
+                                             links=links, main=blaag_html).encode("utf-8"))
+            #Append post to main page
+            shortcomments = comments_short_tpl.substitute(parts, 
+                                                          link=url(parts), 
+                                                          threadid=identifier(parts))
+            main.append(blaag_tpl.substitute(parts, 
+                                             comments=shortcomments, 
+                                             link=url(parts)))
+    #Write main page
+    with open(os.path.join(HTML_PATH, "index.html"), "w") as target:
+        target.write(page_tpl.substitute(defaults, links=links, 
+                                         main="<hr/>".join(main)).encode("utf-8"))
+
+if __name__ == "__main__":
+    generate_blaag(get_entries(), "-f" in sys.argv)