Add a completion script generator for the fish shell
[ytdl] / devscripts / fish-completion.py
1 #!/usr/bin/env python
2 from __future__ import unicode_literals
3
4 import optparse
5 import os
6 from os.path import dirname as dirn
7 import sys
8
9 sys.path.append(dirn(dirn((os.path.abspath(__file__)))))
10 import youtube_dl
11 from youtube_dl.utils import shell_quote
12
13 FISH_COMPLETION_FILE = 'youtube-dl.fish'
14 FISH_COMPLETION_TEMPLATE = 'devscripts/fish-completion.in'
15
16 EXTRA_ARGS = {
17     'recode-video': ['--arguments', 'mp4 flv ogg webm mkv', '--exclusive'],
18
19     # Options that need a file parameter
20     'download-archive': ['--require-parameter'],
21     'cookies': ['--require-parameter'],
22     'load-info': ['--require-parameter'],
23     'batch-file': ['--require-parameter'],
24 }
25
26 def build_completion(opt_parser):
27     commands = []
28
29     for group in opt_parser.option_groups:
30         for option in group.option_list:
31             long_option = option.get_opt_string().strip('-')
32             help_msg = shell_quote([option.help])
33             complete_cmd = ['complete', '--command', 'youtube-dl', '--long-option', long_option]
34             if option._short_opts:
35                 complete_cmd += ['--short-option', option._short_opts[0].strip('-')]
36             if option.help != optparse.SUPPRESS_HELP:
37                 complete_cmd += ['--description', option.help]
38             complete_cmd.extend(EXTRA_ARGS.get(long_option, []))
39             commands.append(shell_quote(complete_cmd))
40
41     with open(FISH_COMPLETION_TEMPLATE) as f:
42         template = f.read()
43     filled_template = template.replace('{{commands}}', '\n'.join(commands))
44     with open(FISH_COMPLETION_FILE, 'w') as f:
45         f.write(filled_template)
46
47 parser = youtube_dl.parseOpts()[0]
48 build_completion(parser)