optcomplete-1.2/0000750000175000017500000000000010006444531014451 5ustar calvincalvin00000000000000optcomplete-1.2/index.html0000640000175000017500000001247210006225500016446 0ustar calvincalvin00000000000000 optcomplete: Shell Completion Self-Generator for Python

optcomplete: Shell Completion Self-Generator for Python

Table of Contents

Description

This Python module aims at providing almost automatically shell completion for any Python program that already uses the optparse module.

Motivation

This module aims at placing the shell completion routine and the option parsing code in a single location: in the program itself.

The logic is that since a program already knows about its options, and in Python we have a standard module to specify them programmatically since Python-2.3 (optparse), the program itself is in the best position to suggest completions for an incomplete command-line to a shell that invokes it.

Traditionally, this has been done by writing shell-specific descriptions separate from the programs themselves, such as the Bash Programmable Completion project. This approach requires maintaining the shell completion functions up-to-date with the programs.

During development of this proof-of-concept, we were interested in finding if the programs could not describe their completion routines themselves, using the well-specified completion protocol in bash. Similar completion routines could be easily written for other shells and we could extend this module to them.

Documentation

optcomplete consists of a simple module optcomplete.py which you should install somewhere in your PYTHONPATH.

To add simple support to a program which already uses optparse, simply add the following code after the optparse declarations, before calling the parse_args() function on your options parser:

import optcomplete
optcomplete.autocomplete(parser)

Optionally, you can pass a completer as a second argument (see module code).

You also need to source a Bash function and then to tell Bash to trigger optcomplete completion for the specific programs that use it:

complete -F _optcomplete <program>

More examples:

Download

Author

Martin Blais <blais@furius.ca>

optcomplete-1.2/test/0000750000175000017500000000000010006444531015430 5ustar calvincalvin00000000000000optcomplete-1.2/test/a.tar.bz20000640000175000017500000000000010005126251017036 0ustar calvincalvin00000000000000optcomplete-1.2/test/b.tar.gz0000640000175000017500000000000010005126251016762 0ustar calvincalvin00000000000000optcomplete-1.2/test/script2.py0000750000175000017500000000000010005126252017355 0ustar calvincalvin00000000000000optcomplete-1.2/test/script.sh0000640000175000017500000000000010005126252017253 0ustar calvincalvin00000000000000optcomplete-1.2/test/script1.py0000750000175000017500000000000010005126252017354 0ustar calvincalvin00000000000000optcomplete-1.2/test/a.tar0000640000175000017500000000000010005126251016342 0ustar calvincalvin00000000000000optcomplete-1.2/etc/0000750000175000017500000000000010006444531015224 5ustar calvincalvin00000000000000optcomplete-1.2/etc/env0000640000175000017500000000042510005062235015735 0ustar calvincalvin00000000000000#!/bin/sh # # $Id: env,v 1.2 2004/01/26 00:51:41 blais Exp $ # # My environment initialization for this project. This could or could not be # used as an example for your own settings for development. USERPATH=$USERPATH:$PROJDIR/bin PYTHONPATH=$PYTHONPATH:$PROJDIR/lib/python optcomplete-1.2/etc/bashrc0000640000175000017500000000067210005644344016422 0ustar calvincalvin00000000000000#!/bin/sh # # $Id: bashrc,v 1.5 2004/01/28 05:30:12 blais Exp $ # $Source: /u/blais/cvsroot/optcomplete/etc/bashrc,v $ # # Bash configuration for this project. # # source the optcomplete shell functions. . $PROJDIR/etc/optcomplete.bash # Make bash invoke optcomplete completion for the test programs. complete -F _optcomplete optcomplete-simple complete -F _optcomplete optcomplete-conditional complete -F _optcomplete optcomplete-commands optcomplete-1.2/etc/optcomplete.bash0000640000175000017500000000076310005131260020414 0ustar calvincalvin00000000000000#!/bin/sh # # $Id: optcomplete.bash,v 1.6 2004/01/26 06:24:48 blais Exp $ # $Source: /u/blais/cvsroot/optcomplete/etc/optcomplete.bash,v $ # # optcomplete harness for bash shell. You then need to tell # bash to invoke this shell function with a command like # this:: # # complete -F _optcomplete optcomplete-test # _optcomplete() { COMPREPLY=( $( \ COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \ COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ OPTPARSE_AUTO_COMPLETE=1 $1 ) ) } optcomplete-1.2/etc/docutilsrc0000640000175000017500000000007410005647236017332 0ustar calvincalvin00000000000000README index.html doc/sample-output.txt doc/conditional.txt optcomplete-1.2/VERSION0000600000175000017500000000000410006244674015516 0ustar calvincalvin000000000000001.2 optcomplete-1.2/CHANGES0000640000175000017500000000074110006225617015451 0ustar calvincalvin00000000000000==================== CHANGES: optcomplete ==================== Current ======= - Following a user's suggestion, changed license to BSD-style license so that it is compatible with the Python code and optparse. - Added setup.py - Implemented support for --opt= syntax to work. - Implemented support for subcommands, fixed bugs. - Implemented more completers - [2004-01-27] Added ListCompleter, while writing support for scripts with subcommands. - Initial public release. optcomplete-1.2/TODO0000640000175000017500000000077010005652016015144 0ustar calvincalvin00000000000000================= TODO: optcomplete ================= - bug: we need a better way to pass the COMP_WORDS array to the program, lest the space delimited arguments will be split (bleh). perhaps use a random string to do this. - provide more completers. .. end - how will it work with my multiple subcommand framework? - see if we can support csh. - we could add an option that would make the short options automatically expand to long options, this depends how the shell treats our answers. optcomplete-1.2/COPYING0000640000175000017500000000273310006225417015512 0ustar calvincalvin00000000000000Copyright (c) 2003-2004, Martin Blais All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Martin Blais, Furius, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. optcomplete-1.2/doc/0000750000175000017500000000000010006444530015215 5ustar calvincalvin00000000000000optcomplete-1.2/doc/conditional.txt0000640000175000017500000000476010005652016020270 0ustar calvincalvin00000000000000=============================== Using optcomplete Conditionally =============================== :Author: Martin Blais :Date: 2004-01-28 :Abstract: Notes on adding conditionals for scripts to keep on working even without optcomplete. Motivation ========== Sometimes it is important for a particular script to be able to work without the presence of the non-standard ``optcomplete`` module. After that, if that is the only thing that is missing, the script is still able to do its work without completion. This document contains little notes on how to do this but still take advantage of auto-generated completion if the module is available. Note ---- Note that if your shell binding hooks a program to the autocomplete function, the program will be invoked without arguments and you will see the output that calling it as such would generate, unless the program is written to handle this case by manually recognizing completion is being called for, e.g.:: .... elif 'COMP_LINE' in os.environ: return -1 Simple ====== You can import like this:: try: import optcomplete except ImportError: optcomplete = None Then, further one, you can use a global conditional for the completion code:: if optcomplete: ... e.g.:: if optcomplete: optcomplete.autocomplete(parser, ['.*\.tar.*']) With Subcommands ================ Importing, with a base class for commands:: try: import optcomplete CmdComplete = optcomplete.CmdComplete except ImportError: optcomplete, CmdComplete = None, object Then you can use the same conditional:: class CmdCompleting(CmdFoo): ... if optcomplete: completer = ....... def addopts( self, parser ): CmdFoo.addopts(self, parser) opt = parser.add_option(.... if optcomplete: opt.completer = ..... You can also check for completions manually and return nothing if the invocation is from completion:: # subcommand completions if optcomplete: scmap = {} for sc in subcmds: for n in sc.names: scmap[n] = sc listcter = optcomplete.ListCompleter(scmap.keys()) subcter = optcomplete.ListCompleter( ['some', 'default', 'commands', 'completion']) optcomplete.autocomplete( gparser, listcter, None, subcter, subcommands=scmap) elif 'COMP_LINE' in os.environ: return -1 optcomplete-1.2/doc/sample-output.txt0000640000175000017500000001443310005652016020602 0ustar calvincalvin00000000000000================================== optcomplete: Sample Example Output ================================== :Author: Martin Blais :Date: 2004-01-26 :Abstract: Some sample output and examples of what optcomplete provides. Basic Features ============== For some input script with the following ``optparse`` declarations:: parser = optparse.OptionParser() parser.add_option('-s', '--simple', action='store_true', help="Simple really simple option without argument.") parser.add_option('-o', '--output', action='store', help="Option that requires an argument.") parser.add_option('-p', '--script', action='store', help="Option that takes python scripts args only.") We modify the last option simply to add one option-specific completer (this is option, for this demo):: opt = parser.add_option('-p', '--script', action='store', help="Option that takes python scripts args only.") opt.completer = optcomplete.RegexCompleter('.*\.py') And then, to add support for completions, we need only add a call to the autocomplete function, with optional regexps for filename completion:: # Support completion for the command-line of this script. optcomplete.autocomplete(parser, ['.*\.tar.*']) Here is sample output from the script. .. note:: At the end of each input line I pressed and not . Files present in the test directory:: elbow:~/p/optcomplete/test$ ls -l total 24 drwxr-xr-x 2 blais users 4096 Jan 26 00:59 CVS -rw-r--r-- 1 blais users 0 Jan 26 00:38 a.tar -rw-r--r-- 1 blais users 0 Jan 26 00:38 a.tar.bz2 -rw-r--r-- 1 blais users 0 Jan 26 00:38 b.tar.gz drwxr-xr-x 3 blais users 4096 Jan 26 00:38 dir1 -rw-r--r-- 1 blais users 5803 Jan 26 01:03 sample-output.html -rw-r--r-- 1 blais users 4160 Jan 26 01:04 sample-output.txt -rw-r--r-- 1 blais users 0 Jan 26 00:38 script.sh -rw-r--r-- 1 blais users 0 Jan 26 00:38 script1.py -rw-r--r-- 1 blais users 0 Jan 26 00:38 script2.py Completing without prefix outputs long and short options, and filename completion:: elbow:~/p/optcomplete/test$ optcomplete-test --help --script -h -p a.tar b.tar.gz --output --simple -o -s a.tar.bz2 Completing existing short options completes simply:: elbow:~/p/optcomplete/test$ optcomplete-test - --help --output --script --simple -h -o -p -s elbow:~/p/optcomplete/test$ optcomplete-test -s Completing existing long options works the same:: elbow:~/p/optcomplete/test$ optcomplete-test -- --help --output --script --simple elbow:~/p/optcomplete/test$ optcomplete-test --s elbow:~/p/optcomplete/test$ optcomplete-test --simple Note that if an option requires an argument, other options following it are not listed as possible completions:: elbow:~/p/optcomplete/test$ optcomplete-test --output a.tar a.tar.bz2 b.tar.gz elbow:~/p/optcomplete/test$ optcomplete-test --simple --help --script -h -p a.tar b.tar.gz --output --simple -o -s a.tar.bz2 Option-specific completion can be easily implemented as seen above, in this example, the option ``--script`` takes files that end with ``.py`` only:: elbow:~/p/optcomplete/test$ optcomplete-test --script script1.py script2.py This works anywhere on the command-line, and so on:: elbow:~/p/optcomplete/test$ optcomplete-test --simple --script script1.py --help --script -h -p a.tar b.tar.gz --output --simple -o -s a.tar.bz2 Note that a partial filename will restrict the choices, as expected:: elbow:~/p/optcomplete/test$ optcomplete-test --simple --script script1.py a. a.tar a.tar.bz2 elbow:~/p/optcomplete/test$ optcomplete-test --simple --script script1.py a.tar And running the program has the usual behaviour of ``optparse``, nothing changes:: ---------------------------------------------------------- opts args ['a.tar'] ---------------------------------------------------------- .. note:: It is important to note that a shell completion hook is required in order for the shell to invoke the Python script with the appropriate input to request ``optcomplete`` completion in the first place. This can be done in a bash/shell initialization file for each supported program once the shell ``_optcomplete`` function has been sourced, it could easily be setup globally:: complete -F _optcomplete optcomplete-test Using Subcommands ================= You can also implement completion for subcommands, given very few restrictions. Basically, you build a map from command name to command object and give that to the ``autocomplete()`` function and it works it out for you:: elbow:~/p/optcomplete$ optcomplete-commands --global --version -v foo help --help -g bar goo man --verbose -h completing gore simplest elbow:~/p/optcomplete$ optcomplete-commands Subcommands can have their own custom completion for their own arguments:: elbow:~/p/optcomplete$ optcomplete-commands bar --help -L commands some --local -h completion --local-other -l default elbow:~/p/optcomplete$ optcomplete-commands bar For the following interface:: elbow:~/p/optcomplete$ optcomplete-commands bar --help usage: Bar command description, derived from foo. options: -h, --help show this help message and exit -l, --local Some local option. -L, --local-other Some other local option. elbow:~/p/optcomplete$ Note above that the completions have been set to a default for all the commands, so that the words 'commands', 'some', 'completion', 'default' are produced. You can setup command-specific completion as well:: elbow:~/p/optcomplete$ optcomplete-commands foo --help -h foo_topic1 --local -l foo_topic2 elbow:~/p/optcomplete$ optcomplete-commands foo optcomplete-1.2/doc/sample-output.html0000640000175000017500000002057510005652016020733 0ustar calvincalvin00000000000000 optcomplete: Sample Example Output

optcomplete: Sample Example Output

Author: Martin Blais <blais@furius.ca>
Date: 2004-01-26

Abstract

Some sample output and examples of what optcomplete provides.

Basic Features

For some input script with the following optparse declarations:

parser = optparse.OptionParser()

parser.add_option('-s', '--simple', action='store_true',
                  help="Simple really simple option without argument.")

parser.add_option('-o', '--output', action='store',
                  help="Option that requires an argument.")

parser.add_option('-p', '--script', action='store',
                  help="Option that takes python scripts args only.")

We modify the last option simply to add one option-specific completer (this is option, for this demo):

opt = parser.add_option('-p', '--script', action='store',
                        help="Option that takes python scripts args only.")
opt.completer = optcomplete.RegexCompleter('.*\.py')

And then, to add support for completions, we need only add a call to the autocomplete function, with optional regexps for filename completion:

# Support completion for the command-line of this script.
optcomplete.autocomplete(parser, ['.*\.tar.*'])

Here is sample output from the script.

Note

At the end of each input line I pressed <TAB> and not <ENTER>.

Files present in the test directory:

elbow:~/p/optcomplete/test$ ls -l
total 24
drwxr-xr-x    2 blais    users        4096 Jan 26 00:59 CVS
-rw-r--r--    1 blais    users           0 Jan 26 00:38 a.tar
-rw-r--r--    1 blais    users           0 Jan 26 00:38 a.tar.bz2
-rw-r--r--    1 blais    users           0 Jan 26 00:38 b.tar.gz
drwxr-xr-x    3 blais    users        4096 Jan 26 00:38 dir1
-rw-r--r--    1 blais    users        5803 Jan 26 01:03 sample-output.html
-rw-r--r--    1 blais    users        4160 Jan 26 01:04 sample-output.txt
-rw-r--r--    1 blais    users           0 Jan 26 00:38 script.sh
-rw-r--r--    1 blais    users           0 Jan 26 00:38 script1.py
-rw-r--r--    1 blais    users           0 Jan 26 00:38 script2.py

Completing without prefix outputs long and short options, and filename completion:

elbow:~/p/optcomplete/test$ optcomplete-test
--help     --script   -h         -p         a.tar      b.tar.gz
--output   --simple   -o         -s         a.tar.bz2

Completing existing short options completes simply:

elbow:~/p/optcomplete/test$ optcomplete-test -
--help    --output  --script  --simple  -h        -o        -p        -s

elbow:~/p/optcomplete/test$ optcomplete-test -s

Completing existing long options works the same:

elbow:~/p/optcomplete/test$ optcomplete-test --
--help    --output  --script  --simple

elbow:~/p/optcomplete/test$ optcomplete-test --s
elbow:~/p/optcomplete/test$ optcomplete-test --simple

Note that if an option requires an argument, other options following it are not listed as possible completions:

elbow:~/p/optcomplete/test$ optcomplete-test --output
a.tar      a.tar.bz2  b.tar.gz

elbow:~/p/optcomplete/test$ optcomplete-test --simple
--help     --script   -h         -p         a.tar      b.tar.gz
--output   --simple   -o         -s         a.tar.bz2

Option-specific completion can be easily implemented as seen above, in this example, the option --script takes files that end with .py only:

elbow:~/p/optcomplete/test$ optcomplete-test --script
script1.py  script2.py

This works anywhere on the command-line, and so on:

elbow:~/p/optcomplete/test$ optcomplete-test --simple --script script1.py
--help     --script   -h         -p         a.tar      b.tar.gz
--output   --simple   -o         -s         a.tar.bz2

Note that a partial filename will restrict the choices, as expected:

elbow:~/p/optcomplete/test$ optcomplete-test --simple --script script1.py a.
a.tar      a.tar.bz2
elbow:~/p/optcomplete/test$ optcomplete-test --simple --script script1.py a.tar

And running the program has the usual behaviour of optparse, nothing changes:

----------------------------------------------------------
opts <Values at 0x404181ac: {'simple': None, 'output': None, 'script': 'script1.py'}>
args ['a.tar']
----------------------------------------------------------

Note

It is important to note that a shell completion hook is required in order for the shell to invoke the Python script with the appropriate input to request optcomplete completion in the first place. This can be done in a bash/shell initialization file for each supported program once the shell _optcomplete function has been sourced, it could easily be setup globally:

complete -F _optcomplete optcomplete-test

Using Subcommands

You can also implement completion for subcommands, given very few restrictions. Basically, you build a map from command name to command object and give that to the autocomplete() function and it works it out for you:

elbow:~/p/optcomplete$ optcomplete-commands
--global    --version   -v          foo         help
--help      -g          bar         goo         man
--verbose   -h          completing  gore        simplest
elbow:~/p/optcomplete$ optcomplete-commands

Subcommands can have their own custom completion for their own arguments:

elbow:~/p/optcomplete$ optcomplete-commands bar
--help         -L             commands       some
--local        -h             completion
--local-other  -l             default
elbow:~/p/optcomplete$ optcomplete-commands bar

For the following interface:

elbow:~/p/optcomplete$ optcomplete-commands bar --help
usage: Bar command description, derived from foo.

options:
  -h, --help         show this help message and exit
  -l, --local        Some local option.
  -L, --local-other  Some other local option.
elbow:~/p/optcomplete$

Note above that the completions have been set to a default for all the commands, so that the words 'commands', 'some', 'completion', 'default' are produced.

You can setup command-specific completion as well:

elbow:~/p/optcomplete$ optcomplete-commands foo 
--help      -h          foo_topic1  
--local     -l          foo_topic2  
elbow:~/p/optcomplete$ optcomplete-commands foo 
optcomplete-1.2/doc/conditional.html0000640000175000017500000000767510005652016020425 0ustar calvincalvin00000000000000 Using optcomplete Conditionally

Using optcomplete Conditionally

Author: Martin Blais <blais@furius.ca>
Date: 2004-01-28

Abstract

Notes on adding conditionals for scripts to keep on working even without optcomplete.

Motivation

Sometimes it is important for a particular script to be able to work without the presence of the non-standard optcomplete module. After that, if that is the only thing that is missing, the script is still able to do its work without completion.

This document contains little notes on how to do this but still take advantage of auto-generated completion if the module is available.

Note

Note that if your shell binding hooks a program to the autocomplete function, the program will be invoked without arguments and you will see the output that calling it as such would generate, unless the program is written to handle this case by manually recognizing completion is being called for, e.g.:

....
elif 'COMP_LINE' in os.environ:
    return -1

Simple

You can import like this:

try:
    import optcomplete
except ImportError:
    optcomplete = None

Then, further one, you can use a global conditional for the completion code:

if optcomplete:
    ...

e.g.:

if optcomplete:
    optcomplete.autocomplete(parser, ['.*\.tar.*'])

With Subcommands

Importing, with a base class for commands:

try:
    import optcomplete
    CmdComplete = optcomplete.CmdComplete
except ImportError:
    optcomplete, CmdComplete = None, object

Then you can use the same conditional:

class CmdCompleting(CmdFoo):

    ...

    if optcomplete:
        completer = .......

    def addopts( self, parser ):
        CmdFoo.addopts(self, parser)
        opt = parser.add_option(....
        if optcomplete:
            opt.completer = .....

You can also check for completions manually and return nothing if the invocation is from completion:

# subcommand completions
if optcomplete:
    scmap = {}
    for sc in subcmds:
        for n in sc.names:
            scmap[n] = sc

    listcter = optcomplete.ListCompleter(scmap.keys())
    subcter = optcomplete.ListCompleter(
        ['some', 'default', 'commands', 'completion'])
    optcomplete.autocomplete(
        gparser, listcter, None, subcter, subcommands=scmap)
elif 'COMP_LINE' in os.environ:
    return -1
optcomplete-1.2/setup.py0000750000175000017500000000335410006246577016205 0ustar calvincalvin00000000000000#!/usr/bin/env python # # Install script for tengis. # __version__ = "$Revision: 1.3 $" __author__ = "Martin Blais " from distutils.core import setup def read_version(): try: return open('VERSION', 'r').readline().strip() except IOError, e: raise SystemExit( "Error: you must run setup from the root directory (%s)" % str(e)) setup(name="optcomplete", version=read_version(), description=\ "Automatic shell completion support for scripts that use optparse.", long_description=""" This module provide automatic bash completion support for programs that use the optparse module. The premise is that the optparse options parser specifies enough information (and more) for us to be able to generate completion strings esily. Another advantage of this over traditional completion schemes where the completion strings are hard-coded in a separate bash source file, is that the same code that parses the options is used to generate the completions, so the completions is always up-to-date with the program itself. In addition, we allow you specify a list of regular expressions or code that define what kinds of files should be proposed as completions to this file if needed. If you want to implement more complex behaviour, you can instead specify a function, which will be called with the current directory as an argument. You need to activate bash completion using the shell script function that comes with optcomplete (see http://furius.ca/optcomplete for more details). """, license="BSD", author="Martin Blais", author_email="blais@furius.ca", url="http://furius.ca/optcomplete", package_dir = {'': 'lib/python'}, py_modules = ['optcomplete'], ) optcomplete-1.2/lib/0000750000175000017500000000000010006444531015217 5ustar calvincalvin00000000000000optcomplete-1.2/lib/python/0000750000175000017500000000000010006444531016540 5ustar calvincalvin00000000000000optcomplete-1.2/lib/python/optcomplete.py0000750000175000017500000004110010006225417021444 0ustar calvincalvin00000000000000#!/usr/bin/env python #******************************************************************************\ #* Copyright (c) 2003-2004, Martin Blais #* All rights reserved. #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are #* met: #* #* * Redistributions of source code must retain the above copyright #* notice, this list of conditions and the following disclaimer. #* #* * Redistributions in binary form must reproduce the above copyright #* notice, this list of conditions and the following disclaimer in the #* documentation and/or other materials provided with the distribution. #* #* * Neither the name of the Martin Blais, Furius, nor the names of its #* contributors may be used to endorse or promote products derived from #* this software without specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #******************************************************************************\ """Automatic completion for optparse module. This module provide automatic bash completion support for programs that use the optparse module. The premise is that the optparse options parser specifies enough information (and more) for us to be able to generate completion strings esily. Another advantage of this over traditional completion schemes where the completion strings are hard-coded in a separate bash source file, is that the same code that parses the options is used to generate the completions, so the completions is always up-to-date with the program itself. In addition, we allow you specify a list of regular expressions or code that define what kinds of files should be proposed as completions to this file if needed. If you want to implement more complex behaviour, you can instead specify a function, which will be called with the current directory as an argument. You need to activate bash completion using the shell script function that comes with optcomplete (see http://furius.ca/optcomplete for more details). """ __version__ = "$Revision: 1.11 $" __author__ = "Martin Blais " ## Bash Protocol Description ## ------------------------- ## ## `COMP_CWORD' ## An index into `${COMP_WORDS}' of the word containing the current ## cursor position. This variable is available only in shell ## functions invoked by the programmable completion facilities (*note ## Programmable Completion::). ## ## `COMP_LINE' ## The current command line. This variable is available only in ## shell functions and external commands invoked by the programmable ## completion facilities (*note Programmable Completion::). ## ## `COMP_POINT' ## The index of the current cursor position relative to the beginning ## of the current command. If the current cursor position is at the ## end of the current command, the value of this variable is equal to ## `${#COMP_LINE}'. This variable is available only in shell ## functions and external commands invoked by the programmable ## completion facilities (*note Programmable Completion::). ## ## `COMP_WORDS' ## An array variable consisting of the individual words in the ## current command line. This variable is available only in shell ## functions invoked by the programmable completion facilities (*note ## Programmable Completion::). ## ## `COMPREPLY' ## An array variable from which Bash reads the possible completions ## generated by a shell function invoked by the programmable ## completion facility (*note Programmable Completion::). #=============================================================================== # EXTERNAL DECLARATIONS #=============================================================================== import sys, os, os.path import types import re from pprint import pprint, pformat #=============================================================================== # PUBLIC DECLARATIONS #=============================================================================== debugfn = None # for debugging only #------------------------------------------------------------------------------- # class AllCompleter: """Completes by listing all possible files in current directory.""" def __call__( self, pwd, line, point, prefix, suffix ): return os.listdir(pwd) #------------------------------------------------------------------------------- # class NoneCompleter: """Generates empty completion list.""" def __call__( self, pwd, line, point, prefix, suffix ): return [] #------------------------------------------------------------------------------- # class DirCompleter: """Completes by listing subdirectories only.""" def __call__( self, pwd, line, point, prefix, suffix ): return filter(os.path.isdir, os.listdir(pwd)) #------------------------------------------------------------------------------- # class RegexCompleter: """Completes by filtering all possible files with the given list of regexps.""" def __init__( self, regexlist ): if isinstance(regexlist, types.StringType): regexlist = [regexlist] self.regexlist = [] for r in regexlist: if isinstance(r, types.StringType): r = re.compile(r) self.regexlist.append(r) def __call__( self, pwd, line, point, prefix, suffix ): files = os.listdir(pwd) ofiles = [] for fn in files: for r in self.regexlist: if r.match(fn): ofiles.append(fn) break return ofiles #------------------------------------------------------------------------------- # class ListCompleter: """Completes by filtering using a fixed list of strings.""" def __init__( self, stringlist ): self.olist = stringlist def __call__( self, pwd, line, point, prefix, suffix ): return self.olist #------------------------------------------------------------------------------- # def extract_word( line, point ): """Return a prefix and suffix of the enclosing word. The character under the cursor is the first character of the suffix.""" wsre = re.compile('[ \t]') if point < 0 or point > len(line): return '', '' preii = point - 1 while preii >= 0: if wsre.match(line[preii]): break preii -= 1 preii += 1 sufii = point while sufii < len(line): if wsre.match(line[sufii]): break sufii += 1 return line[preii : point], line[point : sufii] #------------------------------------------------------------------------------- # def autocomplete( parser, arg_completer=None, # means use default. opt_completer=None, subcmd_completer=None, subcommands=None ): """Automatically detect if we are requested completing and if so generate completion automatically from given parser. 'parser' is the options parser to use. 'file_completer' is a callable object that gets invoked to produce a list of completions for arguments completion (oftentimes files). 'opt_completer' is the default completer to the options that require a value. 'subcmd_completer' is the default completer for the subcommand arguments. If 'subcommands' is specified, the script expects it to be a map of command-name to an object of any kind. We are assuming that this object is a map from command name to a pair of (options parser, completer) for the command. If the value is not such a tuple, the method 'autocomplete(completer)' is invoked on the resulting object. This will attempt to match the first non-option argument into a subcommand name and if so will use the local parser in the corresponding map entry's value. This is used to implement completion for subcommand syntax and will not be needed in most cases.""" # If we are not requested for complete, simply return silently, let the code # caller complete. This is the normal path of execution. if not os.environ.has_key('OPTPARSE_AUTO_COMPLETE'): return # Set default completers. if not arg_completer: arg_completer = AllCompleter() if not opt_completer: opt_completer = AllCompleter() if not subcmd_completer: subcmd_completer = arg_completer # By default, completion will be arguments completion, unless we find out # later we're trying to complete for an option. completer = arg_completer # # Completing... # # Fetching inputs... not sure if we're going to use these. cwords = os.environ['COMP_WORDS'].split() cline = os.environ['COMP_LINE'] cpoint = int(os.environ['COMP_POINT']) cword = int(os.environ['COMP_CWORD']) # If requested, try subcommand syntax to find an options parser for that # subcommand. if subcommands: assert isinstance(subcommands, types.DictType) value = guess_first_nonoption(parser, subcommands) if value: if isinstance(value, types.ListType) or \ isinstance(value, types.TupleType): parser = value[0] if len(value) > 1 and value[1]: # override completer for command if it is present. completer = value[1] else: completer = subcmd_completer return autocomplete(parser, completer) else: # Call completion method on object. This should call # autocomplete() recursively with appropriate arguments. if hasattr(value, 'autocomplete'): return value.autocomplete(subcmd_completer) else: sys.exit(1) # no completions for that command object # Extract word enclosed word. prefix, suffix = extract_word(cline, cpoint) # The following would be less exact, but will work nonetheless . # prefix, suffix = cwords[cword], None # Look at previous word, if it is an option and it requires an argument, # check for a local completer. If there is no completer, what follows # directly cannot be another option, so mark to not add those to # completions. optarg = False try: # Look for previous word, which will be containing word if the option # has an equals sign in it. prev = None if cword < len(cwords): mo = re.search('(--.*)=(.*)', cwords[cword]) if mo: prev, prefix = mo.groups() if not prev: prev = cwords[cword - 1] if prev and prev.startswith('-'): option = parser.get_option(prev) if option: if option.nargs > 0: optarg = True if hasattr(option, 'completer'): completer = option.completer else: completer = opt_completer # Warn user at least, it could help him figure out the problem. elif hasattr(option, 'completer'): raise SystemExit( "Error: optparse option with a completer " "does not take arguments: %s" % str(option)) except KeyError: pass completions = [] # Options completion. if not optarg and (not prefix or prefix.startswith('-')): completions += parser._short_opt.keys() completions += parser._long_opt.keys() # Note: this will get filtered properly below. # File completion. if completer and (not prefix or not prefix.startswith('-')): # Call appropriate completer depending on type. if isinstance(completer, types.StringType) or \ isinstance(completer, types.ListType) or \ isinstance(completer, types.TupleType): completer = RegexCompleter(completer) completions += completer(os.getcwd(), cline, cpoint, prefix, suffix) elif isinstance(completer, types.FunctionType) or \ isinstance(completer, types.LambdaType) or \ isinstance(completer, types.ClassType) or \ isinstance(completer, types.ObjectType): completions += completer(os.getcwd(), cline, cpoint, prefix, suffix) # Filter using prefix. if prefix: completions = filter(lambda x: x.startswith(prefix), completions) # Print result. print ' '.join(completions) # Print debug output (if needed). You can keep a shell with 'tail -f' to # the log file to monitor what is happening. if debugfn: f = open(debugfn, 'a') print >> f, '---------------------------------------------------------' print >> f, 'CWORDS', cwords print >> f, 'CLINE', cline print >> f, 'CPOINT', cpoint print >> f, 'CWORD', cword print >> f, '\nShort options' print >> f, pformat(parser._short_opt) print >> f, '\nLong options' print >> f, pformat(parser._long_opt) print >> f, 'Prefix/Suffix:', prefix, suffix print >> f, 'completions', completions f.close() # Exit with error code (we do not let the caller continue on purpose, this # is a run for completions only.) sys.exit(1) #------------------------------------------------------------------------------- # def guess_first_nonoption( gparser, subcmds_map ): """Given a global options parser, try to guess the first non-option without generating an exception. This is used for scripts that implement a subcommand syntax, so that we can generate the appropriate completions for the subcommand.""" import copy gparser = copy.deepcopy(gparser) def print_usage_nousage (self, file=None): pass gparser.print_usage = print_usage_nousage prev_interspersed = gparser.allow_interspersed_args # save state to restore gparser.disable_interspersed_args() cwords = os.environ['COMP_WORDS'].split() try: gopts, args = gparser.parse_args(cwords[1:]) except SystemExit: return None value = None if args: subcmdname = args[0] try: value = subcmds_map[subcmdname] except KeyError: pass gparser.allow_interspersed_args = prev_interspersed # restore state return value # can be None, indicates no command chosen. #------------------------------------------------------------------------------- # class CmdComplete: """Simple default base class implementation for a subcommand that supports command completion. This class is assuming that there might be a method addopts(self, parser) to declare options for this subcommand, and an optional completer data member to contain command-specific completion. Of course, you don't really have to use this, but if you do it is convenient to have it here.""" def autocomplete( self, completer ): import optparse parser = optparse.OptionParser(self.__doc__.strip()) if hasattr(self, 'addopts'): self.addopts(parser) if hasattr(self, 'completer'): completer = self.completer return autocomplete(parser, completer) #=============================================================================== # TEST #=============================================================================== def test(): print extract_word("extraire un mot d'une phrase", 11) print extract_word("extraire un mot d'une phrase", 12) print extract_word("extraire un mot d'une phrase", 13) print extract_word("extraire un mot d'une phrase", 14) print extract_word("extraire un mot d'une phrase", 0) print extract_word("extraire un mot d'une phrase", 28) print extract_word("extraire un mot d'une phrase", 29) print extract_word("extraire un mot d'une phrase", -2) print extract_word("optcomplete-test do", 19) if __name__ == '__main__': test() optcomplete-1.2/bin/0000750000175000017500000000000010006444530015220 5ustar calvincalvin00000000000000optcomplete-1.2/bin/optparse-commands0000750000175000017500000002104210006225417020602 0ustar calvincalvin00000000000000#!/usr/bin/env python #******************************************************************************\ #* Copyright (c) 2003-2004, Martin Blais #* All rights reserved. #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are #* met: #* #* * Redistributions of source code must retain the above copyright #* notice, this list of conditions and the following disclaimer. #* #* * Redistributions in binary form must reproduce the above copyright #* notice, this list of conditions and the following disclaimer in the #* documentation and/or other materials provided with the distribution. #* #* * Neither the name of the Martin Blais, Furius, nor the names of its #* contributors may be used to endorse or promote products derived from #* this software without specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #******************************************************************************\ """optparse-commands [] command [] [ ...] Example for implementing programs with command-line interfaces with many commands, with separate global options and command options. This script is my template when I create new scripts like that require this interface. All of the mechanics are implemented using the standard optparse module that comes with Python >=2.3. """ __moredoc__ = """ Each command consists of a class, which has the following properties: - Must have a class member 'names' which is a list of the names for the command; - Can optionally have a addopts(self, parser) method which adds options to the given parser. This defines command options. """ __version__ = "$Revision: 1.7 $" __author__ = "Martin Blais " __depends__ = ['Python-2.3'] #=============================================================================== # EXTERNAL DECLARATIONS #=============================================================================== import sys, os from os.path import * import re from pprint import pprint, pformat #=============================================================================== # LOCAL DECLARATIONS #=============================================================================== #=============================================================================== # CLASS CmdSimplest #=============================================================================== class CmdSimplest: """Description of simplest command.""" names = ['simplest'] def execute( self, args ): print 'Doing something simple.' #=============================================================================== # CLASS CmdFoo #=============================================================================== class CmdFoo: """Foo command description.""" names = ['foo', 'goo'] def addopts( self, parser ): parser.add_option('-l', '--local', action='store_true', help="Some local option.") def execute( self, args ): print 'Executing CmdFoo' pprint(args) pprint(self.gopts) pprint(self.opts) #=============================================================================== # CLASS CmdBar #=============================================================================== class CmdBar(CmdFoo): """Bar command description, derived from foo.""" names = ['bar', 'gore'] def addopts( self, parser ): CmdFoo.addopts(self, parser) parser.add_option('-L', '--local-other', action='store_true', help="Some other local option.") def execute( self, args ): print 'Executing CmdBar' pprint(args) pprint(self.gopts) pprint(self.opts) #=============================================================================== # CLASS CmdHelp #=============================================================================== class CmdHelp: """Help as a command. This is not really necessary.""" names =['help', 'man'] def execute( self, args ): import optparse if args: cmdname = args[0] try: sc = subcmds_map[cmdname] lparser = optparse.OptionParser(sc.__doc__.strip()) if hasattr(sc, 'addopts'): sc.addopts(lparser) lparser.print_help() except KeyError: raise SystemExit("Error: invalid command '%s'" % cmdname) else: gparser.parse_args(['--help']) #------------------------------------------------------------------------------- # def parse_subcommands( gparser, subcmds ): """Parse given global arguments, find subcommand from given list of subcommand objects, parse local arguments and return a tuple of global options, selected command object, command options, and command arguments. Call execute() on the command object to run. The command object has members 'gopts' and 'opts' set for global and command options respectively, you don't need to call execute with those but you could if you wanted to.""" import optparse global subcmds_map # needed for help command only. # Build map of name -> command and docstring. subcmds_map = {} gparser.usage += '\n\nAvailable Subcommands\n\n' for sc in subcmds: gparser.usage += '- %s: %s\n' % (', '.join(sc.names), sc.__doc__.splitlines()[0]) for n in sc.names: assert n not in subcmds_map subcmds_map[n] = sc # Declare and parse global options. gparser.disable_interspersed_args() gopts, args = gparser.parse_args() if not args: gparser.print_help() raise SystemExit("Error: you must specify a command to use.") subcmdname, subargs = args[0], args[1:] # Parse command arguments and invoke command. try: sc = subcmds_map[subcmdname] lparser = optparse.OptionParser(sc.__doc__.strip()) if hasattr(sc, 'addopts'): sc.addopts(lparser) sc.gopts = gopts sc.opts, subsubargs = lparser.parse_args(subargs) except KeyError: raise SystemExit("Error: invalid command '%s'" % subcmdname) return sc.gopts, sc, sc.opts, subsubargs #=============================================================================== # MAIN #=============================================================================== def main(): # Create global options parser. global gparser # only need for 'help' command (optional) import optparse gparser = optparse.OptionParser(__doc__.strip(), version=__version__) gparser.add_option('-v', '--verbose', action='store_true', help="Verbose mode.") gparser.add_option('-g', '--global', action='store_true', help="Some global option.") # Declare subcommands. subcmds = [ CmdSimplest(), CmdFoo(), CmdBar(), CmdHelp(), ] gopts, sc, opts, args = parse_subcommands(gparser, subcmds) sc.execute(args) #=============================================================================== # TEST #=============================================================================== def test(): tests = [ '', '--help', 'help', 'help foo', 'help goo', 'foo', 'goo', 'foo --help', 'bar', 'bar --help', 'bar arg1 arg2', 'bar arg1 --local arg2', ] print '#!/bin/sh' for s in tests: cmd = '%s %s' % (sys.argv[0], s) print 'clear ; ( echo "%s" ; %s 2>&1 ) | /usr/bin/less' % (cmd, cmd) # Run as main, otherwise run tests. if os.environ.has_key('optparse_commands_test'): test() elif __name__ == '__main__': try: main() except KeyboardInterrupt: print "Interrupted, exiting." optcomplete-1.2/bin/optcomplete-simple0000750000175000017500000000670110006225417020775 0ustar calvincalvin00000000000000#!/usr/bin/env python #******************************************************************************\ #* Copyright (c) 2003-2004, Martin Blais #* All rights reserved. #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are #* met: #* #* * Redistributions of source code must retain the above copyright #* notice, this list of conditions and the following disclaimer. #* #* * Redistributions in binary form must reproduce the above copyright #* notice, this list of conditions and the following disclaimer in the #* documentation and/or other materials provided with the distribution. #* #* * Neither the name of the Martin Blais, Furius, nor the names of its #* contributors may be used to endorse or promote products derived from #* this software without specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #******************************************************************************\ """optcomplete-simple [] Test code for optcomplete. Write some partial arguments and press TAB lots of times. See what happens. """ __version__ = "$Revision: 1.8 $" __author__ = "Martin Blais " #=============================================================================== # EXTERNAL DECLARATIONS #=============================================================================== import os import optparse, optcomplete #=============================================================================== # LOCAL DECLARATIONS #=============================================================================== optcomplete.debugfn = '/tmp/optcomplete.log' #=============================================================================== # MAIN #=============================================================================== def main(): parser = optparse.OptionParser() parser.add_option('-s', '--simple', action='store_true', help="Simple really simple option without argument.") parser.add_option('-o', '--output', action='store', help="Option that requires an argument.") opt = parser.add_option('-p', '--script', action='store', help="Option that takes python scripts args only.") opt.completer = optcomplete.RegexCompleter('.*\.py') # Support completion for the command-line of this script. optcomplete.autocomplete(parser, ['.*\.tar.*']) opts, args = parser.parse_args() print '----------------------------------------------------------' print 'opts', opts print 'args', args print '----------------------------------------------------------' if __name__ == '__main__': main() optcomplete-1.2/bin/optcomplete-conditional0000750000175000017500000000664210006225417022013 0ustar calvincalvin00000000000000#!/usr/bin/env python #******************************************************************************\ #* Copyright (c) 2003-2004, Martin Blais #* All rights reserved. #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are #* met: #* #* * Redistributions of source code must retain the above copyright #* notice, this list of conditions and the following disclaimer. #* #* * Redistributions in binary form must reproduce the above copyright #* notice, this list of conditions and the following disclaimer in the #* documentation and/or other materials provided with the distribution. #* #* * Neither the name of the Martin Blais, Furius, nor the names of its #* contributors may be used to endorse or promote products derived from #* this software without specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #******************************************************************************\ """optcomplete-test [] Test code for optcomplete. Write some partial arguments and press TAB lots of times. See what happens. """ __version__ = "$Revision: 1.2 $" __author__ = "Martin Blais " #=============================================================================== # EXTERNAL DECLARATIONS #=============================================================================== import os import optparse try: import optcomplete optcomplete.debugfn = '/tmp/optcomplete.log' except ImportError: optcomplete = None #=============================================================================== # MAIN #=============================================================================== def main(): parser = optparse.OptionParser() parser.add_option('-s', '--simple', action='store_true', help="Simple really simple option without argument.") parser.add_option('-o', '--output', action='store', help="Option that requires an argument.") opt = parser.add_option('-p', '--script', action='store', help="Option that takes python scripts args only.") if optcomplete: opt.completer = optcomplete.RegexCompleter('.*\.py') # Support completion for the command-line of this script. if optcomplete: optcomplete.autocomplete(parser, ['.*\.tar.*']) elif 'COMP_LINE' in os.environ: return 0 opts, args = parser.parse_args() print '----------------------------------------------------------' print 'opts', opts print 'args', args print '----------------------------------------------------------' if __name__ == '__main__': main() optcomplete-1.2/bin/optcomplete-commands0000750000175000017500000002332210006225417021303 0ustar calvincalvin00000000000000#!/usr/bin/env python #******************************************************************************\ #* Copyright (c) 2003-2004, Martin Blais #* All rights reserved. #* #* Redistribution and use in source and binary forms, with or without #* modification, are permitted provided that the following conditions are #* met: #* #* * Redistributions of source code must retain the above copyright #* notice, this list of conditions and the following disclaimer. #* #* * Redistributions in binary form must reproduce the above copyright #* notice, this list of conditions and the following disclaimer in the #* documentation and/or other materials provided with the distribution. #* #* * Neither the name of the Martin Blais, Furius, nor the names of its #* contributors may be used to endorse or promote products derived from #* this software without specific prior written permission. #* #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #******************************************************************************\ """optcomplete-commands [] command [] [ ...] Example for implementing programs with command-line interfaces with many commands, with separate global options and command options, and command-based completion. See optparse-commands(). """ __moredoc__ = """ Each command consists of a class, which has the following properties: - Must have a class member 'names' which is a list of the names for the command; - Can optionally have a addopts(self, parser) method which adds options to the given parser. This defines command options. """ __version__ = "$Revision: 1.10 $" __author__ = "Martin Blais " __depends__ = ['Python-2.3'] #=============================================================================== # EXTERNAL DECLARATIONS #=============================================================================== import sys, os from os.path import * import re from pprint import pprint, pformat import optcomplete CmdComplete = optcomplete.CmdComplete #=============================================================================== # LOCAL DECLARATIONS #=============================================================================== #=============================================================================== # CLASS CmdSimplest #=============================================================================== class CmdSimplest(CmdComplete): """Description of simplest command.""" names = ['simplest'] def execute( self, args ): print 'Doing something simple.' #=============================================================================== # CLASS CmdFoo #=============================================================================== class CmdFoo(CmdComplete): """Foo command description.""" names = ['foo', 'goo'] completer = optcomplete.ListCompleter(['foo_topic1', 'foo_topic2']) def addopts( self, parser ): parser.add_option('-l', '--local', action='store_true', help="Some local option.") def execute( self, args ): print 'Executing CmdFoo' pprint(args) pprint(self.gopts) pprint(self.opts) #=============================================================================== # CLASS CmdBar #=============================================================================== class CmdBar(CmdFoo): """Bar command description, derived from foo.""" names = ['bar', 'gore'] def addopts( self, parser ): CmdFoo.addopts(self, parser) parser.add_option('-L', '--local-other', action='store_true', help="Some other local option.") def execute( self, args ): print 'Executing CmdBar' pprint(args) pprint(self.gopts) pprint(self.opts) #=============================================================================== # CLASS CmdHelp #=============================================================================== class CmdHelp: """Help as a command. This is not really necessary.""" names =['help', 'man'] def execute( self, args ): import optparse if args: cmdname = args[0] try: sc = subcmds_map[cmdname] lparser = optparse.OptionParser(sc.__doc__.strip()) if hasattr(sc, 'addopts'): sc.addopts(lparser) lparser.print_help() except KeyError: raise SystemExit("Error: invalid command '%s'" % cmdname) else: gparser.parse_args(['--help']) #=============================================================================== # CLASS CmdCompleting #=============================================================================== class CmdCompleting(CmdFoo): """Completing command description.""" names = ['completing'] completer = optcomplete.ListCompleter(['kikirinkin', 'ararara']) def addopts( self, parser ): CmdFoo.addopts(self, parser) opt = parser.add_option('-L', '--local-other', action='store', help="Some other local option.") opt.completer = optcomplete.ListCompleter(['garabato', 'briumba']) def execute( self, args ): print 'Executing CmdBar' pprint(args) pprint(self.gopts) pprint(self.opts) #------------------------------------------------------------------------------- # def parse_subcommands( gparser, subcmds ): """Parse given global arguments, find subcommand from given list of subcommand objects, parse local arguments and return a tuple of global options, selected command object, command options, and command arguments. Call execute() on the command object to run. The command object has members 'gopts' and 'opts' set for global and command options respectively, you don't need to call execute with those but you could if you wanted to.""" import optparse global subcmds_map # needed for help command only. # Build map of name -> command and docstring. subcmds_map = {} gparser.usage += '\n\nAvailable Subcommands\n\n' for sc in subcmds: gparser.usage += '- %s: %s\n' % (', '.join(sc.names), sc.__doc__.splitlines()[0]) for n in sc.names: assert n not in subcmds_map subcmds_map[n] = sc # Declare and parse global options. gparser.disable_interspersed_args() gopts, args = gparser.parse_args() if not args: gparser.print_help() raise SystemExit("Error: you must specify a command to use.") subcmdname, subargs = args[0], args[1:] # Parse command arguments and invoke command. try: sc = subcmds_map[subcmdname] lparser = optparse.OptionParser(sc.__doc__.strip()) if hasattr(sc, 'addopts'): sc.addopts(lparser) sc.gopts = gopts sc.opts, subsubargs = lparser.parse_args(subargs) except KeyError: raise SystemExit("Error: invalid command '%s'" % subcmdname) return sc.gopts, sc, sc.opts, subsubargs #=============================================================================== # MAIN #=============================================================================== def main(): # Create global options parser. global gparser # only need for 'help' command (optional) import optparse gparser = optparse.OptionParser(__doc__.strip(), version=__version__) gparser.add_option('-v', '--verbose', action='store_true', help="Verbose mode.") gparser.add_option('-g', '--global', action='store_true', help="Some global option.") # Declare subcommands. subcmds = [ CmdSimplest(), CmdFoo(), CmdBar(), CmdCompleting(), CmdHelp(), ] # subcommand completions scmap = {} for sc in subcmds: for n in sc.names: scmap[n] = sc listcter = optcomplete.ListCompleter(scmap.keys()) subcter = optcomplete.ListCompleter( ['some', 'default', 'commands', 'completion']) optcomplete.autocomplete( gparser, listcter, None, subcter, subcommands=scmap) gopts, sc, opts, args = parse_subcommands(gparser, subcmds) sc.execute(args) #=============================================================================== # TEST #=============================================================================== def test(): tests = [ '', '--help', 'help', 'help foo', 'help goo', 'foo', 'goo', 'foo --help', 'bar', 'bar --help', 'bar arg1 arg2', 'bar arg1 --local arg2', ] print '#!/bin/sh' for s in tests: cmd = '%s %s' % (sys.argv[0], s) print 'clear ; ( echo "%s" ; %s 2>&1 ) | /usr/bin/less' % (cmd, cmd) # Run as main, otherwise run tests. if os.environ.has_key('optparse_commands_test'): test() elif __name__ == '__main__': try: main() except KeyboardInterrupt: print "Interrupted, exiting." optcomplete-1.2/README0000640000175000017500000000531110006225417015332 0ustar calvincalvin00000000000000======================================================= optcomplete: Shell Completion Self-Generator for Python ======================================================= .. contents:: Table of Contents Description =========== This Python module aims at providing almost automatically shell completion for any Python program that already uses the ``optparse`` module. Motivation ---------- This module aims at placing the shell completion routine and the option parsing code in a single location: in the program itself. The logic is that since a program already knows about its options, and in Python we have a standard module to specify them programmatically since Python-2.3 (``optparse``), the program itself is in the best position to suggest completions for an incomplete command-line to a shell that invokes it. Traditionally, this has been done by writing shell-specific descriptions *separate* from the programs themselves, such as the `Bash Programmable Completion `_ project. This approach requires maintaining the shell completion functions up-to-date with the programs. During development of this proof-of-concept, we were interested in finding if the programs could not describe their completion routines themselves, using the well-specified completion protocol in bash. Similar completion routines could be easily written for other shells and we could extend this module to them. Documentation ============= ``optcomplete`` consists of a simple module `optcomplete.py `_ which you should install somewhere in your PYTHONPATH. To add simple support to a program which already uses ``optparse``, simply add the following code after the optparse declarations, *before* calling the ``parse_args()`` function on your options parser:: import optcomplete optcomplete.autocomplete(parser) Optionally, you can pass a completer as a second argument (see module code). You also need to `source a Bash function `_ and then to tell Bash to trigger optcomplete completion for the specific programs that use it:: complete -F _optcomplete More examples: - `Examples --- sample example output `_; - `A note about conditionals `_; - `Simple test program speaks for itself `_; - `Test program with subcommands `_; - `CHANGES `_ - `TODO `_ Download ======== - `Download `_ Copyright and License ===================== Copyright (C) 2001-2004 Martin Blais. All Rights Reserved. This code is distributed under the `BSD License `_. Author ====== Martin Blais