template.py 816 B

1234567891011121314151617181920212223242526272829303132
  1. """Helper functions for working with templates"""
  2. import os
  3. import re
  4. import string
  5. def render_templatefile(path, **kwargs):
  6. with open(path, 'rb') as fp:
  7. raw = fp.read().decode('utf8')
  8. content = string.Template(raw).substitute(**kwargs)
  9. render_path = path[:-len('.tmpl')] if path.endswith('.tmpl') else path
  10. with open(render_path, 'wb') as fp:
  11. fp.write(content.encode('utf8'))
  12. if path.endswith('.tmpl'):
  13. os.remove(path)
  14. CAMELCASE_INVALID_CHARS = re.compile(r'[^a-zA-Z\d]')
  15. def string_camelcase(string):
  16. """ Convert a word to its CamelCase version and remove invalid chars
  17. >>> string_camelcase('lost-pound')
  18. 'LostPound'
  19. >>> string_camelcase('missing_images')
  20. 'MissingImages'
  21. """
  22. return CAMELCASE_INVALID_CHARS.sub('', string.title())