Debian Codegraph @

relational_readline/linegui.py

raw symbols SCIP
1 # Relational
2 # Copyright (C) 2010-2025 Salvo "LtWorf" Tomaselli
3 #
4 # Relational is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17 # author Salvo "LtWorf" Tomaselli <[email protected]>
18 # Initial readline code from
19 # http://www.doughellmann.com/PyMOTW/readline/index.html
20
21 import readline
22 import logging
23 import os.path
24 import os
25 import sys
26 from typing import Optional, Literal
27 from gettext import gettext as _
28
29 from relational import relation, parser, rtypes
30 from relational import maintenance
31 from termcolor import cprint, colored
32
33 PROMPT_COLOR: Literal['yellow'] = 'yellow'
34 ERROR_COLOR: Literal['red'] = 'red'
35 COLOR_GREEN: Literal['green'] = 'green'
36
37 TTY = os.isatty(0) and os.isatty(1)
38
39 version = ''
40
41
42 class SimpleCompleter:
43
44 '''Handles completion'''
45
46 def __init__(self, options) -> None:
47 '''Takes a list of valid completion options'''
48 self.options = sorted(options)
49
50 def add_completion(self, option):
51 '''Adds one string to the list of the valid completion options'''
52 if option not in self.options:
53 self.options.append(option)
54 self.options.sort()
55
56 def remove_completion(self, option):
57 '''Removes one completion from the list of the valid completion options'''
58 if option in self.options:
59 self.options.remove(option)
60
61 def complete(self, text, state):
62 response = None
63 if state == 0:
64 # This is the first time for this text, so build a match list.
65 if text:
66 self.matches = [s
67 for s in self.options
68 if s and s.startswith(text)]
69
70 # Add the completion for files here
71 try:
72 d = os.path.dirname(text)
73 listf = os.listdir(d)
74
75 d += "/"
76 except:
77 d = ""
78 listf = os.listdir('.')
79
80 for i in listf:
81 i = (d + i).replace('//', '/')
82 if i.startswith(text):
83 if os.path.isdir(i):
84 i = i + "/"
85 self.matches.append(i)
86
87 logging.debug('%s matches: %s', repr(text), self.matches)
88 else:
89 self.matches = self.options[:]
90 logging.debug('(empty input) matches: %s', self.matches)
91
92 # Return the state'th item from the match list,
93 # if we have that many.
94 try:
95 response = self.matches[state]
96 except IndexError:
97 response = None
98 logging.debug('complete(%s, %s) => %s',
99 repr(text), state, repr(response))
100 return response
101
102 ui = maintenance.UserInterface()
103 completer = SimpleCompleter(
104 ['SURVEY', 'LIST', 'LOAD ', 'UNLOAD ', 'HELP ', 'QUIT', 'SAVE ', '_PRODUCT ', '_UNION ', '_INTERSECTION ',
105 '_DIFFERENCE ', '_JOIN ', '_LJOIN ', '_RJOIN ', '_FJOIN ', '_PROJECTION ', '_RENAME_TO ', '_SELECTION ', '_RENAME ', '_DIVISION '])
106
107
108 def load_relation(filename: str, defname: Optional[str]) -> Optional[str]:
109 '''
110 Loads a relation into the set. Defname is the given name
111 to the relation.
112
113 Returns the name to the relation, or None if it was
114 not loaded.
115 '''
116 if not os.path.isfile(filename):
117 cprint(
118 _('%s is not a file') % filename, ERROR_COLOR, file=sys.stderr)
119 return None
120
121 if defname is None:
122 f = filename.split('/')
123 defname = f[-1].lower()
124 if defname.endswith(".csv"): # removes the extension
125 defname = defname[:-4]
126
127 if not rtypes.is_valid_relation_name(defname):
128 cprint(_(
129 '%s is not a valid relation name') % defname, ERROR_COLOR, file=sys.stderr)
130 return None
131 try:
132 ui.load(filename, defname)
133
134 completer.add_completion(defname)
135 if TTY:
136 cprint(_('Loaded relation: %s') % defname, COLOR_GREEN)
137 return defname
138 except Exception as e:
139 cprint(str(e), ERROR_COLOR, file=sys.stderr)
140 return None
141
142
143 def survey() -> None:
144 '''performs a survey'''
145 post = {'software': 'Relational algebra (cli)', 'version': version}
146
147 fields = ('System', 'Country', 'School', 'Age', 'How did you find',
148 'email (only if you want a reply)', 'Comments')
149 for i in fields:
150 a = input('%s: ' % i)
151 post[i] = a
152 response = maintenance.send_survey(post)
153 if response == -1:
154 print(_('Yeah, not sending that.'))
155
156
157 def help(command: str) -> None:
158 '''Prints help on the various functions'''
159 p = command.split(' ', 1)
160 if len(p) == 1:
161 print(_(
162 'HELP [command]\n'
163 '\n'
164 'Comments are obtained starting with a ;\n'
165 '\n'
166 'To execute a query:\n'
167 '[relation =] query\n'
168 '\n'
169 'If the 1st part is omitted, the result will be stored in the relation last_.\n'
170 '\n'
171 'To prevent from printing the relation, append a ; to the end of the query.\n'
172 '\n'
173 'To insert relational operators, type _OPNAME, they will be internally replaced with the correct symbol.\n'
174 '\n'
175 'Rember: completion is enabled and can be very helpful if you can\'t remember something.'
176 ))
177 return
178 cmd = p[1]
179
180 cmdhelp = {
181 'QUIT': _('Quits the program'),
182 'LIST': _('Lists the relations loaded'),
183 'LOAD': _('LOAD filename [relationame]\nLoads a relation into memory'),
184 'UNLOAD': _('UNLOAD relationame\nUnloads a relation from memory'),
185 'SAVE': _('SAVE filename relationame\nSaves a relation in a file'),
186 'HELP': _('Prints the help on a command'),
187 'SURVEY': _('Fill and send a survey'),
188 }
189 print(cmdhelp.get(cmd, _('Unknown command: %s') % cmd))
190
191
192 def exec_line(command: str) -> None:
193 '''
194 Executes a line.
195
196 If it's a command, runs it, if it's a query runs it too
197 '''
198 command = command.strip()
199
200 if command.startswith(';'):
201 return
202 elif command == 'QUIT':
203 sys.exit(0)
204 elif command.startswith('HELP'):
205 help(command)
206 elif command == 'LIST': # Lists all the loaded relations
207 for i in ui.relations:
208 if not i.startswith('_'):
209 print(i)
210 elif command == 'SURVEY':
211 survey()
212 elif command.startswith('LOAD '): # Loads a relation
213 pars = command.split(' ')
214 if len(pars) == 1:
215 cprint(_("Missing parameter"), ERROR_COLOR)
216 return
217
218 filename = pars[1]
219 defname = None
220 if len(pars) > 2:
221 defname = pars[2]
222 load_relation(filename, defname)
223
224 elif command.startswith('UNLOAD '):
225 pars = command.split(' ')
226 if len(pars) < 2:
227 cprint(_("Missing parameter"), ERROR_COLOR)
228 elif len(pars) > 2:
229 cprint(_("Too many parameter"), ERROR_COLOR)
230 if pars[1] in ui.relations:
231 ui.unload(pars[1])
232 completer.remove_completion(pars[1])
233 else:
234 cprint(_("No such relation %s") % pars[1], ERROR_COLOR)
235 elif command.startswith('SAVE '):
236 pars = command.split(' ')
237 if len(pars) != 3:
238 cprint(_("Missing parameter"), ERROR_COLOR)
239 return
240
241 filename = pars[1]
242 defname = pars[2]
243
244 try:
245 ui.store(filename, defname)
246 except Exception as e:
247 cprint(e, ERROR_COLOR)
248 else:
249 exec_query(command)
250
251
252 def replacements(query: str) -> str:
253 '''This funcion replaces ascii easy operators with the correct ones'''
254 rules = (
255 ('_PRODUCT', parser.PRODUCT),
256 ('_UNION', parser.UNION),
257 ('_INTERSECTION', parser.INTERSECTION),
258 ('_DIFFERENCE', parser.DIFFERENCE),
259 ('_JOIN', parser.JOIN),
260 ('_LJOIN', parser.JOIN_LEFT),
261 ('_RJOIN', parser.JOIN_RIGHT),
262 ('_FJOIN', parser.JOIN_FULL),
263 ('_PROJECTION', parser.PROJECTION),
264 ('_RENAME_TO', parser.ARROW),
265 ('_SELECTION', parser.SELECTION),
266 ('_RENAME', parser.RENAME),
267 ('_DIVISION', parser.DIVISION),
268 )
269 for asciiop, op in rules:
270 query = query.replace(asciiop, op)
271 return query
272
273
274 def exec_query(command: str) -> None:
275 '''
276 Executes a query and prints the result on the screen
277 if the command terminates with ";" the result will not be printed.
278
279 Updates the set of relations.
280 '''
281
282 # If it terminates with ; doesn't print the result
283 if command.endswith(';'):
284 command = command[:-1]
285 printrel = False
286 else:
287 printrel = True
288
289 # Performs replacements for weird operators
290 command = replacements(command)
291
292 # Finds the name in where to save the query
293 parts = command.split('=', 1)
294 relname,query = maintenance.UserInterface.split_query(command)
295
296 # Execute query
297 try:
298 pyquery = parser.parse(query)
299 result = pyquery(ui.relations)
300
301 if TTY:
302 cprint(_("-> query: %s") % pyquery, COLOR_GREEN)
303
304 if printrel:
305 print()
306 print(result.pretty_string())
307
308 ui.relations[relname] = result
309
310 completer.add_completion(relname)
311 except Exception as e:
312 cprint(str(e), ERROR_COLOR)
313
314
315 def main(files=[]):
316 if TTY:
317 cprint('> ', PROMPT_COLOR, end='')
318 print(_("; Type HELP to get the HELP"))
319 cprint('> ', PROMPT_COLOR, end='')
320 print(_("; Completion is activated using the tab (if supported by the terminal)"))
321
322 for i in files:
323 load_relation(i, None)
324
325 readline.set_completer(completer.complete)
326
327 readline.parse_and_bind('tab: complete')
328 readline.parse_and_bind('set editing-mode emacs')
329 readline.set_completer_delims(" ")
330
331 while True:
332 try:
333 line = input(colored('> ', PROMPT_COLOR))
334 if isinstance(line, str) and len(line) > 0:
335 exec_line(line)
336 except KeyboardInterrupt:
337 if TTY:
338 print('^C\n')
339 continue
340 else:
341 break
342 except EOFError:
343 if TTY:
344 print()
345 sys.exit(0)
346
347
348 if __name__ == "__main__":
349 main()