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
|
package conflicts
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"sort"
"strings"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus"
"gitlab.com/gitlab-org/gitaly/v14/internal/git"
"gitlab.com/gitlab-org/gitaly/v14/internal/git/conflict"
"gitlab.com/gitlab-org/gitaly/v14/internal/git/localrepo"
"gitlab.com/gitlab-org/gitaly/v14/internal/git/remoterepo"
"gitlab.com/gitlab-org/gitaly/v14/internal/git/repository"
"gitlab.com/gitlab-org/gitaly/v14/internal/git2go"
"gitlab.com/gitlab-org/gitaly/v14/internal/gitalyssh"
"gitlab.com/gitlab-org/gitaly/v14/internal/helper"
"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func (s *server) ResolveConflicts(stream gitalypb.ConflictsService_ResolveConflictsServer) error {
firstRequest, err := stream.Recv()
if err != nil {
return err
}
header := firstRequest.GetHeader()
if header == nil {
return status.Errorf(codes.InvalidArgument, "ResolveConflicts: empty ResolveConflictsRequestHeader")
}
if err = validateResolveConflictsHeader(header); err != nil {
return status.Errorf(codes.InvalidArgument, "ResolveConflicts: %v", err)
}
err = s.resolveConflicts(header, stream)
return handleResolveConflictsErr(err, stream)
}
func handleResolveConflictsErr(err error, stream gitalypb.ConflictsService_ResolveConflictsServer) error {
var errStr string // normalized error message
if err != nil {
errStr = strings.TrimPrefix(err.Error(), "resolve: ") // remove subcommand artifact
errStr = strings.TrimSpace(errStr) // remove newline artifacts
// only send back resolution errors that match expected pattern
for _, p := range []string{
"Missing resolution for section ID:",
"Resolved content has no changes for file",
"Missing resolutions for the following files:",
} {
if strings.HasPrefix(errStr, p) {
// log the error since the interceptor won't catch this
// error due to the unique way the RPC is defined to
// handle resolution errors
ctxlogrus.
Extract(stream.Context()).
WithError(err).
Error("ResolveConflicts: unable to resolve conflict")
return stream.SendAndClose(&gitalypb.ResolveConflictsResponse{
ResolutionError: errStr,
})
}
}
return err
}
return stream.SendAndClose(&gitalypb.ResolveConflictsResponse{})
}
func validateResolveConflictsHeader(header *gitalypb.ResolveConflictsRequestHeader) error {
if header.GetOurCommitOid() == "" {
return fmt.Errorf("empty OurCommitOid")
}
if header.GetRepository() == nil {
return fmt.Errorf("empty Repository")
}
if header.GetTargetRepository() == nil {
return fmt.Errorf("empty TargetRepository")
}
if header.GetTheirCommitOid() == "" {
return fmt.Errorf("empty TheirCommitOid")
}
if header.GetSourceBranch() == nil {
return fmt.Errorf("empty SourceBranch")
}
if header.GetTargetBranch() == nil {
return fmt.Errorf("empty TargetBranch")
}
if header.GetCommitMessage() == nil {
return fmt.Errorf("empty CommitMessage")
}
if header.GetUser() == nil {
return fmt.Errorf("empty User")
}
return nil
}
func (s *server) resolveConflicts(header *gitalypb.ResolveConflictsRequestHeader, stream gitalypb.ConflictsService_ResolveConflictsServer) error {
b := bytes.NewBuffer(nil)
for {
req, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
if _, err := b.Write(req.GetFilesJson()); err != nil {
return err
}
}
var checkKeys []map[string]interface{}
if err := json.Unmarshal(b.Bytes(), &checkKeys); err != nil {
return err
}
for _, ck := range checkKeys {
_, sectionExists := ck["sections"]
_, contentExists := ck["content"]
if !sectionExists && !contentExists {
return helper.ErrInvalidArgumentf("missing sections or content for a resolution")
}
}
var resolutions []conflict.Resolution
if err := json.Unmarshal(b.Bytes(), &resolutions); err != nil {
return err
}
ctx := stream.Context()
sourceRepo := s.localrepo(header.GetRepository())
targetRepo, err := remoterepo.New(ctx, header.GetTargetRepository(), s.pool)
if err != nil {
return err
}
if err := s.repoWithBranchCommit(ctx,
sourceRepo,
targetRepo,
header.TargetBranch,
); err != nil {
return err
}
repoPath, err := s.locator.GetRepoPath(sourceRepo)
if err != nil {
return err
}
authorDate := time.Now()
if header.Timestamp != nil {
authorDate, err = ptypes.Timestamp(header.Timestamp)
if err != nil {
return helper.ErrInvalidArgument(err)
}
}
if git.ValidateObjectID(header.GetOurCommitOid()) != nil ||
git.ValidateObjectID(header.GetTheirCommitOid()) != nil {
return errors.New("Rugged::InvalidError: unable to parse OID - contains invalid characters")
}
result, err := git2go.ResolveCommand{
MergeCommand: git2go.MergeCommand{
Repository: repoPath,
AuthorName: string(header.User.Name),
AuthorMail: string(header.User.Email),
AuthorDate: authorDate,
Message: string(header.CommitMessage),
Ours: header.GetOurCommitOid(),
Theirs: header.GetTheirCommitOid(),
},
Resolutions: resolutions,
}.Run(stream.Context(), s.cfg)
if err != nil {
if errors.Is(err, git2go.ErrInvalidArgument) {
return helper.ErrInvalidArgument(err)
}
return err
}
commitOID, err := git.NewObjectIDFromHex(result.CommitID)
if err != nil {
return err
}
if err := sourceRepo.UpdateRef(
ctx,
git.ReferenceName("refs/heads/"+string(header.GetSourceBranch())),
commitOID,
"",
); err != nil {
return err
}
return nil
}
func sameRepo(left, right repository.GitRepo) bool {
lgaod := left.GetGitAlternateObjectDirectories()
rgaod := right.GetGitAlternateObjectDirectories()
if len(lgaod) != len(rgaod) {
return false
}
sort.Strings(lgaod)
sort.Strings(rgaod)
for i := 0; i < len(lgaod); i++ {
if lgaod[i] != rgaod[i] {
return false
}
}
if left.GetGitObjectDirectory() != right.GetGitObjectDirectory() {
return false
}
if left.GetRelativePath() != right.GetRelativePath() {
return false
}
if left.GetStorageName() != right.GetStorageName() {
return false
}
return true
}
// repoWithCommit ensures that the source repo contains the same commit we
// hope to merge with from the target branch, else it will be fetched from the
// target repo. This is necessary since all merge/resolve logic occurs on the
// same filesystem
func (s *server) repoWithBranchCommit(ctx context.Context, sourceRepo *localrepo.Repo, targetRepo *remoterepo.Repo, targetBranch []byte) error {
const peelCommit = "^{commit}"
targetRevision := "refs/heads/" + git.Revision(string(targetBranch)) + peelCommit
if sameRepo(sourceRepo, targetRepo) {
_, err := sourceRepo.ResolveRevision(ctx, targetRevision)
return err
}
oid, err := targetRepo.ResolveRevision(ctx, targetRevision)
if err != nil {
return fmt.Errorf("could not resolve target revision %q: %w", targetRevision, err)
}
ok, err := sourceRepo.HasRevision(ctx, git.Revision(oid)+peelCommit)
if err != nil {
return err
}
if ok {
// target branch commit already exists in source repo; nothing
// to do
return nil
}
env, err := gitalyssh.UploadPackEnv(ctx, s.cfg, &gitalypb.SSHUploadPackRequest{
Repository: targetRepo.Repository,
GitConfigOptions: []string{"uploadpack.allowAnySHA1InWant=true"},
})
if err != nil {
return err
}
var stderr bytes.Buffer
if err := sourceRepo.ExecAndWait(ctx,
git.SubCmd{
Name: "fetch",
Flags: []git.Option{git.Flag{Name: "--no-tags"}},
Args: []string{gitalyssh.GitalyInternalURL, oid.String()},
},
git.WithStderr(&stderr),
git.WithEnv(env...),
git.WithRefTxHook(ctx, sourceRepo, s.cfg),
); err != nil {
return fmt.Errorf("could not fetch target commit: %w, stderr: %q", err, stderr.String())
}
return nil
}
|