install_extras.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import os
  4. import pathlib
  5. import platform
  6. import subprocess
  7. import tarfile
  8. import httpx
  9. CURRENT_DIR = pathlib.Path(__file__).parent
  10. def main():
  11. delta()
  12. eza()
  13. def delta():
  14. if platform.system() == 'Darwin':
  15. print('$ brew install git-delta')
  16. subprocess.run(['brew', 'install', 'git-delta'], check=True)
  17. return
  18. else:
  19. assert platform.system() == 'Linux'
  20. if subprocess.run(['dpkg', '-l', 'git-delta'], stdout=subprocess.DEVNULL).returncode == 0:
  21. print('git-delta package already installed')
  22. return
  23. client = httpx.Client()
  24. latest = gh_latest_version(client, 'dandavision', 'delta')
  25. version = latest['name']
  26. arch = get_output(['dpkg', '--print-architecture'])
  27. filename = f'git-delta_{version}_{arch}.deb'
  28. (asset,) = (asset for asset in latest['assets'] if asset['name'] == filename)
  29. deb_path = CURRENT_DIR / 'git-delta.deb'
  30. download(client, asset['browser_download_url'], deb_path)
  31. try:
  32. subprocess.run(['sudo', 'dpkg', '-i', deb_path], check=True)
  33. finally:
  34. os.unlink(deb_path)
  35. def eza():
  36. if platform.system() == 'Darwin':
  37. print('$ brew install eza')
  38. subprocess.run(['brew', 'install', 'eza'], check=True)
  39. return
  40. else:
  41. assert platform.system() == 'Linux'
  42. if (CURRENT_DIR / 'eza').exists():
  43. print('eza already downloaded')
  44. return
  45. client = httpx.Client()
  46. if platform.system() == 'Linux':
  47. url = f'https://github.com/eza-community/eza/releases/latest/download/eza_{platform.machine()}-unknown-linux-gnu.tar.gz'
  48. download(client, url, CURRENT_DIR / 'eza.tar.gz')
  49. with tarfile.open(CURRENT_DIR / 'eza.tar.gz', 'r:gz') as tar:
  50. tar.extract('./eza', CURRENT_DIR)
  51. os.unlink(CURRENT_DIR / 'eza.tar.gz')
  52. def get_output(argv: list[str]) -> str:
  53. proc = subprocess.run(argv, check=True, capture_output=True, encoding='ascii')
  54. return proc.stdout.rstrip('\n')
  55. def gh_latest_version(client: httpx.Client, org: str, repo: str) -> dict:
  56. r = client.get(f'https://api.github.com/repos/{org}/{repo}/releases/latest',
  57. headers={'Accept': 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28'})
  58. r.raise_for_status()
  59. return r.json()
  60. def download(client: httpx.Client, url: str, path: pathlib.Path) -> None:
  61. print('downloading', url, 'to', path)
  62. with client.stream('GET', url, follow_redirects=True) as r:
  63. r.raise_for_status()
  64. with path.open('wb') as f:
  65. for chunk in r.iter_bytes():
  66. f.write(chunk)
  67. if __name__ == '__main__':
  68. main()