From 23f0b9f9393aba42c04a4ff09d935063a41ecdad Mon Sep 17 00:00:00 2001 From: Danny Grove Date: Mon, 26 Oct 2020 02:26:38 -0700 Subject: [PATCH] Fix default path for config and parent directories The default path was missing a / causing issues for calls without a -c option. When using the `mtls config` option and the config file or any parent directories don't exist they should be created. --- mtls/cli.py | 19 ++++++++----------- test/test_cli.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/mtls/cli.py b/mtls/cli.py index 662c8c2..79c9f9e 100644 --- a/mtls/cli.py +++ b/mtls/cli.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import os +import pathlib import sys from configparser import ConfigParser from datetime import datetime @@ -104,7 +105,7 @@ def get_gpg_keys_for_email(email): "--config", "-c", type=click.Path(), - default=os.path.join(HOME, "mtls/config.ini"), + default=os.path.join(HOME, "/mtls/config.ini"), help=f"config file. [{HOME}/mtls/config.ini]", ) @click.option("--gpg-password", type=str, hidden=True) @@ -149,16 +150,12 @@ def config(ctx, key, value): config_path = ctx.obj["config_path"] if not os.path.exists(config_path): - if config_path != f"{HOME}/mtls/config.ini": - click.secho( - f"Config file not found, please run `mtls -c {config_path} init`", - fg="red", - ) - else: - click.secho( - "Config file not found, please run `mtls init`", fg="red" - ) - sys.exit(1) + config = ConfigParser() + config["DEFAULT"] = {} + config_dir = pathlib.Path(config_path).parent + config_dir.mkdir(parents=True, exist_ok=True) + with open(config_path, "w") as config_file: + config.write(config_file) if key not in ALLOWED_KEYS: click.secho(AK_MSG, fg="red") diff --git a/test/test_cli.py b/test/test_cli.py index 8fcf3be..b6fbe15 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -1156,3 +1156,38 @@ def test_create_certificate(self): if result.exception: traceback.print_exception(*result.exc_info) self.assertEqual(result.exit_code, 0, msg=result.exc_info) + +class TestCliNoConfig(TestCliBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.env = { + "GNUPGHOME": cls.USER_GNUPGHOME.name, + "HOME": cls.HOME.name, + "XDG_CONFIG_HOME": f"{cls.HOME.name}/.config", + "USER": "test", + "HOST": str(platform.uname()[1]), + } + cls.runner = CliRunner(env=cls.env) + cls.config["DEFAULT"] = { + "name": "John Doe", + "email": "johndoe@example.com", + "fingerprint": cls.user.pgp_key.fingerprint, + "organization_name": "My Org", + } + + def test_add_config_missing_file(self): + config_path = f"{self.env['XDG_CONFIG_HOME']}/mtls/config.ini" + result = self.runner.invoke( + cli, + [ + "-c", + config_path, + "config", + "name", + "\"Test User\"" + ] + ) + if result.exception: + traceback.print_exception(*result.exc_info) + self.assertEqual(result.exit_code, 0, msg=result.exc_info)