From ed7be3a86717678464ca35e032fb89109b0b547a Mon Sep 17 00:00:00 2001 From: "John T. Wodder II" Date: Thu, 9 Nov 2023 11:06:37 -0500 Subject: [PATCH] Use `ghtoken` to fetch GitHub token from more sources --- README.rst | 8 +++++--- setup.cfg | 1 + src/tinuous/util.py | 24 +++++++++--------------- 3 files changed, 15 insertions(+), 18 deletions(-) diff --git a/README.rst b/README.rst index 1bab36c..c9b7698 100644 --- a/README.rst +++ b/README.rst @@ -549,9 +549,11 @@ alternative to setting them directly in the environment. GitHub ~~~~~~ -In order to retrieve assets from GitHub, a GitHub OAuth token must be specified -either via the ``GITHUB_TOKEN`` environment variable or as the value of the -``hub.oauthtoken`` Git config option. +In order to retrieve assets from GitHub, a GitHub access token with appropriate +permissions must be provided. Specify the token via the ``GH_TOKEN`` or +``GITHUB_TOKEN`` environment variable, by storing a token with the ``gh`` or +``hub`` command, or by setting the ``hub.oauthtoken`` Git config option in your +``~/.gitconfig`` file. Travis ~~~~~~ diff --git a/setup.cfg b/setup.cfg index 6eb68fb..1b919c0 100644 --- a/setup.cfg +++ b/setup.cfg @@ -45,6 +45,7 @@ install_requires = click >= 7.0 click-loglevel ~= 0.2 in_place ~= 0.4 + ghtoken ~= 0.1 pydantic ~= 1.7 python-dateutil ~= 2.7 python-dotenv >= 0.11, < 2.0 diff --git a/src/tinuous/util.py b/src/tinuous/util.py index bea1693..373ec55 100644 --- a/src/tinuous/util.py +++ b/src/tinuous/util.py @@ -5,14 +5,14 @@ from datetime import datetime, timezone import email.utils import logging -import os from pathlib import Path import re from string import Formatter -import subprocess from time import time from typing import Any, Optional +from ghtoken import GHTokenNotFound, get_ghtoken + log = logging.getLogger("tinuous") @@ -128,20 +128,14 @@ def parse_slice(s: str) -> slice: def get_github_token() -> str: - token = os.environ.get("GITHUB_TOKEN") - if not token: - r = subprocess.run( - ["git", "config", "hub.oauthtoken"], - stdout=subprocess.PIPE, - universal_newlines=True, + try: + # main() already loads the user's dotenv file, so don't load it again + return get_ghtoken(dotenv=False) + except GHTokenNotFound: + raise RuntimeError( + "GitHub token not found. Set via GH_TOKEN, GITHUB_TOKEN, gh, hub," + " or hub.oauthtoken." ) - if r.returncode != 0 or not r.stdout.strip(): - raise RuntimeError( - "GitHub OAuth token not set. Set via GITHUB_TOKEN" - " environment variable or hub.oauthtoken Git config option." - ) - token = r.stdout.strip() - return token def sanitize_pathname(s: str) -> str: