Created
May 17, 2018 12:27
-
-
Save Enucatl/e120930a45783dbd34d63cd57e95a052 to your computer and use it in GitHub Desktop.
upload new release to github
This file contains 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 | |
# -*- coding: utf-8 -*- | |
import click | |
import os | |
from subprocess import check_call | |
from urllib.parse import urljoin | |
import requests | |
import logging | |
import logging.config | |
import uritemplate | |
import mimetypes | |
def get_config_dict(verbose): | |
levels = [ | |
'INFO', | |
'DEBUG', | |
] | |
verbose = min(len(levels) - 1, verbose) | |
return dict( | |
version=1, | |
disable_existing_loggers=False, | |
formatters={ | |
'f': {'format': | |
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'} | |
}, | |
handlers={ | |
'h': { | |
'class': 'logging.StreamHandler', | |
'formatter': 'f', | |
'level': levels[verbose], | |
} | |
}, | |
root={ | |
'handlers': ['h'], | |
'level': levels[verbose], | |
}, | |
) | |
@click.command() | |
@click.option("--owner", "-o") | |
@click.option("--token", "-t") | |
@click.option("--repo", "-r") | |
@click.option("--tag", "-t") | |
@click.argument("file_name", type=click.Path(exists=True)) | |
@click.option("--verbose", "-v", count=True) | |
def main(owner, token, repo, tag, file_name, verbose): | |
logger = logging.getLogger() | |
logging.config.dictConfig(get_config_dict(verbose)) | |
github_api = "https://api.github.com" | |
headers = {"Authorization": "token {}".format(token)} | |
releases_url = urljoin(github_api, "repos/{}/{}/releases".format(owner, repo)) | |
with requests.Session() as s: | |
s.headers.update(headers) | |
payload = { | |
"tag_name": tag, | |
} | |
response = s.post(releases_url, json=payload) | |
response.raise_for_status() | |
upload_url_template = uritemplate.URITemplate( | |
response.json()["upload_url"]) | |
name = os.path.basename(file_name) | |
logger.debug(upload_url_template.expand(name=name)) | |
with open(file_name, "rb") as asset_file: | |
content_type = mimetypes.guess_type(name)[0] | |
response = s.post( | |
upload_url_template.expand(name=name), | |
headers={"Content-Type": content_type}, | |
data=asset_file, | |
) | |
logger.debug(response.json()) | |
response.raise_for_status() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment