Skip to content

Commit 213b6d2

Browse files
authored
fix: check user input config exist or not (#304)
1 parent 5dd8c73 commit 213b6d2

4 files changed

Lines changed: 50 additions & 36 deletions

File tree

commit_check/config.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,16 @@ def load_config(path_hint: str = "") -> Dict[str, Any]:
2222
"""Load and validate config from TOML file."""
2323
if path_hint:
2424
p = Path(path_hint)
25-
if p.exists():
26-
with open(p, "rb") as f:
27-
return toml_load(f)
25+
if not p.exists():
26+
raise FileNotFoundError(f"Specified config file not found: {path_hint}")
27+
with open(p, "rb") as f:
28+
return toml_load(f)
29+
30+
# Check default config paths only when no specific path is provided
2831
for candidate in DEFAULT_CONFIG_PATHS:
2932
if candidate.exists():
3033
with open(candidate, "rb") as f:
3134
return toml_load(f)
32-
raise FileNotFoundError("No config file found (cchk.toml or commit-check.toml)")
35+
36+
# Return empty config if no default config files found
37+
return {}

commit_check/main.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,8 @@ def main() -> int:
135135
stdin_reader = StdinReader()
136136

137137
try:
138-
# Load configuration (fallback to defaults when no file found)
139-
try:
140-
config_data = load_config(args.config)
141-
except FileNotFoundError:
142-
config_data = {}
138+
# Load configuration
139+
config_data = load_config(args.config)
143140

144141
# Build validation rules from config
145142
rule_builder = RuleBuilder(config_data)
@@ -220,6 +217,9 @@ def main() -> int:
220217
# Return appropriate exit code
221218
return 0 if result == ValidationResult.PASS else 1
222219

220+
except FileNotFoundError as e:
221+
print(f"Error: {e}", file=sys.stderr)
222+
return 1
223223
except Exception as e:
224224
print(f"Error: {e}", file=sys.stderr)
225225
return 1

tests/config_test.py

Lines changed: 15 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -29,26 +29,12 @@ def test_load_config_with_path_hint(self):
2929
os.unlink(f.name)
3030

3131
def test_load_config_with_nonexistent_path_hint(self):
32-
"""Test loading config when path hint doesn't exist, falls back to default paths."""
33-
# Create a temporary cchk.toml in current directory
34-
config_content = b"""
35-
[checks]
36-
fallback = true
37-
"""
38-
original_cwd = os.getcwd()
39-
with tempfile.TemporaryDirectory() as tmpdir:
40-
os.chdir(tmpdir)
41-
try:
42-
# Create cchk.toml in temp directory
43-
with open("cchk.toml", "wb") as f:
44-
f.write(config_content)
45-
46-
# Try to load with nonexistent path hint
47-
config = load_config("nonexistent.toml")
48-
assert "checks" in config
49-
assert config["checks"]["fallback"] is True
50-
finally:
51-
os.chdir(original_cwd)
32+
"""Test loading config when path hint doesn't exist - should raise FileNotFoundError."""
33+
# Test that specifying a nonexistent config file raises an error
34+
with pytest.raises(
35+
FileNotFoundError, match="Specified config file not found: nonexistent.toml"
36+
):
37+
load_config("nonexistent.toml")
5238

5339
def test_load_config_default_cchk_toml(self):
5440
"""Test loading config from default cchk.toml path."""
@@ -89,23 +75,27 @@ def test_load_config_default_commit_check_toml(self):
8975
os.chdir(original_cwd)
9076

9177
def test_load_config_file_not_found(self):
92-
"""Test FileNotFoundError when no config files exist."""
78+
"""Test returning empty config when no default config files exist."""
9379
original_cwd = os.getcwd()
9480
with tempfile.TemporaryDirectory() as tmpdir:
9581
os.chdir(tmpdir)
9682
try:
97-
with pytest.raises(FileNotFoundError, match="No config file found"):
98-
load_config()
83+
# Should return empty config when no default files exist
84+
config = load_config()
85+
assert config == {}
9986
finally:
10087
os.chdir(original_cwd)
10188

10289
def test_load_config_file_not_found_with_invalid_path_hint(self):
103-
"""Test FileNotFoundError when path hint and default paths don't exist."""
90+
"""Test FileNotFoundError when specified path hint doesn't exist."""
10491
original_cwd = os.getcwd()
10592
with tempfile.TemporaryDirectory() as tmpdir:
10693
os.chdir(tmpdir)
10794
try:
108-
with pytest.raises(FileNotFoundError, match="No config file found"):
95+
with pytest.raises(
96+
FileNotFoundError,
97+
match="Specified config file not found: nonexistent.toml",
98+
):
10999
load_config("nonexistent.toml")
110100
finally:
111101
os.chdir(original_cwd)

tests/main_test.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,9 @@ def test_main_with_invalid_config_file(self, mocker):
237237
"--message", # empty -> read from stdin
238238
]
239239

240-
# This should not crash, just use default config
240+
# This should fail with proper error message when config file doesn't exist
241241
result = main()
242-
assert result == 0
242+
assert result == 1
243243

244244
# Removed problematic tests that had configuration dependency issues
245245

@@ -276,3 +276,22 @@ def test_main_error_handling_subprocess_failure(self, mocker, capsys):
276276
result = main()
277277
# Even if subprocess fails, main should not crash
278278
assert result in [0, 1] # Either passes or fails gracefully
279+
280+
def test_nonexistent_config_file_error(self, capsys):
281+
"""Test that specifying a non-existent config file returns error."""
282+
sys.argv = [
283+
"commit-check",
284+
"--config",
285+
"/nonexistent/config.toml",
286+
"--message",
287+
"feat: test",
288+
]
289+
290+
result = main()
291+
assert result == 1
292+
293+
captured = capsys.readouterr()
294+
assert (
295+
"Error: Specified config file not found: /nonexistent/config.toml"
296+
in captured.err
297+
)

0 commit comments

Comments
 (0)