Skip to content

Commit

Permalink
Improved config loading
Browse files Browse the repository at this point in the history
  • Loading branch information
ssbarnea committed Sep 20, 2020
1 parent 259c78b commit b586aa0
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 23 deletions.
23 changes: 11 additions & 12 deletions gri/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
term = Console(theme=theme, highlighter=rich.highlighter.ReprHighlighter(), record=True)
CFG_FILE = "~/.gertty.yaml"

LOG = logging.getLogger(__name__)
LOG = logging.getLogger(__package__)


class Config(dict):
Expand All @@ -55,10 +55,10 @@ def load_config(config_file):
class App:
def __init__(self, ctx):
self.ctx = ctx
self.cfg = Config(file=ctx.params['config'])
self.cfg = Config(file=ctx.params["config"])
self.servers = []
self.user = ctx.params['user']
server = ctx.params['server']
self.user = ctx.params["user"]
server = ctx.params["server"]
for srv in (
self.cfg["servers"]
if server is None
Expand Down Expand Up @@ -149,9 +149,8 @@ def get_command(self, ctx, cmd_name):
)
@click.option("--user", "-u", default="self", help="Query another user than self")
@click.option(
"--config",
default=CFG_FILE,
help=f"Config file to use, defaults to {CFG_FILE}")
"--config", default=CFG_FILE, help=f"Config file to use, defaults to {CFG_FILE}"
)
@click.option(
"--server",
"-s",
Expand Down Expand Up @@ -180,11 +179,11 @@ def cli(ctx, **kwargs):
LOG.addHandler(handler)

LOG.warning("Called with %s", ctx.params)
if ctx.params['debug']:
if ctx.params["debug"]:
LOG.setLevel(level=logging.DEBUG)

if " " in ctx.params['user']:
ctx.params['user'] = f"\"{ctx.params['user']}\""
if " " in ctx.params["user"]:
ctx.params["user"] = f"\"{ctx.params['user']}\""

# import pdb
# pdb.set_trace()
Expand All @@ -194,8 +193,8 @@ def cli(ctx, **kwargs):
LOG.info("I was invoked without subcommand, assuming implicit `owned` command")
ctx.invoke(owned)

if ctx.params['output']:
term.save_html(path=ctx.params['output'], theme=TERMINAL_THEME)
if ctx.params["output"]:
term.save_html(path=ctx.params["output"], theme=TERMINAL_THEME)


@cli.resultcallback()
Expand Down
29 changes: 21 additions & 8 deletions gri/gerrit.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import json
import logging
import netrc
import os
import sys

import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
from requests.exceptions import HTTPError

try:
from urllib.parse import urlencode, urlparse
Expand All @@ -16,6 +19,7 @@
"https://code.engineering.redhat.com/gerrit/": {"auth": HTTPDigestAuth},
"verify": False,
}
LOG = logging.getLogger(__package__)


# pylint: disable=too-few-public-methods
Expand All @@ -39,17 +43,22 @@ def __init__(self, url, name=None):
# workaround for netrc error: OSError("Could not find .netrc: $HOME is not set")
if "HOME" not in os.environ:
os.environ["HOME"] = os.path.expanduser("~")
netrc_file = os.path.expanduser("~/.netrc")

token = netrc.netrc().authenticators(parsed_uri.netloc)

# saving username (may be needed later)
self.username = token[0]
try:
token = netrc.netrc().authenticators(parsed_uri.netloc)
except FileNotFoundError:
token = None

if not token:
raise SystemError(
f"Unable to load credentials for {url} from ~/.netrc file"
LOG.error(
"Unable to load credentials for %s from %s file, "
"likely to receive 401 errors later.",
url,
netrc_file,
)
self.__session.auth = self.auth_class(token[0], token[2])
else:
self.__session.auth = self.auth_class(token[0], token[2])

self.__session.headers.update(
{
Expand All @@ -71,7 +80,11 @@ def query(self, query=None):

@staticmethod
def parsed(result):
result.raise_for_status()
try:
result.raise_for_status()
except HTTPError as exc:
LOG.error(exc)
sys.exit(2)

if hasattr(result, "text") and result.text[:4] == ")]}'":
return json.loads(result.text[5:])
Expand Down
2 changes: 1 addition & 1 deletion gri/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from gri.console import link

LOG = logging.getLogger(__name__)
LOG = logging.getLogger(__package__)


class Review:
Expand Down
6 changes: 4 additions & 2 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ description = run the tests with pytest under {basepython}
setenv =
PIP_DISABLE_PIP_VERSION_CHECK = 1
VIRTUALENV_NO_DOWNLOAD = 1
# isolate testing to avoid using developer config files:
HOME = {toxworkdir}
passenv =
HOME
PYTEST_*
PYTHONHTTPSVERIFY
REQUESTS_CA_BUNDLE
Expand All @@ -23,7 +24,8 @@ deps =
pip == 19.1.1
whitelist_externals = bash
commands =
gri --config {toxinidir}/test/.gertty.yaml -o report.html owned incoming merged abandon draft watched
gri --help
-gri -o report.html owned incoming merged abandon draft watched

[testenv:lint]
basepython = python3.7
Expand Down

0 comments on commit b586aa0

Please sign in to comment.