Repo moved to http://github.com/husio/aurshell/tree/master
[AurShell.git] / pyshell.py
bloba165a4489d8d39e5f6c4faab758ab7021b0c062a
1 #!/usr/bin/python
2 # -*- coding: utf-8-*-
4 """
5 Aur Shell is simple shell framework.
7 To use it, write some plugins that Aur Shell would use.
8 """
10 import cmd
11 import string
12 import sys
13 import os
14 #import os.path
15 #import types
16 import readline
18 import conf
19 from showinfo import Put
21 __version__ = "0.1"
24 class AurShell(cmd.Cmd):
25 """Interactive shell framework.
26 To use it, write some modules, becouse by default it's very poor shell.
27 """
28 def __init__(self):
29 cmd.Cmd.__init__(self)
30 # use it instead of plain `print`
31 self.put = Put()
32 self.conf = conf
33 # prefix for method callable by shell
34 self.cmdprefix = "do_"
35 self.prompt = conf.shell_prompt
36 # plugins dict
37 self.commands = self.load_plugins(conf.modules_path)
38 # intro message
39 self.intro = "\n\tWelcome to aurShell v%(__version__)s\n" % globals()
40 # load history, create empty file if history doesn't exist
41 if not os.path.isfile(conf.history_file):
42 open(conf.history_file, "w").close()
43 readline.read_history_file(conf.history_file)
44 readline.set_history_length(conf.history_length)
45 # create build_dir if doesn't exist
46 if not os.path.isdir(conf.build_dir):
47 os.mkdir(conf.build_dir)
49 def load_plugins(self, modules_path):
50 """Load all commands modules from modules_path direcotory."""
51 command_modules = []
52 # adding plugins path to sys.path
53 if modules_path not in sys.path:
54 sys.path.append(modules_path)
55 # importing all modules from modules_path
56 for module_name in os.listdir(modules_path):
57 module_path = os.path.abspath(
58 string.join(modules_path, module_name))
59 (module_name, module_extension) = os.path.splitext(module_name)
60 # if it shouldn't be load
61 if os.path.islink(module_path) or \
62 module_path == __file__ or \
63 module_extension != ".py":
64 continue
65 for key in sys.modules.keys():
66 if key == module_name:
67 del sys.modules[key]
68 module = __import__(module_name)
69 command_modules.append({"obj": module_name, "name": module,})
70 # search for class in each module
71 module_objs = {}
72 for module in command_modules:
73 for obj in dir(module["name"]):
74 # TODO
75 # better class serch 2008-01-27 16:56:42
76 if not obj.startswith("_"):
77 try:
78 # check if it's method
79 x = getattr(module['name'], obj)(self.put, conf)
80 # create instance for each class
81 # as agrument give it Put() class instance
82 module_objs[obj] = \
83 getattr(module['name'], obj)(self.put, conf)
84 except TypeError:
85 pass
86 return module_objs
88 def precmd(self, cmd):
89 # check if alias exists and if so, replace command
90 for alias in conf.alias.keys():
91 # command should start with alias, but:
92 # - next char should be white space, or
93 # - there's no next char
94 if cmd.startswith(alias) and \
95 (len(cmd) <= len(alias) or cmd[len(alias)] == " "):
96 cmd = cmd.replace(alias, conf.alias[alias], 1)
97 return cmd
99 def do_shell(self, cmd):
100 """System shell command, for commads which starts with !"""
101 os.system(cmd)
103 def default(self, cmd=None):
104 """Run commands.
106 cmd = (<class>, [method], [arg1], [arg2], ...)
108 # cmd[0] should be class name
109 # cmd[1] should be method name (or arugmet if class is callable)
110 # cmd[1] can be empty
111 # cmd[2:] should be method argumments, can be empty
112 cmd = cmd.split()
113 # operations for single command with no arguments
114 if len(cmd) == 1:
115 # if there's no such command (or plugin class)
116 if not cmd[0] in self.commands.keys():
117 self.put("%s : command not found." % cmd[0])
118 else:
119 self.put("%s : bad usege. Try to run help." % cmd[0])
120 # if command was called with arguments
121 elif len(cmd) > 1:
122 cmd[1] = self.cmdprefix + cmd[1]
123 if not cmd[0] in self.commands.keys():
124 self.put("%s : command not found." % cmd[0])
125 # if method named arg[1] exist in class arg[0], try to run it
126 elif cmd[1] in dir(self.commands[cmd[0]]):
127 #print dir(self.commands[cmd[0]])
128 try:
129 getattr(self.commands[cmd[0]], cmd[1])(*cmd[2:])
130 except TypeError:
131 # show __doc__ if exist
132 doc = getattr(self.commands[cmd[0]], cmd[1])
133 if doc.__doc__:
134 self.put(doc.__doc__)
135 else:
136 self.put("%s : bad usage" % cmd[1][3:])
137 else:
138 # try tu run __call__() method
139 try:
140 cmd[1] = cmd[1][len(self.cmdprefix):]
141 getattr(self.commands[cmd[0]], "__call__")(*cmd)
142 except TypeError:
143 self.put("%s : bad usage" % cmd[0])
145 def completenames(self, text, *ignored):
146 """Complete commands"""
147 dotext = self.cmdprefix + text
148 # local methods
149 local_cmd_list = \
150 [a[3:] + " " for a in self.get_names() if a.startswith(dotext)]
151 # + all metrods from modules
152 module_cmd_list = \
153 [a + " " for a in self.commands.keys() if a.startswith(text)]
154 # + all aliases
155 aliases_cmd_list = \
156 [a + " " for a in self.conf.alias.keys() if a.startswith(text)]
157 return local_cmd_list + module_cmd_list + aliases_cmd_list
159 def completedefault(self, text, line, begidx, endidx):
160 """Complete commands argument"""
161 dotext = self.cmdprefix + text
162 line = line.split()
163 # if only commands was given
164 if len(line) == 1:
165 cmds = [a[3:] + " " for a in dir(self.commands[line[0]]) \
166 if a.startswith(dotext)]
167 elif len(line) == 2:
168 cmds = [a[3:] + " " for a in dir(self.commands[line[0]]) \
169 if a.startswith(dotext)]
170 # else don't complete (or should I?)
171 else:
172 cmds = []
173 return cmds
175 def do_help(self, arg):
176 """Show help for commands"""
177 arg = arg.split()
178 if not arg:
179 self.put("Usage: help <command>")
180 elif len(arg) == 1:
181 # first - build-in methods
182 if self.cmdprefix + arg[0] in dir(self):
183 doc = getattr(self, self.cmdprefix + arg[0]).__doc__
184 if doc:
185 self.put(doc)
186 # modules help
187 else:
188 try:
189 # try to run help() method
190 self.put(getattr(self.commands[arg[0]], "help")())
191 except AttributeError:
192 # try to show __doc__
193 if self.commands[arg[0]].__doc__:
194 self.put(self.commands[arg[0]].__doc__)
195 else:
196 self.put("No help found.")
197 except KeyError:
198 self.put("No help found.")
200 elif len(arg) == 2:
201 try:
202 if arg[0] in self.commands.keys():
203 arg[1] = self.cmdprefix + arg[1]
204 doc = getattr(self.commands[arg[0]], arg[1]).__doc__
205 self.put(doc)
206 except AttributeError:
207 self.put("%s : no help found" % arg[1][3:])
208 else:
209 self.put("Try to do something else.\nThis option doesn't work well now.")
211 def do_clear(self, *ignored):
212 """Clear the screen"""
213 # TODO 2008-02-09 20:44:50
214 self.put("Todo, sorry")
216 def do_history(self, hnumb=None, *ignored):
217 """Show the history"""
218 # TODO better history listing
219 # 2008-01-27 18:51:22
220 # print whole history
221 if not hnumb:
222 for number in range(1, conf.history_length):
223 cmd = readline.get_history_item(number)
224 if not cmd:
225 break
226 self.put("%6d %s" % (number, cmd))
227 # for history range 12-22 or -22 or 22-
228 else:
229 try:
230 if "-" in hnumb:
231 if hnumb[-1] == "-" or hnumb[0] == "-":
232 start = int(hnumb.replace("-", " "))
233 end = conf.history_length
234 else:
235 start, end = hnumb.split("-")
236 start = int(start)
237 end = int(end) + 1
238 for number in range(start, end):
239 cmd = readline.get_history_item(number)
240 if not cmd:
241 break
242 self.put("%6d %s" % (number, cmd))
243 else:
244 hnumb = int(hnumb)
245 self.put(readline.get_history_item(hnumb))
246 except ValueError:
247 self.put("""Bad value.
248 Usage: history <number or range>
249 history 11-20 -> from 11 to 20
250 history 22- -> from 22 fo the end of history file
251 history -22 -> same as 22-""")
253 def do_quit(self, *ignored):
254 """Quit from shell"""
255 if conf.history_length:
256 readline.write_history_file(conf.history_file)
257 print ""
258 sys.exit(1)
260 # function aliases
261 do_EOF = do_quit
262 do_exit = do_quit
265 if __name__ == "__main__":
266 shell = AurShell()
267 try:
268 shell.cmdloop()
269 except KeyboardInterrupt:
270 # TODO 2008-01-27 16:56:31
271 sys.exit(shell.do_quit())