1
0

npm.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. from pathlib import Path
  17. import requests
  18. def prepare(path: Path) -> Path:
  19. path.parent.mkdir(parents=True, exist_ok=True)
  20. return path
  21. def cleanup(path: Path) -> Path:
  22. shutil.rmtree(path, ignore_errors=True)
  23. return path
  24. def url_to_filename(url: str) -> str:
  25. return re.sub(r'[^a-zA-Z0-9]', '_', url)
  26. def download_buffered(url: str) -> Path:
  27. path = Path('/tmp/nicegui_dependencies')
  28. path.mkdir(exist_ok=True)
  29. filepath = path / url_to_filename(url)
  30. if not filepath.exists():
  31. response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
  32. filepath.write_bytes(response.content)
  33. return filepath
  34. DEPENDENCIES = (Path(__file__).parent / 'DEPENDENCIES.md').open('w')
  35. DEPENDENCIES.write('# Included Web Dependencies\n\n')
  36. # Create a hidden folder to work in.
  37. tmp = cleanup(Path('.npm'))
  38. dependencies: dict[str, dict] = json.loads(Path('npm.json').read_text())
  39. for key, dependency in dependencies.items():
  40. # Reset destination folder.
  41. destination = prepare(Path('nicegui', dependency['destination'], key))
  42. # Get package info from NPM.
  43. package_name = dependency.get('package', key)
  44. npm_data = json.loads(download_buffered(f'https://registry.npmjs.org/{package_name}').read_text())
  45. npm_version = dependency.get('version', npm_data['dist-tags']['latest'])
  46. npm_tarball = npm_data['versions'][npm_version]['dist']['tarball']
  47. print(f'{key}: {npm_version} - {npm_tarball}')
  48. DEPENDENCIES.write(f'- {key}: {npm_version}\n')
  49. # Handle the special case of tailwind. Hopefully remove this soon.
  50. if 'download' in dependency:
  51. download_path = download_buffered(dependency['download'])
  52. shutil.copyfile(download_path, prepare(Path(destination, dependency['rename'])))
  53. # Download and extract.
  54. tgz_file = prepare(Path(tmp, key, f'{key}.tgz'))
  55. tgz_download = download_buffered(npm_tarball)
  56. shutil.copyfile(tgz_download, tgz_file)
  57. with tarfile.open(tgz_file) as archive:
  58. to_be_extracted: list[tarfile.TarInfo] = []
  59. for tarinfo in archive.getmembers():
  60. for keep in dependency['keep']:
  61. if re.match(f'^{keep}$', tarinfo.name):
  62. to_be_extracted.append(tarinfo) # TODO: simpler?
  63. archive.extractall(members=to_be_extracted, path=Path(tmp, key))
  64. for extracted in to_be_extracted:
  65. filename: str = extracted.name
  66. for rename in dependency['rename']:
  67. filename = filename.replace(rename, dependency['rename'][rename])
  68. newfile = prepare(Path(destination, filename))
  69. Path(tmp, key, extracted.name).rename(newfile)
  70. # Delete destination folder if empty.
  71. if not any(destination.iterdir()):
  72. destination.rmdir()
  73. cleanup(tmp)