-
Notifications
You must be signed in to change notification settings - Fork 226
/
draft.go
303 lines (257 loc) · 9.72 KB
/
draft.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
303
// Copyright 2022 Google LLC
//
// 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"
"path"
"time"
"github.com/GoogleContainerTools/kpt/porch/api/porch/v1alpha1"
"github.com/GoogleContainerTools/kpt/porch/pkg/repository"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/transport"
"go.opentelemetry.io/otel/trace"
"k8s.io/klog/v2"
)
type gitPackageDraft struct {
parent *gitRepository
path string
revision string
workspaceName v1alpha1.WorkspaceName
updated time.Time
tasks []v1alpha1.Task
// New value of the package revision lifecycle
lifecycle v1alpha1.PackageRevisionLifecycle
// ref to the base of the package update commit chain (used for conditional push)
base *plumbing.Reference
// name of the branch where the changes will be pushed
branch BranchName
// Current HEAD of the package changes (commit sha)
commit plumbing.Hash
// Cached tree of the package itself, some descendent of commit.Tree()
tree plumbing.Hash
}
var _ repository.PackageDraft = &gitPackageDraft{}
func (d *gitPackageDraft) UpdateResources(ctx context.Context, new *v1alpha1.PackageRevisionResources, change *v1alpha1.Task) error {
ctx, span := tracer.Start(ctx, "gitPackageDraft::UpdateResources", trace.WithAttributes())
defer span.End()
ch, err := newCommitHelper(d.parent.repo, d.parent.userInfoProvider, d.commit, d.path, plumbing.ZeroHash)
if err != nil {
return fmt.Errorf("failed to commit package: %w", err)
}
for k, v := range new.Spec.Resources {
ch.storeFile(path.Join(d.path, k), v)
}
// Because we can't read the package back without a Kptfile, make sure one is present
{
p := path.Join(d.path, "Kptfile")
_, err := ch.readFile(p)
if os.IsNotExist(err) {
// We could write the file here; currently we return an error
return fmt.Errorf("package must contain Kptfile at root")
}
}
annotation := &gitAnnotation{
PackagePath: d.path,
WorkspaceName: d.workspaceName,
Revision: d.revision,
Task: change,
}
message := "Intermediate commit"
if change != nil {
message += fmt.Sprintf(": %s", change.Type)
d.tasks = append(d.tasks, *change)
}
message += "\n"
message, err = AnnotateCommitMessage(message, annotation)
if err != nil {
return err
}
commitHash, packageTree, err := ch.commit(ctx, message, d.path)
if err != nil {
return fmt.Errorf("failed to commit package: %w", err)
}
d.tree = packageTree
d.commit = commitHash
return nil
}
func (d *gitPackageDraft) UpdateLifecycle(ctx context.Context, new v1alpha1.PackageRevisionLifecycle) error {
d.lifecycle = new
return nil
}
// Finish round of updates.
func (d *gitPackageDraft) Close(ctx context.Context) (repository.PackageRevision, error) {
ctx, span := tracer.Start(ctx, "gitPackageDraft::Close", trace.WithAttributes())
defer span.End()
return d.parent.closeDraft(ctx, d)
}
func (r *gitRepository) closeDraft(ctx context.Context, d *gitPackageDraft) (*gitPackageRevision, error) {
refSpecs := newPushRefSpecBuilder()
draftBranch := createDraftName(d.path, d.workspaceName)
proposedBranch := createProposedName(d.path, d.workspaceName)
var newRef *plumbing.Reference
switch d.lifecycle {
case v1alpha1.PackageRevisionLifecyclePublished:
// Finalize the package revision. Assign it a revision number of latest + 1.
revisions, err := r.ListPackageRevisions(ctx, repository.ListPackageRevisionFilter{
Package: d.path,
})
d.revision, err = repository.NextRevisionNumber(revisions)
if err != nil {
return nil, err
}
// Finalize the package revision. Commit it to main branch.
commitHash, newTreeHash, commitBase, err := r.commitPackageToMain(ctx, d)
if err != nil {
return nil, err
}
tag := createFinalTagNameInLocal(d.path, d.revision)
refSpecs.AddRefToPush(commitHash, r.branch.RefInLocal()) // Push new main branch
refSpecs.AddRefToPush(commitHash, tag) // Push the tag
refSpecs.RequireRef(commitBase) // Make sure main didn't advance
// Delete base branch (if one exists and should be deleted)
switch base := d.base; {
case base == nil: // no branch to delete
case base.Name() == draftBranch.RefInLocal(), base.Name() == proposedBranch.RefInLocal():
refSpecs.AddRefToDelete(base)
}
// Update package draft
d.commit = commitHash
d.tree = newTreeHash
newRef = plumbing.NewHashReference(tag, commitHash)
case v1alpha1.PackageRevisionLifecycleProposed:
// Push the package revision into a proposed branch.
refSpecs.AddRefToPush(d.commit, proposedBranch.RefInLocal())
// Delete base branch (if one exists and should be deleted)
switch base := d.base; {
case base == nil: // no branch to delete
case base.Name() != proposedBranch.RefInLocal():
refSpecs.AddRefToDelete(base)
}
// Update package referemce (commit and tree hash stay the same)
newRef = plumbing.NewHashReference(proposedBranch.RefInLocal(), d.commit)
case v1alpha1.PackageRevisionLifecycleDraft:
// Push the package revision into a draft branch.
refSpecs.AddRefToPush(d.commit, draftBranch.RefInLocal())
// Delete base branch (if one exists and should be deleted)
switch base := d.base; {
case base == nil: // no branch to delete
case base.Name() != draftBranch.RefInLocal():
refSpecs.AddRefToDelete(base)
}
// Update package referemce (commit and tree hash stay the same)
newRef = plumbing.NewHashReference(draftBranch.RefInLocal(), d.commit)
default:
return nil, fmt.Errorf("package has unrecognized lifecycle: %q", d.lifecycle)
}
if err := d.parent.pushAndCleanup(ctx, refSpecs); err != nil {
// No changes is fine. No need to return an error.
if !errors.Is(err, git.NoErrAlreadyUpToDate) {
return nil, err
}
}
// for backwards compatibility with packages that existed before porch supported
// descriptions, we populate the workspaceName as the revision number if it is empty
if d.workspaceName == "" {
d.workspaceName = v1alpha1.WorkspaceName(d.revision)
}
return &gitPackageRevision{
repo: d.parent,
path: d.path,
revision: d.revision,
workspaceName: d.workspaceName,
updated: d.updated,
ref: newRef,
tree: d.tree,
commit: newRef.Hash(),
tasks: d.tasks,
}, nil
}
// doGitWithAuth fetches auth information for git and provides it
// to the provided function which performs the operation against a git repo.
func (r *gitRepository) doGitWithAuth(ctx context.Context, op func(transport.AuthMethod) error) error {
auth, err := r.getAuthMethod(ctx, false)
if err != nil {
return fmt.Errorf("failed to obtain git credentials: %w", err)
}
err = op(auth)
if err != nil {
if !errors.Is(err, transport.ErrAuthenticationRequired) {
return err
}
klog.Infof("Authentication failed. Trying to refresh credentials")
// TODO: Consider having some kind of backoff here.
auth, err := r.getAuthMethod(ctx, true)
if err != nil {
return fmt.Errorf("failed to obtain git credentials: %w", err)
}
return op(auth)
}
return nil
}
func (r *gitRepository) commitPackageToMain(ctx context.Context, d *gitPackageDraft) (commitHash, newPackageTreeHash plumbing.Hash, base *plumbing.Reference, err error) {
branch := r.branch
localRef := branch.RefInLocal()
var zero plumbing.Hash
repo := r.repo
// Fetch main
switch err := r.doGitWithAuth(ctx, func(auth transport.AuthMethod) error {
return repo.Fetch(&git.FetchOptions{
RemoteName: OriginName,
RefSpecs: []config.RefSpec{branch.ForceFetchSpec()},
Auth: auth,
})
}); err {
case nil, git.NoErrAlreadyUpToDate:
// ok
default:
return zero, zero, nil, fmt.Errorf("failed to fetch remote repository: %w", err)
}
// Find localTarget branch
localTarget, err := repo.Reference(localRef, false)
if err != nil {
// TODO: handle empty repositories - NotFound error
return zero, zero, nil, fmt.Errorf("failed to find 'main' branch: %w", err)
}
headCommit, err := repo.CommitObject(localTarget.Hash())
if err != nil {
return zero, zero, nil, fmt.Errorf("failed to resolve main branch to commit: %w", err)
}
packagePath := d.path
// TODO: Check for out-of-band update of the package in main branch
// (compare package tree in target branch and common base)
ch, err := newCommitHelper(repo, r.userInfoProvider, headCommit.Hash, packagePath, d.tree)
if err != nil {
return zero, zero, nil, fmt.Errorf("failed to initialize commit of package %s to %s", packagePath, localRef)
}
// Add a commit without changes to mark that the package revision is approved. The gitAnnotation is
// included so that we can later associate the commit with the correct packagerevision.
message, err := AnnotateCommitMessage(fmt.Sprintf("Approve %s/%s", packagePath, d.revision), &gitAnnotation{
PackagePath: packagePath,
WorkspaceName: d.workspaceName,
Revision: d.revision,
})
if err != nil {
return zero, zero, nil, fmt.Errorf("failed annotation commit message for package %s: %v", packagePath, err)
}
commitHash, newPackageTreeHash, err = ch.commit(ctx, message, packagePath, d.commit)
if err != nil {
return zero, zero, nil, fmt.Errorf("failed to commit package %s to %s", packagePath, localRef)
}
return commitHash, newPackageTreeHash, localTarget, nil
}