-
Notifications
You must be signed in to change notification settings - Fork 394
/
detectgit.go
270 lines (252 loc) · 7.33 KB
/
detectgit.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package buildcontext
import (
"context"
"fmt"
"os/exec"
"path"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/vladaionescu/earthly/domain"
)
var (
// ErrNoGitBinary is an error returned when no git binary is found.
ErrNoGitBinary = errors.New("No git binary found")
// ErrNotAGitDir is an error returned when a given directory is not a git dir.
ErrNotAGitDir = errors.New("Not a git directory")
// ErrCouldNotDetectRemote is an error returned when git remote could not be detected or parsed.
ErrCouldNotDetectRemote = errors.New("Could not auto-detect or parse Git remote URL")
)
// GitMetadata is a collection of git information about a certain directory.
type GitMetadata struct {
BaseDir string
RelDir string
RemoteURL string
GitVendor string
GitProject string
Hash string
Branch []string
Tags []string
}
// Metadata performs git metadata detection on the provided directory.
func Metadata(ctx context.Context, dir string) (*GitMetadata, error) {
err := detectGitBinary(ctx)
if err != nil {
return nil, err
}
err = detectIsGitDir(ctx, dir)
if err != nil {
return nil, err
}
baseDir, err := detectGitBaseDir(ctx, dir)
if err != nil {
return nil, err
}
remoteURL, err := detectGitRemoteURL(ctx, dir)
if err != nil {
return nil, err
}
var vendor, project string
if remoteURL != "" {
vendor, project, err = parseGitRemoteURL(remoteURL)
if err != nil {
return nil, err
}
}
hash, err := detectGitHash(ctx, dir)
if err != nil {
return nil, err
}
branch, err := detectGitBranch(ctx, dir)
if err != nil {
return nil, err
}
tags, err := detectGitTags(ctx, dir)
if err != nil {
// Most likely no tags. Keep going.
tags = nil
}
relDir, isRel, err := gitRelDir(baseDir, dir)
if err != nil {
return nil, errors.Wrapf(err, "get rel dir for %s when base git path is %s", dir, baseDir)
}
if !isRel {
return nil, errors.New("Unexpected non-relative path within git dir")
}
return &GitMetadata{
BaseDir: filepath.ToSlash(baseDir),
RelDir: filepath.ToSlash(relDir),
GitVendor: vendor,
GitProject: project,
Hash: hash,
Branch: branch,
Tags: tags,
}, nil
}
// Clone returns a copy of the GitMetadata object.
func (gm *GitMetadata) Clone() *GitMetadata {
return &GitMetadata{
BaseDir: gm.BaseDir,
RelDir: gm.RelDir,
GitVendor: gm.GitVendor,
GitProject: gm.GitProject,
Hash: gm.Hash,
Branch: gm.Branch,
Tags: gm.Tags,
}
}
func detectGitBinary(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "/bin/sh", "-c", "which git")
_, err := cmd.Output()
if err != nil {
return ErrNoGitBinary
}
return nil
}
func detectIsGitDir(ctx context.Context, dir string) error {
cmd := exec.CommandContext(ctx, "git", "status")
cmd.Dir = dir
_, err := cmd.Output()
if err != nil {
return ErrNotAGitDir
}
return nil
}
func parseGitRemoteURL(url string) (string, string, error) {
// TODO: Should use a more robust method for origin URL parsing.
if strings.HasPrefix(url, "git@github.com:") {
ret := strings.TrimPrefix(url, "git@github.com:")
ret = strings.TrimSuffix(ret, ".git")
return "github.com", ret, nil
} else if strings.HasPrefix(url, "ssh://git@github.com/") {
ret := strings.TrimPrefix(url, "ssh://git@github.com/")
ret = strings.TrimSuffix(ret, ".git")
return "github.com", ret, nil
} else if strings.HasPrefix(url, "ssh://git@github.com:") {
ret := strings.TrimPrefix(url, "ssh://git@github.com:")
ret = strings.TrimSuffix(ret, ".git")
return "github.com", ret, nil
} else if strings.HasPrefix(url, "https://") {
ret := strings.TrimPrefix(url, "https://")
ret = strings.TrimSuffix(ret, ".git")
parts := strings.SplitN(ret, "/", 2)
if len(parts) < 2 {
return "", "", errors.Wrapf(ErrCouldNotDetectRemote, "could not parse git URL %s", url)
}
return parts[0], parts[1], nil
} else {
return "", "", errors.Wrapf(
ErrCouldNotDetectRemote, "could not parse git URL %s. Maybe not github.com?", url)
}
}
func detectGitRemoteURL(ctx context.Context, dir string) (string, error) {
cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
return "", errors.Wrapf(
ErrCouldNotDetectRemote, "returned error %s: %s", err.Error(), string(out))
}
outStr := string(out)
if outStr == "" {
return "", errors.Wrapf(ErrCouldNotDetectRemote, "no remote origin url output")
}
return strings.SplitN(outStr, "\n", 2)[0], nil
}
func detectGitBaseDir(ctx context.Context, dir string) (string, error) {
cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
return "", errors.Wrap(err, "detect git directory")
}
outStr := string(out)
if outStr == "" {
return "", errors.New("No output returned for git base dir")
}
return strings.SplitN(outStr, "\n", 2)[0], nil
}
func detectGitHash(ctx context.Context, dir string) (string, error) {
cmd := exec.CommandContext(ctx, "git", "rev-parse", "HEAD")
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
return "", errors.Wrap(err, "detect git hash")
}
outStr := string(out)
if outStr == "" {
return "", errors.New("No output returned for git hash")
}
return strings.SplitN(outStr, "\n", 2)[0], nil
}
func detectGitBranch(ctx context.Context, dir string) ([]string, error) {
cmd := exec.CommandContext(ctx, "git", "rev-parse", "--abbrev-ref", "HEAD")
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
return nil, errors.Wrap(err, "detect git current branch")
}
outStr := string(out)
if outStr != "" {
return strings.Split(outStr, "\n"), nil
}
return nil, nil
}
func detectGitTags(ctx context.Context, dir string) ([]string, error) {
cmd := exec.CommandContext(ctx, "git", "describe", "--exact-match", "--tags")
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
return nil, errors.Wrap(err, "detect git current tags")
}
outStr := string(out)
if outStr != "" {
return strings.Split(outStr, "\n"), nil
}
return nil, nil
}
func gitRelDir(basePath string, path string) (string, bool, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return "", false, errors.Wrapf(err, "get abs path for %s", path)
}
if !filepath.IsAbs(basePath) {
return "", false, fmt.Errorf("Git base path %s is not absolute", basePath)
}
basePathSlash := filepath.ToSlash(basePath)
pathSlash := filepath.ToSlash(absPath)
basePathParts := strings.Split(basePathSlash, "/")
pathParts := strings.Split(pathSlash, "/")
if len(pathParts) < len(basePathParts) {
return "", false, nil
}
for index := range basePathParts {
if basePathParts[index] != pathParts[index] {
return "", false, nil
}
}
relPath := strings.Join(pathParts[len(basePathParts):], "/")
if relPath == "" {
return ".", true, nil
}
return filepath.FromSlash(relPath), true, nil
}
// TargetWithGitMeta applies git metadata to the target naming.
func TargetWithGitMeta(target domain.Target, gitMeta *GitMetadata) domain.Target {
if gitMeta == nil {
return target
}
targetRet := target
targetRet.Registry = gitMeta.GitVendor
targetRet.ProjectPath = path.Join(gitMeta.GitProject, gitMeta.RelDir)
if targetRet.Tag == "" {
if len(gitMeta.Tags) > 0 {
targetRet.Tag = gitMeta.Tags[0]
} else if len(gitMeta.Branch) > 0 {
targetRet.Tag = gitMeta.Branch[0]
} else {
targetRet.Tag = gitMeta.Hash
}
}
return targetRet
}