clanguru 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clanguru-0.1.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+
2
+ MIT License
3
+
4
+ Copyright (c) 2024 cuinixam
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.1
2
+ Name: clanguru
3
+ Version: 0.1.0
4
+ Summary: C language utils and tools based on the clang module.
5
+ Home-page: https://github.com/cuinixam/clanguru
6
+ License: MIT
7
+ Author: cuinixam
8
+ Author-email: me@cuinixam.com
9
+ Requires-Python: >=3.10,<4.0
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Natural Language :: English
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Dist: libclang (>=18.1,<19.0)
21
+ Requires-Dist: mashumaro (>=3.13,<4.0)
22
+ Requires-Dist: py-app-dev (>=2.1,<3.0)
23
+ Requires-Dist: typer (>=0.12.3,<0.13.0)
24
+ Project-URL: Bug Tracker, https://github.com/cuinixam/clanguru/issues
25
+ Project-URL: Changelog, https://github.com/cuinixam/clanguru/blob/main/CHANGELOG.md
26
+ Project-URL: Documentation, https://clanguru.readthedocs.io
27
+ Project-URL: Repository, https://github.com/cuinixam/clanguru
28
+ Description-Content-Type: text/markdown
29
+
30
+ # clanguru
31
+
32
+ <p align="center">
33
+ <a href="https://github.com/cuinixam/clanguru/actions/workflows/ci.yml?query=branch%3Amain">
34
+ <img src="https://img.shields.io/github/actions/workflow/status/cuinixam/clanguru/ci.yml?branch=main&label=CI&logo=github&style=flat-square" alt="CI Status" >
35
+ </a>
36
+ <a href="https://clanguru.readthedocs.io">
37
+ <img src="https://img.shields.io/readthedocs/clanguru.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
38
+ </a>
39
+ <a href="https://codecov.io/gh/cuinixam/clanguru">
40
+ <img src="https://img.shields.io/codecov/c/github/cuinixam/clanguru.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
41
+ </a>
42
+ </p>
43
+ <p align="center">
44
+ <a href="https://python-poetry.org/">
45
+ <img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAJJSURBVHgBfZLPa1NBEMe/s7tNXoxW1KJQKaUHkXhQvHgW6UHQQ09CBS/6V3hKc/AP8CqCrUcpmop3Cx48eDB4yEECjVQrlZb80CRN8t6OM/teagVxYZi38+Yz853dJbzoMV3MM8cJUcLMSUKIE8AzQ2PieZzFxEJOHMOgMQQ+dUgSAckNXhapU/NMhDSWLs1B24A8sO1xrN4NECkcAC9ASkiIJc6k5TRiUDPhnyMMdhKc+Zx19l6SgyeW76BEONY9exVQMzKExGKwwPsCzza7KGSSWRWEQhyEaDXp6ZHEr416ygbiKYOd7TEWvvcQIeusHYMJGhTwF9y7sGnSwaWyFAiyoxzqW0PM/RjghPxF2pWReAowTEXnDh0xgcLs8l2YQmOrj3N7ByiqEoH0cARs4u78WgAVkoEDIDoOi3AkcLOHU60RIg5wC4ZuTC7FaHKQm8Hq1fQuSOBvX/sodmNJSB5geaF5CPIkUeecdMxieoRO5jz9bheL6/tXjrwCyX/UYBUcjCaWHljx1xiX6z9xEjkYAzbGVnB8pvLmyXm9ep+W8CmsSHQQY77Zx1zboxAV0w7ybMhQmfqdmmw3nEp1I0Z+FGO6M8LZdoyZnuzzBdjISicKRnpxzI9fPb+0oYXsNdyi+d3h9bm9MWYHFtPeIZfLwzmFDKy1ai3p+PDls1Llz4yyFpferxjnyjJDSEy9CaCx5m2cJPerq6Xm34eTrZt3PqxYO1XOwDYZrFlH1fWnpU38Y9HRze3lj0vOujZcXKuuXm3jP+s3KbZVra7y2EAAAAAASUVORK5CYII=" alt="Poetry">
46
+ </a>
47
+ <a href="https://github.com/astral-sh/ruff">
48
+ <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="ruff">
49
+ </a>
50
+ <a href="https://github.com/pre-commit/pre-commit">
51
+ <img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
52
+ </a>
53
+ </p>
54
+ <p align="center">
55
+ <a href="https://pypi.org/project/clanguru/">
56
+ <img src="https://img.shields.io/pypi/v/clanguru.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
57
+ </a>
58
+ <img src="https://img.shields.io/pypi/pyversions/clanguru.svg?style=flat-square&logo=python&amp;logoColor=fff" alt="Supported Python versions">
59
+ <img src="https://img.shields.io/pypi/l/clanguru.svg?style=flat-square" alt="License">
60
+ </p>
61
+
62
+ C language utils and tools based on the clang module.
63
+
64
+ ## Installation
65
+
66
+ Install this via pip (or your favourite package manager):
67
+
68
+ `pip install clanguru`
69
+
70
+ ## Start developing
71
+
72
+ The project uses Poetry for dependencies management and packaging.
73
+ Run the `build.ps1` script to install Python and create the virtual environment.
74
+
75
+ ```powershell
76
+ .\build.ps1 -install
77
+ ```
78
+
79
+ This will also generate a `poetry.lock` file, you should track this file in version control.
80
+
81
+ To execute the test suite, call pytest inside Poetry's virtual environment via `poetry run`:
82
+
83
+ ```shell
84
+ .venv/Scripts/poetry run pytest
85
+ ```
86
+
87
+ Check out the Poetry documentation for more information on the available commands.
88
+
89
+ For those using [VS Code](https://code.visualstudio.com/) there are tasks defined for the most common commands:
90
+
91
+ - bootstrap
92
+ - install dependencies
93
+ - run tests
94
+ - run all checks configured for pre-commit
95
+ - generate documentation
96
+
97
+ See the `.vscode/tasks.json` for more details.
98
+
99
+ ## Committing changes
100
+
101
+ This repository uses [commitlint](https://github.com/conventional-changelog/commitlint) for checking if the commit message meets the [conventional commit format](https://www.conventionalcommits.org/en).
102
+
103
+ ## Contributors ✨
104
+
105
+ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
106
+
107
+ <!-- prettier-ignore-start -->
108
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
109
+ <!-- markdownlint-disable -->
110
+ <!-- markdownlint-enable -->
111
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
112
+ <!-- prettier-ignore-end -->
113
+
114
+ This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
115
+
116
+ ## Credits
117
+
118
+ This package was created with
119
+ [Copier](https://copier.readthedocs.io/) and the
120
+ [cuinixam/pypackage-template](https://github.com/cuinixam/pypackage-template)
121
+ project template.
122
+
@@ -0,0 +1,92 @@
1
+ # clanguru
2
+
3
+ <p align="center">
4
+ <a href="https://github.com/cuinixam/clanguru/actions/workflows/ci.yml?query=branch%3Amain">
5
+ <img src="https://img.shields.io/github/actions/workflow/status/cuinixam/clanguru/ci.yml?branch=main&label=CI&logo=github&style=flat-square" alt="CI Status" >
6
+ </a>
7
+ <a href="https://clanguru.readthedocs.io">
8
+ <img src="https://img.shields.io/readthedocs/clanguru.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
9
+ </a>
10
+ <a href="https://codecov.io/gh/cuinixam/clanguru">
11
+ <img src="https://img.shields.io/codecov/c/github/cuinixam/clanguru.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
12
+ </a>
13
+ </p>
14
+ <p align="center">
15
+ <a href="https://python-poetry.org/">
16
+ <img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAJJSURBVHgBfZLPa1NBEMe/s7tNXoxW1KJQKaUHkXhQvHgW6UHQQ09CBS/6V3hKc/AP8CqCrUcpmop3Cx48eDB4yEECjVQrlZb80CRN8t6OM/teagVxYZi38+Yz853dJbzoMV3MM8cJUcLMSUKIE8AzQ2PieZzFxEJOHMOgMQQ+dUgSAckNXhapU/NMhDSWLs1B24A8sO1xrN4NECkcAC9ASkiIJc6k5TRiUDPhnyMMdhKc+Zx19l6SgyeW76BEONY9exVQMzKExGKwwPsCzza7KGSSWRWEQhyEaDXp6ZHEr416ygbiKYOd7TEWvvcQIeusHYMJGhTwF9y7sGnSwaWyFAiyoxzqW0PM/RjghPxF2pWReAowTEXnDh0xgcLs8l2YQmOrj3N7ByiqEoH0cARs4u78WgAVkoEDIDoOi3AkcLOHU60RIg5wC4ZuTC7FaHKQm8Hq1fQuSOBvX/sodmNJSB5geaF5CPIkUeecdMxieoRO5jz9bheL6/tXjrwCyX/UYBUcjCaWHljx1xiX6z9xEjkYAzbGVnB8pvLmyXm9ep+W8CmsSHQQY77Zx1zboxAV0w7ybMhQmfqdmmw3nEp1I0Z+FGO6M8LZdoyZnuzzBdjISicKRnpxzI9fPb+0oYXsNdyi+d3h9bm9MWYHFtPeIZfLwzmFDKy1ai3p+PDls1Llz4yyFpferxjnyjJDSEy9CaCx5m2cJPerq6Xm34eTrZt3PqxYO1XOwDYZrFlH1fWnpU38Y9HRze3lj0vOujZcXKuuXm3jP+s3KbZVra7y2EAAAAAASUVORK5CYII=" alt="Poetry">
17
+ </a>
18
+ <a href="https://github.com/astral-sh/ruff">
19
+ <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="ruff">
20
+ </a>
21
+ <a href="https://github.com/pre-commit/pre-commit">
22
+ <img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
23
+ </a>
24
+ </p>
25
+ <p align="center">
26
+ <a href="https://pypi.org/project/clanguru/">
27
+ <img src="https://img.shields.io/pypi/v/clanguru.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
28
+ </a>
29
+ <img src="https://img.shields.io/pypi/pyversions/clanguru.svg?style=flat-square&logo=python&amp;logoColor=fff" alt="Supported Python versions">
30
+ <img src="https://img.shields.io/pypi/l/clanguru.svg?style=flat-square" alt="License">
31
+ </p>
32
+
33
+ C language utils and tools based on the clang module.
34
+
35
+ ## Installation
36
+
37
+ Install this via pip (or your favourite package manager):
38
+
39
+ `pip install clanguru`
40
+
41
+ ## Start developing
42
+
43
+ The project uses Poetry for dependencies management and packaging.
44
+ Run the `build.ps1` script to install Python and create the virtual environment.
45
+
46
+ ```powershell
47
+ .\build.ps1 -install
48
+ ```
49
+
50
+ This will also generate a `poetry.lock` file, you should track this file in version control.
51
+
52
+ To execute the test suite, call pytest inside Poetry's virtual environment via `poetry run`:
53
+
54
+ ```shell
55
+ .venv/Scripts/poetry run pytest
56
+ ```
57
+
58
+ Check out the Poetry documentation for more information on the available commands.
59
+
60
+ For those using [VS Code](https://code.visualstudio.com/) there are tasks defined for the most common commands:
61
+
62
+ - bootstrap
63
+ - install dependencies
64
+ - run tests
65
+ - run all checks configured for pre-commit
66
+ - generate documentation
67
+
68
+ See the `.vscode/tasks.json` for more details.
69
+
70
+ ## Committing changes
71
+
72
+ This repository uses [commitlint](https://github.com/conventional-changelog/commitlint) for checking if the commit message meets the [conventional commit format](https://www.conventionalcommits.org/en).
73
+
74
+ ## Contributors ✨
75
+
76
+ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
77
+
78
+ <!-- prettier-ignore-start -->
79
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
80
+ <!-- markdownlint-disable -->
81
+ <!-- markdownlint-enable -->
82
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
83
+ <!-- prettier-ignore-end -->
84
+
85
+ This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
86
+
87
+ ## Credits
88
+
89
+ This package was created with
90
+ [Copier](https://copier.readthedocs.io/) and the
91
+ [cuinixam/pypackage-template](https://github.com/cuinixam/pypackage-template)
92
+ project template.
@@ -0,0 +1,156 @@
1
+ [tool.poetry]
2
+ name = "clanguru"
3
+ version = "0.1.0"
4
+ description = "C language utils and tools based on the clang module."
5
+ authors = ["cuinixam <me@cuinixam.com>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ repository = "https://github.com/cuinixam/clanguru"
9
+ documentation = "https://clanguru.readthedocs.io"
10
+ classifiers = [
11
+ "Development Status :: 2 - Pre-Alpha",
12
+ "Intended Audience :: Developers",
13
+ "Natural Language :: English",
14
+ "Operating System :: OS Independent",
15
+ "Topic :: Software Development :: Libraries",
16
+ ]
17
+ packages = [
18
+ { include = "clanguru", from = "src" },
19
+ ]
20
+
21
+ [tool.poetry.urls]
22
+ "Bug Tracker" = "https://github.com/cuinixam/clanguru/issues"
23
+ "Changelog" = "https://github.com/cuinixam/clanguru/blob/main/CHANGELOG.md"
24
+
25
+ [tool.poetry.dependencies]
26
+ python = "^3.10"
27
+ py-app-dev = "^2.1"
28
+ libclang = "^18.1"
29
+ typer = "^0.12.3"
30
+ mashumaro = "^3.13"
31
+
32
+
33
+ [tool.poetry.group.dev.dependencies]
34
+ pytest = "^7.0"
35
+ pytest-cov = "^4.0"
36
+ pre-commit = "^3.1.1"
37
+ ruff = "^0.3.0"
38
+
39
+ [tool.poetry.group.docs.dependencies]
40
+ myst-parser = ">=0.16"
41
+ sphinx = ">=4.0"
42
+ sphinxcontrib-mermaid = "^0.8.1"
43
+ mlx-traceability = "^10.0.0"
44
+ sphinx-copybutton = "^0.5.2"
45
+ sphinx-new-tab-link = "^0.2.2"
46
+ sphinx-book-theme = "^1.1.2"
47
+ sphinx-design = "^0.5.0"
48
+
49
+ [tool.semantic_release]
50
+ version_toml = ["pyproject.toml:tool.poetry.version"]
51
+ version_variables = [
52
+ "src/clanguru/__init__.py:__version__",
53
+ "docs/conf.py:release",
54
+ ]
55
+ build_command = "pip install poetry && poetry build"
56
+
57
+ [tool.semantic_release.changelog]
58
+ exclude_commit_patterns = [
59
+ "chore*",
60
+ "ci*",
61
+ ]
62
+
63
+ [tool.semantic_release.changelog.environment]
64
+ keep_trailing_newline = true
65
+
66
+ [tool.semantic_release.branches.main]
67
+ match = "main"
68
+
69
+ [tool.semantic_release.branches.noop]
70
+ match = "(?!main$)"
71
+ prerelease = true
72
+
73
+ [tool.pytest.ini_options]
74
+ addopts = "-vv -Wdefault --cov=clanguru --cov-report=term-missing:skip-covered -s"
75
+ pythonpath = ["src"]
76
+
77
+ [tool.coverage.run]
78
+ branch = true
79
+
80
+ [tool.coverage.report]
81
+ exclude_lines = [
82
+ "pragma: no cover",
83
+ "@overload",
84
+ "if TYPE_CHECKING",
85
+ "raise NotImplementedError",
86
+ 'if __name__ == "__main__":',
87
+ ]
88
+
89
+ [tool.ruff]
90
+ target-version = "py38"
91
+ line-length = 180
92
+ lint.ignore = [
93
+ "D203", # 1 blank line required before class docstring
94
+ "D212", # Multi-line docstring summary should start at the first line
95
+ "D100", # Missing docstring in public module
96
+ "D101", # Missing docstring in public class
97
+ "D102", # Missing docstring in public method
98
+ "D103", # Missing docstring in public function
99
+ "D104", # Missing docstring in public package
100
+ "D107", # Missing docstring in `__init__`
101
+ "D401", # First line of docstring should be in imperative mood
102
+ ]
103
+ lint.select = [
104
+ "B", # flake8-bugbear
105
+ "C4", # flake8-comprehensions
106
+ "S", # flake8-bandit
107
+ "F", # pyflake
108
+ "E", # pycodestyle
109
+ "W", # pycodestyle
110
+ "UP", # pyupgrade
111
+ "I", # isort
112
+ "RUF", # ruff specific
113
+ ]
114
+
115
+ [tool.ruff.lint.per-file-ignores]
116
+ "tests/**/*" = [
117
+ "D100",
118
+ "D101",
119
+ "D102",
120
+ "D103",
121
+ "D104",
122
+ "S101",
123
+ ]
124
+ "setup.py" = ["D100"]
125
+ "conftest.py" = ["D100"]
126
+ "docs/conf.py" = ["D100"]
127
+
128
+ [tool.ruff.lint.isort]
129
+ known-first-party = ["clanguru", "tests"]
130
+
131
+ [tool.mypy]
132
+ check_untyped_defs = true
133
+ disallow_any_generics = true
134
+ disallow_incomplete_defs = true
135
+ disallow_untyped_defs = true
136
+ mypy_path = "src/"
137
+ no_implicit_optional = true
138
+ show_error_codes = true
139
+ warn_unreachable = true
140
+ warn_unused_ignores = true
141
+ exclude = [
142
+ 'docs/.*',
143
+ 'setup.py',
144
+ ]
145
+
146
+ [[tool.mypy.overrides]]
147
+ module = "tests.*"
148
+ allow_untyped_defs = true
149
+
150
+ [[tool.mypy.overrides]]
151
+ module = "docs.*"
152
+ ignore_errors = true
153
+
154
+ [build-system]
155
+ requires = ["poetry-core>=1.0.0"]
156
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,12 @@
1
+ """
2
+ Used to run clanguru from the command line when run from this repository.
3
+
4
+ This is required because clanguru module is not visible when running from the repository.
5
+ """
6
+
7
+ import runpy
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ sys.path.insert(0, Path(__file__).parent.parent.absolute().as_posix())
12
+ runpy.run_module("clanguru.main", run_name="__main__")
@@ -0,0 +1,123 @@
1
+ import io
2
+ import json
3
+ import traceback
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import ClassVar, List, Optional
7
+
8
+ from mashumaro import DataClassDictMixin
9
+ from mashumaro.config import TO_DICT_ADD_OMIT_NONE_FLAG, BaseConfig
10
+ from mashumaro.mixins.json import DataClassJSONMixin
11
+ from mashumaro.types import SerializableType
12
+ from py_app_dev.core.exceptions import UserNotificationException
13
+
14
+
15
+ class PathField(SerializableType):
16
+ def _serialize(self) -> str:
17
+ return str(self)
18
+
19
+ @classmethod
20
+ def _deserialize(cls, value: str) -> Path:
21
+ return Path(value)
22
+
23
+
24
+ @dataclass
25
+ class CompileCommand(DataClassDictMixin):
26
+ directory: Path
27
+ file: Path
28
+ arguments: List[str] = field(default_factory=list)
29
+ command: Optional[str] = None
30
+ output: Optional[Path] = None
31
+
32
+ def get_compile_options(self) -> List[str]:
33
+ options = []
34
+ if self.arguments:
35
+ options = self.arguments
36
+ if self.command:
37
+ options = self.command.split()
38
+ return self.clean_up_arguments(options)
39
+
40
+ def get_file_path(self) -> Path:
41
+ return self.file if self.file.is_absolute() else self.directory / self.file
42
+
43
+ def clean_up_arguments(self, arguments: List[str]) -> List[str]:
44
+ """
45
+ Clean up the command line to only get the compilation options.
46
+
47
+ Ignore the first argument which is the compiler.
48
+ Remove the options for the output and input files.
49
+ Any arguments containing the input or output file names or paths are removed.
50
+ For example: -DStuff -ISome/Path -o output.o input.c -> -DStuff -ISome/Path
51
+ """
52
+ cleaned_args = []
53
+ skip_next = False
54
+ input_filename = self.file.name
55
+ output_filename = self.output.name if self.output else None
56
+
57
+ for arg in arguments[1:]: # Skip the first argument (compiler)
58
+ if skip_next:
59
+ skip_next = False
60
+ continue
61
+
62
+ # Skip -o and its value
63
+ if arg == "-o":
64
+ skip_next = True
65
+ continue
66
+
67
+ # Skip -c option
68
+ if arg == "-c":
69
+ continue
70
+
71
+ # Skip arguments containing input or output file names or paths
72
+ if input_filename in arg or (output_filename and output_filename in arg):
73
+ continue
74
+
75
+ # Keep all other arguments
76
+ cleaned_args.append(arg)
77
+
78
+ return cleaned_args
79
+
80
+
81
+ @dataclass
82
+ class CompilationDatabase(DataClassJSONMixin):
83
+ commands: List[CompileCommand]
84
+
85
+ def getCompileCommands(self, file: Path) -> List[CompileCommand]:
86
+ return [command for command in self.commands if command.get_file_path() == file]
87
+
88
+ class Config(BaseConfig):
89
+ code_generation_options: ClassVar[List[str]] = [TO_DICT_ADD_OMIT_NONE_FLAG]
90
+
91
+ @classmethod
92
+ def from_json_file(cls, file_path: Path) -> "CompilationDatabase":
93
+ try:
94
+ result = cls.from_dict({"commands": json.loads(file_path.read_text())})
95
+ except Exception as e:
96
+ output = io.StringIO()
97
+ traceback.print_exc(file=output)
98
+ raise UserNotificationException(output.getvalue()) from e
99
+ return result
100
+
101
+ def to_json_string(self) -> str:
102
+ return json.dumps(self.to_dict(omit_none=True), indent=2)
103
+
104
+ def to_json_file(self, file_path: Path) -> None:
105
+ file_path.write_text(self.to_json_string())
106
+
107
+
108
+ class CompilationOptionsManager:
109
+ def __init__(self, compilation_database: Optional[Path] = None, no_default: bool = False):
110
+ self.compilation_database: Optional[CompilationDatabase] = CompilationDatabase.from_json_file(compilation_database) if compilation_database else None
111
+ self.no_default = no_default
112
+ self.default_options = ["-std=c11"]
113
+
114
+ def get_compile_options(self, file: Path) -> List[str]:
115
+ if self.compilation_database:
116
+ commands: List[CompileCommand] = self.compilation_database.getCompileCommands(file)
117
+ # TODO: how to handle multiple commands for the same file?
118
+ if commands:
119
+ return commands[0].get_compile_options()
120
+ return [] if self.no_default else self.default_options
121
+
122
+ def set_default_options(self, options: List[str]) -> None:
123
+ self.default_options = options
@@ -0,0 +1,335 @@
1
+ import re
2
+ from collections import OrderedDict
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Any, List, Optional, Type, TypeVar
6
+
7
+ from clang.cindex import Cursor, CursorKind, Index, SourceRange
8
+ from clang.cindex import Token as _Token
9
+ from clang.cindex import TranslationUnit as _TranslationUnit
10
+
11
+ from clanguru.compilation_options_manager import CompilationOptionsManager
12
+
13
+
14
+ @dataclass
15
+ class Token:
16
+ raw_token: _Token
17
+ previous_token: Optional["Token"]
18
+ next_token: Optional["Token"]
19
+
20
+ @property
21
+ def is_comment(self) -> bool:
22
+ return self.raw_token.kind.name == "COMMENT"
23
+
24
+ def __hash__(self) -> int:
25
+ return hash(str(self))
26
+
27
+ def __eq__(self, other: Any) -> bool:
28
+ if isinstance(other, Token):
29
+ return str(self) == str(other)
30
+ return False
31
+
32
+ def __str__(self) -> str:
33
+ return f"{self.raw_token.kind.name} ('{self.raw_token.spelling}' at line {self.raw_token.location.line})"
34
+
35
+
36
+ class TokensCollection(List[Token]):
37
+ def __init__(self, tokens: List[Token]) -> None:
38
+ super().__init__(tokens)
39
+ self.tokens_ordered_dict = OrderedDict((token, token) for token in tokens)
40
+
41
+ def first(self) -> Optional[Token]:
42
+ """Get the first token in the collection."""
43
+ return self[0] if self else None
44
+
45
+ def find_matching_token(self, raw_token: _Token) -> Optional[Token]:
46
+ """Find the token in the collection by the raw token."""
47
+ # TODO: Find a nicer way to do this. Currently we rely on the fact that the token previous and next tokens are ignored while hashing.
48
+ return self.tokens_ordered_dict.get(Token(raw_token, None, None), None)
49
+
50
+
51
+ @dataclass
52
+ class Node:
53
+ raw_node: Cursor
54
+ previous_node: Optional["Node"]
55
+ next_node: Optional["Node"]
56
+ tokens: TokensCollection
57
+ parent: "TranslationUnit"
58
+
59
+ def is_function_definition(self) -> bool:
60
+ """Check if the node type is function declaration and it is a definition."""
61
+ return self.raw_node.kind.name == "FUNCTION_DECL" and self.raw_node.is_definition()
62
+
63
+ def __str__(self) -> str:
64
+ return f"{self.raw_node.kind.name} ('{self.raw_node.spelling}' at line {self.raw_node.location.line})"
65
+
66
+
67
+ @dataclass
68
+ class TranslationUnit:
69
+ raw_tu: _TranslationUnit
70
+ tokens: TokensCollection
71
+ nodes: List[Node]
72
+
73
+ @property
74
+ def source_file(self) -> Path:
75
+ return Path(self.raw_tu.spelling)
76
+
77
+ def __str__(self) -> str:
78
+ return "\n".join(
79
+ [
80
+ f"Translation unit for {self.source_file}",
81
+ "Tokens:",
82
+ *[str(token) for token in self.tokens],
83
+ "Nodes:",
84
+ *[str(node) for node in self.nodes],
85
+ ]
86
+ )
87
+
88
+
89
+ T = TypeVar("T", bound="Declaration")
90
+
91
+
92
+ class Declaration:
93
+ def __init__(self, name: str, origin: Node, description_token: Optional[Token], body: str):
94
+ self.name = name
95
+ self.origin = origin
96
+ self.description_token = description_token
97
+ self.body = body
98
+
99
+ @property
100
+ def description(self) -> Optional[str]:
101
+ return CLangParser.get_comment_content(self.description_token) if self.description_token else None
102
+
103
+
104
+ class Function(Declaration):
105
+ @property
106
+ def is_definition(self) -> bool:
107
+ return self.origin.is_function_definition()
108
+
109
+
110
+ class CppClass(Declaration):
111
+ pass
112
+
113
+
114
+ class Variable(Declaration):
115
+ def get_init_value(self) -> Optional[str]:
116
+ """Get the initialization value for the variable."""
117
+ var_cursor = self.origin.raw_node
118
+
119
+ # The initializer is usually represented as a child cursor
120
+ for child in var_cursor.get_children():
121
+ if child.kind.is_expression() or child.kind == CursorKind.INIT_LIST_EXPR:
122
+ # Extract the initializer value from the child cursor
123
+ init_value = self._extract_init_value(child)
124
+ return init_value
125
+
126
+ # If no initializer is found
127
+ return None
128
+
129
+ def _extract_init_value(self, expr_cursor: Cursor) -> Optional[str]:
130
+ """Recursively extract the initialization value from an expression cursor."""
131
+ kind = expr_cursor.kind
132
+
133
+ if kind in (
134
+ CursorKind.INTEGER_LITERAL,
135
+ CursorKind.FLOATING_LITERAL,
136
+ CursorKind.STRING_LITERAL,
137
+ CursorKind.CHARACTER_LITERAL,
138
+ ):
139
+ tokens = list(expr_cursor.get_tokens())
140
+ return tokens[0].spelling if tokens else None
141
+
142
+ elif kind in (
143
+ CursorKind.UNARY_OPERATOR,
144
+ CursorKind.BINARY_OPERATOR,
145
+ CursorKind.COMPOUND_ASSIGNMENT_OPERATOR,
146
+ CursorKind.CALL_EXPR,
147
+ CursorKind.DECL_REF_EXPR,
148
+ CursorKind.MEMBER_REF_EXPR,
149
+ CursorKind.ARRAY_SUBSCRIPT_EXPR,
150
+ CursorKind.CXX_BOOL_LITERAL_EXPR,
151
+ CursorKind.CXX_NULL_PTR_LITERAL_EXPR,
152
+ CursorKind.CXX_STATIC_CAST_EXPR,
153
+ CursorKind.CXX_REINTERPRET_CAST_EXPR,
154
+ CursorKind.CXX_CONST_CAST_EXPR,
155
+ CursorKind.CXX_FUNCTIONAL_CAST_EXPR,
156
+ CursorKind.PAREN_EXPR,
157
+ CursorKind.INIT_LIST_EXPR,
158
+ ):
159
+ # For complex expressions, collect tokens recursively
160
+ tokens = []
161
+ for token in expr_cursor.get_tokens():
162
+ tokens.append(token.spelling)
163
+ value = "".join(tokens)
164
+ return value
165
+ else:
166
+ # For other expressions, attempt to collect tokens
167
+ tokens = []
168
+ for child in expr_cursor.get_children():
169
+ child_value = self._extract_init_value(child)
170
+ if child_value is not None:
171
+ tokens.append(child_value)
172
+ if tokens:
173
+ return "".join(tokens)
174
+ else:
175
+ return None
176
+
177
+
178
+ class CLangParser:
179
+ def __init__(self) -> None:
180
+ self.index = Index.create()
181
+
182
+ def load(self, file: Path, compilation_options_manager: Optional[CompilationOptionsManager] = None) -> TranslationUnit:
183
+ args = compilation_options_manager.get_compile_options(file) if compilation_options_manager else []
184
+ translation_unit = TranslationUnit(raw_tu=self.index.parse(str(file), args=args), tokens=TokensCollection([]), nodes=[])
185
+ translation_unit.tokens = self._extract_tokens(translation_unit.raw_tu.cursor)
186
+ translation_unit.nodes = self._extract_nodes(translation_unit)
187
+ return translation_unit
188
+
189
+ def _extract_tokens(self, cursor: Cursor) -> TokensCollection:
190
+ tokens: List[Token] = []
191
+ for token in cursor.get_tokens():
192
+ current_token = Token(raw_token=token, previous_token=None, next_token=None)
193
+ if tokens:
194
+ previous_token = tokens[-1]
195
+ previous_token.next_token = current_token
196
+ current_token.previous_token = previous_token
197
+ tokens.append(current_token)
198
+ return TokensCollection(tokens)
199
+
200
+ def _extract_nodes(self, translation_unit: TranslationUnit) -> List[Node]:
201
+ nodes: List[Node] = []
202
+ for child in translation_unit.raw_tu.cursor.get_children():
203
+ current_node = Node(raw_node=child, previous_node=None, next_node=None, tokens=self._collect_node_tokens(child, translation_unit.tokens), parent=translation_unit)
204
+ if nodes:
205
+ previous_node = nodes[-1]
206
+ previous_node.next_node = current_node
207
+ current_node.previous_node = previous_node
208
+ nodes.append(current_node)
209
+ return nodes
210
+
211
+ def _collect_node_tokens(self, node: Cursor, tokens: TokensCollection) -> TokensCollection:
212
+ """Get the raw tokens for the node and search for them in the given tokens list."""
213
+ node_tokens = []
214
+ # Do not use node.get_tokens() directly, as it may return an empty list for nodes generated from macros
215
+ # Iterate over all the tokens in CTokensCollection and find the ones with their locations within the node extent
216
+ for token in tokens:
217
+ if node.extent.start.offset <= token.raw_token.extent.start.offset <= node.extent.end.offset:
218
+ node_tokens.append(token)
219
+
220
+ return TokensCollection(node_tokens)
221
+
222
+ @staticmethod
223
+ def _get_declarations(tu: TranslationUnit, declaration_type: str, declaration_class: Type[T]) -> List[T]:
224
+ declarations = []
225
+ for node in tu.nodes:
226
+ if node.raw_node.kind.name == declaration_type:
227
+ name = node.raw_node.spelling
228
+ description = CLangParser.search_description(node)
229
+ source_code = CLangParser.get_node_source_code(node)
230
+ declarations.append(declaration_class(name, node, description, source_code))
231
+ return declarations
232
+
233
+ @staticmethod
234
+ def get_functions(tu: TranslationUnit) -> List[Function]:
235
+ return CLangParser._get_declarations(tu, "FUNCTION_DECL", Function)
236
+
237
+ @staticmethod
238
+ def get_variables(tu: TranslationUnit) -> List[Variable]:
239
+ return CLangParser._get_declarations(tu, "VAR_DECL", Variable)
240
+
241
+ @staticmethod
242
+ def get_classes(tu: TranslationUnit) -> List[CppClass]:
243
+ return CLangParser._get_declarations(tu, "CLASS_DECL", CppClass)
244
+
245
+ @staticmethod
246
+ def search_description(node: Node) -> Optional[Token]:
247
+ """
248
+ Get the description comment for a node.
249
+
250
+ This method searches for a comment token immediately preceding the node's first token,
251
+ but on a different line. If found, it returns the comment token, otherwise None.
252
+ """
253
+ if first_token := node.tokens.first():
254
+ current_token = first_token
255
+ while current_token.previous_token:
256
+ prev_token = current_token.previous_token
257
+ if prev_token.raw_token.location.line < current_token.raw_token.location.line:
258
+ if prev_token.is_comment:
259
+ return prev_token
260
+ else:
261
+ break
262
+ current_token = prev_token
263
+ return None
264
+
265
+ @staticmethod
266
+ def get_node_source_code(node: Node) -> str:
267
+ if not isinstance(node.raw_node, Cursor):
268
+ raise ValueError(f"The node {node} is not a valid cursor")
269
+
270
+ # Get the function's extent (source range)
271
+ extent = node.raw_node.extent
272
+
273
+ if not isinstance(extent, SourceRange):
274
+ raise ValueError(f"The node {node} extent is not a valid source range")
275
+
276
+ # Get the start and end locations
277
+ start = extent.start
278
+ end = extent.end
279
+
280
+ # Get the source file
281
+ source_file = start.file
282
+
283
+ if source_file is None or not source_file.name:
284
+ raise ValueError(f"The source file is not available for node {node}")
285
+
286
+ # Read the relevant part of the source file
287
+ with open(source_file.name) as f:
288
+ f.seek(start.offset)
289
+ return f.read(end.offset - start.offset)
290
+
291
+ @staticmethod
292
+ def get_comment_content(token: Token) -> str:
293
+ """Get the comment content from the token.
294
+
295
+ This method extracts the comment content for single-line, multi-line,and Doxygen style comments.
296
+ It removes the comment delimiters while preserving the internal structure and indentation.
297
+ """
298
+ if not token.is_comment:
299
+ return ""
300
+
301
+ content = token.raw_token.spelling.strip()
302
+
303
+ # Single-line comment
304
+ if content.startswith("//"):
305
+ return content[2:].strip()
306
+
307
+ # Multi-line comment (including Doxygen-style)
308
+ if content == "/**/":
309
+ return ""
310
+ if content.startswith("/*"):
311
+ # Remove the starting "/*", "/*!", or "/**" and the ending "*/" or "**/"
312
+ content = re.sub(r"^\/\*+\!?|\*+\/$", "", content, flags=re.MULTILINE)
313
+
314
+ lines = content.split("\n")
315
+
316
+ # Find the minimum indentation (excluding empty lines)
317
+ min_indent = min((len(line) - len(line.lstrip()) for line in lines if line.strip()), default=0)
318
+
319
+ # Remove the minimum indentation and leading asterisks, but preserve structure
320
+ cleaned_lines = []
321
+ for line in lines:
322
+ if line.strip():
323
+ cleaned_line = line[min_indent:].lstrip()
324
+ if cleaned_line.startswith("* "):
325
+ cleaned_line = cleaned_line[2:]
326
+ elif cleaned_line.startswith("*"):
327
+ cleaned_line = cleaned_line[1:]
328
+ cleaned_lines.append(cleaned_line)
329
+ else:
330
+ cleaned_lines.append("")
331
+
332
+ return "\n".join(cleaned_lines).strip()
333
+
334
+ # If it's neither a single-line nor a multi-line comment, return as is
335
+ return content
@@ -0,0 +1,166 @@
1
+ from abc import ABC, abstractmethod
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ from typing import List, Union
5
+
6
+ from clanguru.cparser import CLangParser, TranslationUnit
7
+
8
+
9
+ @dataclass
10
+ class TextContent:
11
+ text: str
12
+
13
+
14
+ @dataclass
15
+ class CodeContent:
16
+ code: str
17
+ language: str = "c"
18
+
19
+
20
+ SectionContent = Union[TextContent, CodeContent]
21
+
22
+
23
+ class Section:
24
+ def __init__(self, title: str):
25
+ self.title = title
26
+ self.content: List[SectionContent] = []
27
+ self.subsections: List[Section] = []
28
+
29
+ def add_content(self, content: SectionContent) -> None:
30
+ self.content.append(content)
31
+
32
+ def add_subsection(self, subsection: "Section") -> None:
33
+ self.subsections.append(subsection)
34
+
35
+
36
+ class DocStructure:
37
+ """Format independent documentation structure."""
38
+
39
+ def __init__(self, title: str):
40
+ self.title = title
41
+ self.sections: List[Section] = []
42
+
43
+ def add_section(self, section: Section) -> None:
44
+ self.sections.append(section)
45
+
46
+
47
+ class OutputFormatter(ABC):
48
+ """Abstract base class for output formatters."""
49
+
50
+ @abstractmethod
51
+ def format(self, doc: DocStructure) -> str:
52
+ pass
53
+
54
+ @abstractmethod
55
+ def format_text(self, text: str) -> str:
56
+ pass
57
+
58
+ @abstractmethod
59
+ def format_code(self, code: str, language: str) -> str:
60
+ pass
61
+
62
+ @abstractmethod
63
+ def file_extension(self) -> str:
64
+ pass
65
+
66
+
67
+ class MarkdownFormatter(OutputFormatter):
68
+ """Markdown output formatter for documentation."""
69
+
70
+ def format(self, doc: DocStructure) -> str:
71
+ output = f"# {doc.title}\n\n"
72
+ for section in doc.sections:
73
+ output += self._format_section(section, 2)
74
+ return output.rstrip() + "\n"
75
+
76
+ def _format_section(self, section: Section, level: int) -> str:
77
+ output = f"{'#' * level} {section.title}\n\n"
78
+ for content in section.content:
79
+ if isinstance(content, TextContent):
80
+ output += self.format_text(content.text) + "\n\n"
81
+ elif isinstance(content, CodeContent):
82
+ output += self.format_code(content.code, content.language) + "\n\n"
83
+ for subsection in section.subsections:
84
+ output += self._format_section(subsection, level + 1)
85
+ return output
86
+
87
+ def format_text(self, text: str) -> str:
88
+ return text.strip()
89
+
90
+ def format_code(self, code: str, language: str) -> str:
91
+ return f"```{language}\n{code}\n```"
92
+
93
+ def file_extension(self) -> str:
94
+ return "md"
95
+
96
+
97
+ class RSTFormatter(OutputFormatter):
98
+ """reStructuredText output formatter for documentation."""
99
+
100
+ def format(self, doc: DocStructure) -> str:
101
+ output = f"{doc.title}\n{'=' * len(doc.title)}\n\n"
102
+ for section in doc.sections:
103
+ output += self._format_section(section, 1)
104
+ return output.rstrip() + "\n"
105
+
106
+ def _format_section(self, section: Section, level: int) -> str:
107
+ underlines = "=-~^"
108
+ output = f"{section.title}\n{underlines[level] * len(section.title)}\n\n"
109
+ for content in section.content:
110
+ if isinstance(content, TextContent):
111
+ output += self.format_text(content.text) + "\n\n"
112
+ elif isinstance(content, CodeContent):
113
+ output += self.format_code(content.code, content.language) + "\n\n"
114
+ for subsection in section.subsections:
115
+ output += self._format_section(subsection, level + 1)
116
+ return output
117
+
118
+ def format_text(self, text: str) -> str:
119
+ return text.strip()
120
+
121
+ def format_code(self, code: str, language: str) -> str:
122
+ return f".. code-block:: {language}\n\n{self._indent_code(code)}\n"
123
+
124
+ def _indent_code(self, code: str) -> str:
125
+ return "\n".join(f" {line}" for line in code.split("\n"))
126
+
127
+ def file_extension(self) -> str:
128
+ return "rst"
129
+
130
+
131
+ def generate_doc_structure(translation_unit: TranslationUnit) -> DocStructure:
132
+ """Generate documentation structure from a translation unit.
133
+
134
+ Uses the CLangParser to extract functions and classes from the translation unit
135
+ and creates a DocStructure object with the extracted information.
136
+ """
137
+ doc = DocStructure(translation_unit.source_file.name)
138
+ functions = CLangParser.get_functions(translation_unit)
139
+ if functions:
140
+ functions_section = Section("Functions")
141
+ doc.add_section(functions_section)
142
+
143
+ for func in functions:
144
+ if func.is_definition:
145
+ func_section = Section(func.name)
146
+ if func.description_token:
147
+ func_section.add_content(TextContent(CLangParser.get_comment_content(func.description_token)))
148
+ func_section.add_content(CodeContent(func.body))
149
+ functions_section.add_subsection(func_section)
150
+ classes = CLangParser.get_classes(translation_unit)
151
+ if classes:
152
+ classes_section = Section("Classes")
153
+ doc.add_section(classes_section)
154
+
155
+ for cls in classes:
156
+ cls_section = Section(cls.name)
157
+ if cls.description_token:
158
+ cls_section.add_content(TextContent(CLangParser.get_comment_content(cls.description_token)))
159
+ classes_section.add_subsection(cls_section)
160
+
161
+ return doc
162
+
163
+
164
+ def generate_documentation(translation_unit: TranslationUnit, formatter: OutputFormatter, output_file: Path) -> None:
165
+ """Generate documentation from a translation unit and write it to a file using the specified formatter."""
166
+ output_file.write_text(formatter.format(generate_doc_structure(translation_unit)))
@@ -0,0 +1,67 @@
1
+ import sys
2
+ from pathlib import Path
3
+ from typing import Optional
4
+
5
+ import typer
6
+ from py_app_dev.core.exceptions import UserNotificationException
7
+ from py_app_dev.core.logging import logger, setup_logger, time_it
8
+
9
+ from clanguru import __version__
10
+ from clanguru.compilation_options_manager import CompilationOptionsManager
11
+ from clanguru.cparser import CLangParser
12
+ from clanguru.doc_generator import MarkdownFormatter, generate_documentation
13
+
14
+ package_name = "clanguru"
15
+
16
+ app = typer.Typer(name=package_name, help="C language utils and tools based on the libclang module.", no_args_is_help=True, add_completion=False)
17
+
18
+
19
+ @app.callback(invoke_without_command=True)
20
+ def version(
21
+ version: bool = typer.Option(None, "--version", "-v", is_eager=True, help="Show version and exit."),
22
+ ) -> None:
23
+ if version:
24
+ typer.echo(f"{package_name} {__version__}")
25
+ raise typer.Exit()
26
+
27
+
28
+ @app.command()
29
+ @time_it("generate")
30
+ def generate(
31
+ source_file: Path = typer.Option(help="Input source file"), # noqa: B008
32
+ output_file: Path = typer.Option(help="Output file"), # noqa: B008
33
+ compilation_database: Optional[Path] = typer.Option(None, help="Compilation database file required if the source file includes external headers."), # noqa: B008
34
+ ) -> None:
35
+ parser = CLangParser()
36
+ translation_unit = parser.load(source_file, CompilationOptionsManager(compilation_database))
37
+ generate_documentation(translation_unit, MarkdownFormatter(), output_file)
38
+
39
+
40
+ @app.command()
41
+ @time_it("parse")
42
+ def parse(
43
+ source_file: Path = typer.Option(help="Input source file"), # noqa: B008
44
+ output_file: Optional[Path] = typer.Option(None, help="Output file"), # noqa: B008
45
+ compilation_database: Optional[Path] = typer.Option(None, help="Compilation database file required if the source file includes external headers."), # noqa: B008
46
+ ) -> None:
47
+ parser = CLangParser()
48
+ translation_unit = parser.load(source_file, CompilationOptionsManager(compilation_database))
49
+ if output_file:
50
+ with open(output_file, "w") as f:
51
+ f.write(str(translation_unit))
52
+ else:
53
+ logger.info(translation_unit)
54
+
55
+
56
+ def main() -> int:
57
+ try:
58
+ setup_logger()
59
+ app()
60
+ return 0
61
+ except UserNotificationException as e:
62
+ logger.error(f"{e}")
63
+ return 1
64
+
65
+
66
+ if __name__ == "__main__":
67
+ sys.exit(main())
@@ -0,0 +1,14 @@
1
+ from pathlib import Path
2
+
3
+ from py_app_dev.core.docs_utils import fulfills
4
+ from py_app_dev.core.logging import logger
5
+
6
+
7
+ class MyApp:
8
+ def __init__(self, project_dir: Path) -> None:
9
+ self.project_dir = project_dir
10
+ self.logger = logger.bind()
11
+
12
+ @fulfills("REQ-MY_APP_PROJECT_DIR-0.0.1")
13
+ def run(self) -> None:
14
+ self.logger.info(f"Running {self.__class__.__name__} in '{self.project_dir}'")
File without changes