changeset 91:4a9c5cf9fec9

STUB: decoupage/templates.py decoupage/index.py
author Jeff Hammel <k0scist@gmail.com>
date Sat, 29 Mar 2014 17:17:21 -0700
parents 55719bcdc2c2
children c5895d87c65e
files decoupage/index.py decoupage/templates.py
diffstat 2 files changed, 87 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/decoupage/index.py	Sat Mar 29 17:17:21 2014 -0700
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+index.ini
+"""
+
+import argparse
+import os
+import subprocess
+import sys
+
+here = os.path.dirname(os.path.realpath(__file__))
+string = (str, unicode)
+
+def index(directory):
+    return '\n'.join(['{name} = {name}'.format(name=name)
+                      for name in sorted(os.listdir(directory), key=lambda name: name.lower())
+                      if not name.startswith('.')])
+
+def main(args=sys.argv[1:]):
+
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument('directory', help='directory')
+    parser.add_argument('-o', '--output', dest='output',
+                        type=argparse.FileType('w'), default=sys.stdout,
+                        help='output')
+    options = parser.parse_args(args)
+
+if __name__ == '__main__':
+    main()
--- a/decoupage/templates.py	Mon Mar 03 17:14:40 2014 -0800
+++ b/decoupage/templates.py	Sat Mar 29 17:17:21 2014 -0700
@@ -4,13 +4,16 @@
 functionality related to templates
 """
 
+import argparse
 import os
 import sys
-from optparse import OptionParser
+from .index import index
 from pkg_resources import iter_entry_points
 from pkg_resources import resource_filename
 
 def template_dirs():
+    """registered template directories"""
+
     template_dirs = set()
     for formatter in iter_entry_points('decoupage.formatters'):
         try:
@@ -24,6 +27,7 @@
 
 
 def templates():
+    """templates"""
     templates = []
     for directory in template_dirs():
         templates.extend([os.path.join(directory, filename)
@@ -31,17 +35,61 @@
                           if filename.endswith('.html')])
     return templates
 
+def template_dict():
+    """return a dict of templates"""
+    return {os.path.basename(template):template for template in templates()}
 
 def main(args=sys.argv[1:]):
+    """CLI"""
 
-    # comman line option parser
-    description = 'list available templates'
-    parser = OptionParser(description=description)
-    options, args = parser.parse_args(args)
+    # parse command line
+    description = 'list and output available templates'
+    parser = argparse.ArgumentParser(description=description)
+    parser.add_argument('template', nargs='?',
+                        help="output this template")
+    parser.add_argument('-o', '--output', dest='output',
+                        help="output to file or directory or stdout")
+    # TODO
+    parser.add_argument('--cwd', dest='cwd',
+                        help="output to current working directory")
+    options = parser.parse_args(args)
+
+    # retrieve templates
+    _templates = template_dict()
+
+    template = options.template
+    if template:
 
-    # list templates
-    for template in templates():
-        print template
+        # look up template
+        if not template.endswith('.html'):
+            template = template + '.html'
+        filename = _templates.get(template)
+        if filename is None:
+            parser.error("Template '{}' not in {}".format(template, ', '.join(sorted(_templates.keys()))))
+        content = open(filename, 'r').read()
+
+        # divine output
+        output = options.output
+        if output:
+            if os.path.isdir(output):
+                output = os.path.join(output, 'index.html')
+            with open(output, 'w') as f:
+                f.write(content)
+
+            directory = os.path.dirname(os.path.abspath(output))
+            ini = os.path.join(directory, 'index.ini')
+            if not os.path.exists(ini):
+                pass
+                # TODO: output directory contents to ini
+                # if specified
+
+        else:
+            print (content)
+
+    else:
+        # list templates
+        for template in templates():
+            print (template)
 
 
 if __name__ == '__main__':