Commits

Fredrik Håård committed eeb7975 Merge

merge

Comments (0)

Files changed (6)

-[content]
-title = Fredrik Håård's Blaag
-author = Fredrik Håård
-description = YAB
-entries_path = entries
-
-[html]
-css_name = haze.css
-css_url = /haze.css
-css_path = css
-templates_path = templates
-html_path = html
-base_url = http://blaag.haard.se/
-
-[disqus]
-name = devrantblaag
+[content]
+title = Fredrik Håård's Blaag
+author = Fredrik Håård
+description = YAB
+entries_path = entries
+
+[html]
+css_name = haze.css
+css_url = /haze.css
+css_path = css
+templates_path = templates
+html_path = html
+base_url = http://blaag.haard.se/
+
+[disqus]
+name = devrantblaag
+
+[google_analytics]
+account = UA-27784490-1
 # -*- encoding: utf-8 -*-
 from string import Template
 from datetime import datetime, timedelta
-from time import time
-import os, os.path, shutil, re
+from time import time, mktime
+import sys, os, os.path, shutil, re
 from docutils.core import publish_parts
 from hgapi import hgapi
 import PyRSS2Gen
-from ConfigParser import SafeConfigParser
+from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError
 import codecs
 
 def get_configuration(path):
             'description': u"Unknown description",
             'entries': 'entries',
             },
+        'datetime': {
+            'use_filename_for_creation_time': False,
+            },
         'html': {
             'templates_path': 'templates',
             'html_path': 'html',
     entries.sort(reverse=True)
     return entries
 
-def get_data_entries(entries, entries_path):
+def get_data_entries(entries, entries_path, use_filename):
     """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, entries_path))
+            if not use_filename:
+                entry_timeinfo = get_entry_dates(entry, entries_path)
+            else:
+                entry_timeinfo = get_filename_entry_dates(entry)
+            parts.update(entry_timeinfo)
             data.append(parts)
     return data
 
         modified = hgdate_to_utc(times[0])
     return {'created': created, 'modified': modified}
 
-def get_timestamp(created, modified, created_tpl, modified_tpl):
+def get_filename_entry_dates(entry):
+    """Get creation and last modification based on filename as unix time UTC."""
+    year, month, day, extra = entry.split('-')
+    t = int(mktime(datetime(int(year), int(month), int(day)).timetuple()))
+    return {'created': t, 'modified': t}
+
+def format_timestamp(ts, template, dt_format):
+    dt = datetime.fromtimestamp(ts)
+    return dt.strftime(dt_format)
+    
+def get_timestamp(created, modified, created_tpl, modified_tpl, dt_format):
     """Return string representing timestamp in post"""
-    cr, mod = [datetime.fromtimestamp(ts) for ts in created, modified]
-    ts_str = created_tpl.substitute(timestamp=cr.strftime("%y%m%d %H:%M"))
+    created_dt = datetime.fromtimestamp(created)
+    modified_dt = datetime.fromtimestamp(modified)
+
+    result = created_tpl.substitute(timestamp=created_dt.strftime(dt_format))
     #Add modification date if last change is more than 10 minutes after creation
-    if mod - cr > timedelta(minutes=10):
-        ts_str += modified_tpl.substitute(timestamp=mod.strftime("%y%m%d %H:%M"))
-    return ts_str
+    if modified_dt - created_dt > timedelta(minutes=10):
+        result += modified_tpl.substitute(
+            timestamp=modified_dt.strftime(dt_format))
+    return result
 
 class Templates(object):
     def __init__(self, templates_path):
         f.close()
         return result
 
-def generate_blaag():
+def generate_blaag(config_path):
     """Generate html from blaag entries."""
-    config = get_configuration('blaag.cfg')
+    config = get_configuration(config_path)
 
     templates = Templates(config.get('html', 'templates_path'))
 
 
     entries_path = config.get('content', 'entries_path')
     entries = get_entries(entries_path)
-    data = get_data_entries(entries, entries_path)
+    try:
+        use_filename_for_creation_time = config.getboolean(
+            'datetime',
+            'use_filename_for_creation_time')
+    except (NoSectionError, NoOptionError):
+        use_filename_for_creation_time = False
+        
+    data = get_data_entries(
+        entries, entries_path,
+        use_filename_for_creation_time)
+
     main = []
 
     base_url = config.get('html', 'base_url')
-    def get_url(parts):
-        """Create a url from a document"""
-        return base_url + identifier(parts)
-
+    def get_relative_url(parts):
+        """Create a relative url from a document"""
+        return identifier(parts)
+    def get_absolute_url(parts):
+        """Create absolute url for a document"""
+        return base_url + get_relative_url(parts)
+    
     #Get timestamps from Mercurial
+    try:
+        dt_format = config.get('datetime', 'datetime_format')
+    except (NoSectionError, NoOptionError):
+        dt_format = '%y%m%d %H:%M'
     for parts in data:
         timestamp = timestamp_tpl.substitute(
             timestamps=get_timestamp(parts['created'], parts['modified'],
-                                     created_tpl, modified_tpl))
+                                     created_tpl, modified_tpl, dt_format))
         parts.update({
                 'timestamp': timestamp,
                 'identifier': identifier(parts)
     #Sort by creation date
     data.sort(cmp=lambda x, y: y['created']-x['created'])
     #Create links
-    links = "\n".join([menu_link_tpl.substitute(link=get_url(parts), 
-                                                   title=parts['title']) 
-                          for parts in data])
+    links = "\n".join([
+            menu_link_tpl.substitute(
+                link=get_relative_url(parts), 
+                title=parts['title']) 
+            for parts in data])
 
     title = config.get('content', 'title')
 
+    disqus_name = config.get('disqus', 'name')
+    
     defaults = {
-        'disqus_name': config.get('disqus', 'name'),
+        'disqus_name': disqus_name,
         'css': config.get('html', 'css_url') + "?" + str(int(time())), #force reload. 
         'page_title': title,
         'blaag_title': title,
         'author': config.get('content', 'author'),
+        'google_analytics_account': config.get('google_analytics', 'account'),
         }
 
     for parts in data: 
 
         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)
+            fullcomments = comments_full_tpl.substitute(
+                parts,
+                threadid=htmltitle,
+                disqus_name=disqus_name)
             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"))
+            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=get_url(parts), 
-                                                          threadid=identifier(parts))
-            main.append(blaag_tpl.substitute(parts, 
-                                             comments=shortcomments, 
-                                             link=get_url(parts)))
+            shortcomments = comments_short_tpl.substitute(
+                parts, 
+                link=get_relative_url(parts), 
+                threadid=identifier(parts))
+            main.append(blaag_tpl.substitute(
+                    parts, 
+                    comments=shortcomments, 
+                    link=get_relative_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="\n".join(main)).encode("utf-8"))
+        target.write(page_tpl.substitute(
+                defaults,
+                links=links, 
+                main="\n".join(main)).encode("utf-8"))
     #Write rss
 
     description = config.get('content', 'description')
-    base_url = config.get('html', 'base_url')
     
     for name in FEEDS:        
         rss = generate_rss(data, FEEDS[name], title, description, base_url,
-                           get_url)
+                           get_absolute_url)
         f = open(os.path.join(html_path, name), 'w')
         rss.write_xml(f)
         f.close()
         
 def pretxncommit_hook(*args, **kwargs):
     """Run before commit"""
-    generate_blaag()
+    generate_blaag('blaag.cfg')
+
+def blaag_script():
+    try:
+        config_path = sys.argv[1]
+    except IndexError:
+        config_path = 'blaag.cfg'
+
+    generate_blaag(config_path)
 
 if __name__ == "__main__":
-    generate_blaag()
+    blaag_script()
 [buildout]
 develop = .
-parts = devpython pyflakes
+parts = devpython blaag pyflakes
 versions = versions
 unzip = true
 
 recipe = z3c.recipe.scripts:interpreter
 eggs = blaag
 
+[blaag]
+recipe = z3c.recipe.scripts
+eggs = blaag
+
 [pyflakes]
 recipe = z3c.recipe.scripts
 eggs = setuptools 
-# -*- encoding: utf-8 -*-
-from setuptools import setup
-
-long_description = (
-    open('readme.rst').read())
-#    + '\n' +
-#    open('CHANGES.txt').read())
-
-setup(
-    name='blaag',
-    version='0.5.1a1',
-    description="Blaag - restructured text based static blog",
-     keywords='blog rst restructured',
-    author=u'Fredrik Håård',
-    author_email='fredrik@haard.se',
-    long_description=long_description,
-    license='MIT',
-    url='https://bitbucket.org/haard/blaag',
-    py_modules=['blaag'],
-    zip_safe=False,
-    install_requires=[
-        'hgapi',
-        'PyRSS2Gen',
-        'docutils',
-        ],
-    entry_points = {
-        'console_scripts': [
-            'blaag = blaag:generate_blaag'
-            ]
-        },
-    classifiers = [
-          'Development Status :: 4 - Beta',
-          'Environment :: Console',
-          'Environment :: Web Environment',
-          'License :: OSI Approved :: MIT License',
-          'Operating System :: MacOS :: MacOS X',
-          'Operating System :: Microsoft :: Windows',
-          'Operating System :: POSIX',
-          'Programming Language :: Python',
-        ],
-
-    )
+# -*- encoding: utf-8 -*-
+from setuptools import setup
+
+long_description = (
+    open('readme.rst').read())
+#    + '\n' +
+#    open('CHANGES.txt').read())
+
+setup(
+    name='blaag',
+    version='0.5.1a1',
+    description="Blaag - restructured text based static blog",
+     keywords='blog rst restructured',
+    author=u'Fredrik Håård',
+    author_email='fredrik@haard.se',
+    long_description=long_description,
+    license='MIT',
+    url='https://bitbucket.org/haard/blaag',
+    py_modules=['blaag'],
+    zip_safe=False,
+    install_requires=[
+        'hgapi',
+        'PyRSS2Gen',
+        'docutils',
+        ],
+    entry_points = {
+        'console_scripts': [
+            'blaag = blaag:blaag_script',
+            ]
+        },
+    classifiers = [
+          'Development Status :: 4 - Beta',
+          'Environment :: Console',
+          'Environment :: Web Environment',
+          'License :: OSI Approved :: MIT License',
+          'Operating System :: MacOS :: MacOS X',
+          'Operating System :: Microsoft :: Windows',
+          'Operating System :: POSIX',
+          'Programming Language :: Python',
+        ],
+
+    )

templates/comments_full.html

     <div id="disqus_thread"></div>
     <script type="text/javascript">
         /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
-        var disqus_shortname = 'devrantblaag'; // required: replace example with your forum shortname
+        var disqus_shortname = '${disqus_name}';
         var disqus_identifier = '${threadid}';
         /* * * DON'T EDIT BELOW THIS LINE * * */
-        (function() {
+        (function(d) {
             var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
             dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
             (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
     </script>
     <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
     <a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>
-</div>
+</div>

templates/pagetemplate.html

 
     <section class="page">
       <header class="page">
-        <h1>Fredrik Håård's Blaag</h1>  
+        <h1>${page_title}</h1>  
       </header>  
       
       ${main}
       </footer>
     </section>
     
-    <!-- Add JavaScript after this point, it makes the page load faster when client does not need to intrepret JS at start -->
+    <!-- Add JavaScript after this point, it makes the page load faster when client does not need to interpret JS at start -->
     <script type="text/javascript">
       var _gaq = _gaq || [];
-      _gaq.push(['_setAccount', 'UA-27784490-1']);
+      _gaq.push(['_setAccount', '${google_analytics_account}']);
       _gaq.push(['_trackPageview']);
       (function() {
         var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
     </script>
      
     <script type="text/javascript">
-      var disqus_shortname = 'devrantblaag'; 
+      var disqus_shortname = '${disqus_name}'; 
       (function () {
         var s = document.createElement('script'); s.async = true;
         s.type = 'text/javascript';
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.