~gpanders/gandi-cli

6c61afabfa669f9312b60883b53b2f3d1492fcc9 — Greg Anders 2 months ago 16fca99
Gracefully handle missing config file

This allows for subcommands that don't need a config file (e.g. a
'setup' command).
2 files changed, 20 insertions(+), 8 deletions(-)

M src/gandi/auth.py
M src/gandi/console.py
M src/gandi/auth.py => src/gandi/auth.py +8 -1
@@ 1,7 1,14 @@
class MissingApiKeyError(Exception):
    pass


class GandiAuth:
    def __init__(self, api_key):
        self.api_key = api_key

    def __call__(self, req):
        req.headers["Authorization"] = f"Apikey {self.api_key}"
        if not self.api_key:
            raise MissingApiKeyError()

        req.headers["Authorization"] = "Apikey {}".format(self.api_key)
        return req

M src/gandi/console.py => src/gandi/console.py +12 -7
@@ 6,7 6,7 @@ import sys
from pathlib import Path

from gandi import __version__, commands
from gandi.auth import GandiAuth
from gandi.auth import GandiAuth, MissingApiKeyError


def run():


@@ 15,9 15,15 @@ def run():
    setup_logging(args)
    config = read_config(args.config)

    auth = GandiAuth(config["api_key"])
    ret = args.func(config, auth, args)
    sys.exit(0 if ret else 1)
    auth = GandiAuth(os.environ.get("GANDI_API_KEY", config.get("apikey")))
    try:
        # Not all subcommands need the API key, so we won't know whether or not we need
        # it until we actually run the subcommand function
        ret = args.func(config, auth, args)
        sys.exit(0 if ret else 1)
    except MissingApiKeyError:
        print("Missing API key")
        sys.exit(1)


def parse_args():


@@ 59,10 65,9 @@ def read_config(conf_file=None):

    config = configparser.ConfigParser()
    try:
        with conf_file.open() as fil:
        with conf_file.open("r") as fil:
            config.read_file(fil)
    except FileNotFoundError:
        logging.error("Configuration file %s not found", conf_file)
        sys.exit(1)
        config.read_dict({"gandi": {}})

    return config["gandi"]