File: customcomplete.py

package info (click to toggle)
python-shtab 1.7.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 256 kB
  • sloc: python: 1,002; makefile: 6; sh: 4
file content (64 lines) | stat: -rwxr-xr-x 2,174 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
"""
`argparse`-based CLI app with custom file completion as well as subparsers.

See `pathcomplete.py` for a more basic version.
"""
import argparse

import shtab  # for completion magic

TXT_FILE = {
    "bash": "_shtab_greeter_compgen_TXTFiles", "zsh": "_files -g '(*.txt|*.TXT)'",
    "tcsh": "f:*.txt"}
PREAMBLE = {
    "bash": """
# $1=COMP_WORDS[1]
_shtab_greeter_compgen_TXTFiles() {
  compgen -d -- $1  # recurse into subdirs
  compgen -f -X '!*?.txt' -- $1
  compgen -f -X '!*?.TXT' -- $1
}
""", "zsh": "", "tcsh": ""}


def process(args):
    print(
        "received <input_txt>=%r [<suffix>=%r] --input-file=%r --output-name=%r --hidden-opt=%r" %
        (args.input_txt, args.suffix, args.input_file, args.output_name, args.hidden_opt))


def get_main_parser():
    main_parser = argparse.ArgumentParser(prog="customcomplete")
    subparsers = main_parser.add_subparsers()
    # make required (py3.7 API change); vis. https://bugs.python.org/issue16308
    subparsers.required = True
    subparsers.dest = "subcommand"

    parser = subparsers.add_parser("completion", help="print tab completion")
    shtab.add_argument_to(parser, "shell", parent=main_parser, preamble=PREAMBLE) # magic!

    parser = subparsers.add_parser("process", help="parse files")
    # `*.txt` file tab completion
    parser.add_argument("input_txt", nargs='?').complete = TXT_FILE
    # file tab completion builtin shortcut
    parser.add_argument("-i", "--input-file").complete = shtab.FILE
    parser.add_argument(
        "-o",
        "--output-name",
        help=("output file name. Completes directory names to avoid users"
              " accidentally overwriting existing files."),
    ).complete = shtab.DIRECTORY
    # directory tab completion builtin shortcut

    parser.add_argument("suffix", choices=['json', 'csv'], default='json', nargs='?',
                        help="Output format")
    parser.add_argument("--hidden-opt", action='store_true', help=argparse.SUPPRESS)
    parser.set_defaults(func=process)
    return main_parser


if __name__ == "__main__":
    parser = get_main_parser()
    args = parser.parse_args()
    args.func(args)