po2js.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/python
  2. """convert .po to .js file."""
  3. import json
  4. import optparse
  5. import os
  6. import polib
  7. import re
  8. import sys
  9. parser = optparse.OptionParser(usage="usage: %prog [options] pofile...")
  10. parser.add_option("--callback", default="_.setTranslation", dest="callback",
  11. help="callback function to call with data")
  12. parser.add_option("--quiet", action="store_false", default=True,
  13. dest="verbose", help="don't print status messages to stdout")
  14. (options, args) = parser.parse_args()
  15. if args is None or len(args) == 0:
  16. print("ERROR: you must specify at least one po file to translate")
  17. sys.exit(1)
  18. paramFix = re.compile("(\\(([0-9])\\))")
  19. for srcfile in args:
  20. destfile = os.path.splitext(srcfile)[0] + ".js"
  21. if options.verbose:
  22. print("INFO: converting %s to %s" % (srcfile, destfile))
  23. xlate_map = {}
  24. po = polib.pofile(srcfile, autodetect_encoding=False,
  25. encoding="utf-8", wrapwidth=-1)
  26. for entry in po:
  27. if entry.obsolete or entry.msgstr == '' or entry.msgstr == entry.msgid:
  28. continue
  29. xlate_map[entry.msgid] = entry.msgstr
  30. dest = open(destfile, "w")
  31. dest.write(options.callback)
  32. dest.write("(")
  33. encoder = json.JSONEncoder()
  34. for part in encoder.iterencode(xlate_map):
  35. if part.startswith('"function('):
  36. dest.write(part[1:-1])
  37. else:
  38. dest.write(part)
  39. dest.write(");\n")
  40. dest.close()