make-memzip.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python
  2. #
  3. # Takes a directory of files and zips them up (as uncompressed files).
  4. # This then gets converted into a C data structure which can be read
  5. # like a filesystem at runtime.
  6. #
  7. # This is somewhat like frozen modules in python, but allows arbitrary files
  8. # to be used.
  9. from __future__ import print_function
  10. import argparse
  11. import os
  12. import subprocess
  13. import sys
  14. import types
  15. def create_zip(zip_filename, zip_dir):
  16. abs_zip_filename = os.path.abspath(zip_filename)
  17. save_cwd = os.getcwd()
  18. os.chdir(zip_dir)
  19. if os.path.exists(abs_zip_filename):
  20. os.remove(abs_zip_filename)
  21. subprocess.check_call(['zip', '-0', '-r', '-D', abs_zip_filename, '.'])
  22. os.chdir(save_cwd)
  23. def create_c_from_file(c_filename, zip_filename):
  24. with open(zip_filename, 'rb') as zip_file:
  25. with open(c_filename, 'wb') as c_file:
  26. print('#include <stdint.h>', file=c_file)
  27. print('', file=c_file)
  28. print('const uint8_t memzip_data[] = {', file=c_file)
  29. while True:
  30. buf = zip_file.read(16)
  31. if not buf:
  32. break
  33. print(' ', end='', file=c_file)
  34. for byte in buf:
  35. if type(byte) is types.StringType:
  36. print(' 0x{:02x},'.format(ord(byte)), end='', file=c_file)
  37. else:
  38. print(' 0x{:02x},'.format(byte), end='', file=c_file)
  39. print('', file=c_file)
  40. print('};', file=c_file)
  41. def main():
  42. parser = argparse.ArgumentParser(
  43. prog='make-memzip.py',
  44. usage='%(prog)s [options] [command]',
  45. description='Generates a C source memzip file.'
  46. )
  47. parser.add_argument(
  48. '-z', '--zip-file',
  49. dest='zip_filename',
  50. help='Specifies the name of the created zip file.',
  51. default='memzip_files.zip'
  52. )
  53. parser.add_argument(
  54. '-c', '--c-file',
  55. dest='c_filename',
  56. help='Specifies the name of the created C source file.',
  57. default='memzip_files.c'
  58. )
  59. parser.add_argument(
  60. dest='source_dir',
  61. default='memzip_files'
  62. )
  63. args = parser.parse_args(sys.argv[1:])
  64. print('args.zip_filename =', args.zip_filename)
  65. print('args.c_filename =', args.c_filename)
  66. print('args.source_dir =', args.source_dir)
  67. create_zip(args.zip_filename, args.source_dir)
  68. create_c_from_file(args.c_filename, args.zip_filename)
  69. if __name__ == "__main__":
  70. main()