File: make_bash_completion.py

package info (click to toggle)
nghttp2 1.64.0-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,844 kB
  • sloc: cpp: 55,820; ansic: 52,049; python: 2,927; makefile: 1,371; sh: 200; ruby: 66; lisp: 2
file content (75 lines) | stat: -rwxr-xr-x 1,801 bytes parent folder | download | duplicates (2)
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
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess
import io
import re
import sys
import os.path

class Option:
    def __init__(self, long_opt, short_opt):
        self.long_opt = long_opt
        self.short_opt = short_opt

def get_all_options(cmd):
    opt_pattern = re.compile(r'  (?:(-.), )?(--[^\s\[=]+)(\[)?')
    proc = subprocess.Popen([cmd, "--help"], stdout=subprocess.PIPE)
    stdoutdata, _ = proc.communicate()
    cur_option = None
    opts = {}
    for line in io.StringIO(stdoutdata.decode('utf-8')):
        match = opt_pattern.match(line)
        if not match:
            continue
        long_opt = match.group(2)
        short_opt = match.group(1)
        opts[long_opt] = Option(long_opt, short_opt)

    return opts

def output_case(out, name, opts):
    out.write('''\
_{name}()
{{
    local cur prev split=false
    COMPREPLY=()
    COMP_WORDBREAKS=${{COMP_WORDBREAKS//=}}

    cmd=${{COMP_WORDS[0]}}
    _get_comp_words_by_ref cur prev
'''.format(name=name))

    # Complete option name.
    out.write('''\
    case $cur in
        -*)
            COMPREPLY=( $( compgen -W '\
''')
    for opt in opts.values():
        out.write(opt.long_opt)
        out.write(' ')

    out.write('''\
' -- "$cur" ) )
            ;;
''')
    # If no option found for completion then complete with files.
    out.write('''\
        *)
            _filedir
            return 0
    esac
    return 0
}}
complete -F _{name} {name}
'''.format(name=name))

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Generates bash_completion using `/path/to/cmd --help'")
        print("Usage: make_bash_completion.py /path/to/cmd")
        exit(1)
    name = os.path.basename(sys.argv[1])
    opts = get_all_options(sys.argv[1])
    output_case(sys.stdout, name, opts)