File: fish_utils.py

package info (click to toggle)
crazy-complete 0.3.6-2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 2,404 kB
  • sloc: python: 7,949; sh: 4,636; makefile: 74
file content (214 lines) | stat: -rw-r--r-- 6,805 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
'''Fish utility functions and classes.'''

from .errors import InternalError
from . import shell


class FishString:
    '''A utility class for handling command-line strings that may or may not require escaping.

    When building command-line commands, it's important to ensure that strings are properly
    escaped to prevent shell injection vulnerabilities or syntax errors. However, in some
    cases, the string may already be escaped, and applying escaping again would result in
    incorrect behavior. The `FishString` class provides an abstraction to manage both
    escaped and unescaped strings.

    Attributes:
        s (str):
            The string that represents the command or command argument.
        raw (bool):
            A flag that indicates whether the string is already escaped. If `True`,
            the string is assumed to be already escaped and will not be escaped again.

    Args:
        s (str):
            The string to be used in the command.
        raw (bool, optional):
            If `True`, the string will be treated as already escaped. Defaults to `False`.

    Methods:
        escape():
            Returns the escaped version of the string, unless the string is already escaped (`raw=True`).
        __str__():
            Returns the raw string `s` for direct use or display.
    '''

    def __init__(self, s, raw=False):
        '''Initializes a FishString instance.

        Args:
            s (str):
                The string to be used for command-line purposes.
            raw (bool, optional):
                If True, indicates that the string `s` is already escaped
                and should not be escaped again. Defaults to False.
        '''
        assert isinstance(s, str)
        assert isinstance(raw, bool)
        self.s = s
        self.raw = raw

    def escape(self):
        '''Escapes the string unless it's marked as already escaped.

        If the `raw` attribute is set to `True`, the method returns the string without any changes.
        Otherwise, it applies shell escaping to ensure the string is safe to use in a command-line context.

        Returns:
            str: The escaped string, or the raw string if it's already escaped.
        '''
        if self.raw:
            return self.s
        return shell.escape(self.s)

    def __str__(self):
        return self.s

    def __repr__(self):
        return repr(self.s)


def make_fish_string(s, raw):
    '''Make a fish string.'''

    if s is not None:
        return FishString(s, raw)

    return None


class FishCompleteCommand:
    '''Class for creating Fish's `complete` command.'''

    # pylint: disable=too-many-instance-attributes

    def __init__(self):
        self.command       = None
        self.description   = None
        self.condition     = None
        self.arguments     = None
        self.short_options = []
        self.long_options  = []
        self.old_options   = []
        self.flags         = set()

    def set_command(self, command, raw=False):
        '''Set the command (-c|--command).'''
        self.command = make_fish_string(command, raw)

    def set_description(self, description, raw=False):
        '''Set the description (-d|--description).'''
        self.description = make_fish_string(description, raw)

    def add_short_options(self, opts, raw=False):
        '''Add short options (-s|--short-option).'''
        self.short_options.extend(make_fish_string(o.lstrip('-'), raw) for o in opts)

    def add_long_options(self, opts, raw=False):
        '''Add long options (-l|--long-option).'''
        self.long_options.extend(make_fish_string(o.lstrip('-'), raw) for o in opts)

    def add_old_options(self, opts, raw=False):
        '''Add old options (-o|--old-option).'''
        self.old_options.extend(make_fish_string(o.lstrip('-'), raw) for o in opts)

    def set_condition(self, condition, raw=False):
        '''Set the condition (-n|--condition).'''
        self.condition = make_fish_string(condition, raw)

    def set_arguments(self, arguments, raw=False):
        '''Set the arguments (-a|--arguments).'''
        self.arguments = make_fish_string(arguments, raw)

    def add_flag(self, flag):
        '''Set a flag.'''
        self.flags.add(flag)

    def parse_args(self, args):
        '''Parse args (an iterable) and apply it to the instance.'''
        args = list(args)

        while len(args) > 0:
            arg = args.pop(0)

            if arg == '-f':
                self.add_flag('f')
            elif arg == '-F':
                self.add_flag('F')
            elif arg == '-a':
                try:
                    self.set_arguments(args.pop(0))
                except IndexError as e:
                    raise InternalError('Option `-a` requires an argument') from e
            else:
                raise InternalError(f'Unknown option for `complete`: {arg}')

    def get(self):
        '''Return the `complete` command.'''

        r = ['complete']

        if self.command is not None:
            r.extend(['-c', self.command])

        if self.condition is not None:
            r.extend(['-n', self.condition])

        for o in self.short_options:
            r.extend(['-s', o])

        for o in self.long_options:
            r.extend(['-l', o])

        for o in self.old_options:
            r.extend(['-o', o])

        if self.description is not None:
            r.extend(['-d', self.description])

        # -r -f is the same as -x
        if 'r' in self.flags and 'f' in self.flags:
            self.flags.add('x')

        # -x implies -r -f
        if 'x' in self.flags:
            self.flags.discard('r')
            self.flags.discard('f')

        if self.flags:
            r.append('-%s' % ''.join(sorted(self.flags)))

        if self.arguments is not None:
            r.extend(['-a', self.arguments])

        return ' '.join(v if isinstance(v, str) else v.escape() for v in r)


class VariableManager:
    '''
    Manages the creation of unique shell variables for a given name prefix.
    '''

    def __init__(self, variable_name):
        self.variable_name = variable_name
        self.value_to_variable  = {}
        self.counter = 0

    def add(self, value):
        '''Add a value and get its associated shell variable.'''

        if value in self.value_to_variable:
            return '$%s' % self.value_to_variable[value]

        var = '%s%03d' % (self.variable_name, self.counter)
        self.value_to_variable[value] = var
        self.counter += 1
        return '$%s' % var

    def get_lines(self):
        '''Generate shell code to define all stored variables.'''

        r = []
        for value, variable in self.value_to_variable.items():
            r.append('set -l %s %s' % (variable, value))
        return r