-
Notifications
You must be signed in to change notification settings - Fork 153
/
repo.go
302 lines (267 loc) · 8.85 KB
/
repo.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// Copyright 2020 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
var (
ErrNoChange = errors.New("no change")
)
// Repo provides functions to get and handle git data.
type Repo interface {
GetPath() string
GetClonedBranch() string
Copy(dest string) (Repo, error)
ListCommits(ctx context.Context, visionRange string) ([]Commit, error)
GetLatestCommit(ctx context.Context) (Commit, error)
GetCommitHashForRev(ctx context.Context, rev string) (string, error)
ChangedFiles(ctx context.Context, from, to string) ([]string, error)
Checkout(ctx context.Context, commitish string) error
CheckoutPullRequest(ctx context.Context, number int, branch string) error
Clean() error
Pull(ctx context.Context, branch string) error
MergeRemoteBranch(ctx context.Context, branch, commit, mergeCommitMessage string) error
Push(ctx context.Context, branch string) error
CommitChanges(ctx context.Context, branch, message string, newBranch bool, changes map[string][]byte) error
}
type repo struct {
dir string
gitPath string
remote string
clonedBranch string
gitEnvs []string
}
// NewRepo creates a new Repo instance.
func NewRepo(dir, gitPath, remote, clonedBranch string, gitEnvs []string) *repo {
return &repo{
dir: dir,
gitPath: gitPath,
remote: remote,
clonedBranch: clonedBranch,
gitEnvs: gitEnvs,
}
}
// GetPath returns the path to the local git directory.
func (r *repo) GetPath() string {
return r.dir
}
// GetClonedBranch returns the name of cloned branch.
func (r *repo) GetClonedBranch() string {
return r.clonedBranch
}
// Copy does copying the repository to the given destination.
// NOTE: the given “dest” must be a path that doesn’t exist yet.
// If you don't, it copies the repo root itself to the given dest as a subdirectory.
func (r *repo) Copy(dest string) (Repo, error) {
cmd := exec.Command("cp", "-rf", r.dir, dest)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, formatCommandError(err, out)
}
return &repo{
dir: dest,
gitPath: r.gitPath,
remote: r.remote,
clonedBranch: r.clonedBranch,
}, nil
}
// ListCommits returns a list of commits in a given revision range.
func (r *repo) ListCommits(ctx context.Context, revisionRange string) ([]Commit, error) {
args := []string{
"log",
"--no-decorate",
fmt.Sprintf("--pretty=format:%s", commitLogFormat),
}
if revisionRange != "" {
args = append(args, revisionRange)
}
out, err := r.runGitCommand(ctx, args...)
if err != nil {
return nil, formatCommandError(err, out)
}
return parseCommits(string(out))
}
// GetLatestCommit returns the most recent commit of current branch.
func (r *repo) GetLatestCommit(ctx context.Context) (Commit, error) {
commits, err := r.ListCommits(ctx, "-1")
if err != nil {
return Commit{}, err
}
if len(commits) != 1 {
return Commit{}, fmt.Errorf("commits must contain one item, got: %d", len(commits))
}
return commits[0], nil
}
// GetCommitHashForRev returns the hash value of the commit for a given rev.
func (r *repo) GetCommitHashForRev(ctx context.Context, rev string) (string, error) {
out, err := r.runGitCommand(ctx, "rev-parse", rev)
if err != nil {
return "", formatCommandError(err, out)
}
return strings.TrimSpace(string(out)), nil
}
// ChangedFiles returns a list of files those were touched between two commits.
func (r *repo) ChangedFiles(ctx context.Context, from, to string) ([]string, error) {
out, err := r.runGitCommand(ctx, "diff", "--name-only", from, to)
if err != nil {
return nil, formatCommandError(err, out)
}
var (
lines = strings.Split(string(out), "\n")
files = make([]string, 0, len(lines))
)
// The result may include some empty lines
// so we need to remove all of them.
for _, f := range lines {
if f != "" {
files = append(files, f)
}
}
return files, nil
}
// Checkout checkouts to a given commitish.
func (r *repo) Checkout(ctx context.Context, commitish string) error {
out, err := r.runGitCommand(ctx, "checkout", commitish)
if err != nil {
return formatCommandError(err, out)
}
return nil
}
// CheckoutPullRequest checkouts to the latest commit of a given pull request.
func (r *repo) CheckoutPullRequest(ctx context.Context, number int, branch string) error {
target := fmt.Sprintf("pull/%d/head:%s", number, branch)
out, err := r.runGitCommand(ctx, "fetch", r.remote, target)
if err != nil {
return formatCommandError(err, out)
}
return r.Checkout(ctx, branch)
}
// Pull fetches from and integrate with a local branch.
func (r *repo) Pull(ctx context.Context, branch string) error {
out, err := r.runGitCommand(ctx, "pull", r.remote, branch)
if err != nil {
return formatCommandError(err, out)
}
return nil
}
// MergeRemoteBranch merges all commits until the given one
// from a remote branch to current local branch.
// This always adds a new merge commit into tree.
func (r *repo) MergeRemoteBranch(ctx context.Context, branch, commit, mergeCommitMessage string) error {
out, err := r.runGitCommand(ctx, "fetch", r.remote, branch)
if err != nil {
return formatCommandError(err, out)
}
out, err = r.runGitCommand(ctx, "merge", "-q", "--no-ff", "-m", mergeCommitMessage, commit)
if err != nil {
return formatCommandError(err, out)
}
return nil
}
// Push pushes local changes of a given branch to the remote.
func (r *repo) Push(ctx context.Context, branch string) error {
out, err := r.runGitCommand(ctx, "push", r.remote, branch)
if err != nil {
return formatCommandError(err, out)
}
return nil
}
// CommitChanges commits some changes into a branch.
func (r *repo) CommitChanges(ctx context.Context, branch, message string, newBranch bool, changes map[string][]byte) error {
if newBranch {
if err := r.checkoutNewBranch(ctx, branch); err != nil {
return fmt.Errorf("failed to checkout new branch, branch: %v, error: %v", branch, err)
}
} else {
if err := r.Checkout(ctx, branch); err != nil {
return fmt.Errorf("failed to checkout branch, branch: %v, error: %v", branch, err)
}
}
// Apply the changes.
for p, bytes := range changes {
filePath := filepath.Join(r.dir, p)
dirPath := filepath.Dir(filePath)
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
if err := os.MkdirAll(dirPath, os.ModePerm); err != nil {
return fmt.Errorf("failed to create directory, dir: %s, err: %v", dirPath, err)
}
}
if err := os.WriteFile(filePath, bytes, os.ModePerm); err != nil {
return fmt.Errorf("failed to write file, file: %s, error: %v", filePath, err)
}
}
// Commit the changes.
if err := r.addCommit(ctx, message); err != nil {
return fmt.Errorf("failed to commit, branch: %s, error: %v", branch, err)
}
return nil
}
// Clean deletes all local git data.
func (r repo) Clean() error {
return os.RemoveAll(r.dir)
}
func (r *repo) checkoutNewBranch(ctx context.Context, branch string) error {
out, err := r.runGitCommand(ctx, "checkout", "-b", branch)
if err != nil {
return formatCommandError(err, out)
}
return nil
}
func (r repo) addCommit(ctx context.Context, message string) error {
out, err := r.runGitCommand(ctx, "add", ".")
if err != nil {
return formatCommandError(err, out)
}
out, err = r.runGitCommand(ctx, "commit", "-m", message)
if err != nil {
msg := string(out)
if strings.Contains(msg, "nothing to commit, working tree clean") {
return ErrNoChange
}
return formatCommandError(err, out)
}
return nil
}
// setUser configures username and email for local user of this repo.
func (r *repo) setUser(ctx context.Context, username, email string) error {
if out, err := r.runGitCommand(ctx, "config", "user.name", username); err != nil {
return formatCommandError(err, out)
}
if out, err := r.runGitCommand(ctx, "config", "user.email", email); err != nil {
return formatCommandError(err, out)
}
return nil
}
func (r *repo) setRemote(ctx context.Context, remote string) error {
out, err := r.runGitCommand(ctx, "remote", "set-url", "origin", remote)
if err != nil {
return formatCommandError(err, out)
}
return nil
}
func (r *repo) runGitCommand(ctx context.Context, args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, r.gitPath, args...)
cmd.Dir = r.dir
cmd.Env = append(os.Environ(), r.gitEnvs...)
return cmd.CombinedOutput()
}
func formatCommandError(err error, out []byte) error {
return fmt.Errorf("err: %w, out: %s", err, string(out))
}