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