1
0

npm.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/env python3
  2. """
  3. Update dependencies according to npm.json configurations using the NPM packagist.
  4. npm.json file is a JSON object key => dependency.
  5. - key: is the key name of the dependency. It will be the folder name where the dependency will be stored.
  6. - dependency: a JSON object key-pair value with the following meaning full keys:
  7. - package (optional): if provided, this is the NPM package name. Otherwise, key is used as an NPM package name.
  8. - version (optional): if provided, this will fix the version to use. Otherwise, the latest available NPM package version will be used.
  9. - destination: the destination folder where the dependency should end up.
  10. - keep: an array of regexp of files to keep within the downloaded NPM package.
  11. - rename: an array of rename rules (string replace). Used to change the package structure after download to match NiceGUI expectations.
  12. """
  13. import json
  14. import re
  15. import shutil
  16. import tarfile
  17. from pathlib import Path
  18. import requests
  19. def prepare(path: Path) -> Path:
  20. path.parent.mkdir(parents=True, exist_ok=True)
  21. return path
  22. def cleanup(path: Path) -> Path:
  23. shutil.rmtree(path, ignore_errors=True)
  24. return path
  25. def url_to_filename(url: str) -> str:
  26. return re.sub(r'[^a-zA-Z0-9]', '_', url)
  27. def download_buffered(url: str) -> Path:
  28. path = Path('/tmp/nicegui_dependencies')
  29. path.mkdir(exist_ok=True)
  30. filepath = path / url_to_filename(url)
  31. if not filepath.exists():
  32. response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
  33. filepath.write_bytes(response.content)
  34. return filepath
  35. DEPENDENCIES = (Path(__file__).parent / 'DEPENDENCIES.md').open('w')
  36. DEPENDENCIES.write('# Included Web Dependencies\n\n')
  37. # Create a hidden folder to work in.
  38. tmp = cleanup(Path('.npm'))
  39. dependencies: dict[str, dict] = json.loads(Path('npm.json').read_text())
  40. for key, dependency in dependencies.items():
  41. # Reset destination folder.
  42. destination = prepare(Path('nicegui', dependency['destination'], key))
  43. # Get package info from NPM.
  44. package_name = dependency.get('package', key)
  45. npm_data = json.loads(download_buffered(f'https://registry.npmjs.org/{package_name}').read_text())
  46. npm_version = dependency.get('version', npm_data['dist-tags']['latest'])
  47. npm_tarball = npm_data['versions'][npm_version]['dist']['tarball']
  48. print(f'{key}: {npm_version} - {npm_tarball}')
  49. DEPENDENCIES.write(f'- {key}: {npm_version}\n')
  50. # Handle the special case of tailwind. Hopefully remove this soon.
  51. if 'download' in dependency:
  52. path = download_buffered(dependency['download'])
  53. shutil.copyfile(path, prepare(Path(destination, dependency['rename'])))
  54. # Download and extract.
  55. tgz_file = prepare(Path(tmp, key, f'{key}.tgz'))
  56. tgz_download = download_buffered(npm_tarball)
  57. shutil.copyfile(tgz_download, tgz_file)
  58. with tarfile.open(tgz_file) as archive:
  59. to_be_extracted: list[tarfile.TarInfo] = []
  60. for tarinfo in archive.getmembers():
  61. for keep in dependency['keep']:
  62. if re.match(f'^{keep}$', tarinfo.name):
  63. to_be_extracted.append(tarinfo) # TODO: simpler?
  64. archive.extractall(members=to_be_extracted, path=Path(tmp, key))
  65. for extracted in to_be_extracted:
  66. filename: str = extracted.name
  67. for rename in dependency['rename']:
  68. filename = filename.replace(rename, dependency['rename'][rename])
  69. newfile = prepare(Path(destination, filename))
  70. Path(tmp, key, extracted.name).rename(newfile)
  71. # Delete destination folder if empty.
  72. if not any(destination.iterdir()):
  73. destination.rmdir()
  74. cleanup(tmp)