Commits

faassen committed 9bcd1bc

Experimental class refactoring, but need to do other steps before considering this.

Comments (0)

Files changed (1)

 
 def get_entries(entries_path):
     """Get the filenames of all entries, sorted using [].sort(reverse=True)"""
-    entries = [x for x in os.listdir(entries_path) if x.endswith(".rst")]
-    entries.sort(reverse=True)
-    return entries
+    filenames = [x for x in os.listdir(entries_path) if x.endswith(".rst")]
+    filenames.sort(reverse=True)
+    return [Entry(os.path.join(entries_path, filename))
+            for filename in filenames]
 
 def get_data_entries(entries, entries_path, use_filename):
     """Read and parse entries, return document parts as generated by docutils"""
     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, entries_path):
-    """Get (creation, last modification) as unix time UTC"""
-    repo = hgapi.Repo(entries_path)
-    times = repo.hg_log(template='{date|hgdate}\n', filespec=entry).split("\n")
-   
-    if times == ['']: #not in repo yet
-        print("Warning: %s is not version controlled" % (entry,))
-        created = modified = int(time())
-    else:
-
-        if not times[-1]: del times[-1]
-        created = hgdate_to_utc(times[-1])
-        modified = hgdate_to_utc(times[0])
-    return {'created': created, 'modified': modified}
-
-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)
             timestamp=modified_dt.strftime(dt_format))
     return result
 
+class Entry(object):
+    def __init__(self, path, config, templates):
+        self.path = path
+        self.filename = os.path.basename(path)
+        self.config = config
+        self.templates = templates
+        with open(self.path) as source:
+            self.parts = get_data(source.read().decode('utf-8'))
+        
+        if self.config.get('datetime', 'use_filename_for_creation_time'):
+            self.created, modified = get_filename_datetimes(path)
+        else:
+            self.created, self.modified = get_hg_datetimes(path)
+
+    def generate(self):
+        datetime_format = self.config.get('datetime', 'datetime_format')
+        rendered_timestamps = self.templates.created.substitute(
+            timestamp=self.created.stftime(datetime_format))
+
+        # add modification date if last change is more than 10 minutes
+        # after creation
+        if self.modified - self.created > timedelta(minutes=10):
+            rendered_modified = self.templates.modified.substitute(
+                timestamp=self.modified.strftime(datetime_format))
+            rendered_timestamps += rendered_modified
+
+        # XXX naming is still confusing, rendered_timestamps versus
+        # rendered_timestamp
+        rendered_timestamp = self.templates.timestamp.substitute(
+            timestamps=rendered_timestamps)
+
+        self.parts.update({
+                'disqus_name': disqus_name,
+                'css': self.config.get('html', 'css_url') + "?" + str(int(time())), #force reload. 
+                'page_title': title,
+                'blaag_title': title,
+                'author': self.config.get('content', 'author'),
+                'google_analytics_account': self.config.get('google_analytics', 'account'),
+                'timestamp': rendered_timestamp,
+                'identifier': identifier(self.parts),
+                'threadid': identifier(self.parts),
+                })
+        target_path = os.path.join(
+            self.config.get('html', 'html_path'),
+            identifier(parts))
+        if not os.path.exists(target_path):
+            os.mkdir(target_path)
+
+        rendered_fullcomments = self.templates.comments_full.substitute(
+            parts)
+        rendered_blaag = self.templates.blaag.substitute(
+            parts,
+            comments=rendered_fullcomments)
+        rendered_page = self.templates.page.substitute(
+            parts, title=self.title, links=self.links, main=rendered_blaag)
+        
+def get_filename_datetimes(path):
+    year, month, day, extra = os.path.basename(path).split('-')
+    created = datetime(int(year), int(month), int(day))
+    modified = created
+    return created, modified
+
+def get_hg_datetimes(path):    
+    repo = hgapi.Repo(os.path.dirname(path))
+    times = repo.hg_log(
+        template='{date|hgdate}\n', filespec=os.path.basename(path)).split("\n")
+
+    if times == ['']: #not in repo yet
+        print("Warning: %s is not version controlled" % (entry,))
+        created = modified = datetime.now()
+        return created, modified
+
+    if not times[-1]:
+        del times[-1]
+    created = hgdate_to_datetime(times[-1])
+    modified = hgdate_to_datetime(times[0])
+    return created, modified
+
+def hgdate_to_datetime(hgdate_string):
+    """Convert a hgdate format string to Python datetime."""
+    t = sum([int(i) for i in hgdate_string.split()])
+    return datetime.fromtimestamp(t)
+
 class Templates(object):
     def __init__(self, templates_path):
         self.templates_path = templates_path
-
-    def get(self, name):
-        f = open(os.path.join(self.templates_path, name), 'r')
-        result = Template(f.read().decode('utf-8'))
-        f.close()
-        return result
+        for filename in os.listdir(templates_path):
+            path = os.path.join(templates_path, filename)
+            name, extension = os.path.splitext(filename) 
+            with open(path, 'r') as source:
+                setattr(self, name, f.read().decode('utf-8'))
 
 def generate_blaag(config_path, test_mode=False):
     """Generate html from blaag entries."""
     entries_path = config.get('content', 'entries_path')
     entries = get_entries(entries_path)
 
-    use_filename_for_creation_time = config.getboolean(
-        'datetime',
-        'use_filename_for_creation_time')
-        
-    data = get_data_entries(
-        entries, entries_path,
-        use_filename_for_creation_time)
-
     main = []
 
     if not test_mode:
     
     #Get timestamps from Mercurial
     datetime_format = config.get('datetime', 'datetime_format')
-    for parts in data:
+    for entry in entries:
         timestamp = timestamp_tpl.substitute(
             timestamps=get_timestamp(parts['created'], parts['modified'],
                                      created_tpl, modified_tpl, datetime_format))