Skip to content

Commit 828716d

Browse files
committed
fix: Improve error message handling in tree and flatten commands
This commit modifies the error handling in the `tree_command` and `flatten_command` functions to print error messages without Rich markup parsing. The changes ensure that unexpected errors are displayed clearly, even when they contain markup-like characters. Additionally, a new test has been added to verify that exceptions with such characters are handled correctly.
1 parent 65d0f2a commit 828716d

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

src/contextcraft/main.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,8 @@ def tree_command(
176176
except typer.Exit:
177177
raise
178178
except Exception as e:
179-
console.print(f"[bold red]An unexpected error occurred during tree generation: {e}[/bold red]")
179+
console.print("[bold red]An unexpected error occurred during tree generation: [/bold red]", end="")
180+
console.print(str(e), markup=False)
180181
raise typer.Exit(code=1) from e
181182

182183

@@ -279,7 +280,8 @@ def flatten_command(
279280
except typer.Exit:
280281
raise
281282
except Exception as e:
282-
console.print(f"[bold red]An unexpected error occurred during code flattening: {e}[/bold red]")
283+
console.print("[bold red]An unexpected error occurred during code flattening: [/bold red]", end="")
284+
console.print(str(e), markup=False)
283285
raise typer.Exit(code=1) from e
284286

285287

tests/test_main.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,3 +436,24 @@ def test_flatten_integration_with_config_excludes(tmp_path: Path):
436436
assert "# --- File: docs/index.md ---" not in content
437437
assert "print('ignored')" not in content # Content from ignored.py
438438
assert "# Docs" not in content # Content from docs/index.md
439+
440+
441+
# --- Test for exceptions with markup-like chars in the message ---
442+
443+
444+
class ProblematicError(Exception):
445+
def __str__(self):
446+
return "Error with [square brackets] and maybe a backslash \\!"
447+
448+
449+
@mock.patch("src.contextcraft.tools.flattener.flatten_code_logic", side_effect=ProblematicError())
450+
def test_flatten_command_handles_exception_with_markup_chars(mock_flatten_error, tmp_path: Path):
451+
"""Test flatten command handles exceptions with markup-like chars in the message."""
452+
result = runner.invoke(app, ["flatten", str(tmp_path)])
453+
assert result.exit_code == 1
454+
455+
# Verify the original error message is printed (now without markup parsing)
456+
assert "Error with [square brackets] and maybe a backslash \\!" in result.stdout
457+
# Check that no MarkupError occurred and the core message is there:
458+
assert "An unexpected error occurred during code flattening:" in result.stdout
459+
mock_flatten_error.assert_called_once()

0 commit comments

Comments
 (0)