comp.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package cobra
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. _ "embed"
  6. "fmt"
  7. "io"
  8. )
  9. //go:generate go run gen.go
  10. //go:embed comp.bash.gz
  11. var compBash string
  12. func ScriptBash(w io.Writer, name, compCmd, nameForVar string) error {
  13. return fmtgz(
  14. w, compBash,
  15. name, compCmd,
  16. ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
  17. ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
  18. )
  19. }
  20. //go:embed comp.zsh.gz
  21. var compZsh string
  22. func ScriptZsh(w io.Writer, name, compCmd, nameForVar string) error {
  23. return fmtgz(
  24. w, compZsh,
  25. name, compCmd,
  26. ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
  27. ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
  28. )
  29. }
  30. //go:embed comp.fish.gz
  31. var compFish string
  32. func ScriptFish(w io.Writer, name, compCmd, nameForVar string) error {
  33. return fmtgz(
  34. w, compFish,
  35. nameForVar, name, compCmd,
  36. ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
  37. ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
  38. )
  39. }
  40. //go:embed comp.ps1.gz
  41. var compPowershell string
  42. func ScriptPowershell(w io.Writer, name, compCmd, nameForVar string) error {
  43. return fmtgz(
  44. w, compPowershell,
  45. name, nameForVar, compCmd,
  46. ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
  47. ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
  48. )
  49. }
  50. func fmtgz(w io.Writer, formatgz string, args ...any) error {
  51. f, err := gzip.NewReader(bytes.NewBufferString(formatgz))
  52. if err != nil {
  53. return fmt.Errorf("decompressing script: %w", err)
  54. }
  55. format, err := io.ReadAll(f)
  56. if err != nil {
  57. return fmt.Errorf("decompressing script: %w", err)
  58. }
  59. _, err = fmt.Fprintf(w, string(format), args...)
  60. return err
  61. }