/
save.go
254 lines (217 loc) · 6.88 KB
/
save.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
// Copyright 2019 Sorint.lab
//
// 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 gitsave
import (
"context"
"io"
"os"
"path/filepath"
"github.com/gofrs/uuid"
"github.com/rs/zerolog"
"github.com/sorintlab/errors"
"agola.io/agola/internal/util"
)
const (
gitIndexFile = "index"
defaultRefsPrefix = "refs/gitsave"
)
func copyFile(src, dest string) error {
srcf, err := os.Open(src)
if err != nil {
return errors.WithStack(err)
}
defer srcf.Close()
destf, err := os.Create(dest)
if err != nil {
return errors.WithStack(err)
}
defer destf.Close()
_, err = io.Copy(destf, srcf)
return errors.WithStack(err)
}
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return false, errors.WithStack(err)
}
return !errors.Is(err, os.ErrNotExist), nil
}
// GitDir returns the git dir relative to the working dir
func GitDir() (string, error) {
git := &util.Git{}
lines, err := git.OutputLines(context.Background(), nil, "rev-parse", "--git-dir")
if err != nil {
return "", errors.WithStack(err)
}
if len(lines) != 1 {
return "", errors.Errorf("received %d lines, expected one line", len(lines))
}
return lines[0], errors.WithStack(err)
}
func currentGitBranch() (string, error) {
git := &util.Git{}
lines, err := git.OutputLines(context.Background(), nil, "symbolic-ref", "--short", "HEAD")
if err != nil {
return "", errors.WithStack(err)
}
if len(lines) != 1 {
return "", errors.Errorf("received %d lines, expected one line", len(lines))
}
return lines[0], errors.WithStack(err)
}
// gitDir returns the git dir relative to the working dir
func gitWriteTree(indexPath string) (string, error) {
git := &util.Git{Env: []string{"GIT_INDEX_FILE=" + indexPath}}
lines, err := git.OutputLines(context.Background(), nil, "write-tree")
if err != nil {
return "", errors.WithStack(err)
}
if len(lines) != 1 {
return "", errors.Errorf("received %d lines, expected one line", len(lines))
}
return lines[0], errors.WithStack(err)
}
func gitCommitTree(message, treeSHA string) (string, error) {
git := &util.Git{}
lines, err := git.OutputLines(context.Background(), nil, "commit-tree", "-m", message, treeSHA)
if err != nil {
return "", errors.WithStack(err)
}
if len(lines) != 1 {
return "", errors.Errorf("received %d lines, expected one line", len(lines))
}
return lines[0], errors.WithStack(err)
}
func gitUpdateRef(message, ref, commitSHA string) error {
git := &util.Git{}
_, err := git.Output(context.Background(), nil, "update-ref", "-m", message, ref, commitSHA)
return errors.WithStack(err)
}
func gitUpdateFiles(indexPath string) error {
git := &util.Git{Env: []string{"GIT_INDEX_FILE=" + indexPath}}
_, err := git.Output(context.Background(), nil, "add", "-u")
return errors.WithStack(err)
}
func gitAddUntrackedFiles(indexPath string) error {
git := &util.Git{Env: []string{"GIT_INDEX_FILE=" + indexPath}}
_, err := git.Output(context.Background(), nil, "add", ".")
return errors.WithStack(err)
}
func gitAddIgnoredFiles(indexPath string) error {
git := &util.Git{Env: []string{"GIT_INDEX_FILE=" + indexPath}}
_, err := git.Output(context.Background(), nil, "add", "-f", "-A", ".")
return errors.WithStack(err)
}
func GitAddRemote(configPath, name, url string) error {
git := &util.Git{}
_, err := git.Output(context.Background(), nil, "remote", "add", name, url)
return errors.WithStack(err)
}
func GitPush(configPath, remote, branch string) error {
git := &util.Git{}
_, err := git.Output(context.Background(), nil, "push", remote, branch, "-f")
return errors.WithStack(err)
}
type GitSaveConfig struct {
AddUntracked bool
AddIgnored bool
RefsPrefix string
}
type GitSave struct {
log zerolog.Logger
conf *GitSaveConfig
refsPrefix string
}
func NewGitSave(log zerolog.Logger, conf *GitSaveConfig) *GitSave {
refsPrefix := conf.RefsPrefix
if refsPrefix == "" {
refsPrefix = defaultRefsPrefix
}
return &GitSave{
log: log,
conf: conf,
refsPrefix: refsPrefix,
}
}
func (s *GitSave) RefsPrefix() string {
return s.refsPrefix
}
// Save adds files to the provided index, creates a tree and a commit pointing to
// that tree, finally it creates a branch poiting to that commit
// Save will use the current worktree index if available to speed the index generation
func (s *GitSave) Save(message, branchName string) (string, error) {
gitdir, err := GitDir()
if err != nil {
return "", errors.WithStack(err)
}
tmpIndexPath := filepath.Join(gitdir, "gitsave-index-"+uuid.Must(uuid.NewV4()).String())
defer os.Remove(tmpIndexPath)
indexPath := filepath.Join(gitdir, gitIndexFile)
curBranch, err := currentGitBranch()
if err != nil {
return "", errors.WithStack(err)
}
indexExists, err := fileExists(indexPath)
if err != nil {
return "", errors.WithStack(err)
}
if indexExists {
// copy current git index to a temporary index
if err := copyFile(indexPath, tmpIndexPath); err != nil {
return "", errors.WithStack(err)
}
s.log.Info().Msgf("created temporary index: %s", tmpIndexPath)
// read the current branch tree information into the index
git := &util.Git{Env: []string{"GIT_INDEX_FILE=" + tmpIndexPath}}
_, err = git.Output(context.Background(), nil, "read-tree", curBranch)
if err != nil {
return "", errors.WithStack(err)
}
} else {
s.log.Info().Msgf("index %s does not exist", indexPath)
}
s.log.Info().Msgf("updating files already in the index")
if err := gitUpdateFiles(tmpIndexPath); err != nil {
return "", errors.WithStack(err)
}
if s.conf.AddUntracked {
s.log.Info().Msgf("adding untracked files")
if err := gitAddUntrackedFiles(tmpIndexPath); err != nil {
return "", errors.WithStack(err)
}
}
if s.conf.AddIgnored {
s.log.Info().Msgf("adding ignored files")
if err := gitAddIgnoredFiles(tmpIndexPath); err != nil {
return "", errors.WithStack(err)
}
}
s.log.Info().Msgf("writing tree file")
treeSHA, err := gitWriteTree(tmpIndexPath)
if err != nil {
return "", errors.WithStack(err)
}
s.log.Info().Msgf("tree: %s", treeSHA)
s.log.Info().Msgf("committing tree")
commitSHA, err := gitCommitTree(message, treeSHA)
if err != nil {
return "", errors.WithStack(err)
}
s.log.Info().Msgf("commit: %s", commitSHA)
s.log.Info().Msgf("updating ref")
if err = gitUpdateRef("git-save", filepath.Join(s.refsPrefix, branchName), commitSHA); err != nil {
return "", errors.WithStack(err)
}
return commitSHA, nil
}