(cmd *cobra.Command, exportTarget *Exporter, fields []string)
| 52 | } |
| 53 | |
| 54 | func setupJsonFlags(cmd *cobra.Command, exportTarget *Exporter, fields []string) { |
| 55 | |
| 56 | _ = cmd.RegisterFlagCompletionFunc("json", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { |
| 57 | var results []string |
| 58 | var prefix string |
| 59 | if idx := strings.LastIndexByte(toComplete, ','); idx >= 0 { |
| 60 | prefix = toComplete[:idx+1] |
| 61 | toComplete = toComplete[idx+1:] |
| 62 | } |
| 63 | toComplete = strings.ToLower(toComplete) |
| 64 | for _, f := range fields { |
| 65 | if strings.HasPrefix(strings.ToLower(f), toComplete) { |
| 66 | results = append(results, prefix+f) |
| 67 | } |
| 68 | } |
| 69 | sort.Strings(results) |
| 70 | return results, cobra.ShellCompDirectiveNoSpace |
| 71 | }) |
| 72 | |
| 73 | oldPreRun := cmd.PreRunE |
| 74 | cmd.PreRunE = func(c *cobra.Command, args []string) error { |
| 75 | if oldPreRun != nil { |
| 76 | if err := oldPreRun(c, args); err != nil { |
| 77 | return err |
| 78 | } |
| 79 | } |
| 80 | if export, err := checkJSONFlags(c); err == nil { |
| 81 | if export == nil { |
| 82 | *exportTarget = nil |
| 83 | } else { |
| 84 | allowedFields := set.NewStringSet() |
| 85 | allowedFields.AddValues(fields) |
| 86 | for _, f := range export.fields { |
| 87 | if !allowedFields.Contains(f) { |
| 88 | sort.Strings(fields) |
| 89 | return JSONFlagError{fmt.Errorf("Unknown JSON field: %q\nAvailable fields:\n %s", f, strings.Join(fields, "\n "))} |
| 90 | } |
| 91 | } |
| 92 | *exportTarget = export |
| 93 | } |
| 94 | } else { |
| 95 | return err |
| 96 | } |
| 97 | return nil |
| 98 | } |
| 99 | |
| 100 | cmd.SetFlagErrorFunc(func(c *cobra.Command, e error) error { |
| 101 | if c == cmd && e.Error() == "flag needs an argument: --json" { |
| 102 | sort.Strings(fields) |
| 103 | return JSONFlagError{fmt.Errorf("Specify one or more comma-separated fields for `--json`:\n %s", strings.Join(fields, "\n "))} |
| 104 | } |
| 105 | if cmd.HasParent() { |
| 106 | return cmd.Parent().FlagErrorFunc()(c, e) |
| 107 | } |
| 108 | return e |
| 109 | }) |
| 110 | |
| 111 | if len(fields) == 0 { |
no test coverage detected