#!/usr/bin/python
from dt_ParseArgs import parse_args, NO_ARGS
from dt_StructuredDoc import StructuredDoc
from dt_FilePath import canonical, strip_filename, relative_to
import posix, sys, copy, re
ops, args=parse_args(
[(['h', 'help'], NO_ARGS, 'display this help and exit'),
(['version'], NO_ARGS, 'output version information and exit'),
(['r', 'site-root', 'root'], posix.getcwd(),
('ROOT', 'The root of the web pages')),
(['b', 'body'], "docbody",
('FIELD', 'put body of CONTENT in the field FIELD (default=docbody)')),
(['t', 'title'], 'doctitle',
('FIELD', 'put title of CONTENT in the field FIELD (default=doctitle)')),
(['suffix'], "", ('SUFFIX', 'write modified file with SUFFIX (default=no suffix')),
(['s', 'to-stdout'], NO_ARGS,
'write to stdout (default=overwrite file)')],
name='dt_new',
usage='Usage: dt_new [OPTION] TEMPLATE CONTENT ...',
description='Add TEMPLATE to CONTENT',
comments="""
Automatically adds TEMPLATE to CONTENT, finding
... and
... to insert (see -b and -t to change how these are inserted)
""",
version='0.0.1')
if len(args)<2:
sys.stderr.write('dt_new: must give at least two arguments (TEMPLATE and CONTENT)\n')
sys.stderr.write("Try `dt_new --help' for more information\n")
sys.exit(1)
template_filename=args[0]
content_filename_list=args[1:]
site_root=ops['r']
titlematch=re.compile(".*", re.S)
bodymatch=re.compile("(.*)", re.S)
try:
template=StructuredDoc(from_file=template_filename)
except IOError:
sys.stdout.write("error: cannot open template \"%s\"\n"
% template_filename)
sys.exit(1)
template_path=canonical(strip_filename(template_filename))
for content_filename in content_filename_list:
try:
file=open(content_filename, "r")
except IOError:
sys.stdout.write("error: cannot open file \"%s\"\n"
% content_filename)
sys.exit(1)
content=file.read()
file.close()
match=titlematch.search(content)
title=match.group(0)
match=bodymatch.search(content)
body=match.group(1)
s=StructuredDoc()
s.add_editable(ops['t'], title)
s.add_editable(ops['b'], body)
local_template=copy.deepcopy(template)
content_path=canonical(strip_filename(content_filename))
local_template.redirect_links(template_path, content_path)
local_template.filename="/"+relative_to(canonical(template_filename), site_root)
new_s=local_template.insert(s)
if ops.has_key('s'):
out_file=sys.stdout
else:
out_file=open(content_filename+ops['suffix'], "w")
out_file.write(str(new_s))
if not ops.has_key('s'):
out_file.close()