blob: 047452caa045f5f6013ed19d1a520e072b7451fe [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
69 output, err := RunGit(gitRepo, []string{"ls-remote", gitRepo})
70 if err != nil {
71 // Could not read branches.
72 return []string{}, fmt.Errorf("git error: %s\nstderr: %s", err.Error(), output.Stderr)
73 }
74 // Find all branches that match the pattern.
75 branches := strings.Split(output.Stdout, "\n")
76 matchedBranches := []string{}
77 for _, branch := range branches {
78 branch = strings.TrimSpace(branch)
79 if branch == "" {
80 continue
81 }
82 branch = strings.Fields(branch)[1]
Jack Neus10e6a122019-07-18 10:17:44 -060083
84 // Only look at branches which match the namespace.
85 if !namespace.Match([]byte(branch)) {
86 continue
87 }
88 branch = namespace.ReplaceAllString(branch, "")
89
Jack Neusfc3b5772019-07-03 11:18:42 -060090 if pattern.Match([]byte(branch)) {
91 matchedBranches = append(matchedBranches, branch)
92 }
93 }
94 return matchedBranches, nil
95}
96
97// GetGitRepoRevision finds and returns the revision of a branch.
98func GetGitRepoRevision(cwd string) (string, error) {
99 output, err := RunGit(cwd, []string{"rev-parse", "HEAD"})
100 return strings.TrimSpace(output.Stdout), err
101}
102
103// StipRefsHead removes leading 'refs/heads/' from a ref name.
104func StripRefsHead(ref string) string {
105 return strings.TrimPrefix(ref, "refs/heads/")
106}
107
108// NormalizeRef converts git branch refs into fully qualified form.
109func NormalizeRef(ref string) string {
110 if ref == "" || strings.HasPrefix(ref, "refs/") {
111 return ref
112 }
113 return fmt.Sprintf("refs/heads/%s", ref)
114}
115
116// StripRefs removes leading 'refs/heads/', 'refs/remotes/[^/]+/' from a ref name.
117func StripRefs(ref string) string {
118 ref = StripRefsHead(ref)
119 // If the ref starts with ref/remotes/, then we want the part of the string
120 // that comes after the third "/".
121 // Example: refs/remotes/origin/master --> master
122 // Example: refs/remotse/origin/foo/bar --> foo/bar
123 if strings.HasPrefix(ref, "refs/remotes/") {
124 refParts := strings.SplitN(ref, "/", 4)
125 return refParts[len(refParts)-1]
126 }
127 return ref
128}
Jack Neusabdbe192019-07-15 12:23:22 -0600129
130// CreateBranch creates a branch.
131func CreateBranch(gitRepo, branch string) error {
Jack Neus0296c732019-07-17 09:35:01 -0600132 output, err := RunGit(gitRepo, []string{"checkout", "-B", branch})
Jack Neus10e6a122019-07-18 10:17:44 -0600133 if err != nil {
134 if strings.Contains(output.Stderr, "not a valid branch name") {
135 return fmt.Errorf("%s is not a valid branch name", branch)
136 } else {
137 return fmt.Errorf(output.Stderr)
138 }
Jack Neus0296c732019-07-17 09:35:01 -0600139 }
140 return err
141}
142
143// CreateTrackingBranch creates a tracking branch.
144func CreateTrackingBranch(gitRepo, branch string, remoteRef RemoteRef) error {
145 refspec := fmt.Sprintf("%s/%s", remoteRef.Remote, remoteRef.Ref)
146 output, err := RunGit(gitRepo, []string{"fetch", remoteRef.Remote, remoteRef.Ref})
147 if err != nil {
148 return fmt.Errorf("could not fetch %s: %s", refspec, output.Stderr)
149 }
150 output, err = RunGit(gitRepo, []string{"checkout", "-b", branch, "-t", refspec})
151 if err != nil {
152 if strings.Contains(output.Stderr, "not a valid branch name") {
153 return fmt.Errorf("%s is not a valid branch name", branch)
154 } else {
155 return fmt.Errorf(output.Stderr)
156 }
157 }
Jack Neusabdbe192019-07-15 12:23:22 -0600158 return err
159}
160
161// CommitAll adds all local changes and commits them.
162func CommitAll(gitRepo, commitMsg string) error {
Jack Neus0296c732019-07-17 09:35:01 -0600163 if output, err := RunGit(gitRepo, []string{"add", "-A"}); err != nil {
164 return fmt.Errorf(output.Stderr)
Jack Neusabdbe192019-07-15 12:23:22 -0600165 }
Jack Neus0296c732019-07-17 09:35:01 -0600166 if output, err := RunGit(gitRepo, []string{"commit", "-m", commitMsg}); err != nil {
167 if strings.Contains(output.Stdout, "nothing to commit") {
168 return fmt.Errorf(output.Stdout)
169 } else {
170 return fmt.Errorf(output.Stderr)
171 }
Jack Neusabdbe192019-07-15 12:23:22 -0600172 }
173 return nil
174}
175
176// PushGitChanges stages and commits any local changes before pushing the commit
177// to the specified remote ref.
178func PushChanges(gitRepo, localRef, commitMsg string, dryRun bool, pushTo RemoteRef) error {
Jack Neus0296c732019-07-17 09:35:01 -0600179 err := CommitAll(gitRepo, commitMsg)
180 // It's ok if there's nothing to commit, we can still try to push.
181 if err != nil && !strings.Contains(err.Error(), "nothing to commit") {
Jack Neusabdbe192019-07-15 12:23:22 -0600182 return err
183 }
184 ref := fmt.Sprintf("%s:%s", localRef, pushTo.Ref)
185 cmd := []string{"push", pushTo.Remote, ref}
186 if dryRun {
187 cmd = append(cmd, "--dry-run")
188 }
Jack Neus0296c732019-07-17 09:35:01 -0600189 _, err = RunGit(gitRepo, cmd)
190 return err
191}
192
193// Init initializes a repo.
194func Init(gitRepo string, bare bool) error {
195 cmd := []string{"init"}
196 if bare {
197 cmd = append(cmd, "--bare")
198 }
Jack Neusabdbe192019-07-15 12:23:22 -0600199 _, err := RunGit(gitRepo, cmd)
200 return err
201}
Jack Neus0296c732019-07-17 09:35:01 -0600202
203// AddRemote adds a remote.
204func AddRemote(gitRepo, remote, remoteLocation string) error {
205 output, err := RunGit(gitRepo, []string{"remote", "add", remote, remoteLocation})
206 if err != nil {
207 fmt.Printf("remote error: %s\n", output.Stderr)
208 }
209 return err
210}
211
212// Checkout checkouts a branch.
213func Checkout(gitRepo, branch string) error {
214 output, err := RunGit(gitRepo, []string{"checkout", branch})
215 if err != nil && strings.Contains(output.Stderr, "did not match any") {
216 return fmt.Errorf(output.Stderr)
217 }
218 return err
219}
220
221// DeleteBranch checks out to master and then deletes the current branch.
222func DeleteBranch(gitRepo, branch string, force bool) error {
223 cmd := []string{"branch"}
224 if force {
225 cmd = append(cmd, "-D")
226 } else {
227 cmd = append(cmd, "-d")
228 }
229 cmd = append(cmd, branch)
230 output, err := RunGit(gitRepo, cmd)
231
232 if err != nil {
233 if strings.Contains(output.Stderr, "checked out at") {
234 return fmt.Errorf(output.Stderr)
235 }
236 if strings.Contains(output.Stderr, "not fully merged") {
237 return fmt.Errorf("branch %s is not fully merged. use the force parameter if you wish to proceed", branch)
238 }
239 }
240 return err
241}
242
243// Clone clones the remote into the specified dir.
244func Clone(remote, dir string) error {
245 output, err := RunGit(filepath.Dir(dir), []string{"clone", remote, filepath.Base(dir)})
246 if err != nil {
247 return fmt.Errorf(output.Stderr)
248 }
249 return nil
250}