0
# Programmatic API
1
2
Core classes and functions for embedding poethepoet functionality into other applications. Provides full control over task execution, configuration management, and environment setup.
3
4
## Capabilities
5
6
### Main Application Class
7
8
The PoeThePoet class serves as the primary interface for programmatic usage, handling task resolution, execution, and configuration management.
9
10
```python { .api }
11
class PoeThePoet:
12
def __init__(
13
self,
14
cwd: Path | str | None = None,
15
config: Mapping[str, Any] | PoeConfig | None = None,
16
output: PoeIO | IO = None,
17
poetry_env_path: str | None = None,
18
config_name: str | None = None,
19
program_name: str = "poe",
20
env: Mapping[str, str] | None = None,
21
suppress_args: Sequence[str] = tuple()
22
):
23
"""
24
Initialize PoeThePoet application.
25
26
Args:
27
cwd: Working directory path
28
config: Configuration object or mapping
29
output: Output handler for messages
30
poetry_env_path: Poetry virtual environment path
31
config_name: Configuration file name
32
program_name: Program name for help text
33
env: Environment variables
34
suppress_args: Arguments to suppress in help
35
"""
36
37
def __call__(self, cli_args: Sequence[str], internal: bool = False) -> int:
38
"""
39
Execute with CLI arguments.
40
41
Args:
42
cli_args: Command line arguments
43
internal: Internal execution flag
44
45
Returns:
46
Exit code (0 for success)
47
"""
48
49
def resolve_task(self, allow_hidden: bool = False) -> PoeTask | None:
50
"""
51
Resolve task by name from configuration.
52
53
Args:
54
allow_hidden: Allow hidden tasks (starting with _)
55
56
Returns:
57
Resolved task object or None if not found
58
"""
59
60
def run_task(self, task: PoeTask, context: RunContext | None = None) -> int | None:
61
"""
62
Execute a specific task.
63
64
Args:
65
task: Task object to execute
66
context: Execution context
67
68
Returns:
69
Exit code or None
70
"""
71
72
def get_run_context(self, multistage: bool = False) -> RunContext:
73
"""
74
Get execution context for task running.
75
76
Args:
77
multistage: Enable multistage context
78
79
Returns:
80
Runtime context object
81
"""
82
83
def modify_verbosity(self, offset: int) -> None:
84
"""
85
Adjust verbosity level.
86
87
Args:
88
offset: Verbosity change (-2 to +2)
89
"""
90
91
def print_help(
92
self,
93
info: str | None = None,
94
error: str | PoeException | None = None
95
) -> None:
96
"""
97
Print help message.
98
99
Args:
100
info: Additional info message
101
error: Error message or exception
102
"""
103
```
104
105
### Configuration Management
106
107
The PoeConfig class handles loading and parsing of task configurations from various file formats.
108
109
```python { .api }
110
class PoeConfig:
111
def __init__(
112
self,
113
cwd: Optional[Union[Path, str]] = None,
114
table: Optional[Mapping[str, Any]] = None,
115
config_name: Optional[Union[str, Sequence[str]]] = None,
116
io: Optional["PoeIO"] = None
117
):
118
"""
119
Initialize configuration manager.
120
121
Args:
122
cwd: Working directory
123
table: Pre-loaded configuration table
124
config_name: Config file name(s) to search for
125
io: IO handler for messages
126
"""
127
128
def load(
129
self,
130
target_path: Optional[Union[Path, str]] = None,
131
strict: bool = True
132
) -> None:
133
"""
134
Load configuration from files.
135
136
Args:
137
target_path: Specific path to load from
138
strict: Strict validation mode
139
"""
140
141
def lookup_task(self, name: str) -> Mapping[str, Any]:
142
"""
143
Look up task definition by name.
144
145
Args:
146
name: Task name to look up
147
148
Returns:
149
Task definition mapping
150
"""
151
152
def partitions(self, included_first=True) -> Iterator[ConfigPartition]:
153
"""
154
Get configuration partitions.
155
156
Args:
157
included_first: Include first partition
158
159
Yields:
160
Configuration partition objects
161
"""
162
163
def resolve_git_path(self, resource_path: str) -> str:
164
"""
165
Resolve git-relative paths.
166
167
Args:
168
resource_path: Resource path to resolve
169
170
Returns:
171
Resolved absolute path
172
"""
173
174
# Properties
175
@property
176
def executor(self) -> Mapping[str, Any]:
177
"""Executor configuration."""
178
179
@property
180
def task_names(self) -> Iterator[str]:
181
"""Available task names."""
182
183
@property
184
def tasks(self) -> dict[str, Any]:
185
"""Task definitions mapping."""
186
187
@property
188
def default_task_type(self) -> str:
189
"""Default task type."""
190
191
@property
192
def shell_interpreter(self) -> tuple[str, ...]:
193
"""Shell interpreter command."""
194
195
@property
196
def verbosity(self) -> int:
197
"""Verbosity level."""
198
199
@property
200
def is_poetry_project(self) -> bool:
201
"""Whether project uses Poetry."""
202
203
@property
204
def is_uv_project(self) -> bool:
205
"""Whether project uses UV."""
206
207
@property
208
def project_dir(self) -> Path:
209
"""Project root directory."""
210
```
211
212
### Input/Output Management
213
214
The PoeIO class manages input/output streams and verbosity control for poethepoet operations.
215
216
```python { .api }
217
class PoeIO:
218
def __init__(
219
self,
220
parent: PoeIO | None = None,
221
output: IO | None = None,
222
error: IO | None = None,
223
input: IO | None = None,
224
baseline_verbosity: int | None = None,
225
verbosity_offset: int | None = None,
226
ansi: bool | None = None,
227
make_default: bool = False
228
):
229
"""
230
Initialize IO handler.
231
232
Args:
233
parent: Parent IO handler
234
output: Output stream
235
error: Error stream
236
input: Input stream
237
baseline_verbosity: Base verbosity level
238
verbosity_offset: Verbosity offset
239
ansi: ANSI color support
240
make_default: Make default IO instance
241
"""
242
243
@classmethod
244
def get_default_io(cls) -> "PoeIO":
245
"""Get default IO instance."""
246
247
def configure(self, ansi_enabled, baseline, offset, dont_override) -> None:
248
"""Configure IO settings."""
249
250
def print(
251
self,
252
message,
253
message_verbosity=0,
254
end="\n"
255
) -> None:
256
"""
257
Print message with verbosity control.
258
259
Args:
260
message: Message to print
261
message_verbosity: Required verbosity level
262
end: Line ending character
263
"""
264
265
def print_warning(
266
self,
267
message,
268
message_verbosity=0,
269
prefix="Warning",
270
end="\n"
271
) -> None:
272
"""Print warning message."""
273
274
def print_error(self, message, message_verbosity=0, end="\n") -> None:
275
"""Print error message."""
276
277
def print_debug(self, message, message_verbosity=0, end="\n") -> None:
278
"""Print debug message."""
279
280
def is_debug_enabled(self) -> bool:
281
"""Check if debug mode is enabled."""
282
```
283
284
### User Interface Management
285
286
The PoeUi class handles command-line interface construction and argument parsing.
287
288
```python { .api }
289
class PoeUi:
290
def __init__(
291
self,
292
io: PoeIO,
293
program_name: str = "poe",
294
suppress_args: Sequence[str] = tuple()
295
):
296
"""
297
Initialize UI manager.
298
299
Args:
300
io: IO handler
301
program_name: Program name for help
302
suppress_args: Arguments to suppress
303
"""
304
305
def build_parser(self) -> ArgumentParser:
306
"""Build argument parser."""
307
308
def parse_args(self, cli_args: Sequence[str]) -> Tuple[...]:
309
"""Parse CLI arguments."""
310
311
def print_help(self, tasks, info=None, error=None) -> None:
312
"""Print help message."""
313
314
def print_error(self, error) -> None:
315
"""Print error message."""
316
317
def print_version(self) -> None:
318
"""Print version information."""
319
```
320
321
### Context Management
322
323
Context objects manage task execution state and environment.
324
325
```python { .api }
326
class RunContext:
327
"""Runtime execution context for task execution."""
328
329
class InitializationContext:
330
"""Task initialization context."""
331
332
class TaskOutputCache:
333
"""Task output caching."""
334
335
class ContextProtocol:
336
"""Context interface protocol."""
337
```
338
339
### Virtual Environment Support
340
341
The Virtualenv class provides virtual environment detection and executable resolution.
342
343
```python { .api }
344
class Virtualenv:
345
def __init__(self, path: Union[Path, str]):
346
"""
347
Initialize virtualenv handler.
348
349
Args:
350
path: Path to virtual environment
351
"""
352
353
def exists(self) -> bool:
354
"""Check if virtualenv exists."""
355
356
def bin_dir(self) -> Path:
357
"""Get binary directory path."""
358
359
def resolve_executable(self, executable: str) -> str:
360
"""
361
Resolve executable in virtualenv.
362
363
Args:
364
executable: Executable name to resolve
365
366
Returns:
367
Full path to executable
368
"""
369
370
@classmethod
371
def detect(cls, parent_dir: Path) -> bool:
372
"""
373
Detect virtualenv in directory.
374
375
Args:
376
parent_dir: Directory to search in
377
378
Returns:
379
True if virtualenv detected
380
"""
381
```
382
383
## Usage Examples
384
385
### Basic Application Setup
386
387
```python
388
from poethepoet.app import PoeThePoet
389
from poethepoet.io import PoeIO
390
from pathlib import Path
391
import sys
392
393
# Create IO handler
394
io = PoeIO(output=sys.stdout, error=sys.stderr)
395
396
# Create application with custom configuration
397
app = PoeThePoet(
398
cwd=Path("."),
399
output=io,
400
program_name="my_task_runner"
401
)
402
403
# Execute task
404
result = app(cli_args=["test", "--verbose"])
405
```
406
407
### Configuration Loading
408
409
```python
410
from poethepoet.config import PoeConfig
411
from pathlib import Path
412
413
# Load configuration from specific file
414
config = PoeConfig(cwd=Path("."))
415
config.load("./custom_tasks.toml")
416
417
# Access task definitions
418
for task_name in config.task_names:
419
task_def = config.lookup_task(task_name)
420
print(f"Task {task_name}: {task_def}")
421
```
422
423
### Direct Task Execution
424
425
```python
426
from poethepoet.app import PoeThePoet
427
from pathlib import Path
428
429
app = PoeThePoet(cwd=Path("."))
430
431
# Resolve specific task
432
task = app.resolve_task("test")
433
if task:
434
# Get execution context
435
context = app.get_run_context()
436
437
# Run the task
438
result = app.run_task(task, context)
439
print(f"Task completed with exit code: {result}")
440
```