-
Notifications
You must be signed in to change notification settings - Fork 14
/
git.go
178 lines (154 loc) · 4.96 KB
/
git.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
/*
Copyright (C) 2022-2023 ApeCloud Co., Ltd
This file is part of KubeBlocks project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/pkg/errors"
"k8s.io/klog/v2"
)
// CloneGitRepo clones git repo to local path
func CloneGitRepo(url, branch, path string) error {
pullFunc := func(repo *git.Repository) error {
// Get the working directory for the repository
w, err := repo.Worktree()
if err != nil {
return err
}
// Pull the latest changes from the origin remote
err = w.Pull(&git.PullOptions{
RemoteName: "origin",
Progress: os.Stdout,
ReferenceName: plumbing.NewBranchReferenceName(branch),
SingleBranch: true,
})
if !errors.Is(err, git.NoErrAlreadyUpToDate) && !errors.Is(err, git.ErrUnstagedChanges) {
return err
}
return nil
}
// check if local repo path already exists
repo, err := git.PlainOpen(path)
// repo exists, pull it
if err == nil {
if err = pullFunc(repo); err != nil {
return err
}
}
if !errors.Is(err, git.ErrRepositoryNotExists) {
return err
}
// repo does not exists, clone it
_, err = git.PlainClone(path, false, &git.CloneOptions{
URL: url,
Progress: os.Stdout,
ReferenceName: plumbing.NewBranchReferenceName(branch),
SingleBranch: true,
})
return err
}
func GitGetRemoteURL(dir string) (string, error) {
return ExecGitCommand(dir, "config", "--get", "remote.origin.url")
}
// EnsureCloned clones into the destination path, otherwise returns no error.
func EnsureCloned(uri, destinationPath string) error {
if ok, err := IsGitCloned(destinationPath); err != nil {
return err
} else if !ok {
_, err = ExecGitCommand("", "clone", "-v", uri, destinationPath)
return err
}
return nil
}
// IsGitCloned tests if the path is a git dir.
func IsGitCloned(gitPath string) (bool, error) {
f, err := os.Stat(filepath.Join(gitPath, ".git"))
if os.IsNotExist(err) {
return false, nil
}
return err == nil && f.IsDir(), err
}
// EnsureUpdated ensures the destination path exists and is up to date.
func EnsureUpdated(uri, destinationPath string) error {
if err := EnsureCloned(uri, destinationPath); err != nil {
return err
}
return UpdateAndCleanUntracked(destinationPath)
}
// UpdateAndCleanUntracked fetches origin and sets HEAD to origin/HEAD
// and also creates a pristine working directory by removing
// untracked files and directories.
func UpdateAndCleanUntracked(destinationPath string) error {
if _, err := ExecGitCommand(destinationPath, "fetch", "-v"); err != nil {
return errors.Wrapf(err, "fetch index at %q failed", destinationPath)
}
if _, err := ExecGitCommand(destinationPath, "reset", "--hard", "@{upstream}"); err != nil {
return errors.Wrapf(err, "reset index at %q failed", destinationPath)
}
_, err := ExecGitCommand(destinationPath, "clean", "-xfd")
return errors.Wrapf(err, "clean index at %q failed", destinationPath)
}
// ExecGitCommand executes a git command in the given directory.
func ExecGitCommand(pwd string, args ...string) (string, error) {
klog.V(4).Infof("Going to run git %s", strings.Join(args, " "))
cmd := exec.Command("git", args...)
cmd.Dir = pwd
buf := bytes.Buffer{}
var w io.Writer = &buf
if klog.V(2).Enabled() {
w = io.MultiWriter(w, os.Stderr)
}
cmd.Stdout, cmd.Stderr = w, w
if err := cmd.Run(); err != nil {
return "", errors.Wrapf(err, "command execution failure, output=%q", buf.String())
}
return strings.TrimSpace(buf.String()), nil
}
func IsRepoLatest(destinationPath string) (bool, error) {
var (
currentBranch string
commits string
err error
)
if currentBranch, err = GetCurrentBranch(destinationPath); err != nil {
return false, err
}
if _, err = ExecGitCommand(destinationPath, "fetch", "origin", "-v", "-n"); err != nil {
return false, err
}
if commits, err = ExecGitCommand(destinationPath, "rev-list", fmt.Sprintf("%s..origin/%s", currentBranch, currentBranch), "--count"); err == nil {
commits, err := strconv.Atoi(commits)
return err == nil && commits == 0, err
}
return false, err
}
func GetCurrentBranch(destinationPath string) (string, error) {
var (
output string
err error
)
if output, err = ExecGitCommand(destinationPath, "rev-parse", "--abbrev-ref", "HEAD"); err != nil {
return "", err
}
return output, nil
}