jstoc.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. #-------------------------------------------------------------------------------------------------------
  3. # Copyright (C) Microsoft. All rights reserved.
  4. # Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. #-------------------------------------------------------------------------------------------------------
  6. from __future__ import print_function, with_statement # py 2.5
  7. import sys
  8. import os
  9. def print_usage():
  10. print("jstoc tool")
  11. print("creates a (const char array) from a javascript file.")
  12. print("")
  13. print("usage: jstoc.py <js file path> <variable name>")
  14. sys.exit(1)
  15. def convert():
  16. if len(sys.argv) < 3:
  17. print_usage()
  18. js_file_name = sys.argv[1]
  19. if os.path.isfile(js_file_name) == False:
  20. print_usage()
  21. h_file_name = js_file_name + '.h'
  22. js_file_time = os.path.getmtime(js_file_name)
  23. h_file_time = 0
  24. if os.path.isfile(h_file_name):
  25. h_file_time = os.path.getmtime(h_file_name)
  26. str_header = "static const char " + sys.argv[2] + "[] = {\n"
  27. # if header file is up to date and no update to jstoc.py since, skip..
  28. if h_file_time < js_file_time or h_file_time < os.path.getmtime(sys.argv[0]):
  29. with open(js_file_name, "rb") as js_file:
  30. last_break = len(str_header) # skip first line
  31. byte = js_file.read(1)
  32. while byte:
  33. str_header += str(ord(byte))
  34. str_header += ","
  35. # beautify a bit. limit column to ~80
  36. column_check = (len(str_header) + 1) - last_break
  37. if column_check > 5 and column_check % 80 < 5:
  38. last_break = len(str_header) + 1
  39. str_header += "\n"
  40. else:
  41. str_header += " "
  42. byte = js_file.read(1)
  43. str_header += "0\n};"
  44. h_file = open(h_file_name, "w")
  45. h_file.write(str_header)
  46. h_file.close()
  47. print("-- " + h_file_name + " is created")
  48. else:
  49. print("-- " + h_file_name + " is up to date. skipping.")
  50. if __name__ == '__main__':
  51. sys.exit(convert())
  52. else:
  53. print("try without python")