blob: 7395ca8aa78067a834415a9cb0460e4af7d7dcf6 [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 Neusfc3b5772019-07-03 11:18:42 -060015)
16
17var (
Jack Neus07511722019-07-12 15:41:10 -060018 CommandRunnerImpl cmd.CommandRunner = cmd.RealCommandRunner{}
Jack Neusfc3b5772019-07-03 11:18:42 -060019)
20
Jack Neusfc3b5772019-07-03 11:18:42 -060021type CommandOutput struct {
22 Stdout string
23 Stderr string
24}
25
26// Struct representing a remote ref.
27type RemoteRef struct {
28 Remote string
29 Ref string
30}
31
32// RunGit the specified git command in the specified repo. It returns
33// stdout and stderr.
34func RunGit(gitRepo string, cmd []string) (CommandOutput, error) {
35 ctx := context.Background()
36 var stdoutBuf, stderrBuf bytes.Buffer
Jack Neus07511722019-07-12 15:41:10 -060037 err := CommandRunnerImpl.RunCommand(ctx, &stdoutBuf, &stderrBuf, gitRepo, "git", cmd...)
Jack Neusfc3b5772019-07-03 11:18:42 -060038 cmdOutput := CommandOutput{stdoutBuf.String(), stderrBuf.String()}
39 return cmdOutput, err
40}
41
42// GetCurrentBranch returns current branch of a repo, and an empty string
43// if repo is on detached HEAD.
44func GetCurrentBranch(cwd string) string {
45 output, err := RunGit(cwd, []string{"symbolic-ref", "-q", "HEAD"})
46 if err != nil {
47 return ""
48 }
49 return StripRefsHead(strings.TrimSpace(output.Stdout))
50}
51
52// MatchBranchName returns the names of branches who match the specified
53// regular expression.
54func MatchBranchName(gitRepo string, pattern *regexp.Regexp) ([]string, error) {
Jack Neus10e6a122019-07-18 10:17:44 -060055 // MatchBranchWithNamespace trims the namespace off the branches it returns.
56 // Here, we need a namespace that matches every string but doesn't match any character
57 // (so that nothing is trimmed).
58 nullNamespace := regexp.MustCompile("")
59 return MatchBranchNameWithNamespace(gitRepo, pattern, nullNamespace)
60}
61
62// MatchBranchNameWithNamespace returns the names of branches who match the specified
63// pattern and start with the specified namespace.
64func MatchBranchNameWithNamespace(gitRepo string, pattern, namespace *regexp.Regexp) ([]string, error) {
Jack Neusfc3b5772019-07-03 11:18:42 -060065 // Regex should be case insensitive.
Jack Neus10e6a122019-07-18 10:17:44 -060066 namespace = regexp.MustCompile("(?i)^" + namespace.String())
67 pattern = regexp.MustCompile("(?i)" + pattern.String())
Jack Neusfc3b5772019-07-03 11:18:42 -060068
Jack Neus901a6bf2019-07-22 08:30:07 -060069 output, err := RunGit(gitRepo, []string{"show-ref"})
Jack Neusfc3b5772019-07-03 11:18:42 -060070 if err != nil {
Jack Neus901a6bf2019-07-22 08:30:07 -060071 if strings.Contains(err.Error(), "exit status 1") {
72 // Not a fatal error, just no branches.
73 return []string{}, nil
74 }
Jack Neusfc3b5772019-07-03 11:18:42 -060075 // Could not read branches.
Jack Neus901a6bf2019-07-22 08:30:07 -060076 return []string{}, fmt.Errorf("git error: %s\nstdout: %s stderr: %s", err.Error(), output.Stdout, output.Stderr)
Jack Neusfc3b5772019-07-03 11:18:42 -060077 }
78 // Find all branches that match the pattern.
79 branches := strings.Split(output.Stdout, "\n")
80 matchedBranches := []string{}
81 for _, branch := range branches {
82 branch = strings.TrimSpace(branch)
83 if branch == "" {
84 continue
85 }
86 branch = strings.Fields(branch)[1]
Jack Neus10e6a122019-07-18 10:17:44 -060087
88 // Only look at branches which match the namespace.
89 if !namespace.Match([]byte(branch)) {
90 continue
91 }
92 branch = namespace.ReplaceAllString(branch, "")
93
Jack Neusfc3b5772019-07-03 11:18:42 -060094 if pattern.Match([]byte(branch)) {
95 matchedBranches = append(matchedBranches, branch)
96 }
97 }
98 return matchedBranches, nil
99}
100
101// GetGitRepoRevision finds and returns the revision of a branch.
102func GetGitRepoRevision(cwd string) (string, error) {
103 output, err := RunGit(cwd, []string{"rev-parse", "HEAD"})
104 return strings.TrimSpace(output.Stdout), err
105}
106
Jack Neus7440c762019-07-22 10:45:18 -0600107// StripRefsHead removes leading 'refs/heads/' from a ref name.
Jack Neusfc3b5772019-07-03 11:18:42 -0600108func StripRefsHead(ref string) string {
109 return strings.TrimPrefix(ref, "refs/heads/")
110}
111
112// NormalizeRef converts git branch refs into fully qualified form.
113func NormalizeRef(ref string) string {
114 if ref == "" || strings.HasPrefix(ref, "refs/") {
115 return ref
116 }
117 return fmt.Sprintf("refs/heads/%s", ref)
118}
119
120// StripRefs removes leading 'refs/heads/', 'refs/remotes/[^/]+/' from a ref name.
121func StripRefs(ref string) string {
122 ref = StripRefsHead(ref)
123 // If the ref starts with ref/remotes/, then we want the part of the string
124 // that comes after the third "/".
125 // Example: refs/remotes/origin/master --> master
126 // Example: refs/remotse/origin/foo/bar --> foo/bar
127 if strings.HasPrefix(ref, "refs/remotes/") {
128 refParts := strings.SplitN(ref, "/", 4)
129 return refParts[len(refParts)-1]
130 }
131 return ref
132}
Jack Neusabdbe192019-07-15 12:23:22 -0600133
134// CreateBranch creates a branch.
135func CreateBranch(gitRepo, branch string) error {
Jack Neus0296c732019-07-17 09:35:01 -0600136 output, err := RunGit(gitRepo, []string{"checkout", "-B", branch})
Jack Neus10e6a122019-07-18 10:17:44 -0600137 if err != nil {
138 if strings.Contains(output.Stderr, "not a valid branch name") {
139 return fmt.Errorf("%s is not a valid branch name", branch)
140 } else {
141 return fmt.Errorf(output.Stderr)
142 }
Jack Neus0296c732019-07-17 09:35:01 -0600143 }
144 return err
145}
146
147// CreateTrackingBranch creates a tracking branch.
148func CreateTrackingBranch(gitRepo, branch string, remoteRef RemoteRef) error {
149 refspec := fmt.Sprintf("%s/%s", remoteRef.Remote, remoteRef.Ref)
150 output, err := RunGit(gitRepo, []string{"fetch", remoteRef.Remote, remoteRef.Ref})
151 if err != nil {
152 return fmt.Errorf("could not fetch %s: %s", refspec, output.Stderr)
153 }
154 output, err = RunGit(gitRepo, []string{"checkout", "-b", branch, "-t", refspec})
155 if err != nil {
156 if strings.Contains(output.Stderr, "not a valid branch name") {
157 return fmt.Errorf("%s is not a valid branch name", branch)
158 } else {
159 return fmt.Errorf(output.Stderr)
160 }
161 }
Jack Neusabdbe192019-07-15 12:23:22 -0600162 return err
163}
164
165// CommitAll adds all local changes and commits them.
166func CommitAll(gitRepo, commitMsg string) error {
Jack Neus0296c732019-07-17 09:35:01 -0600167 if output, err := RunGit(gitRepo, []string{"add", "-A"}); err != nil {
168 return fmt.Errorf(output.Stderr)
Jack Neusabdbe192019-07-15 12:23:22 -0600169 }
Jack Neus0296c732019-07-17 09:35:01 -0600170 if output, err := RunGit(gitRepo, []string{"commit", "-m", commitMsg}); err != nil {
171 if strings.Contains(output.Stdout, "nothing to commit") {
172 return fmt.Errorf(output.Stdout)
173 } else {
174 return fmt.Errorf(output.Stderr)
175 }
Jack Neusabdbe192019-07-15 12:23:22 -0600176 }
177 return nil
178}
179
Jack Neus7440c762019-07-22 10:45:18 -0600180// CommitEmpty makes an empty commit (assuming nothing is staged).
181func CommitEmpty(gitRepo, commitMsg string) error {
182 if output, err := RunGit(gitRepo, []string{"commit", "-m", commitMsg, "--allow-empty"}); err != nil {
183 return fmt.Errorf(output.Stderr)
184 }
185 return nil
186}
187
Jack Neusabdbe192019-07-15 12:23:22 -0600188// PushGitChanges stages and commits any local changes before pushing the commit
189// to the specified remote ref.
190func PushChanges(gitRepo, localRef, commitMsg string, dryRun bool, pushTo RemoteRef) error {
Jack Neus0296c732019-07-17 09:35:01 -0600191 err := CommitAll(gitRepo, commitMsg)
192 // It's ok if there's nothing to commit, we can still try to push.
193 if err != nil && !strings.Contains(err.Error(), "nothing to commit") {
Jack Neusabdbe192019-07-15 12:23:22 -0600194 return err
195 }
Jack Neuseb25f722019-07-19 16:33:20 -0600196 return PushRef(gitRepo, localRef, dryRun, pushTo)
Jack Neus7440c762019-07-22 10:45:18 -0600197}
198
Jack Neuseb25f722019-07-19 16:33:20 -0600199// PushRef pushes the specified local ref to the specified remote ref.
200func PushRef(gitRepo, localRef string, dryRun bool, pushTo RemoteRef) error {
Jack Neusabdbe192019-07-15 12:23:22 -0600201 ref := fmt.Sprintf("%s:%s", localRef, pushTo.Ref)
202 cmd := []string{"push", pushTo.Remote, ref}
203 if dryRun {
204 cmd = append(cmd, "--dry-run")
205 }
Jack Neus7440c762019-07-22 10:45:18 -0600206 _, err := RunGit(gitRepo, cmd)
Jack Neus0296c732019-07-17 09:35:01 -0600207 return err
208}
209
210// Init initializes a repo.
211func Init(gitRepo string, bare bool) error {
212 cmd := []string{"init"}
213 if bare {
214 cmd = append(cmd, "--bare")
215 }
Jack Neusabdbe192019-07-15 12:23:22 -0600216 _, err := RunGit(gitRepo, cmd)
217 return err
218}
Jack Neus0296c732019-07-17 09:35:01 -0600219
220// AddRemote adds a remote.
221func AddRemote(gitRepo, remote, remoteLocation string) error {
222 output, err := RunGit(gitRepo, []string{"remote", "add", remote, remoteLocation})
223 if err != nil {
Jack Neuseb25f722019-07-19 16:33:20 -0600224 if strings.Contains(output.Stderr, "already exists") {
225 return fmt.Errorf("remote already exists")
226 }
Jack Neus0296c732019-07-17 09:35:01 -0600227 }
228 return err
229}
230
231// Checkout checkouts a branch.
232func Checkout(gitRepo, branch string) error {
233 output, err := RunGit(gitRepo, []string{"checkout", branch})
234 if err != nil && strings.Contains(output.Stderr, "did not match any") {
235 return fmt.Errorf(output.Stderr)
236 }
237 return err
238}
239
240// DeleteBranch checks out to master and then deletes the current branch.
241func DeleteBranch(gitRepo, branch string, force bool) error {
242 cmd := []string{"branch"}
243 if force {
244 cmd = append(cmd, "-D")
245 } else {
246 cmd = append(cmd, "-d")
247 }
248 cmd = append(cmd, branch)
249 output, err := RunGit(gitRepo, cmd)
250
251 if err != nil {
252 if strings.Contains(output.Stderr, "checked out at") {
253 return fmt.Errorf(output.Stderr)
254 }
255 if strings.Contains(output.Stderr, "not fully merged") {
256 return fmt.Errorf("branch %s is not fully merged. use the force parameter if you wish to proceed", branch)
257 }
258 }
259 return err
260}
261
262// Clone clones the remote into the specified dir.
263func Clone(remote, dir string) error {
264 output, err := RunGit(filepath.Dir(dir), []string{"clone", remote, filepath.Base(dir)})
265 if err != nil {
266 return fmt.Errorf(output.Stderr)
267 }
268 return nil
269}