Skip to content

CLI

Argument parser

parser

get_parser

get_parser()
Source code in docstr_health/cli/parser.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def get_parser():
    parser = argparse.ArgumentParser(
        prog="docstr-health",
        description="Health score and visualization for Python projects.",
    )

    parser.add_argument(
        "project_path",
        type=Path,
        nargs="?",
        default=Path("."),
        help="Path to the directory to check.",
    )

    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {__version__}",
        help="Show version and exit.",
    )

    main_group = parser.add_argument_group("basic parameters")

    main_group.add_argument(
        "--repo-url",
        type=str,
        help="Scan a project from a remote Git repository.",
    )

    main_group.add_argument(
        "--pypi-package",
        type=str,
        help="Scan a project from a remote PyPi package.",
    )

    main_group.add_argument(
        "--cache-dir",
        type=Path,
        default=config.get_cache_dir(),
        help=f"Directory for cached repositories (default: {config.get_cache_dir()})",
    )

    parser.add_argument(
        "--no-cache",
        action="store_true",
        help="Do not save cache for remote repositories.",
    )

    parser.add_argument(
        "--compact",
        action="store_true",
        help="Display only general statistics, hiding the list of functions.",
    )

    parser.add_argument(
        "--doc-modules",
        action="store_true",
        help="Check __doc__ of the files themselves",
    )

    parser.add_argument(
        "--ignore-tests",
        action="store_true",
        help="Ignore Test Units",
    )

    parser.add_argument(
        "--short-names",
        action="store_true",
        help="Replaces full path to the file with short ones",
    )

    parser.add_argument(
        "--ci",
        action="store_true",
        help="CI mode suppress output, exit 1 if status ≤ failure_level",
    )

    measurement_group = parser.add_argument_group("parameters of methods measurement")

    measurement_group.add_argument(
        "--threshold-bad",
        type=int,
        help="",
        default=config.parameters["threshold_bad"],
    )

    measurement_group.add_argument(
        "--threshold-warning",
        type=int,
        help="",
        default=config.parameters["threshold_warning"],
    )

    measurement_group.add_argument(
        "--threshold-special",
        type=int,
        help="",
        default=config.parameters["threshold_special"],
    )

    measurement_group.add_argument(
        "--threshold-epic",
        type=int,
        help="",
        default=config.parameters["threshold_epic"],
    )

    # measurement_group.add_argument(
    #     "--allow-failure",
    #     type=str,
    #     help="",
    #     default=config.parameters["threshold_epic"],
    # )

    # parser.add_argument(
    #     "--details-skipped",
    # )

    return parser

Runner

runner

run_check

run_check(project_checker: ProjectChecker)
Source code in docstr_health/cli/runner.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def run_check(project_checker: ProjectChecker):
    quiet = config.parameters.get("ci", False)
    if quiet:
        from collections import deque
        deque(project_checker.docstring_check(), maxlen=0)
        return

    if project_checker.modules:
        start_module_name = project_checker.modules[0].file_path.name
    else:
        start_module_name = "No modules found"
    with progress_bar() as pg:
        _task = pg.add_task(
            "Checking...",
            total=len(project_checker.modules),
            module_name=start_module_name,
        )
        for task in project_checker.docstring_check():
            pg.update(_task, advance=1, module_name=task.file_path.name)

Rich output

cli

RichOutput

RichOutput(quiet: bool = False)
Source code in docstr_health/cli/cli.py
15
16
17
18
19
def __init__(self, quiet: bool = False) -> None:
    self.console = Console()
    # self.text = ""
    self.quiet = quiet
    self.color = "common"

console instance-attribute

console = Console()

quiet instance-attribute

quiet = quiet

color instance-attribute

color = 'common'

set_color

set_color(color: str)
Source code in docstr_health/cli/cli.py
21
22
def set_color(self, color: str):
    self.color = color

cprint

cprint(text: Text)
Source code in docstr_health/cli/cli.py
24
25
26
27
def cprint(self, text: Text):
    if self.quiet:
        return
    self.console.print(text)

func_docstring_status

func_docstring_status(
    func_name: str, status: StatusDocstring
) -> Text
Source code in docstr_health/cli/cli.py
29
30
31
32
33
34
35
def func_docstring_status(self, func_name: str, status: StatusDocstring) -> Text:
    symbol = config.parameters[f"{status.value}_symbol"]
    color = config.parameters[f"{status.value}_color"]

    self.set_color(color)

    return Text(f" - {symbol} {func_name}", style=self.color)

display_panel

display_panel(
    text: list[list[Text]],
    title: str,
    panel_status: str = "common",
)
Source code in docstr_health/cli/cli.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def display_panel(
    self, text: list[list[Text]], title: str, panel_status: str = "common"
):
    if self.quiet:
        return
    symbol = config.parameters[f"{panel_status}_symbol"]
    subtitle = f"{symbol} {panel_status} {symbol}"
    border_style = config.parameters[f"{panel_status}_color"]

    render: list = []

    for i, block in enumerate(text):
        render.extend(block)

        if i < len(text) - 1:
            render.append(Rule(style="dim"))

    content = Group(*render)

    rich_print(
        Panel.fit(
            content,
            title=title,
            subtitle=subtitle,
            border_style=border_style,
            padding=(1, 2),
        )
    )
    print("\n")

display_project_report

display_project_report(project_report: ProjectReport)
Source code in docstr_health/cli/cli.py
67
68
69
70
71
72
73
74
75
76
def display_project_report(self, project_report: ProjectReport):
    if self.quiet:
        return
    print("Project status:", end="")

    project_status = project_report.get_project_status()

    self.cprint(
        self.func_docstring_status(project_status, StatusDocstring(project_status))
    )

display_summary

display_summary(tables: list[Table])
Source code in docstr_health/cli/cli.py
78
79
80
81
82
def display_summary(self, tables: list[Table]):
    if self.quiet:
        return
    print()
    rich_print(Columns(tables))

get_status_with_symbol

get_status_with_symbol(status: str) -> str
Source code in docstr_health/cli/cli.py
92
93
def get_status_with_symbol(self, status: str) -> str:
    return f"{self._get_symbol(status)} {status}"

prepare_dict_table staticmethod

prepare_dict_table(
    data: dict, sorting_reference: list | None = None
) -> list[tuple]

Converts a dictionary to a list of (key, value) tuples.

Parameters:

Name Type Description Default
data dict

The original dictionary.

required
sorting_reference list | None

If supplied, sorts by this order.

None
Source code in docstr_health/cli/cli.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@staticmethod
def prepare_dict_table(
    data: dict, sorting_reference: list | None = None
) -> list[tuple]:
    """
    Converts a dictionary to a list of (key, value) tuples.

    Args:
        data: The original dictionary.
        sorting_reference: If supplied, sorts by this order.
    """
    items = list(data.items())
    if sorting_reference:
        items = sorted(items, key=lambda item: sorting_reference.index(item[0]))
    return [(str(k), str(v)) for k, v in items]

get_table

get_table(
    title: str,
    headers: list[str],
    data: dict,
    sorting_reference: list | None = None,
    last_line_separator: bool = False,
) -> Table
Source code in docstr_health/cli/cli.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def get_table(
    self,
    title: str,
    headers: list[str],
    data: dict,
    sorting_reference: list | None = None,
    last_line_separator: bool = False,
) -> Table:
    table = Table(title=title)

    for header in headers:
        table.add_column(header, justify="center")

    table_data = self.prepare_dict_table(data, sorting_reference)

    style = ""
    end_section = False
    total_rows = len(table_data)
    has_numeric = all(isinstance(v, (int, float)) for v in data.values())

    total = 0
    if has_numeric:
        total = data.get("total", sum(data.values()))

    for i, (status, count) in enumerate(table_data):
        if i == total_rows - 2 and last_line_separator:
            end_section = True
        if status in config.get_sorted_statuses():
            style = self._get_style(status)
            status = self.get_status_with_symbol(status=status)
        status_text = Text(
            status,
            style=style,
            justify="left",
        )
        if has_numeric and total > 0:
            percentage = round(int(count) / total * 100, 1)
            rate_str = f"{percentage}%"
        else:
            rate_str = "-"
        table.add_row(status_text, str(count), rate_str, end_section=end_section)
    return table

Progress bar

progress_bar

progress_bar

progress_bar()
Source code in docstr_health/cli/progress_bar.py
12
13
14
15
16
17
18
19
20
21
@contextmanager
def progress_bar():
    with Progress(
        SpinnerColumn(),
        TextColumn("[bold blue]{task.fields[module_name]:<20}"),
        BarColumn(bar_width=50),
        MofNCompleteColumn(),
        transient=True,
    ) as progress:
        yield progress