Skip to content

Commit edc5ce2

Browse files
committed
[chore:docs] Update all docstring in files
1 parent 5966965 commit edc5ce2

File tree

13 files changed

+367
-66
lines changed

13 files changed

+367
-66
lines changed

src/code_validator/__init__.py

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,57 @@
11
"""A flexible framework for static validation of Python code.
22
3-
This package provides a comprehensive toolkit for statically analyzing Python source
4-
code based on a declarative set of rules defined in a JSON format. It allows
5-
for checking syntax, style, structure, and constraints without executing the code.
6-
7-
Key components exposed by this package include:
8-
- StaticValidator: The main orchestrator for running the validation process.
9-
- AppConfig: A dataclass for configuring the validator's behavior.
10-
- ExitCode: An Enum defining exit codes for CLI operations.
11-
- Custom Exceptions: For fine-grained error handling during validation.
3+
This package provides a comprehensive toolkit for statically analyzing Python
4+
source code based on a declarative set of rules defined in a JSON format. It
5+
allows for checking syntax, style, structure, and constraints without
6+
executing the code.
7+
8+
The primary entry point for using this package programmatically is the
9+
`StaticValidator` class.
10+
11+
Example:
12+
A minimal example of using the validator as a library.
13+
14+
.. code-block:: python
15+
16+
from code_validator import StaticValidator, AppConfig, LogLevel
17+
from code_validator.output import Console, setup_logging
18+
from pathlib import Path
19+
20+
# Basic setup
21+
logger = setup_logging(LogLevel.INFO)
22+
console = Console(logger)
23+
config = AppConfig(
24+
solution_path=Path("path/to/solution.py"),
25+
rules_path=Path("path/to/rules.json"),
26+
log_level=LogLevel.INFO,
27+
is_silent=False,
28+
stop_on_first_fail=False
29+
)
30+
31+
# Run validation
32+
validator = StaticValidator(config, console)
33+
is_valid = validator.run()
34+
35+
if is_valid:
36+
print("Validation Passed!")
37+
38+
Attributes:
39+
__version__ (str): The current version of the package.
40+
__all__ (list[str]): The list of public objects exposed by the package.
41+
1242
"""
1343

14-
from .config import AppConfig, ExitCode
44+
from .config import AppConfig, ExitCode, LogLevel
1545
from .core import StaticValidator
1646
from .exceptions import RuleParsingError, ValidationFailedError
1747

1848
__all__ = [
1949
"StaticValidator",
2050
"AppConfig",
2151
"ExitCode",
52+
"LogLevel",
2253
"ValidationFailedError",
2354
"RuleParsingError",
2455
]
25-
__version__ = "0.1.2"
56+
57+
__version__ = "0.1.3"

src/code_validator/__main__.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
1-
"""Enables running the validator as a module.
1+
"""Enables running the validator as a package.
22
33
This file allows the package to be executed directly from the command line
4-
using `python -m code_validator`. It serves as the main entry point
5-
that invokes the command-line interface logic.
4+
using the ``-m`` flag with Python (e.g., ``python -m code_validator``). It
5+
serves as the primary entry point that finds and invokes the command-line
6+
interface logic defined in the `cli` module.
7+
8+
Example:
9+
You can run the validator package like this from the project root:
10+
11+
.. code-block:: bash
12+
13+
python -m code_validator path/to/solution.py path/to/rules.json
14+
615
"""
716

817
from .cli import run_from_cli

src/code_validator/cli.py

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
33
This module is responsible for parsing command-line arguments, setting up the
44
application configuration, and orchestrating the main validation workflow. It acts
5-
as the primary entry point for user interaction.
5+
as the primary entry point for user interaction when the tool is called from
6+
the terminal.
7+
8+
The main function, `run_from_cli`, handles the entire application lifecycle,
9+
including robust top-level error handling to ensure meaningful exit codes.
610
"""
711

812
import argparse
@@ -19,8 +23,13 @@
1923
def setup_arg_parser() -> argparse.ArgumentParser:
2024
"""Creates and configures the argument parser for the CLI.
2125
26+
This function defines all positional and optional arguments that the
27+
`validate-code` command accepts, including their types, help messages,
28+
and default values.
29+
2230
Returns:
23-
An instance of argparse.ArgumentParser with all arguments defined.
31+
argparse.ArgumentParser: A fully configured parser instance ready to
32+
process command-line arguments.
2433
"""
2534
parser = argparse.ArgumentParser(
2635
prog="validate-code",
@@ -32,7 +41,7 @@ def setup_arg_parser() -> argparse.ArgumentParser:
3241
"-l",
3342
"--log-level",
3443
type=LogLevel,
35-
choices=LogLevel,
44+
choices=list(LogLevel),
3645
default=LogLevel.WARNING,
3746
help="Set the logging level (default: WARNING).",
3847
)
@@ -45,14 +54,20 @@ def setup_arg_parser() -> argparse.ArgumentParser:
4554
def run_from_cli() -> None:
4655
"""Runs the full application lifecycle from the command line.
4756
48-
This function parses arguments, initializes logging and configuration,
49-
runs the validator, and handles all top-level exceptions, exiting with an
50-
appropriate exit code.
57+
This is the main entry point for the `validate-code` script. It performs
58+
the following steps:
59+
1. Parses command-line arguments.
60+
2. Initializes the logger, console, and configuration.
61+
3. Instantiates and runs the `StaticValidator`.
62+
4. Handles all top-level exceptions and exits with an appropriate status code.
63+
64+
Raises:
65+
SystemExit: This function will always terminate the process with an
66+
exit code defined in the `ExitCode` enum.
5167
"""
5268
parser = setup_arg_parser()
5369
args = parser.parse_args()
5470

55-
# 1. Setup environment
5671
logger = setup_logging(args.log_level)
5772
console = Console(logger, is_silent=args.silent)
5873
config = AppConfig(
@@ -63,7 +78,6 @@ def run_from_cli() -> None:
6378
stop_on_first_fail=args.stop_on_first_fail,
6479
)
6580

66-
# 2. Run main logic with robust error handling
6781
try:
6882
console.print(f"Starting validation for: {config.solution_path}", level=LogLevel.INFO)
6983
validator = StaticValidator(config, console)

src/code_validator/components/ast_utils.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
"""Provides utility functions for working with Python's Abstract Syntax Trees (AST)."""
1+
"""Provides utility functions for working with Python's Abstract Syntax Trees (AST).
2+
3+
This module contains helper functions that perform common operations on AST nodes,
4+
such as enriching the tree with parent references. These utilities are used by
5+
various components of the validator to simplify complex tree analysis.
6+
"""
27

38
import ast
49

@@ -36,4 +41,4 @@ def get_full_name(node: ast.AST) -> str | None:
3641
if isinstance(node, ast.Attribute):
3742
base = get_full_name(node.value)
3843
return f"{base}.{node.attr}" if base else node.attr
39-
return None
44+
return None

src/code_validator/components/definitions.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
"""Defines the core component interfaces using Protocols.
1+
"""Defines the core component interfaces for the validator using Protocols.
22
33
This module establishes the fundamental "contracts" for the main architectural
4-
components of the validator: Rules, Selectors, and Constraints. By using
5-
Protocols, we ensure that any class conforming to these interfaces can be used
6-
interchangeably by the system's factories and core engine, enabling a flexible
7-
and decoupled plugin-style architecture.
4+
components: Rules, Selectors, and Constraints. By using `typing.Protocol`, we
5+
ensure that any class conforming to these interfaces can be used interchangeably
6+
by the system's factories and core engine. This enables a flexible and
7+
decoupled plugin-style architecture, where new components can be added without
8+
modifying the core logic.
89
"""
910

1011
import ast

src/code_validator/components/factories.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
"""Contains factories for creating rule, selector, and constraint objects.
22
33
This module implements the Factory Method design pattern to decouple the core
4-
validator engine from the concrete implementation of rules. Factories are
5-
responsible for parsing raw dictionary configurations from JSON and instantiating
6-
the appropriate handler classes.
4+
validator engine from the concrete implementations of its components. Factories
5+
are responsible for parsing raw dictionary configurations from the main JSON
6+
rules file and instantiating the appropriate handler classes from the
7+
`rules_library`.
78
"""
89

910
import dataclasses

src/code_validator/components/scope_handler.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
"""Provides functionality to find and isolate specific scopes within an AST.
22
3-
This module contains helper functions that are used by ScopedSelectors to narrow
4-
down their search area from the entire module to a specific function, class,
5-
or method, based on the `in_scope` configuration from a JSON rule.
3+
This module contains a key helper function, `find_scope_node`, which is used
4+
by `ScopedSelector` instances. Its purpose is to traverse the AST and return
5+
a specific subtree (e.g., a function body or class body) based on the
6+
`in_scope` configuration from a JSON rule. This allows rules to be applied
7+
with high precision to specific parts of the source code.
68
"""
79

810
import ast

src/code_validator/config.py

Lines changed: 58 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,15 @@ class LogLevel(StrEnum):
3434

3535
@dataclass(frozen=True)
3636
class AppConfig:
37-
"""Stores the main application configuration from CLI arguments."""
37+
"""Stores the main application configuration from CLI arguments.
38+
39+
Attributes:
40+
solution_path: The file path to the Python solution to be validated.
41+
rules_path: The file path to the JSON rules file.
42+
log_level: The minimum logging level for console output.
43+
is_silent: If True, suppresses all non-log output to stdout.
44+
stop_on_first_fail: If True, halts validation after the first failed rule.
45+
"""
3846

3947
solution_path: Path
4048
rules_path: Path
@@ -45,7 +53,18 @@ class AppConfig:
4553

4654
@dataclass(frozen=True)
4755
class SelectorConfig:
48-
"""Represents the configuration for a Selector component from a JSON rule."""
56+
"""Represents the configuration for a Selector component from a JSON rule.
57+
58+
This dataclass captures all possible keys within the "selector" block
59+
of a JSON validation rule.
60+
61+
Attributes:
62+
type: The type of the selector to be used (e.g., "function_def").
63+
name: A generic name parameter used by many selectors (e.g., the name
64+
of a function, class, or module).
65+
node_type: The AST node type name for the `ast_node` selector.
66+
in_scope: The scope in which to apply the selector.
67+
"""
4968

5069
type: str
5170
name: str | None = None
@@ -55,7 +74,21 @@ class SelectorConfig:
5574

5675
@dataclass(frozen=True)
5776
class ConstraintConfig:
58-
"""Represents the configuration for a Constraint component from a JSON rule."""
77+
"""Represents the configuration for a Constraint component from a JSON rule.
78+
79+
This dataclass captures all possible keys within the "constraint" block
80+
of a JSON validation rule.
81+
82+
Attributes:
83+
type: The type of the constraint to be applied (e.g., "is_required").
84+
count: The exact number of nodes expected. Used by `is_required`.
85+
parent_name: The expected parent class name. Used by `must_inherit_from`.
86+
expected_type: The expected Python type name. Used by `must_be_type`.
87+
allowed_names: A list of permitted names. Used by `name_must_be_in`.
88+
allowed_values: A list of permitted literal values. Used by `value_must_be_in`.
89+
names: A list of expected argument names. Used by `must_have_args`.
90+
exact_match: A boolean flag for argument matching. Used by `must_have_args`.
91+
"""
5992

6093
type: str
6194
count: int | None = None
@@ -69,15 +102,27 @@ class ConstraintConfig:
69102

70103
@dataclass(frozen=True)
71104
class FullRuleCheck:
72-
"""Represents the 'check' block within a full validation rule."""
105+
"""Represents the 'check' block within a full validation rule.
106+
107+
Attributes:
108+
selector: The configuration for the selector component.
109+
constraint: The configuration for the constraint component.
110+
"""
73111

74112
selector: SelectorConfig
75113
constraint: ConstraintConfig
76114

77115

78116
@dataclass(frozen=True)
79117
class ShortRuleConfig:
80-
"""Represents a 'short' (pre-defined) validation rule from JSON."""
118+
"""Represents a 'short' (pre-defined) validation rule from JSON.
119+
120+
Attributes:
121+
rule_id: The unique integer identifier for the rule.
122+
type: The string identifier for the short rule (e.g., "check_syntax").
123+
message: The error message to display if the rule fails.
124+
params: A dictionary of optional parameters for the rule.
125+
"""
81126

82127
rule_id: int
83128
type: str
@@ -87,7 +132,14 @@ class ShortRuleConfig:
87132

88133
@dataclass(frozen=True)
89134
class FullRuleConfig:
90-
"""Represents a 'full' (custom) validation rule with selector and constraint."""
135+
"""Represents a 'full' (custom) validation rule with a selector and constraint.
136+
137+
Attributes:
138+
rule_id: The unique integer identifier for the rule.
139+
message: The error message to display if the rule fails.
140+
check: An object containing the selector and constraint configurations.
141+
is_critical: If True, validation halts if this rule fails.
142+
"""
91143

92144
rule_id: int
93145
message: str

0 commit comments

Comments
 (0)