|
| 1 | +package git |
| 2 | + |
| 3 | +import ( |
| 4 | + "path/filepath" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/rsteube/carapace" |
| 8 | +) |
| 9 | + |
| 10 | +type LsRemoteRefOption struct { |
| 11 | + Branches bool |
| 12 | + Tags bool |
| 13 | +} |
| 14 | + |
| 15 | +// ActionLsRemoteRefs lists branches and tags for a remote url |
| 16 | +// gh-pages (da4528d0a57ad71417336f0e96fa65ece2fad45a) |
| 17 | +// master (3fbdef3c6a10094812a15cba8e825898b757dfb3) |
| 18 | +func ActionLsRemoteRefs(url string, opts LsRemoteRefOption) carapace.Action { |
| 19 | + return carapace.ActionExecCommand("git", "ls-remote", "--refs", "--tags", "--heads", url)(func(output []byte) carapace.Action { |
| 20 | + lines := strings.Split(string(output), "\n") |
| 21 | + |
| 22 | + vals := make([]string, 0) |
| 23 | + for _, line := range lines[:len(lines)-1] { |
| 24 | + fields := strings.Fields(line) |
| 25 | + if opts.Branches && strings.HasPrefix(fields[1], "refs/heads/") { |
| 26 | + vals = append(vals, strings.TrimPrefix(fields[1], "refs/heads/"), fields[0]) |
| 27 | + } else if opts.Tags && strings.HasPrefix(fields[1], "refs/tags/") { |
| 28 | + vals = append(vals, strings.TrimPrefix(fields[1], "refs/tags/"), fields[0]) |
| 29 | + } |
| 30 | + } |
| 31 | + return carapace.ActionValuesDescribed(vals...) |
| 32 | + }) |
| 33 | +} |
| 34 | + |
| 35 | +// ActionRefFiles lists files of a reference |
| 36 | +// go.mod |
| 37 | +// pkg/ |
| 38 | +func ActionRefFiles(ref string) carapace.Action { |
| 39 | + return carapace.ActionCallback(func(c carapace.Context) carapace.Action { |
| 40 | + args := []string{"ls-tree", "--name-only", "--full-tree", ref} |
| 41 | + if dir := filepath.Dir(c.CallbackValue); dir != "." { |
| 42 | + args = append(args, dir+"/") |
| 43 | + } |
| 44 | + return carapace.ActionExecCommand("git", args...)(func(output []byte) carapace.Action { |
| 45 | + lines := strings.Split(string(output), "\n") |
| 46 | + files := lines[:len(lines)-1] |
| 47 | + |
| 48 | + args = append(args, "-d") // only directories |
| 49 | + return carapace.ActionExecCommand("git", args...)(func(output []byte) carapace.Action { |
| 50 | + lines := strings.Split(string(output), "\n") |
| 51 | + directories := lines[:len(lines)-1] |
| 52 | + |
| 53 | + filesA := carapace.ActionValues(files...).Invoke(c).Filter(directories) |
| 54 | + |
| 55 | + for index, dir := range directories { |
| 56 | + directories[index] = dir + "/" |
| 57 | + } |
| 58 | + directoriesA := carapace.ActionValues(directories...).Invoke(c) |
| 59 | + |
| 60 | + return filesA.Merge(directoriesA).ToA() |
| 61 | + }) |
| 62 | + }) |
| 63 | + }) |
| 64 | +} |
0 commit comments