#!/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 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 (default=current directory)')), (['drop-unused'], NO_ARGS, 'do not saved unused editable regions (default=do save)'), (['s', 'to-stdout'], NO_ARGS, 'write to stdout (default=overwrite file)'), (['suffix'], "", ('SUFFIX', 'write modified file with SUFFIX (default=no suffix')), (['w', '--warn-unused'], NO_ARGS, 'warn if editable fields are not used (default=no warning)')], name='dt-apply', usage='Usage: dt-apply [OPTION] TEMPLATE CONTENT ...', description='Apply TEMPLATE to CONTENT', version='0.0.1') if len(args)<2: sys.stderr.write('dt-apply: must give at least two arguments (TEMPLATE and CONTENT)\n') sys.stderr.write("Try `dt-apply --help' for more information\n") sys.exit(1) template_filename=args[0] content_filename_list=args[1:] site_root=ops['r'] template_path=canonical(strip_filename(template_filename)) try: template=StructuredDoc(from_file=template_filename) except IOError: sys.stdout.write("error: cannot open template \"%s\"\n" % template_filename) sys.exit(1) template.filename="/"+relative_to(canonical(template_filename), site_root) for content_filename in content_filename_list: local_template=copy.deepcopy(template) content_path=canonical(strip_filename(content_filename)) local_template.redirect_links(template_path, content_path) try: s=StructuredDoc(from_file=content_filename) except IOError: sys.stdout.write("error: cannot open file \"%s\"\n" % content_filename) sys.exit(1) s_new=local_template.insert(s) if ops.has_key('drop-unused'): s_new.unused=[] if ops.has_key('w') and s_new.unused: for f in s_new.unused: sys.stdout.write("warning: %s: field not used: \"%s\"\n" % (content_filename, f[0])) if ops.has_key('s'): out_file=sys.stdout else: out_file=open(content_filename+ops['suffix'], "w") out_file.write(str(s_new)) if not ops.has_key('s'): out_file.close()