zsh-completion.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python3
  2. # Allow direct execution
  3. import os
  4. import sys
  5. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  6. import yt_dlp
  7. ZSH_COMPLETION_FILE = 'completions/zsh/_yt-dlp'
  8. ZSH_COMPLETION_TEMPLATE = 'devscripts/zsh-completion.in'
  9. def build_completion(opt_parser):
  10. opts = [opt for group in opt_parser.option_groups
  11. for opt in group.option_list]
  12. opts_file = [opt for opt in opts if opt.metavar == 'FILE']
  13. opts_dir = [opt for opt in opts if opt.metavar == 'DIR']
  14. fileopts = []
  15. for opt in opts_file:
  16. if opt._short_opts:
  17. fileopts.extend(opt._short_opts)
  18. if opt._long_opts:
  19. fileopts.extend(opt._long_opts)
  20. diropts = []
  21. for opt in opts_dir:
  22. if opt._short_opts:
  23. diropts.extend(opt._short_opts)
  24. if opt._long_opts:
  25. diropts.extend(opt._long_opts)
  26. flags = [opt.get_opt_string() for opt in opts]
  27. with open(ZSH_COMPLETION_TEMPLATE) as f:
  28. template = f.read()
  29. template = template.replace('{{fileopts}}', '|'.join(fileopts))
  30. template = template.replace('{{diropts}}', '|'.join(diropts))
  31. template = template.replace('{{flags}}', ' '.join(flags))
  32. with open(ZSH_COMPLETION_FILE, 'w') as f:
  33. f.write(template)
  34. parser = yt_dlp.parseOpts(ignore_config_files=True)[0]
  35. build_completion(parser)