From fa4ddcb740637bec29220f29c0929be78ec241a0 Mon Sep 17 00:00:00 2001 From: NguyenTienDat-GTR Date: Wed, 20 May 2026 16:50:25 +0700 Subject: [PATCH] Handle missing task CLI config --- README.md | 2 +- task.py | 26 ++++++++++++++++++++++---- test_task.py | 17 +++++++++++++++-- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 91da9a7..66ab80f 100644 --- a/README.md +++ b/README.md @@ -33,4 +33,4 @@ python -m pytest test_task.py ## Configuration -Copy `config.yaml.example` to `~/.config/task-cli/config.yaml` and customize. +On first config load, the CLI creates `~/.config/task-cli/config.yaml` with default settings if it is missing. To customize the defaults manually, copy `config.yaml.example` to that path and edit it. diff --git a/task.py b/task.py index 53cc8ed..3c121c5 100644 --- a/task.py +++ b/task.py @@ -10,12 +10,30 @@ from commands.done import mark_done +DEFAULT_CONFIG = """# Default configuration for task CLI +storage: + format: json + max_tasks: 1000 + +display: + color: true + unicode: true +""" + + +def get_config_path(): + """Return the default configuration file 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, encoding="utf-8") + + return config_path.read_text(encoding="utf-8") def main(): diff --git a/test_task.py b/test_task.py index ba98e43..7c92289 100644 --- a/test_task.py +++ b/test_task.py @@ -1,8 +1,8 @@ """Basic tests for task CLI.""" -import json import pytest -from pathlib import Path + +import task from commands.add import add_task, validate_description from commands.done import validate_task_id @@ -28,3 +28,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 initialized instead of crashing.""" + monkeypatch.setattr(task.Path, "home", staticmethod(lambda: tmp_path)) + config_path = tmp_path / ".config" / "task-cli" / "config.yaml" + + assert not config_path.exists() + + config = task.load_config() + + assert config == task.DEFAULT_CONFIG + assert config_path.read_text(encoding="utf-8") == task.DEFAULT_CONFIG