Debian Codegraph @

crazy_complete/fish_utils.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''Fish utility functions and classes.'''
5
6 from .errors import InternalError
7 from . import shell
8
9
10 class FishString:
11 '''A utility class for command-line strings that may require escaping.
12
13 When building command-line commands, it's important to ensure that strings
14 are properly escaped to prevent shell injection vulnerabilities or
15 syntax errors. However, in some cases, the string may already be escaped,
16 and applying escaping again would result in incorrect behavior.
17 The `FishString` class provides an abstraction to manage both escaped and
18 unescaped strings.
19
20 Attributes:
21 string (str):
22 The string that represents the command or command argument.
23
24 raw (bool):
25 A flag that indicates whether the string is already escaped.
26 If `True`, the string is assumed to be already escaped and will
27 not be escaped again.
28
29 Args:
30 string (str):
31 The string to be used in the command.
32
33 raw (bool, optional):
34 If `True`, the string will be treated as already escaped.
35 Defaults to `False`.
36
37 Methods:
38 escape():
39 Returns the escaped version of the string, unless the string is
40 already escaped (`raw=True`).
41
42 __str__():
43 Returns the raw string `string` for direct use or display.
44 '''
45
46 def __init__(self, string, raw=False):
47 '''Initializes a FishString instance.
48
49 Args:
50 string (str):
51 The string to be used for command-line purposes.
52
53 raw (bool, optional):
54 If True, indicates that the string `s` is already escaped
55 and should not be escaped again. Defaults to False.
56 '''
57 assert isinstance(string, str)
58 assert isinstance(raw, bool)
59 self.string = string
60 self.raw = raw
61
62 def escape(self):
63 '''Escapes the string unless it's marked as already escaped.
64
65 If the `raw` attribute is set to `True`, the method returns the string
66 without any changes.
67
68 Otherwise, it applies shell escaping to ensure the string is safe to
69 use in a command-line context.
70
71 Returns:
72 str: The escaped string, or the raw string if it's already escaped.
73 '''
74 if self.raw:
75 return self.string
76 return shell.quote(self.string)
77
78 def __str__(self):
79 return self.string
80
81 def __repr__(self):
82 return repr(self.string)
83
84
85 def make_fish_string(s, raw):
86 '''Make a Fish string.'''
87
88 if s is not None:
89 return FishString(s, raw)
90
91 return None
92
93
94 class FishCompleteCommand:
95 '''Class for creating Fish's `complete` command.'''
96
97 # pylint: disable=too-many-instance-attributes
98
99 def __init__(self):
100 self.command = None
101 self.description = None
102 self.conditions = []
103 self.arguments = None
104 self.short_options = []
105 self.long_options = []
106 self.old_options = []
107 self.flags = set()
108
109 def set_command(self, command, raw=False):
110 '''Set the command (-c|--command).'''
111 self.command = FishString(command, raw)
112
113 def set_description(self, description, raw=False):
114 '''Set the description (-d|--description).'''
115 self.description = make_fish_string(description, raw)
116
117 def add_short_options(self, opts, raw=False):
118 '''Add short options (-s|--short-option).'''
119 self.short_options.extend(FishString(o.lstrip('-'), raw) for o in opts)
120
121 def add_long_options(self, opts, raw=False):
122 '''Add long options (-l|--long-option).'''
123 self.long_options.extend(FishString(o.lstrip('-'), raw) for o in opts)
124
125 def add_old_options(self, opts, raw=False):
126 '''Add old options (-o|--old-option).'''
127 self.old_options.extend(FishString(o.lstrip('-'), raw) for o in opts)
128
129 def add_condition(self, condition, raw=False):
130 '''Add a condition (-n|--condition).'''
131 self.conditions.append(make_fish_string(condition, raw))
132
133 def insert_condition(self, pos, condition, raw=False):
134 '''Insert a condition (-n|--condition)'''
135 self.conditions.insert(pos, make_fish_string(condition, raw))
136
137 def set_arguments(self, arguments, raw=False):
138 '''Set the arguments (-a|--arguments).'''
139 self.arguments = make_fish_string(arguments, raw)
140
141 def add_flag(self, flag):
142 '''Set a flag.'''
143 self.flags.add(flag)
144
145 def parse_args(self, args):
146 '''Parse args (an iterable) and apply it to the instance.'''
147 args = list(args)
148
149 while len(args) > 0:
150 arg = args.pop(0)
151
152 if arg == '-f':
153 self.add_flag('f')
154 elif arg == '-F':
155 self.add_flag('F')
156 elif arg == '-a':
157 try:
158 self.set_arguments(args.pop(0))
159 except IndexError as e:
160 raise InternalError('Option `-a` requires an argument') from e
161 else:
162 raise InternalError(f'Unknown option for `complete`: {arg}')
163
164 def get(self):
165 '''Return the `complete` command.'''
166
167 r = ['complete']
168
169 if self.command is not None:
170 r.extend(['-c', self.command])
171
172 for condition in self.conditions:
173 r.extend(['-n', condition])
174
175 for o in self.short_options:
176 r.extend(['-s', o])
177
178 for o in self.long_options:
179 r.extend(['-l', o])
180
181 for o in self.old_options:
182 r.extend(['-o', o])
183
184 if self.description is not None:
185 r.extend(['-d', self.description])
186
187 # -r -f is the same as -x
188 if 'r' in self.flags and 'f' in self.flags:
189 self.flags.add('x')
190
191 # -x implies -r -f
192 if 'x' in self.flags:
193 self.flags.discard('r')
194 self.flags.discard('f')
195
196 if self.flags:
197 r.append('-%s' % ''.join(sorted(self.flags)))
198
199 if self.arguments is not None:
200 r.extend(['-a', self.arguments])
201
202 # Pylint doesn't understand that .escape is only called when the
203 # value is not a regular Python string.
204 # pylint: disable=no-member
205 return ' '.join(v if isinstance(v, str) else v.escape() for v in r)
206
207
208 class VariableManager:
209 '''
210 Manages the creation of unique shell variables for a given name prefix.
211 '''
212
213 def __init__(self, variable_name):
214 self.variable_name = variable_name
215 self.value_to_variable = {}
216 self.counter = 0
217
218 def add(self, value):
219 '''Add a value and get its associated shell variable.'''
220
221 if value in self.value_to_variable:
222 return '$%s' % self.value_to_variable[value]
223
224 var = '%s%03d' % (self.variable_name, self.counter)
225 self.value_to_variable[value] = var
226 self.counter += 1
227 return '$%s' % var
228
229 def get_lines(self):
230 '''Generate shell code to define all stored variables.'''
231
232 r = []
233 for value, variable in self.value_to_variable.items():
234 r.append('set -l %s %s' % (variable, value))
235 return r