0
# Utilities
1
2
Helper functions for generating CLI commands and working with dotenv programmatically.
3
4
## Capabilities
5
6
### CLI Command Generation
7
8
Generate shell command strings for dotenv operations, useful for automation and integration with other tools.
9
10
```python { .api }
11
def get_cli_string(
12
path: Optional[str] = None,
13
action: Optional[str] = None,
14
key: Optional[str] = None,
15
value: Optional[str] = None,
16
quote: Optional[str] = None
17
) -> str:
18
"""
19
Return a string suitable for running as a shell script.
20
21
Useful for converting arguments passed to a fabric task
22
to be passed to a `local` or `run` command.
23
24
Parameters:
25
path: Path to the .env file (-f option)
26
action: CLI action (get, set, unset, list, run)
27
key: Key name for get/set/unset operations
28
value: Value for set operations
29
quote: Quote mode (-q option: always, auto, never)
30
31
Returns:
32
str: Complete dotenv command string ready for shell execution
33
"""
34
```
35
36
## Usage Examples
37
38
### Basic Command Generation
39
40
```python
41
from dotenv import get_cli_string
42
43
# Generate basic commands
44
cmd = get_cli_string(action='list')
45
print(cmd) # Output: dotenv list
46
47
cmd = get_cli_string(action='get', key='DATABASE_URL')
48
print(cmd) # Output: dotenv get DATABASE_URL
49
50
cmd = get_cli_string(action='set', key='DEBUG', value='True')
51
print(cmd) # Output: dotenv set DEBUG True
52
```
53
54
### Commands with File Paths
55
56
```python
57
# Generate commands with custom file paths
58
cmd = get_cli_string(path='production.env', action='list')
59
print(cmd) # Output: dotenv -f production.env list
60
61
cmd = get_cli_string(path='/etc/app/.env', action='get', key='API_KEY')
62
print(cmd) # Output: dotenv -f /etc/app/.env get API_KEY
63
64
cmd = get_cli_string(path='config.env', action='set', key='HOST', value='localhost')
65
print(cmd) # Output: dotenv -f config.env set HOST localhost
66
```
67
68
### Commands with Quote Modes
69
70
```python
71
# Generate commands with different quote modes
72
cmd = get_cli_string(action='set', key='SIMPLE', value='abc', quote='never')
73
print(cmd) # Output: dotenv -q never set SIMPLE abc
74
75
cmd = get_cli_string(action='set', key='COMPLEX', value='hello world', quote='auto')
76
print(cmd) # Output: dotenv -q auto set COMPLEX "hello world"
77
78
cmd = get_cli_string(action='set', key='QUOTED', value='always', quote='always')
79
print(cmd) # Output: dotenv -q always set QUOTED always
80
```
81
82
### Complex Command Generation
83
84
```python
85
# Generate complex commands with multiple options
86
cmd = get_cli_string(
87
path='staging.env',
88
action='set',
89
key='DATABASE_URL',
90
value='postgresql://user:pass@localhost/db',
91
quote='always'
92
)
93
print(cmd) # Output: dotenv -q always -f staging.env set DATABASE_URL "postgresql://user:pass@localhost/db"
94
```
95
96
### Value Handling
97
98
The function automatically handles values that contain spaces by wrapping them in quotes:
99
100
```python
101
# Values with spaces are automatically quoted
102
cmd = get_cli_string(action='set', key='MESSAGE', value='hello world')
103
print(cmd) # Output: dotenv set MESSAGE "hello world"
104
105
# Values without spaces remain unquoted
106
cmd = get_cli_string(action='set', key='PORT', value='8080')
107
print(cmd) # Output: dotenv set PORT 8080
108
109
# Empty or None values are handled gracefully
110
cmd = get_cli_string(action='get', key='MISSING_KEY')
111
print(cmd) # Output: dotenv get MISSING_KEY
112
```
113
114
## Integration Examples
115
116
### Fabric Integration
117
118
```python
119
from fabric import task
120
from dotenv import get_cli_string
121
122
@task
123
def deploy_config(c, env='production'):
124
"""Deploy configuration to remote server."""
125
126
# Generate commands for different environments
127
commands = [
128
get_cli_string(path=f'{env}.env', action='set', key='DEPLOYED_AT', value='$(date)'),
129
get_cli_string(path=f'{env}.env', action='set', key='VERSION', value='1.2.3'),
130
get_cli_string(path=f'{env}.env', action='list', quote='export')
131
]
132
133
for cmd in commands:
134
c.run(cmd)
135
```
136
137
### Automation Scripts
138
139
```python
140
import subprocess
141
from dotenv import get_cli_string
142
143
def setup_environment(config_file, settings):
144
"""Automate environment setup using generated commands."""
145
146
commands = []
147
148
# Generate set commands for all settings
149
for key, value in settings.items():
150
cmd = get_cli_string(
151
path=config_file,
152
action='set',
153
key=key,
154
value=str(value),
155
quote='auto'
156
)
157
commands.append(cmd)
158
159
# Execute all commands
160
for cmd in commands:
161
print(f"Executing: {cmd}")
162
subprocess.run(cmd, shell=True, check=True)
163
164
# List final configuration
165
list_cmd = get_cli_string(path=config_file, action='list')
166
subprocess.run(list_cmd, shell=True)
167
168
# Usage
169
settings = {
170
'DATABASE_URL': 'postgresql://localhost/myapp',
171
'REDIS_URL': 'redis://localhost:6379',
172
'DEBUG': 'False',
173
'SECRET_KEY': 'production-secret-key'
174
}
175
176
setup_environment('production.env', settings)
177
```
178
179
### Build System Integration
180
181
```python
182
import os
183
from dotenv import get_cli_string
184
185
def generate_build_commands(environment='development'):
186
"""Generate build commands with environment-specific configuration."""
187
188
env_file = f'.env.{environment}'
189
190
# Commands for build process
191
commands = [
192
# Set build-specific variables
193
get_cli_string(path=env_file, action='set', key='NODE_ENV', value=environment),
194
get_cli_string(path=env_file, action='set', key='BUILD_TIME', value='$(date)'),
195
196
# Run build with environment
197
get_cli_string(path=env_file, action='run') + ' npm run build',
198
get_cli_string(path=env_file, action='run') + ' npm run test',
199
]
200
201
return commands
202
203
# Generate commands for different environments
204
dev_commands = generate_build_commands('development')
205
prod_commands = generate_build_commands('production')
206
207
print("Development build commands:")
208
for cmd in dev_commands:
209
print(f" {cmd}")
210
211
print("\nProduction build commands:")
212
for cmd in prod_commands:
213
print(f" {cmd}")
214
```
215
216
### Testing Integration
217
218
```python
219
import pytest
220
from dotenv import get_cli_string
221
import subprocess
222
223
class TestEnvironmentCommands:
224
"""Test environment command generation."""
225
226
def test_basic_commands(self):
227
"""Test basic command generation."""
228
assert get_cli_string(action='list') == 'dotenv list'
229
assert get_cli_string(action='get', key='TEST') == 'dotenv get TEST'
230
231
def test_file_path_commands(self):
232
"""Test commands with file paths."""
233
cmd = get_cli_string(path='test.env', action='list')
234
assert cmd == 'dotenv -f test.env list'
235
236
def test_quote_modes(self):
237
"""Test different quote modes."""
238
cmd = get_cli_string(action='set', key='KEY', value='value', quote='never')
239
assert 'never' in cmd
240
241
def test_command_execution(self, tmp_path):
242
"""Test actual command execution."""
243
env_file = tmp_path / '.env'
244
245
# Generate and execute set command
246
set_cmd = get_cli_string(
247
path=str(env_file),
248
action='set',
249
key='TEST_KEY',
250
value='test_value'
251
)
252
253
subprocess.run(set_cmd, shell=True, check=True)
254
255
# Verify the key was set
256
get_cmd = get_cli_string(path=str(env_file), action='get', key='TEST_KEY')
257
result = subprocess.run(get_cmd, shell=True, capture_output=True, text=True)
258
259
assert result.stdout.strip() == 'test_value'
260
```
261
262
## Command String Format
263
264
The generated command strings follow this format:
265
266
```bash
267
dotenv [global_options] action [action_arguments]
268
```
269
270
Where:
271
- **global_options**: `-q quote_mode`, `-f file_path`
272
- **action**: `list`, `get`, `set`, `unset`, `run`
273
- **action_arguments**: Depend on the specific action
274
275
The function ensures proper ordering and quoting of arguments to generate valid shell commands.