1
0
Fork 0
mirror of https://github.com/ytdl-org/youtube-dl.git synced 2024-06-10 05:49:37 +00:00
youtube-dl/devscripts/zsh-completion.py

65 lines
2.1 KiB
Python
Raw Normal View History

2014-10-06 10:58:25 +00:00
#!/usr/bin/env python
from __future__ import unicode_literals
2014-10-06 10:58:25 +00:00
import os
from os.path import dirname as dirn
import sys
2021-03-05 23:06:35 +00:00
import optparse
2014-10-06 10:58:25 +00:00
sys.path.insert(0, dirn(dirn((os.path.abspath(__file__)))))
2014-10-06 10:58:25 +00:00
import youtube_dl
ZSH_COMPLETION_FILE = "youtube-dl.zsh"
ZSH_COMPLETION_TEMPLATE = "devscripts/zsh-completion.in"
def build_completion(opt_parser):
opts = [opt for group in opt_parser.option_groups
for opt in group.option_list]
2021-03-05 23:06:35 +00:00
# escaping is hard:
# - help may contain colons
# - metavar must have colons : escaped
# - single quotes must be removed
# - help must have square brackets [] escaped
def metaparse(opt):
if "--recode-video" == opt.get_opt_string():
return ":{}:(mp4 flv ogg webm mkv)".format(opt.metavar)
if opt.metavar is None:
return ""
if opt.metavar == "FILE":
return ":FILE:_files"
if opt.metavar == "DIR":
return ":DIR:_directories"
else:
return ":{}:".format(opt.metavar.replace(":", "\\:"))
def helpescape(opthelp):
if opthelp == optparse.SUPPRESS_HELP:
return ""
return "[{}]".format(opthelp.replace("'", "\"").replace("]", "\\]").replace("[", "\\["))
2014-10-06 10:58:25 +00:00
2021-03-05 23:06:35 +00:00
def optionexclude(opt):
# When an argument has a long and short version, the arguments entry shall be
# _arguments \
# "(-t --thing)"{-t,--thing}"[do things]:WHAT_THING:"
# i.e. in parentheses with space the explanation of redundancy and in curly braces
# regular shell expansion to create two mostly identical entries.
2014-10-06 10:58:25 +00:00
if opt._short_opts:
2021-03-05 23:06:35 +00:00
return "({0} {1})'{{{0},{1}}}'".format(opt._short_opts[0], opt.get_opt_string())
return "{}".format(opt.get_opt_string())
2014-10-06 10:58:25 +00:00
2021-03-05 23:06:35 +00:00
mytest = ["'{}{}{}'".format(optionexclude(opt), helpescape(opt.help), metaparse(opt)) for opt in opts]
2014-10-06 10:58:25 +00:00
with open(ZSH_COMPLETION_TEMPLATE) as f:
template = f.read()
2021-03-05 23:06:35 +00:00
template = template.replace("{{args}}", " \\\n ".join(mytest))
2014-10-06 10:58:25 +00:00
with open(ZSH_COMPLETION_FILE, "w") as f:
f.write(template)
2014-10-06 10:58:25 +00:00
parser = youtube_dl.parseOpts()[0]
build_completion(parser)