0
# Data Types and Structures
1
2
Essential data types representing commands, rules, corrections, and settings. These classes form the foundation of the correction system and provide structured data handling throughout the thefuck application.
3
4
## Capabilities
5
6
### Core Command Types
7
8
Fundamental data structures representing commands and their execution results.
9
10
```python { .api }
11
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
12
"""
13
Represents a command and its execution results.
14
15
Fields:
16
- script (str): The command string that was executed
17
- stdout (str): Standard output from command execution
18
- stderr (str): Standard error output from command execution
19
"""
20
21
class CorrectedCommand:
22
"""
23
Represents a corrected command with metadata.
24
25
Attributes:
26
- script (str): The corrected command string
27
- side_effect (callable): Optional function to execute when command runs
28
- priority (int): Priority for ordering multiple corrections
29
"""
30
31
def __init__(self, script, side_effect, priority):
32
"""
33
Initialize a corrected command.
34
35
Parameters:
36
- script (str): Corrected command string
37
- side_effect (callable or None): Function to call when executing
38
- priority (int): Priority value for ordering
39
"""
40
41
def __eq__(self, other):
42
"""
43
Compare commands (ignores priority field).
44
45
Parameters:
46
- other (CorrectedCommand): Other command to compare
47
48
Returns:
49
bool: True if script and side_effect match
50
"""
51
52
def __hash__(self):
53
"""
54
Hash function for use in sets and dictionaries.
55
56
Returns:
57
int: Hash value based on script and side_effect
58
"""
59
```
60
61
### Rule System Types
62
63
Data structures for representing correction rules and their metadata.
64
65
```python { .api }
66
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command', 'enabled_by_default', 'side_effect', 'priority', 'requires_output'))
67
"""
68
Represents a correction rule with all its metadata.
69
70
Fields:
71
- name (str): Rule name/identifier
72
- match (callable): Function to test if rule applies to command
73
- get_new_command (callable): Function to generate corrected command
74
- enabled_by_default (bool): Whether rule is enabled by default
75
- side_effect (callable): Optional function to execute with correction
76
- priority (int): Rule priority for ordering
77
- requires_output (bool): Whether rule needs command output to function
78
"""
79
80
class RulesNamesList(list):
81
"""
82
Wrapper on top of list for storing rule names with special behavior.
83
84
Provides custom __contains__ behavior that checks rule names
85
rather than Rule objects directly.
86
"""
87
88
def __contains__(self, item):
89
"""
90
Check if rule is in the list by name.
91
92
Parameters:
93
- item (Rule): Rule object to check
94
95
Returns:
96
bool: True if rule name is in the list
97
"""
98
```
99
100
### Settings and Configuration
101
102
Configuration management and settings representation.
103
104
```python { .api }
105
class Settings(dict):
106
"""
107
Settings dictionary with attribute access support.
108
109
Extends dict to allow both dictionary-style and attribute-style access
110
to configuration values.
111
"""
112
113
def __getattr__(self, item):
114
"""
115
Get setting value as attribute.
116
117
Parameters:
118
- item (str): Setting name
119
120
Returns:
121
Any: Setting value or None if not found
122
"""
123
124
def update(self, **kwargs):
125
"""
126
Returns new settings with values from kwargs for unset settings.
127
128
Parameters:
129
- **kwargs: Setting key-value pairs
130
131
Returns:
132
Settings: New Settings object with updated values
133
"""
134
```
135
136
### Command Collections
137
138
Specialized collections for managing corrected commands.
139
140
```python { .api }
141
class SortedCorrectedCommandsSequence:
142
"""
143
List-like collection/wrapper around generator that:
144
145
- Immediately gives access to the first commands through []
146
- Realizes generator and sorts commands on first access to other commands
147
- Provides lazy evaluation of command corrections
148
"""
149
150
def __init__(self, commands, settings):
151
"""
152
Initialize the sequence.
153
154
Parameters:
155
- commands (generator): Generator yielding CorrectedCommand objects
156
- settings (Settings): Application settings for debugging
157
"""
158
159
def __getitem__(self, item):
160
"""
161
Get command by index.
162
163
Parameters:
164
- item (int): Index of command to retrieve
165
166
Returns:
167
CorrectedCommand: Command at the specified index
168
"""
169
170
def __len__(self):
171
"""
172
Get number of commands (realizes generator if needed).
173
174
Returns:
175
int: Number of available commands
176
"""
177
178
def __bool__(self):
179
"""
180
Check if sequence has any commands.
181
182
Returns:
183
bool: True if sequence contains commands
184
"""
185
186
def __iter__(self):
187
"""
188
Iterate over commands (realizes generator if needed).
189
190
Returns:
191
iterator: Iterator over CorrectedCommand objects
192
"""
193
```
194
195
## Usage Examples
196
197
### Working with Commands
198
199
```python
200
from thefuck.types import Command, CorrectedCommand
201
202
# Create a command from execution results
203
command = Command(
204
script="git pussh origin main",
205
stdout="",
206
stderr="git: 'pussh' is not a git command. See 'git --help'."
207
)
208
209
# Create a corrected command
210
correction = CorrectedCommand(
211
script="git push origin main",
212
side_effect=None,
213
priority=1000
214
)
215
216
print(f"Original: {command.script}")
217
print(f"Correction: {correction.script}")
218
print(f"Error output: {command.stderr}")
219
```
220
221
### Settings Configuration
222
223
```python
224
from thefuck.types import Settings
225
226
# Create settings with both dict and attribute access
227
settings = Settings({
228
'rules': ['git_push', 'sudo'],
229
'wait_command': 3,
230
'require_confirmation': True,
231
'debug': False
232
})
233
234
# Access as dictionary
235
print(settings['rules'])
236
237
# Access as attributes
238
print(settings.wait_command)
239
print(settings.debug)
240
241
# Update settings
242
new_settings = settings.update(debug=True, wait_command=5)
243
print(new_settings.debug) # True
244
print(settings.debug) # False (original unchanged)
245
```
246
247
### Rule Management
248
249
```python
250
from thefuck.types import Rule, RulesNamesList
251
252
# Create a rule
253
def match_git_typo(command, settings):
254
return 'pussh' in command.script
255
256
def fix_git_typo(command, settings):
257
return command.script.replace('pussh', 'push')
258
259
rule = Rule(
260
name='git_push_typo',
261
match=match_git_typo,
262
get_new_command=fix_git_typo,
263
enabled_by_default=True,
264
side_effect=None,
265
priority=1000,
266
requires_output=False
267
)
268
269
# Work with rule lists
270
rules_list = RulesNamesList(['git_push', 'sudo', 'cd_mkdir'])
271
print(rule in rules_list) # Checks by rule.name
272
```
273
274
### Command Sequence Processing
275
276
```python
277
from thefuck.types import SortedCorrectedCommandsSequence, CorrectedCommand
278
279
# Simulate a generator of corrections
280
def generate_corrections():
281
yield CorrectedCommand("git push origin main", None, 1000)
282
yield CorrectedCommand("git push origin master", None, 2000)
283
yield CorrectedCommand("git push --set-upstream origin main", None, 1500)
284
285
# Create sorted sequence
286
settings = Settings({'debug': False})
287
commands = SortedCorrectedCommandsSequence(generate_corrections(), settings)
288
289
# Access first command immediately (no full generation)
290
first = commands[0]
291
print(f"First correction: {first.script}")
292
293
# Access other commands (triggers full generation and sorting)
294
print(f"Total corrections: {len(commands)}")
295
for cmd in commands:
296
print(f" {cmd.script} (priority: {cmd.priority})")
297
```
298
299
## Type Relationships
300
301
The data types work together to form the correction system:
302
303
1. **Command** captures original failed commands
304
2. **Rule** objects define correction logic
305
3. **CorrectedCommand** represents generated corrections
306
4. **SortedCorrectedCommandsSequence** manages correction ordering
307
5. **Settings** configures system behavior
308
6. **RulesNamesList** manages rule selection
309
310
This type system provides the foundation for thefuck's command correction pipeline.