1091
by Martin Pool
- new shell-complete command to help zsh completion |
1 |
import sys |
2 |
||
3 |
||
4 |
def shellcomplete(context=None, outfile = None): |
|
5 |
if outfile == None: |
|
6 |
outfile = sys.stdout |
|
7 |
if context == None: |
|
8 |
shellcomplete_commands(outfile = outfile) |
|
9 |
else: |
|
10 |
shellcomplete_on_command(context, outfile = outfile) |
|
11 |
||
12 |
def shellcomplete_on_command(cmdname, outfile = None): |
|
13 |
cmdname = str(cmdname) |
|
14 |
||
15 |
if outfile == None: |
|
16 |
outfile = sys.stdout |
|
17 |
||
18 |
from inspect import getdoc |
|
19 |
import commands |
|
20 |
context, cmdclass = commands.get_cmd_class(cmdname) |
|
21 |
||
22 |
doc = getdoc(cmdclass) |
|
23 |
if doc == None: |
|
24 |
raise NotImplementedError("sorry, no detailed shellcomplete yet for %r" % cmdname) |
|
25 |
||
26 |
shellcomplete_on_option(cmdclass.takes_options, outfile = None) |
|
27 |
for aname in cmdclass.takes_args: |
|
28 |
outfile.write(aname + '\n') |
|
29 |
||
30 |
||
31 |
def shellcomplete_on_option(options, outfile = None): |
|
32 |
import commands |
|
33 |
||
34 |
if not options: |
|
35 |
return
|
|
36 |
||
37 |
if outfile == None: |
|
38 |
outfile = sys.stdout |
|
39 |
||
40 |
for on in options: |
|
41 |
for shortname, longname in commands.SHORT_OPTIONS.items(): |
|
42 |
if longname == on: |
|
43 |
l = '"(--' + on + ' -' + shortname + ')"{--' + on + ',-' + shortname + '}' |
|
44 |
break
|
|
45 |
else: |
|
46 |
l = '--' + on |
|
47 |
outfile.write(l + '\n') |
|
48 |
||
49 |
||
50 |
def shellcomplete_commands(outfile = None): |
|
51 |
"""List all commands"""
|
|
52 |
import inspect |
|
53 |
import commands |
|
54 |
from inspect import getdoc |
|
55 |
||
56 |
if outfile == None: |
|
57 |
outfile = sys.stdout |
|
58 |
||
59 |
cmds = [] |
|
60 |
for cmdname, cmdclass in commands.get_all_cmds(): |
|
61 |
cmds.append((cmdname, cmdclass)) |
|
62 |
for alias in cmdclass.aliases: |
|
63 |
cmds.append((alias, cmdclass)) |
|
64 |
cmds.sort() |
|
65 |
for cmdname, cmdclass in cmds: |
|
66 |
if cmdclass.hidden: |
|
67 |
continue
|
|
68 |
doc = getdoc(cmdclass) |
|
69 |
if doc == None: |
|
70 |
outfile.write(cmdname + '\n') |
|
71 |
else: |
|
72 |
doclines = doc.splitlines() |
|
73 |
firstline = doclines[0].lower() |
|
74 |
outfile.write(cmdname + ':' + firstline[0:-1] + '\n') |