npm.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #!/usr/bin/env python3
  2. """Update dependencies according to npm.json configurations using the NPM packagist.
  3. npm.json file is a JSON object key => dependency.
  4. - key: is the key name of the dependency. It will be the folder name where the dependency will be stored.
  5. - dependency: a JSON object key-pair value with the following meaning full keys:
  6. - package (optional): if provided, this is the NPM package name. Otherwise, key is used as an NPM package name.
  7. - version (optional): if provided, this will fix the version to use. Otherwise, the latest available NPM package version will be used.
  8. - destination: the destination folder where the dependency should end up.
  9. - keep: an array of regexp of files to keep within the downloaded NPM package.
  10. - rename: an array of rename rules (string replace). Used to change the package structure after download to match NiceGUI expectations.
  11. """
  12. import json
  13. import re
  14. import shutil
  15. import tarfile
  16. import tempfile
  17. from argparse import ArgumentParser
  18. from pathlib import Path
  19. from typing import Dict, List
  20. import requests
  21. temp_dir = tempfile.TemporaryDirectory()
  22. parser = ArgumentParser()
  23. parser.add_argument('path', default='.', help='path to the root of the repository')
  24. parser.add_argument('--name', nargs='*', help='filter library updates by name')
  25. args = parser.parse_args()
  26. root_path = Path(args.path)
  27. names = args.name or None
  28. def prepare(path: Path) -> Path:
  29. path.parent.mkdir(parents=True, exist_ok=True)
  30. return path
  31. def cleanup(path: Path) -> Path:
  32. shutil.rmtree(path, ignore_errors=True)
  33. return path
  34. def url_to_filename(url: str) -> str:
  35. return re.sub(r'[^a-zA-Z0-9]', '_', url)
  36. def download_buffered(url: str) -> Path:
  37. filepath = Path(temp_dir.name) / url_to_filename(url)
  38. if not filepath.exists():
  39. response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=3)
  40. filepath.write_bytes(response.content)
  41. return filepath
  42. DEPENDENCIES = (root_path / 'DEPENDENCIES.md').open('w', encoding='utf-8')
  43. DEPENDENCIES.write('# Included Web Dependencies\n\n')
  44. KNOWN_LICENSES = {
  45. 'UNKNOWN': 'UNKNOWN',
  46. 'MIT': 'https://opensource.org/licenses/MIT',
  47. 'ISC': 'https://opensource.org/licenses/ISC',
  48. 'Apache-2.0': 'https://opensource.org/licenses/Apache-2.0',
  49. 'BSD-2-Clause': 'https://opensource.org/licenses/BSD-2-Clause',
  50. 'BSD-3-Clause': 'https://opensource.org/licenses/BSD-3-Clause',
  51. }
  52. # Create a hidden folder to work in.
  53. tmp = cleanup(root_path / '.npm')
  54. dependencies: Dict[str, dict] = json.loads((root_path / 'npm.json').read_text(encoding='utf-8'))
  55. for key, dependency in dependencies.items():
  56. if names is not None and key not in names:
  57. continue
  58. # Reset destination folder.
  59. destination = prepare(root_path / dependency['destination'] / key)
  60. # Get package info from NPM.
  61. package_name = dependency.get('package', key)
  62. npm_data = json.loads(download_buffered(f'https://registry.npmjs.org/{package_name}').read_text(encoding='utf-8'))
  63. npm_version = dependency.get('version') or dependency.get('version', npm_data['dist-tags']['latest'])
  64. npm_tarball = npm_data['versions'][npm_version]['dist']['tarball']
  65. license_ = 'UNKNOWN'
  66. if 'license' in npm_data['versions'][npm_version]:
  67. license_ = npm_data['versions'][npm_version]['license']
  68. elif package_name == 'echarts-gl':
  69. license_ = 'BSD-3-Clause'
  70. print(f'{key}: {npm_version} - {npm_tarball} ({license_})')
  71. DEPENDENCIES.write(f'- {key}: {npm_version} ([{license_}]({KNOWN_LICENSES.get(license_, license_)}))\n')
  72. # Handle the special case of tailwind. Hopefully remove this soon.
  73. if 'download' in dependency:
  74. download_path = download_buffered(dependency['download'])
  75. content = download_path.read_text(encoding='utf-8')
  76. MSG = (
  77. 'console.warn("cdn.tailwindcss.com should not be used in production. '
  78. 'To use Tailwind CSS in production, install it as a PostCSS plugin or use the Tailwind CLI: '
  79. 'https://tailwindcss.com/docs/installation");'
  80. )
  81. if MSG not in content:
  82. raise ValueError(f'Expected to find "{MSG}" in {download_path}')
  83. content = content.replace(MSG, '')
  84. prepare(destination / dependency['rename']).write_text(content, encoding='utf-8')
  85. # Download and extract.
  86. tgz_file = prepare(Path(tmp, key, f'{key}.tgz'))
  87. tgz_download = download_buffered(npm_tarball)
  88. shutil.copyfile(tgz_download, tgz_file)
  89. with tarfile.open(tgz_file) as archive:
  90. to_be_extracted: List[tarfile.TarInfo] = []
  91. for tarinfo in archive.getmembers():
  92. for keep in dependency['keep']:
  93. if re.match(f'^{keep}$', tarinfo.name):
  94. to_be_extracted.append(tarinfo) # TODO: simpler?
  95. archive.extractall(members=to_be_extracted, path=Path(tmp, key))
  96. for extracted in to_be_extracted:
  97. filename: str = extracted.name
  98. for rename in dependency['rename']:
  99. filename = filename.replace(rename, dependency['rename'][rename])
  100. newfile = prepare(Path(destination, filename))
  101. if newfile.exists():
  102. newfile.unlink()
  103. Path(tmp, key, extracted.name).rename(newfile)
  104. if 'GLTFLoader' in filename:
  105. content = newfile.read_text(encoding='utf-8')
  106. MSG = '../utils/BufferGeometryUtils.js'
  107. if MSG not in content:
  108. raise ValueError(f'Expected to find "{MSG}" in {filename}')
  109. content = content.replace(MSG, 'BufferGeometryUtils')
  110. newfile.write_text(content, encoding='utf-8')
  111. if 'DragControls.js' in filename:
  112. content = newfile.read_text(encoding='utf-8')
  113. MSG = '_selected = findGroup( _intersections[ 0 ].object )'
  114. if MSG not in content:
  115. raise ValueError(f'Expected to find "{MSG}" in {filename}')
  116. content = content.replace(MSG, MSG + ' || _intersections[ 0 ].object')
  117. newfile.write_text(content, encoding='utf-8')
  118. if 'mermaid.esm.min.mjs' in filename:
  119. content = newfile.read_text(encoding='utf-8')
  120. content = re.sub(r'"\./chunks/mermaid.esm.min/(.*?)\.mjs"', r'"\1"', content)
  121. newfile.write_text(content, encoding='utf-8')
  122. try:
  123. # Delete destination folder if empty.
  124. if not any(destination.iterdir()):
  125. destination.rmdir()
  126. except Exception:
  127. pass
  128. temp_dir.cleanup()
  129. cleanup(tmp)