gen_ub.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import argparse
  2. import os
  3. import tarfile
  4. import contextlib
  5. import hashlib
  6. import base64
  7. import io
  8. stub = """#!/usr/bin/env python
  9. info = {info}
  10. data = "{data}"
  11. import platform
  12. import os
  13. import sys
  14. import tarfile
  15. import contextlib
  16. import io
  17. import base64
  18. def current_platform():
  19. arch = platform.machine().upper()
  20. if arch == 'AMD64':
  21. arch = 'X86_64'
  22. platf = platform.system().upper()
  23. if platf.startswith('WIN'):
  24. platf = 'WIN'
  25. return (platf + '-' + arch).lower()
  26. def extract_file(fname):
  27. with contextlib.closing(tarfile.open(fileobj=io.BytesIO(base64.b64decode(data)))) as f:
  28. return f.extractfile(fname).read()
  29. fname = info[current_platform()]
  30. my_path = os.path.realpath(os.path.abspath(__file__))
  31. tmp_path = my_path + '.tmp'
  32. with open(tmp_path, 'wb') as f:
  33. f.write(extract_file(fname))
  34. os.rename(tmp_path, my_path)
  35. os.chmod(my_path, 0775)
  36. os.execv(sys.argv[0], sys.argv)
  37. """
  38. def gen_ub(output, data):
  39. info = {}
  40. binary = io.BytesIO()
  41. with contextlib.closing(tarfile.open(mode='w:bz2', fileobj=binary, dereference=True)) as f:
  42. for pl, path in data:
  43. fname = os.path.basename(path)
  44. pl = pl.split('-')
  45. pl = pl[1] + '-' + pl[2]
  46. info[pl] = fname
  47. f.add(path, arcname=fname)
  48. binary = binary.getvalue()
  49. info['md5'] = hashlib.md5(binary).hexdigest()
  50. with open(output, 'w') as f:
  51. f.write(stub.format(info=info, data=base64.b64encode(binary)))
  52. os.chmod(output, 0775)
  53. if __name__ == '__main__':
  54. parser = argparse.ArgumentParser()
  55. parser.add_argument('--path', action='append')
  56. parser.add_argument('--platform', action='append')
  57. parser.add_argument('--output', action='store')
  58. args = parser.parse_args()
  59. gen_ub(args.output, zip(args.platform, args.path))