0
# Command Line Interface
1
2
Complete command-line interface with extensible commands, configuration management, plugin system, and comprehensive CLI application framework.
3
4
## Capabilities
5
6
### Main Application Class
7
8
Core CLI application class that handles command parsing, configuration loading, and command execution.
9
10
```python { .api }
11
class DoitMain:
12
"""
13
Main CLI application class for doit command-line interface.
14
15
Handles command parsing, configuration loading, plugin management,
16
and execution of doit commands with proper error handling.
17
"""
18
19
BIN_NAME = sys.argv[0].split('/')[-1] # Binary name for help/error messages
20
DOIT_CMDS = (Help, Run, List, Info, Clean, Forget, Ignore, DumpDB, Strace, TabCompletion, ResetDep)
21
22
def __init__(self, task_loader=None, config_filenames=('pyproject.toml', 'doit.cfg'), extra_config=None):
23
"""
24
Initialize DoitMain instance.
25
26
Args:
27
task_loader: Task loader instance for discovering tasks
28
config_filenames (str|list): Configuration file names to load
29
extra_config (dict, optional): Extra configuration values by section
30
"""
31
32
def run(self, all_args):
33
"""
34
Entry point for all commands.
35
36
Args:
37
all_args (list): Command line arguments
38
39
Returns:
40
int: Exit code (0=success, 1=task failure, 2=task error, 3=user error)
41
"""
42
43
def get_cmds(self):
44
"""
45
Get all available sub-commands including plugins.
46
47
Returns:
48
PluginDict: Dictionary of command name to command class
49
"""
50
51
@staticmethod
52
def print_version():
53
"""Print doit version and library location"""
54
55
def process_args(self, cmd_args):
56
"""
57
Process command line arguments, extract global variables.
58
59
Args:
60
cmd_args (list): Raw command line arguments
61
62
Returns:
63
list: Arguments with global variables removed
64
"""
65
```
66
67
### Configuration Management
68
69
Classes for loading and managing configuration from TOML and INI files.
70
71
```python { .api }
72
class DoitConfig:
73
"""
74
Parse and store values from INI and TOML configuration files.
75
76
Supports both traditional INI format and modern TOML format with
77
proper section handling and plugin configuration.
78
"""
79
80
PLUGIN_TYPES = ['command', 'loader', 'backend', 'reporter']
81
82
def __init__(self):
83
"""Initialize configuration parser"""
84
85
def loads(self, config_filenames):
86
"""
87
Load configuration from multiple files.
88
89
Args:
90
config_filenames (list): List of configuration file paths
91
"""
92
93
@property
94
def toml(self):
95
"""Get available TOML library (tomllib, tomli, or tomlkit)"""
96
97
def as_dict(self):
98
"""Return configuration values in dictionary format"""
99
100
@staticmethod
101
def load_config_ini(filenames):
102
"""
103
Read configuration from INI files.
104
105
Args:
106
filenames (str|list): INI file path(s) to read
107
108
Returns:
109
ConfigParser: Parsed INI configuration
110
"""
111
112
def load_config_toml(self, filename, prefix):
113
"""
114
Read configuration from TOML file.
115
116
Args:
117
filename (str): TOML file path
118
prefix (str): Section prefix (e.g., 'tool.doit')
119
120
Returns:
121
dict: Parsed TOML configuration
122
"""
123
```
124
125
### Variable Management
126
127
Functions for managing command-line variables that can be accessed within tasks.
128
129
```python { .api }
130
def get_var(name, default=None):
131
"""
132
Get value of command-line variable.
133
134
Args:
135
name (str): Variable name
136
default: Default value if variable not set
137
138
Returns:
139
Variable value or default, None if variables not initialized
140
"""
141
142
def set_var(name, value):
143
"""
144
Set command-line variable value.
145
146
Args:
147
name (str): Variable name
148
value: Variable value
149
"""
150
151
def reset_vars():
152
"""Reset all command-line variables to empty state"""
153
```
154
155
### Available Commands
156
157
Built-in commands available through the CLI interface.
158
159
```python { .api }
160
# Core Commands (all extend base command class)
161
class Help: """Display help information"""
162
class Run: """Execute tasks (default command)"""
163
class List: """List available tasks"""
164
class Info: """Show task information and metadata"""
165
class Clean: """Clean task outputs and targets"""
166
class Forget: """Forget task execution state"""
167
class Ignore: """Ignore task failures"""
168
class DumpDB: """Dump dependency database contents"""
169
class Strace: """Trace task file dependencies"""
170
class TabCompletion: """Generate shell tab completion"""
171
class ResetDep: """Reset task dependencies"""
172
```
173
174
### Usage Examples
175
176
#### Basic CLI Usage
177
178
```bash
179
# List all available tasks
180
doit list
181
182
# Run all tasks (default command)
183
doit
184
185
# Run specific tasks
186
doit build test
187
188
# Get help for specific command
189
doit help run
190
191
# Show task information
192
doit info build
193
194
# Clean task outputs
195
doit clean
196
197
# Run with variables
198
doit build version=1.2.0 env=production
199
200
# Run with specific verbosity
201
doit -v 2 build
202
203
# Continue on errors
204
doit --continue build test deploy
205
```
206
207
#### Custom CLI Application
208
209
```python
210
from doit.doit_cmd import DoitMain
211
from doit.cmd_base import ModuleTaskLoader
212
213
def task_custom():
214
"""Custom task"""
215
return {'actions': ['echo "Custom application"']}
216
217
def main():
218
"""Custom CLI application using doit framework"""
219
220
# Create task loader with current module
221
loader = ModuleTaskLoader(globals())
222
223
# Create main application instance
224
app = DoitMain(
225
task_loader=loader,
226
config_filenames=['myapp.cfg', 'pyproject.toml']
227
)
228
229
# Override binary name for help messages
230
app.BIN_NAME = 'myapp'
231
232
# Run with command line arguments
233
import sys
234
result = app.run(sys.argv[1:])
235
sys.exit(result)
236
237
if __name__ == '__main__':
238
main()
239
```
240
241
#### Configuration File Examples
242
243
**TOML Configuration (pyproject.toml):**
244
245
```toml
246
[tool.doit]
247
default_tasks = ["build", "test"]
248
continue = true
249
verbosity = 2
250
251
[tool.doit.commands.run]
252
parallel_type = "process"
253
num_process = 4
254
255
[tool.doit.tasks.build]
256
verbosity = 1
257
258
[tool.doit.plugins.command]
259
my_command = "mypackage.commands:MyCommand"
260
```
261
262
**INI Configuration (doit.cfg):**
263
264
```ini
265
[GLOBAL]
266
default_tasks = build,test
267
continue = True
268
verbosity = 2
269
270
[run]
271
parallel_type = process
272
num_process = 4
273
274
[task:build]
275
verbosity = 1
276
277
[COMMAND]
278
my_command = mypackage.commands:MyCommand
279
```
280
281
#### Variable Usage in Tasks
282
283
```python
284
from doit import get_var
285
286
def task_deploy():
287
"""Deploy to specified environment"""
288
env = get_var('env', 'development')
289
version = get_var('version', '1.0.0')
290
291
return {
292
'actions': [f'deploy.sh --env {env} --version {version}'],
293
'verbosity': 2
294
}
295
296
# Run with: doit deploy env=production version=2.1.0
297
```
298
299
#### Plugin Command Development
300
301
```python
302
from doit.cmd_base import Command
303
304
class MyCustomCommand(Command):
305
"""Custom command plugin"""
306
307
name = 'mycmd'
308
309
@staticmethod
310
def add_cmd_options(parser):
311
"""Add command-specific options"""
312
parser.add_option('--option', help='Custom option')
313
314
def execute(self, opt_values, pos_args):
315
"""Execute custom command"""
316
print(f"Running custom command with option: {opt_values['option']}")
317
return 0 # Success
318
319
# Register in configuration:
320
# [COMMAND]
321
# mycmd = mypackage.commands:MyCustomCommand
322
```