template.py 898 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import os
  2. import re
  3. import shutil
  4. from .fs import make_tree
  5. from .log import debug
  6. __all__ = ['copy_template', 'load_template']
  7. _template_pattern = re.compile('[{][{][ ]*([^{} ]+)[ ]*[}][}]')
  8. def load_template(path, **kwargs):
  9. '''Load a template file and substitue keywords
  10. '''
  11. with open(path) as f:
  12. template = f.read()
  13. def matcher(m):
  14. tag = m.group(1)
  15. try:
  16. return kwargs[tag]
  17. except KeyError:
  18. return tag
  19. return _template_pattern.sub(matcher, template)
  20. def copy_template(path, destination, **kwargs):
  21. '''Copy a template file and substitue keywords
  22. '''
  23. txt = load_template(path, **kwargs)
  24. debug('COPY', '%s as %s', os.path.basename(path), destination)
  25. make_tree(os.path.dirname(destination))
  26. with open(destination, 'w') as f:
  27. f.write(txt)
  28. shutil.copymode(path, destination)