Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 1 | // 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. |
| 4 | package git |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "fmt" |
Jack Neus | 0296c73 | 2019-07-17 09:35:01 -0600 | [diff] [blame] | 10 | "path/filepath" |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 11 | "regexp" |
| 12 | "strings" |
Jack Neus | 0751172 | 2019-07-12 15:41:10 -0600 | [diff] [blame] | 13 | |
| 14 | "go.chromium.org/chromiumos/infra/go/internal/cmd" |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 15 | ) |
| 16 | |
| 17 | var ( |
Jack Neus | 0751172 | 2019-07-12 15:41:10 -0600 | [diff] [blame] | 18 | CommandRunnerImpl cmd.CommandRunner = cmd.RealCommandRunner{} |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 19 | ) |
| 20 | |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 21 | type CommandOutput struct { |
| 22 | Stdout string |
| 23 | Stderr string |
| 24 | } |
| 25 | |
| 26 | // Struct representing a remote ref. |
| 27 | type 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. |
| 34 | func RunGit(gitRepo string, cmd []string) (CommandOutput, error) { |
| 35 | ctx := context.Background() |
| 36 | var stdoutBuf, stderrBuf bytes.Buffer |
Jack Neus | 0751172 | 2019-07-12 15:41:10 -0600 | [diff] [blame] | 37 | err := CommandRunnerImpl.RunCommand(ctx, &stdoutBuf, &stderrBuf, gitRepo, "git", cmd...) |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 38 | 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. |
| 44 | func 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. |
| 54 | func MatchBranchName(gitRepo string, pattern *regexp.Regexp) ([]string, error) { |
Jack Neus | 10e6a12 | 2019-07-18 10:17:44 -0600 | [diff] [blame] | 55 | // 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. |
| 64 | func MatchBranchNameWithNamespace(gitRepo string, pattern, namespace *regexp.Regexp) ([]string, error) { |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 65 | // Regex should be case insensitive. |
Jack Neus | 10e6a12 | 2019-07-18 10:17:44 -0600 | [diff] [blame] | 66 | namespace = regexp.MustCompile("(?i)^" + namespace.String()) |
| 67 | pattern = regexp.MustCompile("(?i)" + pattern.String()) |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 68 | |
Jack Neus | 901a6bf | 2019-07-22 08:30:07 -0600 | [diff] [blame^] | 69 | output, err := RunGit(gitRepo, []string{"show-ref"}) |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 70 | if err != nil { |
Jack Neus | 901a6bf | 2019-07-22 08:30:07 -0600 | [diff] [blame^] | 71 | if strings.Contains(err.Error(), "exit status 1") { |
| 72 | // Not a fatal error, just no branches. |
| 73 | return []string{}, nil |
| 74 | } |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 75 | // Could not read branches. |
Jack Neus | 901a6bf | 2019-07-22 08:30:07 -0600 | [diff] [blame^] | 76 | return []string{}, fmt.Errorf("git error: %s\nstdout: %s stderr: %s", err.Error(), output.Stdout, output.Stderr) |
Jack Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 77 | } |
| 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 Neus | 10e6a12 | 2019-07-18 10:17:44 -0600 | [diff] [blame] | 87 | |
| 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 Neus | fc3b577 | 2019-07-03 11:18:42 -0600 | [diff] [blame] | 94 | 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. |
| 102 | func GetGitRepoRevision(cwd string) (string, error) { |
| 103 | output, err := RunGit(cwd, []string{"rev-parse", "HEAD"}) |
| 104 | return strings.TrimSpace(output.Stdout), err |
| 105 | } |
| 106 | |
| 107 | // StipRefsHead removes leading 'refs/heads/' from a ref name. |
| 108 | func StripRefsHead(ref string) string { |
| 109 | return strings.TrimPrefix(ref, "refs/heads/") |
| 110 | } |
| 111 | |
| 112 | // NormalizeRef converts git branch refs into fully qualified form. |
| 113 | func 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. |
| 121 | func 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 Neus | abdbe19 | 2019-07-15 12:23:22 -0600 | [diff] [blame] | 133 | |
| 134 | // CreateBranch creates a branch. |
| 135 | func CreateBranch(gitRepo, branch string) error { |
Jack Neus | 0296c73 | 2019-07-17 09:35:01 -0600 | [diff] [blame] | 136 | output, err := RunGit(gitRepo, []string{"checkout", "-B", branch}) |
Jack Neus | 10e6a12 | 2019-07-18 10:17:44 -0600 | [diff] [blame] | 137 | 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 Neus | 0296c73 | 2019-07-17 09:35:01 -0600 | [diff] [blame] | 143 | } |
| 144 | return err |
| 145 | } |
| 146 | |
| 147 | // CreateTrackingBranch creates a tracking branch. |
| 148 | func 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 Neus | abdbe19 | 2019-07-15 12:23:22 -0600 | [diff] [blame] | 162 | return err |
| 163 | } |
| 164 | |
| 165 | // CommitAll adds all local changes and commits them. |
| 166 | func CommitAll(gitRepo, commitMsg string) error { |
Jack Neus | 0296c73 | 2019-07-17 09:35:01 -0600 | [diff] [blame] | 167 | if output, err := RunGit(gitRepo, []string{"add", "-A"}); err != nil { |
| 168 | return fmt.Errorf(output.Stderr) |
Jack Neus | abdbe19 | 2019-07-15 12:23:22 -0600 | [diff] [blame] | 169 | } |
Jack Neus | 0296c73 | 2019-07-17 09:35:01 -0600 | [diff] [blame] | 170 | 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 Neus | abdbe19 | 2019-07-15 12:23:22 -0600 | [diff] [blame] | 176 | } |
| 177 | return nil |
| 178 | } |
| 179 | |
| 180 | // PushGitChanges stages and commits any local changes before pushing the commit |
| 181 | // to the specified remote ref. |
| 182 | func PushChanges(gitRepo, localRef, commitMsg string, dryRun bool, pushTo RemoteRef) error { |
Jack Neus | 0296c73 | 2019-07-17 09:35:01 -0600 | [diff] [blame] | 183 | err := CommitAll(gitRepo, commitMsg) |
| 184 | // It's ok if there's nothing to commit, we can still try to push. |
| 185 | if err != nil && !strings.Contains(err.Error(), "nothing to commit") { |
Jack Neus | abdbe19 | 2019-07-15 12:23:22 -0600 | [diff] [blame] | 186 | return err |
| 187 | } |
| 188 | ref := fmt.Sprintf("%s:%s", localRef, pushTo.Ref) |
| 189 | cmd := []string{"push", pushTo.Remote, ref} |
| 190 | if dryRun { |
| 191 | cmd = append(cmd, "--dry-run") |
| 192 | } |
Jack Neus | 0296c73 | 2019-07-17 09:35:01 -0600 | [diff] [blame] | 193 | _, err = RunGit(gitRepo, cmd) |
| 194 | return err |
| 195 | } |
| 196 | |
| 197 | // Init initializes a repo. |
| 198 | func Init(gitRepo string, bare bool) error { |
| 199 | cmd := []string{"init"} |
| 200 | if bare { |
| 201 | cmd = append(cmd, "--bare") |
| 202 | } |
Jack Neus | abdbe19 | 2019-07-15 12:23:22 -0600 | [diff] [blame] | 203 | _, err := RunGit(gitRepo, cmd) |
| 204 | return err |
| 205 | } |
Jack Neus | 0296c73 | 2019-07-17 09:35:01 -0600 | [diff] [blame] | 206 | |
| 207 | // AddRemote adds a remote. |
| 208 | func AddRemote(gitRepo, remote, remoteLocation string) error { |
| 209 | output, err := RunGit(gitRepo, []string{"remote", "add", remote, remoteLocation}) |
| 210 | if err != nil { |
| 211 | fmt.Printf("remote error: %s\n", output.Stderr) |
| 212 | } |
| 213 | return err |
| 214 | } |
| 215 | |
| 216 | // Checkout checkouts a branch. |
| 217 | func Checkout(gitRepo, branch string) error { |
| 218 | output, err := RunGit(gitRepo, []string{"checkout", branch}) |
| 219 | if err != nil && strings.Contains(output.Stderr, "did not match any") { |
| 220 | return fmt.Errorf(output.Stderr) |
| 221 | } |
| 222 | return err |
| 223 | } |
| 224 | |
| 225 | // DeleteBranch checks out to master and then deletes the current branch. |
| 226 | func DeleteBranch(gitRepo, branch string, force bool) error { |
| 227 | cmd := []string{"branch"} |
| 228 | if force { |
| 229 | cmd = append(cmd, "-D") |
| 230 | } else { |
| 231 | cmd = append(cmd, "-d") |
| 232 | } |
| 233 | cmd = append(cmd, branch) |
| 234 | output, err := RunGit(gitRepo, cmd) |
| 235 | |
| 236 | if err != nil { |
| 237 | if strings.Contains(output.Stderr, "checked out at") { |
| 238 | return fmt.Errorf(output.Stderr) |
| 239 | } |
| 240 | if strings.Contains(output.Stderr, "not fully merged") { |
| 241 | return fmt.Errorf("branch %s is not fully merged. use the force parameter if you wish to proceed", branch) |
| 242 | } |
| 243 | } |
| 244 | return err |
| 245 | } |
| 246 | |
| 247 | // Clone clones the remote into the specified dir. |
| 248 | func Clone(remote, dir string) error { |
| 249 | output, err := RunGit(filepath.Dir(dir), []string{"clone", remote, filepath.Base(dir)}) |
| 250 | if err != nil { |
| 251 | return fmt.Errorf(output.Stderr) |
| 252 | } |
| 253 | return nil |
| 254 | } |