mkconst.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env python3
  2. """Embed spry CLI template files as Vala const strings (mkconst-style)."""
  3. import os
  4. import re
  5. import sys
  6. def const_name(filename):
  7. base = filename
  8. for ext in ('.vala', '.html', '.build', '.md'):
  9. if base.endswith(ext):
  10. base = base[: -len(ext)]
  11. break
  12. base = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', base)
  13. base = re.sub(r'[^A-Za-z0-9]', '_', base)
  14. return base.upper()
  15. def vala_literal(text):
  16. text = text.replace('\\', '\\\\').replace('"', '\\"')
  17. text = text.replace('\r', '\\r').replace('\t', '\\t').replace('\n', '\\n')
  18. return '"%s"' % text
  19. def main():
  20. if len(sys.argv) < 3:
  21. sys.stderr.write('usage: mkconst.py OUTPUT TEMPLATE...\n')
  22. return 1
  23. output, templates = sys.argv[1], sys.argv[2:]
  24. with open(output, 'w', encoding='utf-8') as out:
  25. out.write('// Generated by tools/spry/mkconst.py - do not edit.\n')
  26. out.write('namespace Spry.Cli {\n\n')
  27. out.write(' public class Templates : GLib.Object {\n')
  28. for path in templates:
  29. with open(path, 'r', encoding='utf-8') as handle:
  30. text = handle.read()
  31. out.write('\n public const string %s = %s;\n'
  32. % (const_name(os.path.basename(path)), vala_literal(text)))
  33. out.write(' }\n}\n')
  34. return 0
  35. if __name__ == '__main__':
  36. sys.exit(main())