PageRenderTime 29ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 0ms

/bin/rebuild-script.py

http://github.com/pypa/virtualenv
Python | 80 lines | 61 code | 13 blank | 6 comment | 6 complexity | 2eeb2cde79e022bb1f06b6f9aeff842c MD5 | raw file
  1. #!/usr/bin/env python
  2. """
  3. Helper script to rebuild virtualenv.py from virtualenv_support
  4. """
  5. from __future__ import print_function
  6. import os
  7. import re
  8. import codecs
  9. from zlib import crc32 as _crc32
  10. def crc32(data):
  11. """Python version idempotent"""
  12. return _crc32(data) & 0xffffffff
  13. here = os.path.dirname(__file__)
  14. script = os.path.join(here, '..', 'virtualenv.py')
  15. gzip = codecs.lookup('zlib')
  16. b64 = codecs.lookup('base64')
  17. file_regex = re.compile(
  18. br'##file (.*?)\n([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*convert\("""\n(.*?)"""\)',
  19. re.S)
  20. file_template = b'##file %(filename)s\n%(varname)s = convert("""\n%(data)s""")'
  21. def rebuild(script_path):
  22. with open(script_path, 'rb') as f:
  23. script_content = f.read()
  24. parts = []
  25. last_pos = 0
  26. match = None
  27. for match in file_regex.finditer(script_content):
  28. parts += [script_content[last_pos:match.start()]]
  29. last_pos = match.end()
  30. filename, fn_decoded = match.group(1), match.group(1).decode()
  31. varname = match.group(2)
  32. data = match.group(3)
  33. print('Found file %s' % fn_decoded)
  34. pathname = os.path.join(here, '..', 'virtualenv_embedded', fn_decoded)
  35. with open(pathname, 'rb') as f:
  36. embedded = f.read()
  37. new_crc = crc32(embedded)
  38. new_data = b64.encode(gzip.encode(embedded)[0])[0]
  39. if new_data == data:
  40. print(' File up to date (crc: %08x)' % new_crc)
  41. parts += [match.group(0)]
  42. continue
  43. # Else: content has changed
  44. crc = crc32(gzip.decode(b64.decode(data)[0])[0])
  45. print(' Content changed (crc: %08x -> %08x)' %
  46. (crc, new_crc))
  47. new_match = file_template % {
  48. b'filename': filename,
  49. b'varname': varname,
  50. b'data': new_data
  51. }
  52. parts += [new_match]
  53. parts += [script_content[last_pos:]]
  54. new_content = b''.join(parts)
  55. if new_content != script_content:
  56. print('Content updated; overwriting... ', end='')
  57. with open(script_path, 'wb') as f:
  58. f.write(new_content)
  59. print('done.')
  60. else:
  61. print('No changes in content')
  62. if match is None:
  63. print('No variables were matched/found')
  64. if __name__ == '__main__':
  65. rebuild(script)