-
Notifications
You must be signed in to change notification settings - Fork 199
/
show_ref.go
70 lines (58 loc) · 1.52 KB
/
show_ref.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package true_git
import (
"context"
"fmt"
"strings"
)
type RefDescriptor struct {
Commit string
FullName string
IsHEAD bool
IsTag bool
TagName string
IsBranch bool
BranchName string
IsRemote bool
RemoteName string
}
type ShowRefResult struct {
Refs []RefDescriptor
}
func ShowRef(ctx context.Context, repoDir string) (*ShowRefResult, error) {
headRefCmd := NewGitCmd(ctx, &GitCmdOptions{RepoDir: repoDir}, "show-ref", "--head")
if err := headRefCmd.Run(ctx); err != nil {
return nil, fmt.Errorf("git get refs from HEAD command failed: %w", err)
}
res := &ShowRefResult{}
outputLines := strings.Split(headRefCmd.OutBuf.String(), "\n")
for _, line := range outputLines {
parts := strings.SplitN(line, " ", 2)
if len(parts) != 2 {
continue
}
ref := RefDescriptor{
Commit: parts[0],
FullName: parts[1],
}
switch {
case ref.FullName == "HEAD":
ref.IsHEAD = true
case strings.HasPrefix(ref.FullName, "refs/tags/"):
ref.IsTag = true
ref.TagName = strings.TrimPrefix(ref.FullName, "refs/tags/")
case strings.HasPrefix(ref.FullName, "refs/heads/"):
ref.IsBranch = true
ref.BranchName = strings.TrimPrefix(ref.FullName, "refs/heads/")
case strings.HasPrefix(ref.FullName, "refs/remotes/"):
ref.IsBranch = true
ref.IsRemote = true
parts := strings.SplitN(strings.TrimPrefix(ref.FullName, "refs/remotes/"), "/", 2)
if len(parts) != 2 {
continue
}
ref.RemoteName, ref.BranchName = parts[0], parts[1]
}
res.Refs = append(res.Refs, ref)
}
return res, nil
}