0
# Configuration Management
1
2
Comprehensive configuration system supporting pyproject.toml and setup.cfg files with command-line argument merging. This enables flexible deployment across different project structures and integration with various build systems.
3
4
## Capabilities
5
6
### Configuration File Processing
7
8
Functions for reading and processing configuration from standard Python project files.
9
10
```python { .api }
11
def process_pyproject_toml(toml_file_path: str) -> MutableMapping[str, Any] | None:
12
"""
13
Extracts autoflake configuration from a pyproject.toml file.
14
15
Reads the [tool.autoflake] section from pyproject.toml and returns
16
the configuration as a dictionary suitable for merging with command-line args.
17
18
Args:
19
toml_file_path: Path to the pyproject.toml file
20
21
Returns:
22
Dictionary of configuration options, or None if file not found or no config
23
"""
24
```
25
26
```python { .api }
27
def process_config_file(config_file_path: str) -> MutableMapping[str, Any] | None:
28
"""
29
Extracts autoflake configuration from a setup.cfg style configuration file.
30
31
Reads the [autoflake] section from setup.cfg or similar INI-style configuration
32
files and returns parsed configuration options.
33
34
Args:
35
config_file_path: Path to the configuration file (setup.cfg, etc.)
36
37
Returns:
38
Dictionary of configuration options, or None if file not found or no config
39
"""
40
```
41
42
### Configuration Discovery and Merging
43
44
Functions for automatically finding configuration files and merging them with command-line arguments.
45
46
```python { .api }
47
def find_and_process_config(args: Mapping[str, Any]) -> MutableMapping[str, Any] | None:
48
"""
49
Finds and processes configuration files in the project directory.
50
51
Searches for pyproject.toml and setup.cfg files starting from the current
52
directory and moving up the directory tree to find project configuration.
53
54
Args:
55
args: Current command-line arguments (may contain config file path)
56
57
Returns:
58
Merged configuration from found files, or None if no config found
59
"""
60
```
61
62
```python { .api }
63
def merge_configuration_file(
64
flag_args: MutableMapping[str, Any]
65
) -> tuple[MutableMapping[str, Any], bool]:
66
"""
67
Merges configuration file settings with command-line arguments.
68
69
Combines settings from configuration files with command-line flags,
70
with command-line arguments taking precedence over file configuration.
71
72
Args:
73
flag_args: Command-line arguments as parsed by argparse
74
75
Returns:
76
Tuple of (merged_config, config_found) where:
77
- merged_config: Combined configuration dictionary
78
- config_found: Boolean indicating if configuration file was found
79
"""
80
```
81
82
## Configuration Options
83
84
The following configuration options are supported in both file and command-line formats:
85
86
### Import Removal Options
87
88
- **`remove-all-unused-imports`** (bool): Remove all unused imports, not just standard library
89
- **`ignore-init-module-imports`** (bool): Don't remove unused imports in `__init__.py` files
90
- **`expand-star-imports`** (bool): Replace `from module import *` with specific imports
91
92
### Variable and Code Cleanup
93
94
- **`remove-unused-variables`** (bool): Remove unused variable assignments
95
- **`remove-duplicate-keys`** (bool): Remove duplicate keys in dictionaries and sets
96
- **`ignore-pass-statements`** (bool): Don't remove `pass` statements
97
- **`ignore-pass-after-docstring`** (bool): Keep `pass` statements that come after docstrings
98
99
### File Processing Options
100
101
- **`in-place`** (bool): Modify files in place instead of printing to stdout
102
- **`check`** (bool): Check if changes would be made (exit code indicates changes needed)
103
- **`recursive`** (bool): Process directories recursively
104
- **`exclude`** (list): Glob patterns for files/directories to exclude
105
106
### Additional Options
107
108
- **`additional-imports`** (list): Additional modules to treat as unused imports
109
- **`config`** (str): Path to specific configuration file
110
111
## Configuration File Formats
112
113
### pyproject.toml Format
114
115
```toml
116
[tool.autoflake]
117
remove-all-unused-imports = true
118
remove-unused-variables = true
119
remove-duplicate-keys = true
120
ignore-init-module-imports = true
121
exclude = ["__pycache__", "*.pyc", "tests/fixtures/*"]
122
additional-imports = ["django", "requests"]
123
```
124
125
### setup.cfg Format
126
127
```ini
128
[autoflake]
129
remove-all-unused-imports = true
130
remove-unused-variables = true
131
remove-duplicate-keys = true
132
ignore-init-module-imports = true
133
exclude = __pycache__,*.pyc,tests/fixtures/*
134
additional-imports = django,requests
135
```
136
137
## Usage Examples
138
139
### Reading Configuration
140
141
```python
142
import autoflake
143
144
# Read from pyproject.toml
145
config = autoflake.process_pyproject_toml("pyproject.toml")
146
if config:
147
print("Found configuration:", config)
148
149
# Read from setup.cfg
150
config = autoflake.process_config_file("setup.cfg")
151
if config:
152
print("Found configuration:", config)
153
```
154
155
### Automatic Configuration Discovery
156
157
```python
158
import autoflake
159
160
# Automatically find and load configuration
161
args = {"recursive": True} # Some command-line args
162
config = autoflake.find_and_process_config(args)
163
164
if config:
165
print("Auto-discovered configuration:", config)
166
else:
167
print("No configuration file found")
168
```
169
170
### Configuration Merging
171
172
```python
173
import autoflake
174
175
# Simulate command-line arguments
176
cli_args = {
177
"remove_unused_variables": True,
178
"in_place": True,
179
"recursive": False
180
}
181
182
# Merge with configuration file
183
merged_config, config_found = autoflake.merge_configuration_file(cli_args)
184
185
print(f"Configuration file found: {config_found}")
186
print(f"Final configuration: {merged_config}")
187
188
# Use the merged configuration
189
if merged_config.get("recursive"):
190
print("Will process directories recursively")
191
```
192
193
### Custom Configuration Processing
194
195
```python
196
import autoflake
197
import os
198
199
def load_project_config(project_dir):
200
"""Load autoflake configuration for a specific project."""
201
# Try pyproject.toml first
202
pyproject_path = os.path.join(project_dir, "pyproject.toml")
203
if os.path.exists(pyproject_path):
204
config = autoflake.process_pyproject_toml(pyproject_path)
205
if config:
206
return config, "pyproject.toml"
207
208
# Fall back to setup.cfg
209
setup_cfg_path = os.path.join(project_dir, "setup.cfg")
210
if os.path.exists(setup_cfg_path):
211
config = autoflake.process_config_file(setup_cfg_path)
212
if config:
213
return config, "setup.cfg"
214
215
return None, None
216
217
# Usage
218
config, config_file = load_project_config("./my_project")
219
if config:
220
print(f"Loaded configuration from {config_file}")
221
222
# Apply configuration to processing
223
for file_path in ["src/main.py", "src/utils.py"]:
224
autoflake.fix_file(file_path, config)
225
```
226
227
### Integration with Build Systems
228
229
```python
230
import autoflake
231
import subprocess
232
import sys
233
234
def run_autoflake_with_config():
235
"""Run autoflake with project configuration and error handling."""
236
237
# Load configuration
238
merged_config, config_found = autoflake.merge_configuration_file({
239
"check": True, # Check mode - don't modify files
240
"recursive": True
241
})
242
243
if not config_found:
244
print("Warning: No configuration file found, using defaults")
245
246
# Find files to process
247
files = list(autoflake.find_files(
248
["src/"],
249
recursive=merged_config.get("recursive", False),
250
exclude=merged_config.get("exclude", [])
251
))
252
253
# Process files and track results
254
changes_needed = False
255
for file_path in files:
256
exit_code = autoflake.fix_file(file_path, merged_config)
257
if exit_code != 0:
258
changes_needed = True
259
260
if changes_needed:
261
print("Autoflake found issues that need fixing")
262
sys.exit(1)
263
else:
264
print("All files are clean")
265
sys.exit(0)
266
267
# Use in CI/CD pipeline
268
if __name__ == "__main__":
269
run_autoflake_with_config()
270
```