blob: 4a80848cd94188999fd98085e935091a65cc7387 [file] [log] [blame]
Jack Neusfc3b5772019-07-03 11:18:42 -06001// Copyright 2019 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4package git
5
6import (
7 "bytes"
8 "context"
9 "fmt"
Jack Neus0296c732019-07-17 09:35:01 -060010 "path/filepath"
Jack Neusfc3b5772019-07-03 11:18:42 -060011 "regexp"
12 "strings"
Jack Neus07511722019-07-12 15:41:10 -060013
14 "go.chromium.org/chromiumos/infra/go/internal/cmd"
Jack Neus1f489f62019-08-06 12:01:54 -060015 "go.chromium.org/chromiumos/infra/go/internal/test_util"
16 "go.chromium.org/luci/common/errors"
Jack Neusfc3b5772019-07-03 11:18:42 -060017)
18
19var (
Jack Neus07511722019-07-12 15:41:10 -060020 CommandRunnerImpl cmd.CommandRunner = cmd.RealCommandRunner{}
Jack Neusfc3b5772019-07-03 11:18:42 -060021)
22
Jack Neusfc3b5772019-07-03 11:18:42 -060023type CommandOutput struct {
24 Stdout string
25 Stderr string
26}
27
28// Struct representing a remote ref.
29type RemoteRef struct {
30 Remote string
31 Ref string
32}
33
34// RunGit the specified git command in the specified repo. It returns
35// stdout and stderr.
36func RunGit(gitRepo string, cmd []string) (CommandOutput, error) {
37 ctx := context.Background()
38 var stdoutBuf, stderrBuf bytes.Buffer
Jack Neus07511722019-07-12 15:41:10 -060039 err := CommandRunnerImpl.RunCommand(ctx, &stdoutBuf, &stderrBuf, gitRepo, "git", cmd...)
Jack Neusfc3b5772019-07-03 11:18:42 -060040 cmdOutput := CommandOutput{stdoutBuf.String(), stderrBuf.String()}
41 return cmdOutput, err
42}
43
Jack Neus2bcf4a62019-07-25 10:35:05 -060044// RunGitIgnore the specified git command in the specified repo and returns
45// only an error, not the command output.
46func RunGitIgnoreOutput(gitRepo string, cmd []string) error {
47 _, err := RunGit(gitRepo, cmd)
48 return err
49}
50
Jack Neusfc3b5772019-07-03 11:18:42 -060051// GetCurrentBranch returns current branch of a repo, and an empty string
52// if repo is on detached HEAD.
53func GetCurrentBranch(cwd string) string {
54 output, err := RunGit(cwd, []string{"symbolic-ref", "-q", "HEAD"})
55 if err != nil {
56 return ""
57 }
58 return StripRefsHead(strings.TrimSpace(output.Stdout))
59}
60
61// MatchBranchName returns the names of branches who match the specified
62// regular expression.
63func MatchBranchName(gitRepo string, pattern *regexp.Regexp) ([]string, error) {
Jack Neus10e6a122019-07-18 10:17:44 -060064 // MatchBranchWithNamespace trims the namespace off the branches it returns.
65 // Here, we need a namespace that matches every string but doesn't match any character
66 // (so that nothing is trimmed).
67 nullNamespace := regexp.MustCompile("")
68 return MatchBranchNameWithNamespace(gitRepo, pattern, nullNamespace)
69}
70
71// MatchBranchNameWithNamespace returns the names of branches who match the specified
72// pattern and start with the specified namespace.
73func MatchBranchNameWithNamespace(gitRepo string, pattern, namespace *regexp.Regexp) ([]string, error) {
Jack Neusfc3b5772019-07-03 11:18:42 -060074 // Regex should be case insensitive.
Jack Neus10e6a122019-07-18 10:17:44 -060075 namespace = regexp.MustCompile("(?i)^" + namespace.String())
76 pattern = regexp.MustCompile("(?i)" + pattern.String())
Jack Neusfc3b5772019-07-03 11:18:42 -060077
Jack Neus901a6bf2019-07-22 08:30:07 -060078 output, err := RunGit(gitRepo, []string{"show-ref"})
Jack Neusfc3b5772019-07-03 11:18:42 -060079 if err != nil {
Jack Neus901a6bf2019-07-22 08:30:07 -060080 if strings.Contains(err.Error(), "exit status 1") {
81 // Not a fatal error, just no branches.
82 return []string{}, nil
83 }
Jack Neusfc3b5772019-07-03 11:18:42 -060084 // Could not read branches.
Jack Neus901a6bf2019-07-22 08:30:07 -060085 return []string{}, fmt.Errorf("git error: %s\nstdout: %s stderr: %s", err.Error(), output.Stdout, output.Stderr)
Jack Neusfc3b5772019-07-03 11:18:42 -060086 }
87 // Find all branches that match the pattern.
88 branches := strings.Split(output.Stdout, "\n")
89 matchedBranches := []string{}
90 for _, branch := range branches {
91 branch = strings.TrimSpace(branch)
92 if branch == "" {
93 continue
94 }
95 branch = strings.Fields(branch)[1]
Jack Neus10e6a122019-07-18 10:17:44 -060096
97 // Only look at branches which match the namespace.
98 if !namespace.Match([]byte(branch)) {
99 continue
100 }
101 branch = namespace.ReplaceAllString(branch, "")
102
Jack Neusfc3b5772019-07-03 11:18:42 -0600103 if pattern.Match([]byte(branch)) {
104 matchedBranches = append(matchedBranches, branch)
105 }
106 }
107 return matchedBranches, nil
108}
109
110// GetGitRepoRevision finds and returns the revision of a branch.
Jack Neusa7287522019-07-23 16:36:18 -0600111func GetGitRepoRevision(cwd, branch string) (string, error) {
112 if branch == "" {
113 branch = "HEAD"
Jack Neus1f489f62019-08-06 12:01:54 -0600114 } else if branch != "HEAD" {
Jack Neus8b770832019-08-01 15:33:04 -0600115 branch = NormalizeRef(branch)
Jack Neusa7287522019-07-23 16:36:18 -0600116 }
117 output, err := RunGit(cwd, []string{"rev-parse", branch})
Jack Neus1f489f62019-08-06 12:01:54 -0600118 return strings.TrimSpace(output.Stdout), errors.Annotate(err, output.Stderr).Err()
Jack Neusfc3b5772019-07-03 11:18:42 -0600119}
120
Jack Neusa7287522019-07-23 16:36:18 -0600121// IsReachable determines whether one commit ref is reachable from another.
122func IsReachable(cwd, to_ref, from_ref string) (bool, error) {
123 _, err := RunGit(cwd, []string{"merge-base", "--is-ancestor", to_ref, from_ref})
124 if err != nil {
125 if strings.Contains(err.Error(), "exit status 1") {
126 return false, nil
127 }
128 return false, err
129 }
130 return true, nil
131}
132
Jack Neus7440c762019-07-22 10:45:18 -0600133// StripRefsHead removes leading 'refs/heads/' from a ref name.
Jack Neusfc3b5772019-07-03 11:18:42 -0600134func StripRefsHead(ref string) string {
135 return strings.TrimPrefix(ref, "refs/heads/")
136}
137
138// NormalizeRef converts git branch refs into fully qualified form.
139func NormalizeRef(ref string) string {
140 if ref == "" || strings.HasPrefix(ref, "refs/") {
141 return ref
142 }
143 return fmt.Sprintf("refs/heads/%s", ref)
144}
145
146// StripRefs removes leading 'refs/heads/', 'refs/remotes/[^/]+/' from a ref name.
147func StripRefs(ref string) string {
148 ref = StripRefsHead(ref)
149 // If the ref starts with ref/remotes/, then we want the part of the string
150 // that comes after the third "/".
151 // Example: refs/remotes/origin/master --> master
152 // Example: refs/remotse/origin/foo/bar --> foo/bar
153 if strings.HasPrefix(ref, "refs/remotes/") {
154 refParts := strings.SplitN(ref, "/", 4)
155 return refParts[len(refParts)-1]
156 }
157 return ref
158}
Jack Neusabdbe192019-07-15 12:23:22 -0600159
160// CreateBranch creates a branch.
161func CreateBranch(gitRepo, branch string) error {
Jack Neus0296c732019-07-17 09:35:01 -0600162 output, err := RunGit(gitRepo, []string{"checkout", "-B", branch})
Jack Neus10e6a122019-07-18 10:17:44 -0600163 if err != nil {
164 if strings.Contains(output.Stderr, "not a valid branch name") {
165 return fmt.Errorf("%s is not a valid branch name", branch)
166 } else {
167 return fmt.Errorf(output.Stderr)
168 }
Jack Neus0296c732019-07-17 09:35:01 -0600169 }
170 return err
171}
172
173// CreateTrackingBranch creates a tracking branch.
174func CreateTrackingBranch(gitRepo, branch string, remoteRef RemoteRef) error {
175 refspec := fmt.Sprintf("%s/%s", remoteRef.Remote, remoteRef.Ref)
176 output, err := RunGit(gitRepo, []string{"fetch", remoteRef.Remote, remoteRef.Ref})
177 if err != nil {
178 return fmt.Errorf("could not fetch %s: %s", refspec, output.Stderr)
179 }
180 output, err = RunGit(gitRepo, []string{"checkout", "-b", branch, "-t", refspec})
181 if err != nil {
182 if strings.Contains(output.Stderr, "not a valid branch name") {
183 return fmt.Errorf("%s is not a valid branch name", branch)
184 } else {
185 return fmt.Errorf(output.Stderr)
186 }
187 }
Jack Neusabdbe192019-07-15 12:23:22 -0600188 return err
189}
190
191// CommitAll adds all local changes and commits them.
Jack Neusf116fae2019-07-24 15:05:03 -0600192// Returns the sha1 of the commit.
193func CommitAll(gitRepo, commitMsg string) (string, error) {
Jack Neus0296c732019-07-17 09:35:01 -0600194 if output, err := RunGit(gitRepo, []string{"add", "-A"}); err != nil {
Jack Neusf116fae2019-07-24 15:05:03 -0600195 return "", fmt.Errorf(output.Stderr)
Jack Neusabdbe192019-07-15 12:23:22 -0600196 }
Jack Neus0296c732019-07-17 09:35:01 -0600197 if output, err := RunGit(gitRepo, []string{"commit", "-m", commitMsg}); err != nil {
198 if strings.Contains(output.Stdout, "nothing to commit") {
Jack Neusf116fae2019-07-24 15:05:03 -0600199 return "", fmt.Errorf(output.Stdout)
Jack Neus0296c732019-07-17 09:35:01 -0600200 } else {
Jack Neusf116fae2019-07-24 15:05:03 -0600201 return "", fmt.Errorf(output.Stderr)
Jack Neus0296c732019-07-17 09:35:01 -0600202 }
Jack Neusabdbe192019-07-15 12:23:22 -0600203 }
Jack Neusf116fae2019-07-24 15:05:03 -0600204 output, err := RunGit(gitRepo, []string{"rev-parse", "HEAD"})
205 if err != nil {
206 return "", err
207 }
208 return strings.TrimSpace(output.Stdout), nil
Jack Neusabdbe192019-07-15 12:23:22 -0600209}
210
Jack Neus7440c762019-07-22 10:45:18 -0600211// CommitEmpty makes an empty commit (assuming nothing is staged).
Jack Neusf116fae2019-07-24 15:05:03 -0600212// Returns the sha1 of the commit.
213func CommitEmpty(gitRepo, commitMsg string) (string, error) {
Jack Neus7440c762019-07-22 10:45:18 -0600214 if output, err := RunGit(gitRepo, []string{"commit", "-m", commitMsg, "--allow-empty"}); err != nil {
Jack Neusf116fae2019-07-24 15:05:03 -0600215 return "", fmt.Errorf(output.Stderr)
Jack Neus7440c762019-07-22 10:45:18 -0600216 }
Jack Neusf116fae2019-07-24 15:05:03 -0600217 output, err := RunGit(gitRepo, []string{"rev-parse", "HEAD"})
218 if err != nil {
219 return "", nil
220 }
221 return strings.TrimSpace(output.Stdout), nil
Jack Neus7440c762019-07-22 10:45:18 -0600222}
223
Jack Neusf116fae2019-07-24 15:05:03 -0600224// PushChanges stages and commits any local changes before pushing the commit
225// to the specified remote ref. Returns the sha1 of the commit.
226func PushChanges(gitRepo, localRef, commitMsg string, dryRun bool, pushTo RemoteRef) (string, error) {
227 commit, err := CommitAll(gitRepo, commitMsg)
Jack Neus0296c732019-07-17 09:35:01 -0600228 // It's ok if there's nothing to commit, we can still try to push.
229 if err != nil && !strings.Contains(err.Error(), "nothing to commit") {
Jack Neusf116fae2019-07-24 15:05:03 -0600230 return "", err
Jack Neusabdbe192019-07-15 12:23:22 -0600231 }
Jack Neusf116fae2019-07-24 15:05:03 -0600232 return commit, PushRef(gitRepo, localRef, dryRun, pushTo)
Jack Neus7440c762019-07-22 10:45:18 -0600233}
234
Jack Neuseb25f722019-07-19 16:33:20 -0600235// PushRef pushes the specified local ref to the specified remote ref.
236func PushRef(gitRepo, localRef string, dryRun bool, pushTo RemoteRef) error {
Jack Neusabdbe192019-07-15 12:23:22 -0600237 ref := fmt.Sprintf("%s:%s", localRef, pushTo.Ref)
238 cmd := []string{"push", pushTo.Remote, ref}
239 if dryRun {
240 cmd = append(cmd, "--dry-run")
241 }
Jack Neus7440c762019-07-22 10:45:18 -0600242 _, err := RunGit(gitRepo, cmd)
Jack Neus0296c732019-07-17 09:35:01 -0600243 return err
244}
245
246// Init initializes a repo.
247func Init(gitRepo string, bare bool) error {
248 cmd := []string{"init"}
249 if bare {
250 cmd = append(cmd, "--bare")
251 }
Jack Neusabdbe192019-07-15 12:23:22 -0600252 _, err := RunGit(gitRepo, cmd)
253 return err
254}
Jack Neus0296c732019-07-17 09:35:01 -0600255
256// AddRemote adds a remote.
257func AddRemote(gitRepo, remote, remoteLocation string) error {
258 output, err := RunGit(gitRepo, []string{"remote", "add", remote, remoteLocation})
259 if err != nil {
Jack Neuseb25f722019-07-19 16:33:20 -0600260 if strings.Contains(output.Stderr, "already exists") {
261 return fmt.Errorf("remote already exists")
262 }
Jack Neus0296c732019-07-17 09:35:01 -0600263 }
264 return err
265}
266
267// Checkout checkouts a branch.
268func Checkout(gitRepo, branch string) error {
269 output, err := RunGit(gitRepo, []string{"checkout", branch})
Jack Neus91de2402019-08-14 08:26:03 -0600270 if err != nil {
Jack Neus0296c732019-07-17 09:35:01 -0600271 return fmt.Errorf(output.Stderr)
272 }
273 return err
274}
275
276// DeleteBranch checks out to master and then deletes the current branch.
277func DeleteBranch(gitRepo, branch string, force bool) error {
278 cmd := []string{"branch"}
279 if force {
280 cmd = append(cmd, "-D")
281 } else {
282 cmd = append(cmd, "-d")
283 }
284 cmd = append(cmd, branch)
285 output, err := RunGit(gitRepo, cmd)
286
287 if err != nil {
288 if strings.Contains(output.Stderr, "checked out at") {
289 return fmt.Errorf(output.Stderr)
290 }
291 if strings.Contains(output.Stderr, "not fully merged") {
292 return fmt.Errorf("branch %s is not fully merged. use the force parameter if you wish to proceed", branch)
293 }
294 }
295 return err
296}
297
298// Clone clones the remote into the specified dir.
299func Clone(remote, dir string) error {
300 output, err := RunGit(filepath.Dir(dir), []string{"clone", remote, filepath.Base(dir)})
301 if err != nil {
302 return fmt.Errorf(output.Stderr)
303 }
304 return nil
305}
Jack Neus1f489f62019-08-06 12:01:54 -0600306
307// RemoteBranches returns a list of branches on the specified remote.
308func RemoteBranches(gitRepo, remote string) ([]string, error) {
309 output, err := RunGit(gitRepo, []string{"ls-remote", remote})
310 if err != nil {
311 if strings.Contains(output.Stderr, "not appear to be a git repository") {
312 return []string{}, fmt.Errorf("%s is not a valid remote", remote)
313 }
314 return []string{}, err
315 }
316 remotes := []string{}
317 for _, line := range strings.Split(strings.TrimSpace(output.Stdout), "\n") {
318 if line == "" {
319 continue
320 }
321 remotes = append(remotes, StripRefs(strings.Fields(line)[1]))
322 }
323 return remotes, nil
324}
325
326// RemoteHasBranch checks whether or not a branch exists on a remote.
327func RemoteHasBranch(gitRepo, remote, branch string) (bool, error) {
328 branches, err := RemoteBranches(gitRepo, remote)
329 if err != nil {
330 return false, err
331 }
332 branch = StripRefs(branch)
333 for _, remoteBranch := range branches {
334 if branch == remoteBranch {
335 return true, nil
336 }
337 }
338 return false, nil
339}
340
341// AssertGitBranches asserts that the git repo has the given branches (it may have others, too).
342func AssertGitBranches(gitRepo string, branches []string) error {
343 actual, err := MatchBranchNameWithNamespace(gitRepo, regexp.MustCompile(".*"), regexp.MustCompile("refs/heads/"))
344 if err != nil {
345 return errors.Annotate(err, "error getting branches").Err()
346 }
347 if !test_util.UnorderedContains(actual, branches) {
348 return fmt.Errorf("project branch mismatch. expected: %v got %v", branches, actual)
349 }
350 return nil
351}
352
353// AssertGitBranches asserts that the git repo has only the correct branches.
354func AssertGitBranchesExact(gitRepo string, branches []string) error {
355 actual, err := MatchBranchNameWithNamespace(gitRepo, regexp.MustCompile(".*"), regexp.MustCompile("refs/heads/"))
356 if err != nil {
357 return errors.Annotate(err, "error getting branches").Err()
358 }
359 // Remove duplicates from branches. This is OK because branch names are unique identifiers
360 // and so having a branch name twice in branches doesn't mean anything special.
361 branchMap := make(map[string]bool)
362 for _, branch := range branches {
363 branchMap[branch] = true
364 }
365 branches = []string{}
366 for branch := range branchMap {
367 branches = append(branches, branch)
368 }
369 if !test_util.UnorderedEqual(actual, branches) {
370 return fmt.Errorf("project branch mismatch. expected: %v got %v", branches, actual)
371 }
372 return nil
373}