0
# CLI Interface
1
2
Command-line interface functionality for standalone usage of poetry-dynamic-versioning. Provides subcommands for configuration management, version display, and manual version application with comprehensive error handling and reporting.
3
4
## Capabilities
5
6
### Main Entry Point
7
8
Primary entry point for the command-line script that handles argument parsing, command dispatch, and error management for standalone usage.
9
10
```python { .api }
11
def main() -> None:
12
"""
13
Main entry point for poetry-dynamic-versioning command-line script.
14
15
Handles CLI argument parsing, command dispatch, and error reporting.
16
Sets CLI mode and executes appropriate subcommand or default action.
17
18
Exits with code 1 on errors, 0 on success.
19
"""
20
```
21
22
### Configuration Management
23
24
Enable dynamic versioning in project configuration by updating pyproject.toml with appropriate settings for both Classic Poetry and PEP 621 modes.
25
26
```python { .api }
27
def enable() -> None:
28
"""
29
Enable dynamic versioning in project's pyproject.toml.
30
31
Updates configuration to enable the plugin, sets up build system
32
requirements, and configures appropriate project format settings.
33
34
Raises:
35
- RuntimeError: Unable to find pyproject.toml in current directory tree
36
"""
37
38
def _enable_in_doc(doc: tomlkit.TOMLDocument, env: Optional[Mapping] = None) -> tomlkit.TOMLDocument:
39
"""
40
Enable dynamic versioning configuration in a TOML document.
41
42
Parameters:
43
- doc: TOML document to modify
44
- env: Environment variables for override detection
45
46
Returns:
47
tomlkit.TOMLDocument: Modified document with dynamic versioning enabled
48
"""
49
```
50
51
### Version Display
52
53
Display current dynamic version without modifying any files, useful for testing configuration and debugging version detection.
54
55
```python { .api }
56
def show() -> None:
57
"""
58
Display the current dynamic version without modifying files.
59
60
Loads configuration from pyproject.toml and prints the computed
61
version string to stdout.
62
63
Raises:
64
- RuntimeError: Unable to find pyproject.toml or compute version
65
"""
66
```
67
68
### Manual Version Application
69
70
Apply dynamic versioning manually with validation and comprehensive reporting of changes made to project files.
71
72
```python { .api }
73
def apply(*, standalone: bool) -> None:
74
"""
75
Apply dynamic versioning to project files with validation.
76
77
Parameters:
78
- standalone: Whether running in standalone mode (affects reporting)
79
80
Validates configuration, applies version to files, and reports results.
81
82
Raises:
83
- RuntimeError: Unable to determine dynamic version or apply changes
84
"""
85
86
def report_apply(name: str) -> None:
87
"""
88
Report the results of version application.
89
90
Parameters:
91
- name: Project name that was processed
92
93
Prints version information and list of modified files to stderr.
94
"""
95
```
96
97
### Validation System
98
99
Comprehensive configuration validation with detailed error reporting for troubleshooting configuration issues.
100
101
```python { .api }
102
def validate(*, standalone: bool, config: Optional[Mapping] = None) -> None:
103
"""
104
Validate configuration and print any errors found.
105
106
Parameters:
107
- standalone: Whether running in standalone mode (affects error formatting)
108
- config: Configuration to validate (auto-detects if None)
109
110
Prints validation errors to stderr if any are found.
111
"""
112
```
113
114
### Argument Parsing
115
116
Command-line argument parsing system with subcommand support and help text generation.
117
118
```python { .api }
119
def get_parser() -> argparse.ArgumentParser:
120
"""
121
Create and configure argument parser for CLI interface.
122
123
Returns:
124
argparse.ArgumentParser: Configured parser with subcommands
125
"""
126
127
def parse_args(argv=None) -> argparse.Namespace:
128
"""
129
Parse command-line arguments.
130
131
Parameters:
132
- argv: Argument list (defaults to sys.argv)
133
134
Returns:
135
argparse.Namespace: Parsed arguments with command and options
136
"""
137
```
138
139
## CLI Commands
140
141
### Default Command (no subcommand)
142
143
```bash
144
poetry-dynamic-versioning
145
```
146
147
Applies dynamic versioning to the current project, modifying files and leaving changes in place for inspection. Equivalent to `poetry dynamic-versioning` when used as a plugin.
148
149
### Enable Subcommand
150
151
```bash
152
poetry-dynamic-versioning enable
153
```
154
155
Updates pyproject.toml to enable dynamic versioning with standard configuration. Creates or modifies:
156
- `[tool.poetry-dynamic-versioning]` section with `enable = true`
157
- `[build-system]` section with appropriate requirements and backend
158
- PEP 621 `[project]` dynamic version configuration if applicable
159
160
### Show Subcommand
161
162
```bash
163
poetry-dynamic-versioning show
164
```
165
166
Displays the current dynamic version without modifying any files. Useful for:
167
- Testing version computation
168
- Debugging configuration issues
169
- CI/CD pipeline version extraction
170
171
## Configuration Constants
172
173
```python { .api }
174
class Key:
175
"""Configuration key constants."""
176
tool = "tool"
177
pdv = "poetry-dynamic-versioning"
178
enable = "enable"
179
build_system = "build-system"
180
requires = "requires"
181
build_backend = "build-backend"
182
project = "project"
183
poetry = "poetry"
184
dynamic = "dynamic"
185
version = "version"
186
name = "name"
187
188
class Command:
189
"""CLI command name constants."""
190
dv = "dynamic-versioning"
191
enable = "enable"
192
show = "show"
193
dv_enable = "dynamic-versioning enable"
194
dv_show = "dynamic-versioning show"
195
196
class Help:
197
"""Help text constants."""
198
main = "Apply the dynamic version to all relevant files and leave the changes in-place..."
199
enable = "Update pyproject.toml to enable the plugin using a typical configuration..."
200
show = "Print the version without changing any files."
201
```
202
203
## Default Configuration Values
204
205
```python { .api }
206
_DEFAULT_REQUIRES = ["poetry-core>=1.0.0", "poetry-dynamic-versioning>=1.0.0,<2.0.0"]
207
_DEFAULT_BUILD_BACKEND = "poetry_dynamic_versioning.backend"
208
```
209
210
## Usage Examples
211
212
### Basic CLI Usage
213
214
```bash
215
# Apply dynamic versioning to current project
216
poetry-dynamic-versioning
217
218
# Enable dynamic versioning in project configuration
219
poetry-dynamic-versioning enable
220
221
# Show current version without changes
222
poetry-dynamic-versioning show
223
```
224
225
### Programmatic CLI Usage
226
227
```python
228
from poetry_dynamic_versioning.cli import main, enable, show, apply
229
from poetry_dynamic_versioning import _state
230
231
# Set CLI mode
232
_state.cli_mode = True
233
234
# Enable dynamic versioning
235
try:
236
enable()
237
print("Dynamic versioning enabled successfully")
238
except RuntimeError as e:
239
print(f"Failed to enable: {e}")
240
241
# Show current version
242
try:
243
show() # Prints version to stdout
244
except RuntimeError as e:
245
print(f"Failed to show version: {e}")
246
247
# Apply versioning manually
248
try:
249
apply(standalone=True)
250
except RuntimeError as e:
251
print(f"Failed to apply version: {e}")
252
```
253
254
### Configuration Validation
255
256
```python
257
from poetry_dynamic_versioning.cli import validate
258
import tomlkit
259
260
# Load and validate current project configuration
261
validate(standalone=True)
262
263
# Validate specific configuration
264
with open("pyproject.toml", "rb") as f:
265
config = tomlkit.parse(f.read().decode("utf-8"))
266
267
validate(standalone=True, config=config)
268
```
269
270
### Enable Configuration Programmatically
271
272
```python
273
from poetry_dynamic_versioning.cli import _enable_in_doc
274
import tomlkit
275
276
# Load existing pyproject.toml
277
with open("pyproject.toml", "rb") as f:
278
doc = tomlkit.parse(f.read().decode("utf-8"))
279
280
# Enable dynamic versioning
281
updated_doc = _enable_in_doc(doc)
282
283
# Save updated configuration
284
with open("pyproject.toml", "wb") as f:
285
f.write(tomlkit.dumps(updated_doc).encode("utf-8"))
286
287
print("Dynamic versioning configuration added")
288
```
289
290
### Custom Argument Parsing
291
292
```python
293
from poetry_dynamic_versioning.cli import get_parser, parse_args
294
295
# Get configured parser
296
parser = get_parser()
297
298
# Parse custom arguments
299
args = parse_args(["enable"])
300
print(f"Command: {args.cmd}") # "enable"
301
302
# Parse with show command
303
args = parse_args(["show"])
304
print(f"Command: {args.cmd}") # "show"
305
306
# Parse default (no subcommand)
307
args = parse_args([])
308
print(f"Command: {args.cmd}") # None (default action)
309
```
310
311
### Integration with Build Systems
312
313
The CLI can be used in build scripts and CI/CD pipelines:
314
315
```bash
316
#!/bin/bash
317
# Build script example
318
319
# Show version for logging
320
echo "Building version: $(poetry-dynamic-versioning show)"
321
322
# Enable if not already configured
323
poetry-dynamic-versioning enable
324
325
# Build with Poetry
326
poetry build
327
328
# Version is automatically handled during build
329
```
330
331
### Error Handling
332
333
```python
334
import sys
335
from poetry_dynamic_versioning.cli import main
336
337
# The main function handles all errors and exits appropriately
338
try:
339
main()
340
except SystemExit as e:
341
if e.code != 0:
342
print("Command failed")
343
else:
344
print("Command succeeded")
345
```
346
347
### Environment Integration
348
349
The CLI respects the same environment variables as the plugin:
350
351
```bash
352
# Override version globally
353
export POETRY_DYNAMIC_VERSIONING_BYPASS="1.0.0-custom"
354
poetry-dynamic-versioning show # Outputs: 1.0.0-custom
355
356
# Enable debug output
357
export POETRY_DYNAMIC_VERSIONING_DEBUG="1"
358
poetry-dynamic-versioning # Shows debug information
359
360
# Override specific project
361
export POETRY_DYNAMIC_VERSIONING_OVERRIDE="my-project=2.0.0"
362
poetry-dynamic-versioning show # Uses override if project name matches
363
```