~gpanders/gandi-cli

a7b0dacde756e3715f371ad92e6850cac5f85d80 — Greg Anders 2 months ago c10d328
Add command line options to override config file
2 files changed, 40 insertions(+), 43 deletions(-)

M src/gandi/commands/alias.py
M src/gandi/console.py
M src/gandi/commands/alias.py => src/gandi/commands/alias.py +39 -40
@@ 1,6 1,6 @@
import argparse
import json
from typing import Dict, List
from typing import Dict, List, Optional

import requests



@@ 9,58 9,57 @@ from gandi.auth import GandiAuth

def create_command(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
    subparser = parser.add_parser("alias", help="manage email aliases")
    subparser.add_argument("-l", "--list", action="store_true")
    subparser.add_argument("-a", "--add", metavar="ALIAS", type=str)
    subparser.add_argument("-d", "--delete", metavar="ALIAS", type=str)
    subparser.add_argument("-i", "--id", metavar="MAILBOX_ID", type=str)
    subparser.add_argument("-d", "--domain", type=str)

    actions = subparser.add_mutually_exclusive_group(required=True)
    actions.add_argument("-l", "--list", action="store_true")
    actions.add_argument("-a", "--add", metavar="ALIAS", type=str)
    actions.add_argument("-r", "--remove", metavar="ALIAS", type=str)

    subparser.set_defaults(func=alias)
    return subparser


def alias(config: Dict[str, str], auth: GandiAuth, args: argparse.Namespace):
    domain = config["domain"]
    mailbox_id = config["mailbox_id"]
def alias(config: Dict[str, str], auth: GandiAuth, args: argparse.Namespace) -> bool:
    domain = args.domain if args.domain is not None else config["domain"]
    mailbox_id = args.id if args.id is not None else config["mailbox_id"]
    url = f"https://api.gandi.net/v5/email/mailboxes/{domain}/{mailbox_id}"
    if args.list:
        print("\n".join(get_aliases(url, auth)))
    elif args.add:
        if add_alias(url, auth, args.add):
            print(f"Created alias '{args.add}'")
        else:
            print(f"Alias '{args.add}' already exists")

    elif args.delete:
        if delete_alias(url, auth, args.delete):
            print(f"Removed alias '{args.delete}'")
        else:
            print(f"Alias '{args.delete}' does not exist")
    aliases = get_aliases(url, auth)
    if aliases is None:
        return False

    if args.list:
        print("\n".join(aliases))
    else:
        if args.add:
            if args.add in aliases:
                print(f"Alias '{args.add}' already exists")
                return False

def get_aliases(url: str, auth: GandiAuth):
    res = requests.get(url, auth=auth)
    res.raise_for_status()
    data = json.loads(res.text)
    return data["aliases"]
            aliases.append(args.add)
        elif args.remove:
            if args.remove not in aliases:
                print(f"Alias '{args.remove}' does not exist")
                return False

            aliases.remove(args.remove)

def add_alias(url: str, auth: GandiAuth, alias: str):
    aliases = get_aliases(url, auth)
    if alias in aliases:
        return False
        if not update_aliases(url, auth, aliases):
            return False

    aliases.append(alias)
    update_aliases(url, auth, aliases)
    return True


def delete_alias(url: str, auth: GandiAuth, alias: str):
    aliases = get_aliases(url, auth)
    if alias not in aliases:
        return False
def get_aliases(url: str, auth: GandiAuth) -> Optional[List[str]]:
    res = requests.get(url, auth=auth)
    if res.status_code != 200:
        return None

    aliases.remove(alias)
    update_aliases(url, auth, aliases)
    return True
    data = json.loads(res.text)
    return data["aliases"]


def update_aliases(url: str, auth: GandiAuth, aliases: List[str]):
    requests.patch(url, json={"aliases": aliases}, auth=auth).raise_for_status()
def update_aliases(url: str, auth: GandiAuth, aliases: List[str]) -> bool:
    res = requests.patch(url, json={"aliases": aliases}, auth=auth)
    return res.status_code == 200

M src/gandi/console.py => src/gandi/console.py +1 -3
@@ 59,6 59,4 @@ def read_config(conf_file: Path = None) -> Dict[str, str]:
        logging.error("Configuration file %s not found", conf_file)
        sys.exit(1)

    section = "gandi"
    keys = ("api_key", "domain", "mailbox_id")
    return {k: config.get(section, k) for k in keys}
    return config["gandi"]