Debian Codegraph @

crazy_complete/shell.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''Shell utility functions.'''
5
6 import re
7
8 from . import utils
9
10
11 def make_identifier(string):
12 '''Make `string` a valid shell identifier.
13
14 This function replaces any dashes '-' with underscores '_',
15 removes any characters that are not letters, digits, or underscores,
16 and ensures that consecutive underscores are replaced with a single
17 underscore.
18
19 Args:
20 string (str):
21 The input string to be converted into a valid shell identifier.
22
23 Returns:
24 str: The modified string that is a valid shell identifier.
25 '''
26
27 string = string.replace('-', '_')
28 string = re.sub('[^a-zA-Z0-9_]', '', string)
29 string = re.sub('_+', '_', string)
30 if string and string[0] in '0123456789':
31 return '_' + string
32 return string
33
34
35 def needs_quote(string):
36 '''Return if string needs quoting.'''
37
38 return not re.fullmatch('[a-zA-Z0-9_@%+=:,./-]+', string)
39
40
41 def quote(string, quote_empty_string=True):
42 '''Quotes a string for safe usage in shell commands or scripts.
43
44 Args:
45 string (str):
46 The input string to be quoted.
47
48 quote_empty_string (bool, optional):
49 Determines whether to quote an empty string or not.
50 Defaults to True.
51
52 Returns:
53 str: The quoted string.
54 '''
55
56 if not string and not quote_empty_string:
57 return ''
58
59 if not needs_quote(string):
60 return string
61
62 if "'" not in string:
63 return f"'{string}'"
64
65 if '"' not in string:
66 s = string
67 s = s.replace('\\', '\\\\')
68 s = s.replace('$', '\\$')
69 s = s.replace('`', '\\`')
70 return f'"{s}"'
71
72 s = string.replace("'", '\'"\'"\'')
73 return f"'{s}'"
74
75
76 def join_quoted(arguments, string=' '):
77 '''Joins quoted `arguments` on `string`.'''
78
79 return string.join(quote(arg) for arg in arguments)
80
81
82 class ShellCompleter:
83 '''Base class for argument completion.'''
84
85 # pylint: disable=missing-function-docstring
86 # pylint: disable=too-many-arguments
87 # pylint: disable=too-many-positional-arguments
88
89 def complete(self, ctxt, trace, command, *a):
90 if not hasattr(self, command):
91 utils.warn(f"complete: Falling back from `{command}` to `none`")
92 command = 'none'
93
94 return getattr(self, command)(ctxt, trace, *a)
95
96 def complete_from_def(self, ctxt, trace, definition):
97 command, *args = definition
98 return self.complete(ctxt, trace, command, *args)
99
100 def fallback(self, ctxt, trace, from_, to, *a):
101 utils.warn(f"ShellCompleter: Falling back from `{from_}` to `{to}`")
102 return self.complete(ctxt, trace, to, *a)
103
104 def signal(self, ctxt, trace):
105 signals = {
106 'ABRT': 'Process abort signal',
107 'ALRM': 'Alarm clock',
108 'BUS': 'Access to an undefined portion of a memory object',
109 'CHLD': 'Child process terminated: stopped: or continued',
110 'CONT': 'Continue executing: if stopped',
111 'FPE': 'Erroneous arithmetic operation',
112 'HUP': 'Hangup',
113 'ILL': 'Illegal instruction',
114 'INT': 'Terminal interrupt signal',
115 'KILL': 'Kill (cannot be caught or ignored)',
116 'PIPE': 'Write on a pipe with no one to read it',
117 'QUIT': 'Terminal quit signal',
118 'SEGV': 'Invalid memory reference',
119 'STOP': 'Stop executing (cannot be caught or ignored)',
120 'TERM': 'Termination signal',
121 'TSTP': 'Terminal stop signal',
122 'TTIN': 'Background process attempting read',
123 'TTOU': 'Background process attempting write',
124 'USR1': 'User-defined signal 1',
125 'USR2': 'User-defined signal 2',
126 'POLL': 'Pollable event',
127 'PROF': 'Profiling timer expired',
128 'SYS': 'Bad system call',
129 'TRAP': 'Trace/breakpoint trap',
130 'XFSZ': 'File size limit exceeded',
131 'VTALRM': 'Virtual timer expired',
132 'XCPU': 'CPU time limit exceeded',
133 }
134
135 return self.complete(ctxt, trace, 'choices', signals)
136
137 def exec(self, _ctxt, _trace, _command):
138 raise NotImplementedError
139
140 def list(self, _ctxt, _trace, _command, _opts=None):
141 raise NotImplementedError
142
143 # =========================================================================
144 # Aliases
145 # =========================================================================
146
147 def file_list(self, ctxt, trace, opts=None):
148 list_opts = {
149 'separator': opts.pop('separator', ',') if opts else ',',
150 'duplicates': opts.pop('duplicates', False) if opts else False
151 }
152
153 return self.list(ctxt, trace, ['file', opts], list_opts)
154
155 def directory_list(self, ctxt, trace, opts=None):
156 list_opts = {
157 'separator': opts.pop('separator', ',') if opts else ',',
158 'duplicates': opts.pop('duplicates', False) if opts else False
159 }
160
161 return self.list(ctxt, trace, ['directory', opts], list_opts)
162
163 # =========================================================================
164 # Bonus
165 # =========================================================================
166
167 def login_shell(self, ctxt, trace):
168 return self.exec(ctxt, trace, "command grep -E '^[^#]' /etc/shells")
169
170 def locale(self, ctxt, trace):
171 return self.exec(ctxt, trace, "command locale -a")
172
173 def charset(self, ctxt, trace):
174 return self.exec(ctxt, trace, "command locale -m")