Commits

faassen committed bc22a66

* rearrange configuration system. ConfigParser has an unexpected way of
dealing with default values for section, so instead we manage this
ourselves in a wrapper.

* use argparse to parse options

* introduce -c option to indicate config file (if not blaag.cfg)

* introduce -t to start test mode. This affects URL generation for now,
but might also affect disqus to put it in develop mode later.

  • Participants
  • Parent commits b89a5e4

Comments (0)

Files changed (2)

-36d2d53966efd3937cbc48f959299a100e9a623e example_blaag
+75e227bc8bfff19461b7f8784a8fbdb9efef22d6 example_blaag
 from string import Template
 from datetime import datetime, timedelta
 from time import time, mktime
-import sys, os, os.path, shutil, re
+import os, os.path, shutil, re
 from docutils.core import publish_parts
 from hgapi import hgapi
 import PyRSS2Gen
 from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError
 import codecs
+import argparse
 
+class Config(object):
+    def __init__(self, path, defaults):
+        self.config_parser = SafeConfigParser()
+        f = codecs.open(path, 'r', 'utf-8') # make sure config is read as unicode
+        self.config_parser.readfp(f)
+        f.close()
+        self.defaults = defaults
+
+    def _get_default(self, getfunc, section, option):
+        try:
+            return getfunc(section, option)
+        except (NoSectionError, NoOptionError):
+            d = self.defaults.get(section, None)
+            if d is None:
+                raise NoSectionError(section)
+            try:
+                return d[option]
+            except KeyError:
+                raise NoOptionError(option, section)
+
+    
+    def get(self, section, option):
+        return self._get_default(self.config_parser.get, section, option)
+
+    def getboolean(self, section, option):    
+        return self._get_default(self.config_parser.getboolean, section, option)
+
+    
+            
 def get_configuration(path):
     defaults = {
         'content': {
             'entries': 'entries',
             },
         'datetime': {
+            'datetime_format': '%y%m%d %H:%M',
             'use_filename_for_creation_time': False,
             },
         'html': {
             'templates_path': 'templates',
             'html_path': 'html',
+            'base_url': 'http://localhost:8000/',
+            'test_base_url': 'http://localhost:8000/',
             },
         'disqus': {
             'name': None,
             }
         }
-    config = SafeConfigParser(defaults)
-    f = codecs.open(path, 'r', 'utf-8') # make sure config is read as unicode
-    config.readfp(f)
-    f.close()
-    return config
+    
+    return Config(path, defaults)
 
 def sieve(*words):
     """Filter generator for RSS generation"""
         f.close()
         return result
 
-def generate_blaag(config_path):
+def generate_blaag(config_path, test_mode=False):
     """Generate html from blaag entries."""
     config = get_configuration(config_path)
 
 
     entries_path = config.get('content', 'entries_path')
     entries = get_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
+
+    use_filename_for_creation_time = config.getboolean(
+        'datetime',
+        'use_filename_for_creation_time')
         
     data = get_data_entries(
         entries, entries_path,
 
     main = []
 
-    base_url = config.get('html', 'base_url')
-    def get_relative_url(parts):
-        """Create a relative url from a document"""
-        return identifier(parts)
+    if not test_mode:
+        base_url = config.get('html', 'base_url')
+    else:
+        base_url = config.get('html', 'test_base_url')
     def get_absolute_url(parts):
         """Create absolute url for a document"""
-        return base_url + get_relative_url(parts)
+        return base_url + identifier(parts)
     
     #Get timestamps from Mercurial
-    try:
-        dt_format = config.get('datetime', 'datetime_format')
-    except (NoSectionError, NoOptionError):
-        dt_format = '%y%m%d %H:%M'
+    datetime_format = config.get('datetime', 'datetime_format')
     for parts in data:
         timestamp = timestamp_tpl.substitute(
             timestamps=get_timestamp(parts['created'], parts['modified'],
-                                     created_tpl, modified_tpl, dt_format))
+                                     created_tpl, modified_tpl, datetime_format))
         parts.update({
                 'timestamp': timestamp,
                 'identifier': identifier(parts)
     #Create links
     links = "\n".join([
             menu_link_tpl.substitute(
-                link=get_relative_url(parts), 
+                link=get_absolute_url(parts), 
                 title=parts['title']) 
             for parts in data])
 
             #Append post to main page
             shortcomments = comments_short_tpl.substitute(
                 parts, 
-                link=get_relative_url(parts), 
+                link=get_absolute_url(parts), 
                 threadid=identifier(parts))
             main.append(blaag_tpl.substitute(
                     parts, 
                     comments=shortcomments, 
-                    link=get_relative_url(parts)))
+                    link=get_absolute_url(parts)))
     #Write main page
     with open(os.path.join(html_path, "index.html"), "w") as target:
         target.write(page_tpl.substitute(
     generate_blaag('blaag.cfg')
 
 def blaag_script():
-    try:
-        config_path = sys.argv[1]
-    except IndexError:
-        config_path = 'blaag.cfg'
+    parser = argparse.ArgumentParser(description="generate blog html")
+    parser.add_argument('-t', '--test',
+                        action="store_true",
+                        default=False,
+                        help="generate html for local testing")
+    parser.add_argument('-c', '--config',
+                        default='blaag.cfg',
+                        help="custom .cfg file (defaults to blaag.cfg)")
+    args = parser.parse_args()
 
-    generate_blaag(config_path)
+    generate_blaag(args.config, args.test)
 
 if __name__ == "__main__":
     blaag_script()