Skip to content

Commit fa81793

Browse files
author
catlog22
committed
refactor: 优化异常处理,使用 cached_property 替代 property,增强代码可读性;添加 RelationshipType 枚举以规范化关系类型
1 parent c12ef3e commit fa81793

File tree

3 files changed

+13
-112
lines changed

3 files changed

+13
-112
lines changed

codex-lens/src/codexlens/cli/commands.py

Lines changed: 0 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -248,12 +248,6 @@ def progress_update(msg: str):
248248
else:
249249
console.print(f"[red]Init failed:[/red] {exc}")
250250
raise typer.Exit(code=1)
251-
except Exception as exc:
252-
if json_mode:
253-
print_json(success=False, error=f"Unexpected error: {exc}")
254-
else:
255-
console.print(f"[red]Init failed (unexpected):[/red] {exc}")
256-
raise typer.Exit(code=1)
257251
finally:
258252
if registry is not None:
259253
registry.close()
@@ -457,12 +451,6 @@ def search(
457451
else:
458452
console.print(f"[red]Search failed:[/red] {exc}")
459453
raise typer.Exit(code=1)
460-
except Exception as exc:
461-
if json_mode:
462-
print_json(success=False, error=f"Unexpected error: {exc}")
463-
else:
464-
console.print(f"[red]Search failed (unexpected):[/red] {exc}")
465-
raise typer.Exit(code=1)
466454
finally:
467455
if registry is not None:
468456
registry.close()
@@ -522,12 +510,6 @@ def symbol(
522510
else:
523511
console.print(f"[red]Symbol lookup failed:[/red] {exc}")
524512
raise typer.Exit(code=1)
525-
except Exception as exc:
526-
if json_mode:
527-
print_json(success=False, error=f"Unexpected error: {exc}")
528-
else:
529-
console.print(f"[red]Symbol lookup failed (unexpected):[/red] {exc}")
530-
raise typer.Exit(code=1)
531513
finally:
532514
if registry is not None:
533515
registry.close()
@@ -583,12 +565,6 @@ def inspect(
583565
else:
584566
console.print(f"[red]Inspect failed:[/red] {exc}")
585567
raise typer.Exit(code=1)
586-
except Exception as exc:
587-
if json_mode:
588-
print_json(success=False, error=f"Unexpected error: {exc}")
589-
else:
590-
console.print(f"[red]Inspect failed (unexpected):[/red] {exc}")
591-
raise typer.Exit(code=1)
592568

593569

594570
@app.command()
@@ -727,12 +703,6 @@ def status(
727703
else:
728704
console.print(f"[red]Status failed:[/red] {exc}")
729705
raise typer.Exit(code=1)
730-
except Exception as exc:
731-
if json_mode:
732-
print_json(success=False, error=f"Unexpected error: {exc}")
733-
else:
734-
console.print(f"[red]Status failed (unexpected):[/red] {exc}")
735-
raise typer.Exit(code=1)
736706
finally:
737707
if registry is not None:
738708
registry.close()
@@ -884,12 +854,6 @@ def projects(
884854
else:
885855
console.print(f"[red]Projects command failed:[/red] {exc}")
886856
raise typer.Exit(code=1)
887-
except Exception as exc:
888-
if json_mode:
889-
print_json(success=False, error=f"Unexpected error: {exc}")
890-
else:
891-
console.print(f"[red]Projects command failed (unexpected):[/red] {exc}")
892-
raise typer.Exit(code=1)
893857
finally:
894858
if registry is not None:
895859
registry.close()
@@ -1060,12 +1024,6 @@ def save_config(cfg: Dict[str, Any]) -> None:
10601024
else:
10611025
console.print(f"[red]Config command failed:[/red] {exc}")
10621026
raise typer.Exit(code=1)
1063-
except Exception as exc:
1064-
if json_mode:
1065-
print_json(success=False, error=f"Unexpected error: {exc}")
1066-
else:
1067-
console.print(f"[red]Config command failed (unexpected):[/red] {exc}")
1068-
raise typer.Exit(code=1)
10691027

10701028

10711029
@app.command()
@@ -1192,12 +1150,6 @@ def migrate(
11921150
else:
11931151
console.print(f"[red]Migration failed:[/red] {exc}")
11941152
raise typer.Exit(code=1)
1195-
except Exception as exc:
1196-
if json_mode:
1197-
print_json(success=False, error=f"Unexpected error: {exc}")
1198-
else:
1199-
console.print(f"[red]Migration failed (unexpected):[/red] {exc}")
1200-
raise typer.Exit(code=1)
12011153
finally:
12021154
if registry is not None:
12031155
registry.close()
@@ -1346,12 +1298,6 @@ def clean(
13461298
else:
13471299
console.print(f"[red]Clean failed:[/red] {exc}")
13481300
raise typer.Exit(code=1)
1349-
except Exception as exc:
1350-
if json_mode:
1351-
print_json(success=False, error=f"Unexpected error: {exc}")
1352-
else:
1353-
console.print(f"[red]Clean failed (unexpected):[/red] {exc}")
1354-
raise typer.Exit(code=1)
13551301

13561302

13571303
@app.command("semantic-list")
@@ -1472,12 +1418,6 @@ def semantic_list(
14721418
else:
14731419
console.print(f"[red]Semantic-list failed:[/red] {exc}")
14741420
raise typer.Exit(code=1)
1475-
except Exception as exc:
1476-
if json_mode:
1477-
print_json(success=False, error=f"Unexpected error: {exc}")
1478-
else:
1479-
console.print(f"[red]Semantic-list failed (unexpected):[/red] {exc}")
1480-
raise typer.Exit(code=1)
14811421
finally:
14821422
if registry is not None:
14831423
registry.close()
@@ -1549,12 +1489,6 @@ def model_list(
15491489
console.print("[red]Error:[/red] fastembed not installed")
15501490
console.print("[yellow]Install with:[/yellow] pip install codexlens[semantic]")
15511491
raise typer.Exit(code=1)
1552-
except Exception as exc:
1553-
if json_mode:
1554-
print_json(success=False, error=str(exc))
1555-
else:
1556-
console.print(f"[red]Model-list failed:[/red] {exc}")
1557-
raise typer.Exit(code=1)
15581492

15591493

15601494
@app.command(name="model-download")
@@ -1600,12 +1534,6 @@ def model_download(
16001534
console.print("[red]Error:[/red] fastembed not installed")
16011535
console.print("[yellow]Install with:[/yellow] pip install codexlens[semantic]")
16021536
raise typer.Exit(code=1)
1603-
except Exception as exc:
1604-
if json_mode:
1605-
print_json(success=False, error=str(exc))
1606-
else:
1607-
console.print(f"[red]Model-download failed:[/red] {exc}")
1608-
raise typer.Exit(code=1)
16091537

16101538

16111539
@app.command(name="model-delete")
@@ -1639,13 +1567,6 @@ def model_delete(
16391567
console.print(f" Model: {data['model_name']}")
16401568
console.print(f" Freed space: {data['deleted_size_mb']:.1f} MB")
16411569

1642-
except Exception as exc:
1643-
if json_mode:
1644-
print_json(success=False, error=str(exc))
1645-
else:
1646-
console.print(f"[red]Model-delete failed:[/red] {exc}")
1647-
raise typer.Exit(code=1)
1648-
16491570

16501571
@app.command(name="model-info")
16511572
def model_info(
@@ -1682,13 +1603,6 @@ def model_info(
16821603
console.print(f"\n Description: {data['description']}")
16831604
console.print(f" Use case: {data['use_case']}")
16841605

1685-
except Exception as exc:
1686-
if json_mode:
1687-
print_json(success=False, error=str(exc))
1688-
else:
1689-
console.print(f"[red]Model-info failed:[/red] {exc}")
1690-
raise typer.Exit(code=1)
1691-
16921606

16931607
# ==================== Embedding Management Commands ====================
16941608

@@ -1821,13 +1735,6 @@ def embeddings_status(
18211735
console.print("\n[dim]Generate embeddings with:[/dim]")
18221736
console.print(f" [cyan]codexlens embeddings-generate {index_path}[/cyan]")
18231737

1824-
except Exception as exc:
1825-
if json_mode:
1826-
print_json(success=False, error=str(exc))
1827-
else:
1828-
console.print(f"[red]Embeddings-status failed:[/red] {exc}")
1829-
raise typer.Exit(code=1)
1830-
18311738

18321739
@app.command(name="embeddings-generate")
18331740
def embeddings_generate(
@@ -2011,10 +1918,3 @@ def progress_update(msg: str):
20111918

20121919
console.print("\n[dim]Use vector search with:[/dim]")
20131920
console.print(" [cyan]codexlens search 'your query' --mode pure-vector[/cyan]")
2014-
2015-
except Exception as exc:
2016-
if json_mode:
2017-
print_json(success=False, error=str(exc))
2018-
else:
2019-
console.print(f"[red]Embeddings-generate failed:[/red] {exc}")
2020-
raise typer.Exit(code=1)

codex-lens/src/codexlens/config.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import os
66
from dataclasses import dataclass, field
7+
from functools import cached_property
78
from pathlib import Path
89
from typing import Any, Dict, List, Optional
910

@@ -96,17 +97,17 @@ def __post_init__(self) -> None:
9697
except Exception as exc:
9798
raise ConfigError(f"Failed to initialize data_dir at {self.data_dir}: {exc}") from exc
9899

99-
@property
100+
@cached_property
100101
def cache_dir(self) -> Path:
101102
"""Directory for transient caches."""
102103
return self.data_dir / "cache"
103104

104-
@property
105+
@cached_property
105106
def index_dir(self) -> Path:
106107
"""Directory where index artifacts are stored."""
107108
return self.data_dir / "index"
108109

109-
@property
110+
@cached_property
110111
def db_path(self) -> Path:
111112
"""Default SQLite index path."""
112113
return self.index_dir / "codexlens.db"

codex-lens/src/codexlens/entities.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
from enum import Enum
56
from typing import Any, Dict, List, Optional, Tuple
67

78
from pydantic import BaseModel, Field, field_validator
@@ -62,24 +63,23 @@ def strip_and_validate_nonempty(cls, value: str) -> str:
6263
return cleaned
6364

6465

66+
class RelationshipType(str, Enum):
67+
"""Types of code relationships."""
68+
CALL = "call"
69+
INHERITS = "inherits"
70+
IMPORTS = "imports"
71+
72+
6573
class CodeRelationship(BaseModel):
6674
"""A relationship between code symbols (e.g., function calls, inheritance)."""
6775

6876
source_symbol: str = Field(..., min_length=1, description="Name of source symbol")
6977
target_symbol: str = Field(..., min_length=1, description="Name of target symbol")
70-
relationship_type: str = Field(..., min_length=1, description="Type of relationship (call, inherits, etc.)")
78+
relationship_type: RelationshipType = Field(..., description="Type of relationship (call, inherits, etc.)")
7179
source_file: str = Field(..., min_length=1, description="File path containing source symbol")
7280
target_file: Optional[str] = Field(default=None, description="File path containing target (None if same file)")
7381
source_line: int = Field(..., ge=1, description="Line number where relationship occurs (1-based)")
7482

75-
@field_validator("relationship_type")
76-
@classmethod
77-
def validate_relationship_type(cls, value: str) -> str:
78-
allowed_types = {"call", "inherits", "imports"}
79-
if value not in allowed_types:
80-
raise ValueError(f"relationship_type must be one of {allowed_types}")
81-
return value
82-
8383

8484
class AdditionalLocation(BaseModel):
8585
"""A pointer to another location where a similar result was found.

0 commit comments

Comments
 (0)