ts-backend-check 1.2.1__py3-none-any.whl → 1.3.0__py3-none-any.whl

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.
@@ -1,46 +1,40 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ts-backend-check
3
- Version: 1.2.1
4
- Summary: Check TypeScript types against their corresponding backend models to assure that all fields have been accounted for.
5
- Home-page: https://github.com/activist-org/ts-backend-check
6
- Author: ts-backend-check developers
7
- Author-email: team@activist.org
8
- License: : OSI Approved :: GNU License
3
+ Version: 1.3.0
4
+ Summary: Check TypeScript types against backend models
5
+ Author-email: ts-backend-check developers <engineering@activist.org>
6
+ Project-URL: Homepage, https://github.com/activist-org/ts-backend-check
9
7
  Keywords: backend,typescript,validation,ci,cli
10
8
  Classifier: Development Status :: 5 - Production/Stable
11
9
  Classifier: Intended Audience :: Developers
12
10
  Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
13
11
  Classifier: Programming Language :: Python
14
12
  Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.10
16
- Classifier: Programming Language :: Python :: 3.11
17
13
  Classifier: Programming Language :: Python :: 3.12
18
14
  Classifier: Programming Language :: Python :: 3.13
19
15
  Classifier: Programming Language :: Python :: 3.14
20
16
  Classifier: Operating System :: OS Independent
21
- Requires-Python: >=3.10
17
+ Requires-Python: >=3.12
22
18
  Description-Content-Type: text/markdown
23
19
  License-File: LICENSE.txt
24
- Requires-Dist: certifi>=2025.11.12
25
- Requires-Dist: charset-normalizer>=3.4.4
26
- Requires-Dist: idna>=3.11
27
- Requires-Dist: markdown-it-py>=4.0.0
28
- Requires-Dist: mdurl>=0.1.2
29
- Requires-Dist: pygments>=2.19.2
20
+ Requires-Dist: packaging>=26.0
30
21
  Requires-Dist: pyyaml>=6.0.3
31
22
  Requires-Dist: requests>=2.32.5
32
- Requires-Dist: rich>=14.2.0
33
- Requires-Dist: urllib3>=2.6.2
34
- Dynamic: author
35
- Dynamic: author-email
36
- Dynamic: classifier
37
- Dynamic: description
38
- Dynamic: description-content-type
39
- Dynamic: home-page
23
+ Requires-Dist: rich>=14.3.1
24
+ Provides-Extra: dev
25
+ Requires-Dist: mypy>=1.19.1; extra == "dev"
26
+ Requires-Dist: pre-commit>=4.5.1; extra == "dev"
27
+ Requires-Dist: pytest>=9.0.2; extra == "dev"
28
+ Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
29
+ Requires-Dist: ruff>=0.14.14; extra == "dev"
30
+ Requires-Dist: setuptools>=80.10.1; extra == "dev"
31
+ Requires-Dist: types-PyYAML>=6.0.12.20250915; extra == "dev"
32
+ Requires-Dist: types-requests>=2.32.4.20260107; extra == "dev"
33
+ Provides-Extra: docs
34
+ Requires-Dist: m2r2>=0.3.0; extra == "docs"
35
+ Requires-Dist: numpydoc>=1.10.0; extra == "docs"
36
+ Requires-Dist: sphinx-rtd-theme>=3.1.0; extra == "docs"
40
37
  Dynamic: license-file
41
- Dynamic: requires-dist
42
- Dynamic: requires-python
43
- Dynamic: summary
44
38
 
45
39
  <div align="center">
46
40
  <a href="https://github.com/activist-org/ts-backend-check"><img src="https://raw.githubusercontent.com/activist-org/ts-backend-check/main/.github/resources/TSBackendCheckGitHubBanner.png" width=1024 alt="TS Backend Check logo"></a>
@@ -61,11 +55,17 @@ Dynamic: summary
61
55
 
62
56
  `ts-backend-check` is a Python package used to check TypeScript types against their corresponding backend models to assure that all fields have been accounted for.
63
57
 
58
+ Developed by the [activist community](https://github.com/activist-org), this package is meant to help synchronize the work between frontend and backend development teams. Currently the process supports Django based backends.
59
+
64
60
  <a id="contents"></a>
65
61
 
66
62
  # **Contents**
67
63
 
68
64
  - [Usage](#usage-)
65
+ - [Command Options](#command-options-)
66
+ - [Outputs](#outputs-)
67
+ - [Installation](#installation-)
68
+ - [Configuration](#configuration-)
69
69
  - [Contributing](#contributing-)
70
70
  - [Environment setup](#environment-setup-)
71
71
  - [Contributors](#contributors-)
@@ -74,39 +74,36 @@ Dynamic: summary
74
74
 
75
75
  ## Usage [`⇧`](#contents)
76
76
 
77
- ### Installation
78
-
79
- ```bash
80
- pip install ts-backend-check
81
- ```
82
-
83
- ### Command Options
77
+ <a id="command-options-"></a>
84
78
 
85
- - `backend-model-file` (`bmf`): Path to the backend model file (e.g. Python class)
86
- - `typescript-file` (`tsf`): Path to the TypeScript interface/type file
87
-
88
- ### Basic Usage
79
+ ### Command Options [`⇧`](#contents)
89
80
 
90
81
  The CLI provides a simple interface to check TypeScript types against backend models:
91
82
 
92
83
  ```bash
93
84
  # Show help and available commands:
94
85
  ts-backend-check --help
86
+ ts-backend-check -gcf # generate a configuration file
87
+ ts-backend-check -gtp # generate a test project for experimenting with the CLI
95
88
 
96
89
  # Check a TypeScript type against a backend model:
97
- ts-backend-check -bmf <backend-model-file> -tsf <typescript-file>
90
+ ts-backend-check -m <model-identifier-from-config-file>
91
+ ts-backend-check -a # run all models
98
92
  ```
99
93
 
94
+ <a id="outputs-"></a>
95
+
96
+ ### Outputs [`⇧`](#contents)
97
+
100
98
  Example success and error outputs for the CLI are:
101
99
 
102
100
  ```
103
- ts-backend-check -bmf backend/models/user.py -tsf frontend/types/user.ts
104
-
101
+ ts-backend-check -m user
105
102
  ✅ Success: All backend models are synced with their corresponding TypeScript interfaces for the provided files.
106
103
  ```
107
104
 
108
105
  ```
109
- ts-backend-check -bmf backend/models/user.py -tsf frontend/types/user.ts
106
+ ts-backend-check -m user
110
107
 
111
108
  ❌ ts-backend-check error: There are inconsistencies between the provided backend models and TypeScript interfaces. Please see the output below for details.
112
109
 
@@ -114,7 +111,119 @@ Field 'user_name' (camelCase: 'userName') from model 'UserModel' is missing in t
114
111
  Expected to find this field in the frontend interface: User
115
112
  To ignore this field, add the following comment to the TypeScript interface: '// ts-backend-check: ignore field userName'
116
113
 
117
- Please fix the 1 field above to have the backend models of backend/models/user.py synced with the typescript interfaces of frontend/types/user.ts.
114
+ Please fix the 1 error above to have the backend models of backend/models/user.py synced with the TypeScript interfaces of frontend/types/user.ts.
115
+ ```
116
+
117
+ <a id="installation-"></a>
118
+
119
+ ## Installation
120
+
121
+ `ts-backend-check` is available for installation via [uv](https://docs.astral.sh/uv/) (recommended) or [pip](https://pypi.org/project/ts-backend-check/).
122
+
123
+ ### For Users
124
+
125
+ ```bash
126
+ # Using uv (recommended - fast, Rust-based installer):
127
+ uv pip install ts-backend-check
128
+
129
+ # Or using pip:
130
+ pip install ts-backend-check
131
+ ```
132
+
133
+ ### For Development Build
134
+
135
+ ```bash
136
+ git clone https://github.com/activist-org/ts-backend-check.git # or ideally your fork
137
+ cd ts-backend-check
138
+
139
+ # With uv (recommended):
140
+ uv sync --all-extras # install all dependencies
141
+ source .venv/bin/activate # activate venv (macOS/Linux)
142
+ # .venv\Scripts\activate # activate venv (Windows)
143
+
144
+ # Or with pip:
145
+ python -m venv .venv # create virtual environment
146
+ source .venv/bin/activate # activate venv (macOS/Linux)
147
+ # .venv\Scripts\activate # activate venv (Windows)
148
+ pip install -e .
149
+ ```
150
+
151
+ <a id="configuration-"></a>
152
+
153
+ # Configuration [`⇧`](#contents)
154
+
155
+ ts-backend-check is configured via a `.ts-backend.check.yaml` (or `.yml`) configuration file, with an example being the [configuration file for this repository](/.ts-backend-check.yaml) that we use in testing. The following describes the structure of an entry in this file:
156
+
157
+ ```yaml
158
+ model_identifier: # an identifier you define that you want to pass to the CLI
159
+ backend_model_path: path/to/a/models.py
160
+ ts_interface_path: path/to/the/corresponding/model_interfaces.ts
161
+ check_blank_model_fields: true # whether to assert that fields that can be blank must also be optional
162
+ backend_to_ts_model_name_conversions: # used if the frontend name is not the backend name
163
+ EventModel: [CommunityEvent]
164
+ ```
165
+
166
+ <a id="pre-commit-"></a>
167
+
168
+ ### pre-commit [`⇧`](#contents)
169
+
170
+ The following is an example [pre-commit](https://github.com/pre-commit/pre-commit) hook:
171
+
172
+ ```yaml
173
+ - repo: local
174
+ hooks:
175
+ - id: run-ts-backend-check
176
+ name: run ts-backend-check key-value checks
177
+ files: ^src-dir/
178
+ entry: ts-backend-check -a
179
+ language: python
180
+ pass_filenames: false
181
+ additional_dependencies:
182
+ - ts-backend-check
183
+ ```
184
+
185
+ <a id="github-action-"></a>
186
+
187
+ ### GitHub Action [`⇧`](#contents)
188
+
189
+ The following is an example YAML file for a GitHub Action to check your backend models and TypeScript interface files on PRs and commits:
190
+
191
+ ```yaml
192
+ name: pr_ci_ts_backend_check
193
+ on:
194
+ workflow_dispatch:
195
+ pull_request:
196
+ branches:
197
+ - main
198
+ types:
199
+ - opened
200
+ - reopened
201
+ - synchronize
202
+ push:
203
+ branches:
204
+ - main
205
+
206
+ jobs:
207
+ ts_backend_check:
208
+ runs-on: ubuntu-latest
209
+ steps:
210
+ - name: Checkout Project
211
+ uses: actions/checkout@v4
212
+
213
+ - name: Setup Python
214
+ uses: actions/setup-python@v5
215
+ with:
216
+ python-version: "3.12"
217
+
218
+ - name: Install uv
219
+ uses: astral-sh/setup-uv@v7
220
+
221
+ - name: Install Dependencies
222
+ run: uv sync --frozen --all-extras
223
+
224
+ - name: Execute All ts-backend-check Key-Value Checks
225
+ run: |
226
+ uv run ts-backend-check -a
118
227
  ```
119
228
 
120
229
  <a id="contributing-"></a>
@@ -125,14 +234,14 @@ Please fix the 1 field above to have the backend models of backend/models/user.p
125
234
 
126
235
  activist uses [Matrix](https://matrix.org/) for internal communication. You're more than welcome to [join us in our public chat rooms](https://matrix.to/#/#activist_community:matrix.org) to share ideas, ask questions or just say hi to the team :) We'd suggest that you use the [Element](https://element.io/) client and [Element X](https://element.io/app) for a mobile app.
127
236
 
128
- Please see the [contribution guidelines](CONTRIBUTING.md) if you are interested in contributing. Work that is in progress or could be implemented is tracked in the [issues](https://github.com/activist-org/ts-backend-check/issues) and [projects](https://github.com/activist-org/ts-backend-check/projects).
237
+ Please see the [contribution guide](CONTRIBUTING.md) if you are interested in contributing. Work that is in progress or could be implemented is tracked in the [issues](https://github.com/activist-org/ts-backend-check/issues) and [projects](https://github.com/activist-org/ts-backend-check/projects).
129
238
 
130
239
  > [!NOTE]
131
240
  > Just because an issue is assigned on GitHub doesn't mean the team isn't open to your contribution! Feel free to write [in the issues](https://github.com/activist-org/ts-backend-check/issues) and we can potentially reassign it to you.
132
241
 
133
- Also check the [`-next release-`](https://github.com/activist-org/ts-backend-check/labels/-next%20release-) and [`-priority-`](https://github.com/activist-org/ts-backend-check/labels/-priority-) labels in the [issues](https://github.com/activist-org/ts-backend-check/issues) for those that are most important, as well as those marked [`good first issue`](https://github.com/activist-org/ts-backend-check/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) that are tailored for first-time contributors. For those new to coding or our tech stack, we've collected [links to helpful documentation pages](CONTRIBUTING.md#learning-the-tech-stack-) in the [contribution guidelines](CONTRIBUTING.md).
242
+ Also check the [`-next release-`](https://github.com/activist-org/ts-backend-check/labels/-next%20release-) and [`-priority-`](https://github.com/activist-org/ts-backend-check/labels/-priority-) labels in the [issues](https://github.com/activist-org/ts-backend-check/issues) for those that are most important, as well as those marked [`good first issue`](https://github.com/activist-org/ts-backend-check/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) that are tailored for first-time contributors. For those new to coding or our tech stack, we've collected [links to helpful documentation pages](CONTRIBUTING.md#learning-the-tech-stack-) in the [contribution guide](CONTRIBUTING.md).
134
243
 
135
- We would be happy to discuss granting you further rights as a contributor after your first pull requests, with a maintainer role then being possible after continued interest in the project. activist seeks to be an inclusive, diverse and supportive organization. We'd love to have you on the team!
244
+ We would be happy to discuss granting you further rights as a contributor after your first pull requests, with a maintainer role then being possible after continued interest in the project. activist seeks to be an inclusive, diverse and supportive organization. We'd love to have you on the team! Please see the [mentorship and growth section of the contribution guide](CONTRIBUTING.md#mentorship-and-growth-) for further information.
136
245
 
137
246
  <a id="how-you-can-help-"></a>
138
247
 
@@ -196,24 +305,33 @@ git remote add upstream https://github.com/activist-org/ts-backend-check.git
196
305
  - `origin` (forked repository)
197
306
  - `upstream` (ts-backend-check repository)
198
307
 
199
- 3. Create a virtual environment, activate it and install dependencies:
308
+ 3. Install `uv` if you don't already have it by following the [official installation guide](https://docs.astral.sh/uv/getting-started/installation/).
309
+
310
+ 4. Create a virtual environment for ts-backend-check (Python `>=3.12`), activate it and install dependencies:
200
311
 
201
312
  ```bash
202
- # Unix or MacOS:
203
- python3 -m venv venv
204
- source venv/bin/activate
313
+ uv sync --all-extras # create .venv and install all dependencies from uv.lock
314
+
315
+ # Unix or macOS:
316
+ source .venv/bin/activate
205
317
 
206
318
  # Windows:
207
- python -m venv venv
208
- venv\Scripts\activate.bat
319
+ .venv\Scripts\activate.bat # .venv\Scripts\activate.ps1 (PowerShell)
320
+ ```
209
321
 
210
- # After activating venv:
211
- pip install --upgrade pip
212
- pip install -r requirements-dev.txt
322
+ > [!NOTE]
323
+ > If you change dependencies in `pyproject.toml`, regenerate the lock file with the following command:
324
+ >
325
+ > ```bash
326
+ > uv lock # refresh uv.lock for reproducible installs
327
+ > ```
213
328
 
214
- # To install the CLI for local development:
215
- pip install -e .
216
- ```
329
+ After activating the virtual environment, set up [pre-commit](https://pre-commit.com/) by running:
330
+
331
+ ```bash
332
+ pre-commit install
333
+ # uv run pre-commit run --all-files # lint and fix common problems in the codebase
334
+ ```
217
335
 
218
336
  You're now ready to work on `ts-backend-check`!
219
337
 
@@ -0,0 +1,21 @@
1
+ ts_backend_check/__init__.py,sha256=HSiEqWvU3Q4a6D7tYsoq3-B-g1HdUOGngEeGV45j8ak,172
2
+ ts_backend_check/checker.py,sha256=8ZKVYYMEs7DakF0gsH_OYSnjUVcPUJ9F3_S_HGSOmoc,12237
3
+ ts_backend_check/utils.py,sha256=c_du0n8dplhxVO_vWgfR6AiBKPAd_o6CEKaDjwxoAFE,1581
4
+ ts_backend_check/cli/__init__.py,sha256=wJK9tO9MtI10L0xRjrk7WP_qZZRBjbFw1U9jJbIbX7I,108
5
+ ts_backend_check/cli/generate_config_file.py,sha256=SvNZg2wKyrHf7L61F7pjemxNz4FfKbnl9d8FZljBlkA,7404
6
+ ts_backend_check/cli/generate_test_project.py,sha256=54-sYfrbNdn78GRMeEn9XlDTjcFHlHJ6YsPvexYdXLg,1985
7
+ ts_backend_check/cli/main.py,sha256=ukpLNDFhTuPDLi8U6vdVzA0ZAeWdTVwRLuRM-sEtPtI,10027
8
+ ts_backend_check/cli/upgrade.py,sha256=P2LdIDCLdOFs-fOMuKLQoUMijQIyKEIA5PFZVsAUwDg,2952
9
+ ts_backend_check/cli/version.py,sha256=lsocMaxAfF-FHW9O-NGH1sAo6svjuLgdGFxaC-XVoZc,2845
10
+ ts_backend_check/parsers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ ts_backend_check/parsers/django_parser.py,sha256=LmYpyySO789OIh094BypUDcqyfb8RnO_JyLiM2R9fiM,3899
12
+ ts_backend_check/parsers/typescript_parser.py,sha256=e7Dy8f_gvaxF8ceMS-8PtGCMFlzDXmaVgeFglVUIoZg,3940
13
+ ts_backend_check/test_project/backend/models.py,sha256=Jz2p_36MNGpm-BYuGejZxEUop1DJWNKTTdaivv28BMk,962
14
+ ts_backend_check/test_project/frontend/invalid_interfaces.ts,sha256=QkyXCVQnQFeLAEzhotaTiABFzAIgIeYZvF348gVUZiI,683
15
+ ts_backend_check/test_project/frontend/valid_interfaces.ts,sha256=ifJr9qJfzpc-0lA_vaOdyLRof2_8JZsPMZUhWG5hEJo,427
16
+ ts_backend_check-1.3.0.dist-info/licenses/LICENSE.txt,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
17
+ ts_backend_check-1.3.0.dist-info/METADATA,sha256=OHTRAbyLrHuW19Wk222cFPNTt-4J8qzetuwzAT08vjw,15196
18
+ ts_backend_check-1.3.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
19
+ ts_backend_check-1.3.0.dist-info/entry_points.txt,sha256=QeY7RJu20otBnQlhMMZxPL8nB3mP3M3U3h3nOlSFWSU,68
20
+ ts_backend_check-1.3.0.dist-info/top_level.txt,sha256=VzfNWQ3fPNdl-OBdtUKsUWR8Asdd27E3OJNUg2oQU8Y,17
21
+ ts_backend_check-1.3.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.9.0)
2
+ Generator: setuptools (80.10.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,111 +0,0 @@
1
- # SPDX-License-Identifier: GPL-3.0-or-later
2
- """
3
- Functionality to check TypeScript interfaces for fields that should be optional based on Django models.
4
- """
5
-
6
- import ast
7
- from pathlib import Path
8
- from typing import Dict, Set
9
-
10
- from rich.console import Console
11
-
12
- from ts_backend_check.parsers.django_parser import DjangoModelVisitor
13
-
14
- ROOT_DIR = Path.cwd()
15
- console = Console()
16
-
17
-
18
- class BlankParser(DjangoModelVisitor):
19
- """
20
- AST visitor to extract blank fields from Django models based on DjangoModelVisitor.
21
- """
22
-
23
- def __init__(self) -> None:
24
- super().__init__()
25
- self.blank_models: Dict[str, Set[str]] = {}
26
-
27
- def visit_Assign(self, node: ast.Assign) -> None:
28
- """
29
- Check assignment statements within a class which accepts blank fields.
30
-
31
- Parameters
32
- ----------
33
- node : ast.Assign
34
- An assignment definition from Python AST (Abstract Syntax Tree).
35
- It represents an assignment statement (e.g., x = 42).
36
- """
37
- if not self.current_model:
38
- return
39
-
40
- for target in node.targets:
41
- if (
42
- (
43
- isinstance(target, ast.Name)
44
- and not target.id.startswith("_")
45
- and isinstance(node.value, ast.Call)
46
- and hasattr(node.value.func, "attr")
47
- )
48
- and any(
49
- field_type in node.value.func.attr
50
- for field_type in self.DJANGO_FIELD_TYPES
51
- )
52
- and any(
53
- kw.arg == "blank"
54
- and isinstance(kw.value, ast.Constant)
55
- and kw.value.value is True
56
- for kw in node.value.keywords
57
- )
58
- ):
59
- if self.current_model not in self.blank_models:
60
- self.blank_models[self.current_model] = set()
61
-
62
- self.blank_models[self.current_model].add(target.id)
63
-
64
-
65
- def check_blank(file_path: str) -> Dict[str, Set[str]]:
66
- """
67
- Function to extract fields from Django models file which accepts blank values.
68
-
69
- Parameters
70
- ----------
71
- file_path : str
72
- A models.py file that defines Django models.
73
-
74
- Returns
75
- -------
76
- Dict[str, Set[str]]
77
- The fields from the models file extracted into a dictionary for future processing.
78
- """
79
- model_path = ROOT_DIR / file_path
80
-
81
- if model_path.is_file():
82
- with open(model_path, "r", encoding="utf-8") as f:
83
- content = f.read().strip()
84
- # Skip any empty lines at the beginning.
85
- while content.startswith("\n"):
86
- content = content[1:]
87
-
88
- try:
89
- tree = ast.parse(content)
90
-
91
- except SyntaxError as e:
92
- raise SyntaxError(
93
- f"Failed to parse {model_path}. Make sure it's a valid Python file. Error: {str(e)}"
94
- ) from e
95
-
96
- parser = BlankParser()
97
- parser.visit(tree)
98
-
99
- if len(parser.blank_models) == 0:
100
- console.print("[green]No models have any blank fields specified.[green]")
101
-
102
- else:
103
- for k, v in parser.blank_models.items():
104
- console.print(
105
- f"[yellow]Model {k} has fields {sorted(v)} set as optional."
106
- )
107
-
108
- else:
109
- print("Check the path entered.")
110
-
111
- return parser.blank_models
@@ -1,164 +0,0 @@
1
- # SPDX-License-Identifier: GPL-3.0-or-later
2
- """
3
- Configure cli to run based on a YAML configuration file.
4
- """
5
-
6
- from pathlib import Path
7
-
8
- from yaml import dump
9
-
10
- YAML_CONFIG_FILE_PATH = (
11
- Path(__file__).parent.parent.parent.parent / ".ts-backend-check.yaml"
12
- )
13
-
14
- PROJECT_ROOT_PATH = Path(__file__).parent.parent.parent.parent
15
-
16
-
17
- def configure_paths() -> None:
18
- """
19
- Function to receive paths from user.
20
- """
21
- config_options = {}
22
- while True:
23
- print("\n--- Adding new model/interface configuration ---")
24
-
25
- key = input(
26
- "Enter the model-interface type (eg: 'auth', 'orgs', 'groups'): "
27
- ).strip()
28
- if not key:
29
- print("Key cannot be empty. Please try again.")
30
- continue
31
-
32
- # Get backend path.
33
- while True:
34
- backend_path = input("Enter the path for Django models.py file: ").strip()
35
- if not backend_path:
36
- print("Path cannot be empty.")
37
- continue
38
-
39
- if path_exists(backend_path):
40
- break
41
-
42
- print(f"File not found: {PROJECT_ROOT_PATH / backend_path}")
43
- print("Please check the path and try again.")
44
-
45
- # Get frontend path.
46
- while True:
47
- frontend_path = input("Enter path to TypeScript interface file: ").strip()
48
- if not frontend_path:
49
- print("Path cannot be empty. Please try again.")
50
- continue
51
-
52
- if path_exists(frontend_path):
53
- break
54
-
55
- print(f"File not found: {PROJECT_ROOT_PATH / frontend_path}")
56
- print("Please check the path and try again.")
57
-
58
- config_options[key] = {
59
- "backend_model_path": backend_path,
60
- "frontend_interface_path": frontend_path,
61
- }
62
-
63
- print(f"✓ Added configuration for '{key}'")
64
-
65
- continue_config = input(
66
- "Do you wish to add another model/interface configuration? (y/[n])"
67
- ).strip()
68
-
69
- if continue_config.lower() in ["n", ""]:
70
- if config_options:
71
- write_config(config_options)
72
- print(
73
- f"\n✓ Configuration complete! Added {len(config_options)} configuration(s)."
74
- )
75
- break
76
-
77
- if config_options:
78
- write_config(config_options)
79
- print(
80
- f"\n✓ Configuration complete! Added {len(config_options)} configuration(s)."
81
- )
82
-
83
- else:
84
- print("\nNo configurations added.")
85
-
86
-
87
- def path_exists(path: str) -> bool:
88
- """
89
- Check if path entered by the user exists withing the filesystem.
90
-
91
- Parameters
92
- ----------
93
- path : str
94
- Path should be entered as a string from the user.
95
-
96
- Returns
97
- -------
98
- bool
99
- Return true or false based on if path exists.
100
- """
101
- full_path = Path(__file__).parent.parent.parent.parent / path
102
- if Path(full_path).is_file():
103
- return True
104
-
105
- return False
106
-
107
-
108
- def write_config(config: dict[str, dict[str, str]]) -> None:
109
- """
110
- Function to write into .ts-backend-check.yaml file.
111
-
112
- Parameters
113
- ----------
114
- config : dict[str, dict[str, str]]
115
- Passing a dictionary as key str with another dict as value.
116
- """
117
- try:
118
- options = f"""# Configuration file for ts-backend-check validation.
119
- # See https://github.com/activist-org/ts-backend-check for details.
120
-
121
- # Paths:
122
- {dump(config)}
123
-
124
- """
125
- with open(YAML_CONFIG_FILE_PATH, "w") as file:
126
- file.write(options)
127
-
128
- except IOError as e:
129
- print(f"Error while writing config file: {e}")
130
-
131
-
132
- def create_config() -> None:
133
- """
134
- Main function to create or update configuration.
135
- """
136
- print("ts-backend-check Configuration Setup")
137
- print("=" * 40)
138
-
139
- if YAML_CONFIG_FILE_PATH.is_file():
140
- reconfig_choice = input(
141
- "Configuration file exists. Do you want to re-configure your .ts-backend-check.yaml file? (y/[n]) "
142
- )
143
- if reconfig_choice.lower() in ["n", ""]:
144
- print("Exiting without changes.")
145
- return
146
-
147
- print("Reconfiguring...")
148
-
149
- else:
150
- print("Creating new configuration file...")
151
-
152
- try:
153
- configure_paths()
154
-
155
- except KeyboardInterrupt:
156
- print("\n\nConfiguration cancelled by user.")
157
-
158
- except Exception as e:
159
- print(f"\nError during configuration: {e}")
160
- print("Configuration cancelled.")
161
-
162
-
163
- if __name__ == "__main__":
164
- create_config()