Last active
December 23, 2020 16:59
-
-
Save haykuro/44fde3fa5552b37d6e9e229bfd897806 to your computer and use it in GitHub Desktop.
A python GH CLI updater. https://github.com/cli/cli/releases/latest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Written by Steve Birstok (12-23-2020) | |
Happy Holidays! | |
""" | |
import os | |
import requests | |
import tarfile | |
import shutil | |
LATEST_RELEASE_URL = 'https://api.github.com/repos/cli/cli/releases/latest' | |
def download_asset(asset, save_to, opt_chunk=False): | |
""" | |
Download a File. | |
Adapted from: https://stackoverflow.com/a/16696317 | |
dict - asset - The GitHub Asset dict object | |
string - save_to - Path to save to. | |
bool - opt_chhunk - Set to True, if you have chunk encoded response | |
""" | |
if os.path.exists(save_to): | |
print('Error: "{0}" path exists, aborting.'.format(save_to)) | |
exit(1) | |
download_url = asset['browser_download_url'] | |
download_str = 'Downloading {0}'.format(download_url) | |
print(download_str, end='\r') | |
download_size = asset['size'] | |
downloaded = 0 | |
chunk_size = 8192 | |
if opt_chunk: | |
chunk_size = None | |
with requests.get(download_url, stream=True) as r: | |
r.raise_for_status() | |
with open(save_to, 'wb') as f: | |
for chunk in r.iter_content(chunk_size=chunk_size): | |
if not opt_chunk or ( opt_chunk and chunk ): | |
f.write(chunk) | |
downloaded += len(chunk) | |
print('{download_str}... {downloaded:.2f}%'.format(download_str=download_str, downloaded=downloaded / download_size * 100), end='\r') | |
print() | |
print('Saved to: {save_to}'.format(save_to=save_to)) | |
return (save_to, download_url) | |
def get_latest_dmg_asset(): | |
latest_release = requests.get(LATEST_RELEASE_URL).json() | |
for asset in latest_release['assets']: | |
if 'macOS' in asset['name']: | |
return asset | |
def extract_tar(tar_file): | |
print('Extracting tar file {0}..'.format(tar_file)) | |
tar = tarfile.open(tar_file, 'r:gz') | |
tar.extractall() | |
tar.close() | |
def main(): | |
if not os.path.exists('/tmp/gh'): | |
os.mkdir('/tmp/gh') | |
dmg_asset = get_latest_dmg_asset() | |
(tar, url) = download_asset(dmg_asset, '/tmp/gh/gh.tar.gz') | |
extract_tar(tar) | |
foldername = os.path.basename(url).replace('.tar.gz', '') | |
move_from = '{0}/bin/gh'.format(foldername) | |
move_to = os.path.expanduser('~/.bin/gh') | |
print('Moving {0} to {1}'.format(move_from, move_to)) | |
os.rename(move_from, move_to) | |
print('Removing folder {0}'.format(foldername)) | |
shutil.rmtree(foldername) | |
print('Removing /tmp/gh/gh.tar.gz') | |
os.unlink('/tmp/gh/gh.tar.gz') | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment