From 7b1cfd1c104494c43904012e4c266c477a2dd446 Mon Sep 17 00:00:00 2001 From: Nguyen Duc Huy Date: Thu, 28 May 2026 17:41:05 +0200 Subject: [PATCH] Handle missing config file gracefully --- README.md | 1 + task.py | 22 ++++++++++++++++++---- test_task.py | 14 ++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 91da9a7..2455e2d 100644 --- a/README.md +++ b/README.md @@ -34,3 +34,4 @@ python -m pytest test_task.py ## Configuration Copy `config.yaml.example` to `~/.config/task-cli/config.yaml` and customize. +If the config file is missing, Task CLI creates a default config automatically. diff --git a/task.py b/task.py index 53cc8ed..e78f34c 100644 --- a/task.py +++ b/task.py @@ -10,12 +10,25 @@ from commands.done import mark_done +DEFAULT_CONFIG = """# Task CLI configuration +storage: local +""" + + +def get_config_path(): + """Return the user config path.""" + return Path.home() / ".config" / "task-cli" / "config.yaml" + + def load_config(): """Load configuration from file.""" - config_path = Path.home() / ".config" / "task-cli" / "config.yaml" - # NOTE: This will crash if config doesn't exist - known bug for bounty testing - with open(config_path) as f: - return f.read() + config_path = get_config_path() + + if not config_path.exists(): + config_path.parent.mkdir(parents=True, exist_ok=True) + config_path.write_text(DEFAULT_CONFIG) + + return config_path.read_text() def main(): @@ -34,6 +47,7 @@ def main(): done_parser.add_argument("task_id", type=int, help="Task ID to mark done") args = parser.parse_args() + load_config() if args.command == "add": add_task(args.description) diff --git a/test_task.py b/test_task.py index ba98e43..871ee7b 100644 --- a/test_task.py +++ b/test_task.py @@ -5,6 +5,7 @@ from pathlib import Path from commands.add import add_task, validate_description from commands.done import validate_task_id +from task import DEFAULT_CONFIG, get_config_path, load_config def test_validate_description(): @@ -28,3 +29,16 @@ def test_validate_task_id(): with pytest.raises(ValueError): validate_task_id(tasks, 99) + + +def test_load_config_creates_default_when_missing(tmp_path, monkeypatch): + """Missing config should be created instead of crashing.""" + monkeypatch.setattr(Path, "home", lambda: tmp_path) + + config_path = get_config_path() + assert not config_path.exists() + + config = load_config() + + assert config == DEFAULT_CONFIG + assert config_path.read_text() == DEFAULT_CONFIG