Option C Tools
Loading...
Searching...
No Matches
oct.formatter.oct_format Namespace Reference

Classes

class  FormatterContext

Functions

list[Path] _git_changed_files (Path root)
str _get_relative_path (Path path, Path root)
int _prune_archive (Path archive_dir, str original_name, int max_backups)
int _prune_archive_by_size (Path archive_dir, int max_total_bytes)
None _archive_file (Path path, int max_backups=_DEFAULT_MAX_BACKUPS_PER_FILE, int max_archive_bytes=_DEFAULT_MAX_ARCHIVE_BYTES)
str _detect_indent_style (List[str] lines)
str _get_indent_at_line (List[str] lines, int line_num, str fallback=" ")
List[str] _detect_missing_docstring_sections (str text)
Tuple[bool, str, List[str]] fix_header_block (Path path, str text, FormatterContext ctx)
Tuple[bool, str, List[str]] fix_docstring (Path path, str text, FormatterContext ctx)
Tuple[bool, str, List[str]] fix_dbg_import (Path path, str text, FormatterContext ctx)
Tuple[bool, str, List[str]] fix_func_pattern (Path path, str text, FormatterContext ctx)
Dict[str, Any] format_file (Path path, FormatterContext ctx)
Dict[str, Any] compute_summary (List[Dict[str, Any]] file_results)
None _print_terminal_report (Dict[str, Any] summary, List[Dict[str, Any]] file_results, bool verbose, bool dry_run)
None _print_json_report (Dict[str, Any] summary, List[Dict[str, Any]] file_results, FormatterContext ctx)
None run_formatter (Path project_root, Optional[List[str]] argv=None)

Variables

str SHEBANG = "#!/usr/bin/env python3"
str ENCODING = "# -*- coding: utf-8 -*-"
str IMPORT_BLOCK = "from oc_diagnostics import _dbg\n"
str DOCSTRING_SKELETON
dict MISSING_DOCSTRING_SECTIONS
int _DEFAULT_MAX_BACKUPS_PER_FILE = 10
int _DEFAULT_MAX_ARCHIVE_BYTES = 5 * 1024 * 1024
 project_root = find_project_root(Path.cwd())

Detailed Description

Option C auto-formatter implementation.

Purpose
-------
Detect and fix structural Option C compliance violations automatically.
Complements the linter by fixing violations while preserving code semantics.

Responsibilities
----------------
- Detect formatting violations using reused linter checks.
- Fix violations: headers, docstrings, imports, function patterns.
- Support report-only (dry-run) and fix modes.
- Archive originals before modification.
- Provide terminal and JSON output.
- Respect project exclusions and configuration.

Diagnostics
-----------
Domain: OCT.FORMATTER
Levels:
    L2 — formatter lifecycle and command routing
    L3 — file discovery and processing, fix application decisions
    L4 — detailed fixer implementations, archival operations, output formatting

Contracts
---------
- Files are only modified if fix_mode is True.
- Originals are archived before any modification.
- All code below headers is preserved exactly.
- Docstrings are not replaced; missing sections are appended.
- Each fixer is idempotent (running twice is same as once).

Dependencies
------------
- oct (package version)
- oct.linter.oct_lint (reused validation checks)
- oct.core.exclusions (directory and wildcard exclusion lists)
- oct.core.project_root (project root detection)
- oct.core.parsing (safe AST parsing helper)
- oct.core.git (git changed-file discovery)

Function Documentation

◆ _archive_file()

None oct.formatter.oct_format._archive_file ( Path path,
int max_backups = _DEFAULT_MAX_BACKUPS_PER_FILE,
int max_archive_bytes = _DEFAULT_MAX_ARCHIVE_BYTES )
protected
Archive original file to ``.formatter_archive/`` with timestamp.

After writing the new backup, prune in two passes:

1. Per-file count cap (OI-424): keep only the N newest backups per
   source file name.
2. Per-directory size cap (OI-516): enforce aggregate ``max_archive_bytes``
   across *all* backups in the archive, evicting oldest first.

Definition at line 255 of file oct_format.py.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _detect_indent_style()

str oct.formatter.oct_format._detect_indent_style ( List[str] lines)
protected
Return the dominant body indentation unit used in the file.

Returns ``"\\t"`` if the file uses tabs for body indentation more
often than spaces, otherwise ``"    "`` (four spaces). Only
considers lines with a non-whitespace character so blank lines do
not skew the result (OI-425).

Definition at line 279 of file oct_format.py.

Here is the caller graph for this function:

◆ _detect_missing_docstring_sections()

List[str] oct.formatter.oct_format._detect_missing_docstring_sections ( str text)
protected
Detect which docstring sections are missing.

Definition at line 318 of file oct_format.py.

Here is the caller graph for this function:

◆ _get_indent_at_line()

str oct.formatter.oct_format._get_indent_at_line ( List[str] lines,
int line_num,
str fallback = "    " )
protected
Return the indentation string of a given line.

If the requested line is out of range or whitespace-only, return
``fallback``. The default fallback preserves the historical four-
space behaviour, so existing callers remain unchanged (OI-425).

Definition at line 300 of file oct_format.py.

Here is the caller graph for this function:

◆ _get_relative_path()

str oct.formatter.oct_format._get_relative_path ( Path path,
Path root )
protected
Get relative path from root to path.

Definition at line 176 of file oct_format.py.

Here is the caller graph for this function:

◆ _git_changed_files()

list[Path] oct.formatter.oct_format._git_changed_files ( Path root)
protected
Return .py files modified in the git working tree (staged + unstaged).

Thin shim over :func:`oct.core.git.git_changed_files` (Phase 4A).
Collapses all ``GitError`` to empty list so the formatter never
crashes due to git unavailability.

Definition at line 75 of file oct_format.py.

Here is the caller graph for this function:

◆ _print_json_report()

None oct.formatter.oct_format._print_json_report ( Dict[str, Any] summary,
List[Dict[str, Any]] file_results,
FormatterContext ctx )
protected
Print JSON output.

Definition at line 687 of file oct_format.py.

Here is the caller graph for this function:

◆ _print_terminal_report()

None oct.formatter.oct_format._print_terminal_report ( Dict[str, Any] summary,
List[Dict[str, Any]] file_results,
bool verbose,
bool dry_run )
protected
Print human-readable terminal report.

Definition at line 646 of file oct_format.py.

Here is the caller graph for this function:

◆ _prune_archive()

int oct.formatter.oct_format._prune_archive ( Path archive_dir,
str original_name,
int max_backups )
protected
Keep only the ``max_backups`` most recent backups of ``original_name``.

Matches files shaped like ``{original_name}.*.bak`` and sorts them
by mtime (newest first). Older entries beyond the cap are removed.
Best-effort: any OS error is swallowed so a failed prune can never
block ``oct format`` (OI-424).

Returns the number of files removed. ``max_backups <= 0`` disables
pruning entirely (useful when a project deliberately wants unbounded
history).

Definition at line 184 of file oct_format.py.

Here is the caller graph for this function:

◆ _prune_archive_by_size()

int oct.formatter.oct_format._prune_archive_by_size ( Path archive_dir,
int max_total_bytes )
protected
OI-516: evict oldest ``.bak`` files until total size fits under ``max_total_bytes``.

Runs *after* per-file count pruning so the archive floor is always
correct under the two coexisting policies. Any OS error on size or
unlink is swallowed — a rotation failure must never block formatting.
Returns the number of files removed.

Definition at line 219 of file oct_format.py.

Here is the caller graph for this function:

◆ compute_summary()

Dict[str, Any] oct.formatter.oct_format.compute_summary ( List[Dict[str, Any]] file_results)
Aggregate results into summary.

Definition at line 618 of file oct_format.py.

Here is the caller graph for this function:

◆ fix_dbg_import()

Tuple[bool, str, List[str]] oct.formatter.oct_format.fix_dbg_import ( Path path,
str text,
FormatterContext ctx )
Ensure canonical _dbg import exists at module level.

Skips trivial files (< 20 lines).

Definition at line 428 of file oct_format.py.

◆ fix_docstring()

Tuple[bool, str, List[str]] oct.formatter.oct_format.fix_docstring ( Path path,
str text,
FormatterContext ctx )
Ensure module has complete docstring with all required sections.

If no docstring: insert skeleton.
If incomplete: add missing sections.
If complete: no change.

Definition at line 386 of file oct_format.py.

Here is the call graph for this function:

◆ fix_func_pattern()

Tuple[bool, str, List[str]] oct.formatter.oct_format.fix_func_pattern ( Path path,
str text,
FormatterContext ctx )
Ensure every function with _dbg() calls has func = "function_name" as first statement.

Delegates violation detection to :func:`oct.linter.oct_lint.find_func_pattern_violations`
so the linter remains the single source of truth for what constitutes a
func-pattern violation.  This function only handles the fix (inserting
the ``func = "..."`` line).

Skips trivial files (< 20 lines).

Definition at line 479 of file oct_format.py.

Here is the call graph for this function:

◆ fix_header_block()

Tuple[bool, str, List[str]] oct.formatter.oct_format.fix_header_block ( Path path,
str text,
FormatterContext ctx )
Ensure file has correct 4-line header block.

Returns (changed, new_text, messages). Caller is responsible for
archiving and writing to disk.

Definition at line 339 of file oct_format.py.

Here is the call graph for this function:

◆ format_file()

Dict[str, Any] oct.formatter.oct_format.format_file ( Path path,
FormatterContext ctx )
Process a single file through all formatters.

Definition at line 560 of file oct_format.py.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ run_formatter()

None oct.formatter.oct_format.run_formatter ( Path project_root,
Optional[List[str]] argv = None )
Run the Option C formatter on the given project root.

Parameters
----------
project_root : Path
    The detected Option C project root directory.
argv : list[str] | None
    Optional list of command-line arguments.
    If None, argparse will use sys.argv[1:].

Definition at line 709 of file oct_format.py.

Here is the call graph for this function:

Variable Documentation

◆ _DEFAULT_MAX_ARCHIVE_BYTES

int oct.formatter.oct_format._DEFAULT_MAX_ARCHIVE_BYTES = 5 * 1024 * 1024
protected

Definition at line 150 of file oct_format.py.

◆ _DEFAULT_MAX_BACKUPS_PER_FILE

int oct.formatter.oct_format._DEFAULT_MAX_BACKUPS_PER_FILE = 10
protected

Definition at line 145 of file oct_format.py.

◆ DOCSTRING_SKELETON

str oct.formatter.oct_format.DOCSTRING_SKELETON
Initial value:
1= '''\
2"""
3Purpose
4-------
5Describe the purpose of this module.
6
7Responsibilities
8----------------
9- List the responsibilities of this module.
10
11Diagnostics
12-----------
13Domain: <DOMAIN>
14Levels:
15 L2 — lifecycle
16 L3 — semantic details
17 L4 — deep tracing
18
19Contracts
20---------
21- State the contracts and guarantees of this module.
22"""
23'''

Definition at line 94 of file oct_format.py.

◆ ENCODING

str oct.formatter.oct_format.ENCODING = "# -*- coding: utf-8 -*-"

Definition at line 90 of file oct_format.py.

◆ IMPORT_BLOCK

str oct.formatter.oct_format.IMPORT_BLOCK = "from oc_diagnostics import _dbg\n"

Definition at line 92 of file oct_format.py.

◆ MISSING_DOCSTRING_SECTIONS

dict oct.formatter.oct_format.MISSING_DOCSTRING_SECTIONS
Initial value:
1= {
2 "Purpose": ,
3 "Responsibilities": ,
4 "Diagnostics": ,
5 "Contracts": ,
6}

Definition at line 118 of file oct_format.py.

◆ project_root

oct.formatter.oct_format.project_root = find_project_root(Path.cwd())

Definition at line 839 of file oct_format.py.

◆ SHEBANG

str oct.formatter.oct_format.SHEBANG = "#!/usr/bin/env python3"

Definition at line 89 of file oct_format.py.