Skip to content

Git designed for AI agents.

gitai land: the conflict package for the agent in the SDK and the CLI (c1 WP6)

Federico Eliaad68d3725bc7
diff --git a/cmd/graft/backend.go b/cmd/graft/backend.go
index ebc181d..fb4d529 100644
--- a/cmd/graft/backend.go
+++ b/cmd/graft/backend.go
@@ -228,17 +228,25 @@ func (b *sdkBackend) Land(ctx context.Context, opts workspace.LandOptions) (work
return workspace.LandResult{}, err
}
- res, err := b.repo.Land(ctx, sdk.LandOptions{
+ lo := sdk.LandOptions{
Branch: opts.Branch,
Commit: opts.Commit,
User: b.user(opts.Committer.Name, opts.Committer.Email, false),
Strategy: strategy,
CreateBranch: opts.CreateBranch,
ResolveConflicts: opts.ResolveConflicts,
- })
+ }
+ if r := opts.Resolution; r != nil {
+ lo.Resolution = &sdk.Resolution{Tip: r.Tip, Commit: r.Commit}
+ for _, f := range r.Files {
+ lo.Resolution.Files = append(lo.Resolution.Files, sdk.ResolvedFile{Path: f.Path, Delete: f.Delete, Mode: f.Mode, Content: f.Content})
+ }
+ }
+ res, err := b.repo.Land(ctx, lo)
switch {
case sdk.IsMergeConflict(err):
- return workspace.LandResult{}, fmt.Errorf("%w: %s", workspace.ErrMergeConflict, status.Convert(err).Message())
+ // The gRPC error stays in the chain, so that the conflict package it carries can be read.
+ return workspace.LandResult{}, &landConflictError{msg: status.Convert(err).Message(), err: err}
case sdk.IsNotAncestor(err):
return workspace.LandResult{}, fmt.Errorf("%w: %s", workspace.ErrNotFastForward, status.Convert(err).Message())
case err != nil:
@@ -257,6 +265,22 @@ func (b *sdkBackend) Land(ctx context.Context, opts workspace.LandOptions) (work
}, nil
}
+// landConflictError is a land that failed on a merge conflict: it is workspace.ErrMergeConflict,
+// and it keeps the gRPC error of the land, whose conflict package sdk.LandConflict reads.
+type landConflictError struct {
+ msg string
+ err error
+}
+
+func (e *landConflictError) Error() string {
+ return workspace.ErrMergeConflict.Error() + ": " + e.msg
+}
+
+// Unwrap returns workspace.ErrMergeConflict and the gRPC error.
+func (e *landConflictError) Unwrap() []error {
+ return []error{workspace.ErrMergeConflict, e.err}
+}
+
// DeleteBranch implements workspace.Backend. The sdk has no branch deletion, so
// OperationService.UserDeleteBranch is called over a connection of the backend.
// It is the RPC that agents may call: the reference-transaction policy decides
diff --git a/cmd/graft/commands.go b/cmd/graft/commands.go
index d9f17b7..d53cb64 100644
--- a/cmd/graft/commands.go
+++ b/cmd/graft/commands.go
@@ -10,6 +10,7 @@ import (
"github.com/feder-cr/git-ai/internal/graft/changelog"
"github.com/feder-cr/git-ai/internal/graft/workspace"
+ "github.com/feder-cr/git-ai/sdk"
)
const (
@@ -165,13 +166,38 @@ func cmdLand(ctx context.Context, out io.Writer, o *options, args []string) erro
if err != nil {
return err
}
+ if o.conflictsDir != "" && !o.resolve {
+ return usagef("land --conflicts-dir requires --resolve")
+ }
+ if o.resolved != "" && (o.resolve || o.conflictsDir != "") {
+ return usagef("land --resolved takes neither --resolve nor --conflicts-dir")
+ }
ws, err := openWorkspace(ctx, o)
if err != nil {
return err
}
- res, err := ws.LandResolving(ctx, branch, o.strategy, committer, o.resolve)
+ var res workspace.LandResult
+ if o.resolved != "" {
+ resolution, rerr := readResolution(o.resolved)
+ if rerr != nil {
+ return rerr
+ }
+ res, err = ws.LandResolution(ctx, branch, committer, resolution)
+ } else {
+ res, err = ws.LandResolving(ctx, branch, o.strategy, committer, o.resolve)
+ }
warnSkipped(o, ws)
if err != nil {
+ // A land that asked for resolution fails with the conflict package.
+ if pkg, ok := sdk.LandConflict(err); ok {
+ printConflict(out, pkg)
+ if o.conflictsDir != "" {
+ if werr := writeConflicts(ctx, ws, pkg, o.conflictsDir); werr != nil {
+ return fmt.Errorf("%w (and writing the conflicts failed: %v)", err, werr)
+ }
+ fmt.Fprintf(out, "wrote the conflicts to %s: edit the files, then run graft land --resolved %s\n", o.conflictsDir, o.conflictsDir)
+ }
+ }
return err
}
if res.AlreadyLanded {
diff --git a/cmd/graft/conflicts.go b/cmd/graft/conflicts.go
new file mode 100644
index 0000000..843f420
--- /dev/null
+++ b/cmd/graft/conflicts.go
@@ -0,0 +1,191 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/feder-cr/git-ai/internal/graft/merge3"
+ "github.com/feder-cr/git-ai/internal/graft/workspace"
+ "github.com/feder-cr/git-ai/proto/go/gitalypb"
+)
+
+// The conflicts directory of graft land --conflicts-dir DIR holds, for every conflicting path:
+//
+// DIR/<path> the file as the merge leaves it, with git's diff3 conflict
+// markers around each conflict (or the tip's side when the
+// file is not text, or a side is absent)
+// DIR/.graft/sides/<path>.base the three sides
+// DIR/.graft/sides/<path>.ours
+// DIR/.graft/sides/<path>.theirs
+// DIR/.graft/conflict.json the conflict package
+//
+// graft land --resolved DIR lands the files of DIR as the resolution: a path whose file is present
+// is written, one whose file is absent is deleted.
+const (
+ conflictsMetaDir = ".graft"
+ conflictsPackage = "conflict.json"
+ conflictsSidesDir = "sides"
+)
+
+// printConflict describes a conflict package: the reason the server gave, and each file with its
+// outcome. The paths and reasons come from the server and are escaped with displayText.
+func printConflict(out io.Writer, c *gitalypb.LandConflict) {
+ fmt.Fprintf(out, "the land did not resolve %d conflicting files (tip %s, commit %s)\n", len(c.GetFiles()), shortOID(c.GetTip()), shortOID(c.GetCommit()))
+ if c.GetReason() != "" {
+ fmt.Fprintf(out, " %s\n", displayText(c.GetReason()))
+ }
+ for _, f := range c.GetFiles() {
+ outcome := strings.ToLower(strings.TrimPrefix(f.GetOutcome().String(), "OUTCOME_"))
+ line := fmt.Sprintf(" %s: %s", displayText(string(f.GetPath())), outcome)
+ if f.GetReason() != "" {
+ line += ": " + displayText(f.GetReason())
+ }
+ fmt.Fprintln(out, line)
+ }
+}
+
+// conflictPath returns the file of the conflicts directory for a conflicting path, refusing a
+// path that would leave the directory.
+func conflictPath(dir, p string) (string, error) {
+ if p == "" || path.IsAbs(p) || path.Clean(p) != p || p == ".." || strings.HasPrefix(p, "../") || p == conflictsMetaDir || strings.HasPrefix(p, conflictsMetaDir+"/") {
+ return "", fmt.Errorf("conflicting path %q cannot be written into the conflicts directory", p)
+ }
+ return filepath.Join(dir, filepath.FromSlash(p)), nil
+}
+
+// writeConflicts writes the conflicts directory of a conflict package (see the layout above).
+func writeConflicts(ctx context.Context, ws *workspace.Workspace, c *gitalypb.LandConflict, dir string) error {
+ var oids []string
+ for _, f := range c.GetFiles() {
+ for _, s := range []*gitalypb.LandConflictSide{f.GetBase(), f.GetOurs(), f.GetTheirs()} {
+ if s != nil {
+ oids = append(oids, s.GetOid())
+ }
+ }
+ }
+ blobs, err := ws.GetObjects(ctx, oids)
+ if err != nil {
+ return fmt.Errorf("reading the sides of the conflict: %w", err)
+ }
+ side := func(s *gitalypb.LandConflictSide) ([]byte, error) {
+ if s == nil {
+ return nil, nil
+ }
+ b, ok := blobs[s.GetOid()]
+ if !ok {
+ return nil, fmt.Errorf("side %s is missing from the server", s.GetOid())
+ }
+ if b == nil {
+ b = []byte{}
+ }
+ return b, nil
+ }
+
+ for _, f := range c.GetFiles() {
+ p := string(f.GetPath())
+ target, err := conflictPath(dir, p)
+ if err != nil {
+ return err
+ }
+ var contents [3][]byte
+ for i, s := range []*gitalypb.LandConflictSide{f.GetBase(), f.GetOurs(), f.GetTheirs()} {
+ if contents[i], err = side(s); err != nil {
+ return fmt.Errorf("%s: %w", p, err)
+ }
+ }
+ for i, ext := range []string{"base", "ours", "theirs"} {
+ if contents[i] == nil {
+ continue
+ }
+ sidePath := filepath.Join(dir, conflictsMetaDir, conflictsSidesDir, filepath.FromSlash(p)+"."+ext)
+ if err := writeFileAll(sidePath, contents[i]); err != nil {
+ return err
+ }
+ }
+ if err := writeFileAll(target, conflictFileContent(contents)); err != nil {
+ return err
+ }
+ }
+
+ raw, err := protojson.MarshalOptions{Multiline: true}.Marshal(c)
+ if err != nil {
+ return err
+ }
+ return writeFileAll(filepath.Join(dir, conflictsMetaDir, conflictsPackage), append(raw, '\n'))
+}
+
+// conflictFileContent is the file an agent edits: the merge with markers when both sides are text,
+// otherwise the tip's side (or the landed commit's when the tip deleted the file).
+func conflictFileContent(sides [3][]byte) []byte {
+ base, ours, theirs := sides[0], sides[1], sides[2]
+ text := ours != nil && theirs != nil && !isBinaryContent(base) && !isBinaryContent(ours) && !isBinaryContent(theirs)
+ if text {
+ if r, ok := merge3.Merge(base, ours, theirs); ok {
+ return r.WithMarkers(merge3.Labels{Ours: "ours (the branch tip)", Base: "base", Theirs: "theirs (the change)"})
+ }
+ }
+ if ours != nil {
+ return ours
+ }
+ return theirs
+}
+
+func isBinaryContent(b []byte) bool {
+ return bytes.IndexByte(b, 0) >= 0
+}
+
+func writeFileAll(p string, data []byte) error {
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ return err
+ }
+ return os.WriteFile(p, data, 0o644)
+}
+
+// readResolution reads the resolution of a conflicts directory: the package's tip and commit, and
+// for every conflicting path its file, or a deletion when the file is absent. The mode is the
+// tip's side's, else the landed commit's.
+func readResolution(dir string) (*workspace.Resolution, error) {
+ raw, err := os.ReadFile(filepath.Join(dir, conflictsMetaDir, conflictsPackage))
+ if err != nil {
+ return nil, fmt.Errorf("reading the conflict package of %s (written by graft land --conflicts-dir): %w", dir, err)
+ }
+ var c gitalypb.LandConflict
+ if err := protojson.Unmarshal(raw, &c); err != nil {
+ return nil, fmt.Errorf("%s: %w", filepath.Join(dir, conflictsMetaDir, conflictsPackage), err)
+ }
+ res := &workspace.Resolution{Tip: c.GetTip(), Commit: c.GetCommit()}
+ for _, f := range c.GetFiles() {
+ p := string(f.GetPath())
+ target, err := conflictPath(dir, p)
+ if err != nil {
+ return nil, err
+ }
+ content, err := os.ReadFile(target)
+ if errors.Is(err, fs.ErrNotExist) {
+ res.Files = append(res.Files, workspace.ResolvedFile{Path: p, Delete: true})
+ continue
+ }
+ if err != nil {
+ return nil, err
+ }
+ mode := f.GetOurs().GetMode()
+ if mode == "" {
+ mode = f.GetTheirs().GetMode()
+ }
+ if mode == "" {
+ mode = "100644"
+ }
+ res.Files = append(res.Files, workspace.ResolvedFile{Path: p, Mode: mode, Content: content})
+ }
+ return res, nil
+}
diff --git a/cmd/graft/conflicts_server_test.go b/cmd/graft/conflicts_server_test.go
new file mode 100644
index 0000000..451c0e4
--- /dev/null
+++ b/cmd/graft/conflicts_server_test.go
@@ -0,0 +1,86 @@
+package main
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/feder-cr/git-ai/internal/git/gittest"
+)
+
+// TestCLILandConflictsAndResolved drives the agent's way through a conflict the server does not
+// resolve (it has no resolver here): graft land --resolve --conflicts-dir writes the package, the
+// agent edits the file with the markers, and graft land --resolved lands it.
+func TestCLILandConflictsAndResolved(t *testing.T) {
+ env := startServer(t)
+ base := env.seedMain(t, map[string]string{"x.txt": "1\nbase\n3\n", "y.txt": "y\n"})
+
+ dir := filepath.Join(t.TempDir(), "ws")
+ code, _, stderr := runCLI(t, "clone", "-storage", env.storage, env.addr, env.relPath, dir)
+ require.Equal(t, exitOK, code, stderr)
+
+ // Another writer changes x.txt and y.txt on main; the local change edits x.txt too.
+ gittest.WriteCommit(t, env.cfg, env.repoPath,
+ gittest.WithTree(env.writeTree(t, map[string]string{"x.txt": "1\ntip\n3\n", "y.txt": "y2\n"})),
+ gittest.WithParents(base), gittest.WithBranch("main"))
+ require.NoError(t, os.WriteFile(filepath.Join(dir, "x.txt"), []byte("1\nlocal\n3\n"), 0o644))
+ code, _, stderr = runCLI(t, "commit", "-C", dir, "-author", "Dev <[email protected]>", "-m", "local x")
+ require.Equal(t, exitOK, code, stderr)
+
+ conflicts := filepath.Join(t.TempDir(), "conflicts")
+ code, stdout, stderr := runCLI(t, "land", "-C", dir, "-author", "Dev <[email protected]>", "-strategy", "merge", "-resolve", "-conflicts-dir", conflicts)
+ require.Equal(t, exitError, code, stdout)
+ require.Contains(t, stderr, "merge conflict")
+ require.Contains(t, stdout, "the land did not resolve 1 conflicting files")
+ require.Contains(t, stdout, "x.txt: not_attempted")
+ require.Contains(t, stdout, "conflict resolution is not enabled")
+ require.Contains(t, stdout, "graft land --resolved "+conflicts)
+
+ // The file to edit holds the merge with git's diff3 markers; the sides are beside it.
+ marked, err := os.ReadFile(filepath.Join(conflicts, "x.txt"))
+ require.NoError(t, err)
+ require.Equal(t, "1\n<<<<<<< ours (the branch tip)\ntip\n||||||| base\nbase\n=======\nlocal\n>>>>>>> theirs (the change)\n3\n", string(marked))
+ for side, want := range map[string]string{"base": "1\nbase\n3\n", "ours": "1\ntip\n3\n", "theirs": "1\nlocal\n3\n"} {
+ got, err := os.ReadFile(filepath.Join(conflicts, ".graft", "sides", "x.txt."+side))
+ require.NoError(t, err)
+ require.Equal(t, want, string(got), side)
+ }
+ require.FileExists(t, filepath.Join(conflicts, ".graft", "conflict.json"))
+
+ // The agent resolves the file and lands the resolution.
+ require.NoError(t, os.WriteFile(filepath.Join(conflicts, "x.txt"), []byte("1\ntip and local\n3\n"), 0o644))
+ code, stdout, stderr = runCLI(t, "land", "-C", dir, "-author", "Dev <[email protected]>", "-resolved", conflicts)
+ require.Equal(t, exitOK, code, stderr)
+ require.Contains(t, stdout, "landed at ")
+ require.Contains(t, stdout, "(resolved 1 conflicting files: x.txt)")
+
+ code, stdout, _ = runCLI(t, "cat", "-C", dir, "main:x.txt")
+ require.Equal(t, exitOK, code)
+ require.Equal(t, "1\ntip and local\n3\n", stdout)
+ code, stdout, _ = runCLI(t, "cat", "-C", dir, "main:y.txt")
+ require.Equal(t, exitOK, code)
+ require.Equal(t, "y2\n", stdout, "the other writer's change is kept")
+ code, stdout, _ = runCLI(t, "show", "-C", dir, "-json", "main")
+ require.Equal(t, exitOK, code)
+ var shown struct {
+ Trailers map[string][]string `json:"trailers"`
+ }
+ require.NoError(t, json.Unmarshal([]byte(stdout), &shown), stdout)
+ require.Equal(t, []string{"agent"}, shown.Trailers["Graft-Resolved-By"])
+ require.Equal(t, []string{"x.txt"}, shown.Trailers["Graft-Resolved-Path"])
+ require.NotContains(t, shown.Trailers, "Graft-Checked-By", "no resolver checked it")
+}
+
+func TestCLILandConflictFlagsAreChecked(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "ws")
+ code, _, stderr := runCLI(t, "land", "-C", dir, "-conflicts-dir", "x")
+ require.Equal(t, exitUsage, code)
+ require.Contains(t, stderr, "--conflicts-dir requires --resolve")
+
+ code, _, stderr = runCLI(t, "land", "-C", dir, "-resolved", "x", "-resolve")
+ require.Equal(t, exitUsage, code)
+ require.Contains(t, stderr, "--resolved takes neither")
+}
diff --git a/cmd/graft/main.go b/cmd/graft/main.go
index e5461f8..bd2772c 100644
--- a/cmd/graft/main.go
+++ b/cmd/graft/main.go
@@ -40,23 +40,27 @@ var backendFactory = dialBackend
// options holds the flags and environment shared by all commands.
type options struct {
- address string
- token string
- storage string
- user string
- author string
- dir string
- branch string
- sparse string
- message string
- land string
- abort bool
- resolve bool
- strategy string
- revision string
- after uint64
- limit int
- jsonOut bool
+ address string
+ token string
+ storage string
+ user string
+ author string
+ dir string
+ branch string
+ sparse string
+ message string
+ land string
+ abort bool
+ resolve bool
+ // conflictsDir and resolved are the directories of graft land --conflicts-dir and
+ // --resolved.
+ conflictsDir string
+ resolved string
+ strategy string
+ revision string
+ after uint64
+ limit int
+ jsonOut bool
// stderr receives warnings of commands that succeed.
stderr io.Writer
}
@@ -223,6 +227,8 @@ func bindLand(fs *flag.FlagSet, o *options) {
fs.StringVar(&o.strategy, "strategy", workspace.StrategyRebase, "land strategy: rebase, merge or ff_only")
fs.BoolVar(&o.abort, "abort", false, "drop the pending commit without landing it")
fs.BoolVar(&o.resolve, "resolve", false, "let the server resolve merge conflicts")
+ fs.StringVar(&o.conflictsDir, "conflicts-dir", "", "with --resolve: write the conflicts the server did not resolve into this directory")
+ fs.StringVar(&o.resolved, "resolved", "", "land the resolution in this directory (written by --conflicts-dir, then edited)")
}
func bindLog(fs *flag.FlagSet, o *options) {
@@ -253,7 +259,8 @@ commands:
status list local changes
diff show line changes against the base commit
commit -m MSG commit local changes (--land BRANCH to land them, --resolve for conflicts)
- land [BRANCH] land the pending commit (--strategy, --resolve; --abort drops it)
+ land [BRANCH] land the pending commit (--strategy, --resolve [--conflicts-dir DIR],
+ --resolved DIR; --abort drops it)
revert [PATH...] discard local changes to PATHs (default: all) and restore them
update move the workspace to the tip of its branch
sparse [PREFIX...] restrict the workspace to PREFIX paths
diff --git a/doc/graft/RESOLVE.md b/doc/graft/RESOLVE.md
index 7094526..5dd4e2f 100644
--- a/doc/graft/RESOLVE.md
+++ b/doc/graft/RESOLVE.md
@@ -58,10 +58,23 @@ actors = ["builder", "planner"]
A client asks for resolution per call:
- SDK: `LandOptions.ResolveConflicts`, and `LandResult` reports the
- resolved paths and the resolver name.
+ resolved paths and the resolver name. On a conflict the server did not
+ resolve, `sdk.LandConflict(err)` returns the conflict package,
+ `Repo.ConflictSides` reads the sides, and `LandOptions.Resolution`
+ (start from `sdk.ResolutionFor`) lands the agent's resolution. `Land`
+ refuses a resolution whose request exceeds `sdk.MaxLandRequestBytes`
+ (4 MiB) before sending it.
- CLI: `graft land --resolve`, `graft commit --land BRANCH --resolve`.
+ `graft land --resolve` prints the package when the land fails, and with
+ `--conflicts-dir DIR` writes it: `DIR/<path>` is the merge with git's
+ diff3 markers (the clean changes of both sides applied), the sides are in
+ `DIR/.graft/sides/<path>.base|.ours|.theirs`, the package in
+ `DIR/.graft/conflict.json`. Edit the files, then `graft land --resolved DIR`
+ lands them: a present file is written (with the tip side's mode), an absent
+ one is deleted.
- RPC: `UserLandRequest.resolve_conflicts` (field 10). The response carries
- `resolved_paths` (field 7) and `resolver` (field 8).
+ `resolved_paths` (field 7) and `resolver` (field 8). The re-land is
+ `UserLandRequest.resolution` (field 11).
## Flow
diff --git a/internal/gitaly/service/operations/land_hunks.go b/internal/gitaly/service/operations/land_hunks.go
index 1e59197..894faf9 100644
--- a/internal/gitaly/service/operations/land_hunks.go
+++ b/internal/gitaly/service/operations/land_hunks.go
@@ -1,186 +1,31 @@
package operations
import (
- "bytes"
- "sort"
-
+ "github.com/feder-cr/git-ai/internal/graft/merge3"
"github.com/feder-cr/git-ai/proto/go/gitalypb"
)
-// landHunkMaxCells bounds the table of the line diff of one side against the base (the changed
-// middle of the files, after the common prefix and suffix): about 2800 changed lines on each side.
-// A file whose diff is larger gets no hunks in the conflict package; the agent still has its sides.
-const landHunkMaxCells = 8 << 20
-
-// landLineEdit replaces the base lines [start, end) with n lines of a side.
-type landLineEdit struct {
- start, end int
- n int
-}
-
-// landConflictHunks returns the conflicting regions of a three-way merge of base, ours and theirs,
-// as line ranges of each side (LandConflictHunk). A region is the union of the base lines that one
-// or both sides changed, where edits that touch or overlap are one region; it conflicts when both
-// sides changed it, differently. Each range counts the lines of its own side, 1-based and
-// half-open. It returns nil when a diff exceeds landHunkMaxCells.
+// landConflictHunks returns the conflicting regions of a three-way merge of base, ours and theirs
+// (merge3) as the hunks of the conflict package: line ranges of each side, 1-based and half-open,
+// each counting the lines of its own side. It returns nil when a diff exceeds merge3.MaxCells; the
+// agent still has the sides.
func landConflictHunks(base, ours, theirs []byte) []*gitalypb.LandConflictHunk {
- b, o, t := landSplitLines(base), landSplitLines(ours), landSplitLines(theirs)
- oursEdits, ok := landLineDiff(b, o)
+ result, ok := merge3.Merge(base, ours, theirs)
if !ok {
return nil
}
- theirsEdits, ok := landLineDiff(b, t)
- if !ok {
- return nil
- }
-
- type sideEdit struct {
- landLineEdit
- theirs bool
- }
- all := make([]sideEdit, 0, len(oursEdits)+len(theirsEdits))
- for _, e := range oursEdits {
- all = append(all, sideEdit{landLineEdit: e})
- }
- for _, e := range theirsEdits {
- all = append(all, sideEdit{landLineEdit: e, theirs: true})
- }
- sort.SliceStable(all, func(i, j int) bool {
- if all[i].start != all[j].start {
- return all[i].start < all[j].start
- }
- return all[i].end < all[j].end
- })
-
var hunks []*gitalypb.LandConflictHunk
- // delta is, per side, the lines added minus the lines removed by the edits before the region,
- // which maps a base line to the line of that side.
- var oursDelta, theirsDelta int
- for i := 0; i < len(all); {
- start, end := all[i].start, all[i].end
- j := i
- var oursLines, theirsLines int
- var oursChanged, theirsChanged bool
- var oursCovered, theirsCovered int // base lines replaced by each side's edits in the region
- for ; j < len(all) && (j == i || all[j].start <= end); j++ {
- e := all[j]
- end = max(end, e.end)
- if e.theirs {
- theirsChanged = true
- theirsLines += e.n
- theirsCovered += e.end - e.start
- } else {
- oursChanged = true
- oursLines += e.n
- oursCovered += e.end - e.start
- }
- }
- // A side's text of the region is its edits plus the base lines of the region it kept.
- oursLen := oursLines + (end - start) - oursCovered
- theirsLen := theirsLines + (end - start) - theirsCovered
-
- if oursChanged && theirsChanged && !landSameText(b, o, t, start, end, oursDelta, theirsDelta, oursLen, theirsLen) {
- hunks = append(hunks, &gitalypb.LandConflictHunk{
- Base: landRange(start, end),
- Ours: landRange(start+oursDelta, start+oursDelta+oursLen),
- Theirs: landRange(start+theirsDelta, start+theirsDelta+theirsLen),
- })
- }
- oursDelta += oursLen - (end - start)
- theirsDelta += theirsLen - (end - start)
- i = j
+ for _, h := range result.Hunks() {
+ hunks = append(hunks, &gitalypb.LandConflictHunk{
+ Base: landRange(h.Base),
+ Ours: landRange(h.Ours),
+ Theirs: landRange(h.Theirs),
+ })
}
return hunks
}
-// landSameText reports whether both sides wrote the same lines into the region, which is a clean
-// region and not a conflict.
-func landSameText(b, o, t [][]byte, start, end, oursDelta, theirsDelta, oursLen, theirsLen int) bool {
- if oursLen != theirsLen {
- return false
- }
- for k := 0; k < oursLen; k++ {
- if !bytes.Equal(o[start+oursDelta+k], t[start+theirsDelta+k]) {
- return false
- }
- }
- return true
-}
-
-// landRange returns the 1-based half-open range of the 0-based lines [start, end).
-func landRange(start, end int) *gitalypb.LineRange {
- return &gitalypb.LineRange{Start: uint32(start + 1), End: uint32(end + 1)}
-}
-
-// landSplitLines splits b into lines that keep their terminator.
-func landSplitLines(b []byte) [][]byte {
- if len(b) == 0 {
- return nil
- }
- parts := bytes.SplitAfter(b, []byte("\n"))
- if len(parts[len(parts)-1]) == 0 {
- parts = parts[:len(parts)-1]
- }
- return parts
-}
-
-// landLineDiff returns the line edits that turn a into b, from a longest common subsequence of the
-// lines after the common prefix and suffix. It returns false when the table would exceed
-// landHunkMaxCells.
-func landLineDiff(a, b [][]byte) ([]landLineEdit, bool) {
- pre := 0
- for pre < len(a) && pre < len(b) && bytes.Equal(a[pre], b[pre]) {
- pre++
- }
- suf := 0
- for suf < len(a)-pre && suf < len(b)-pre && bytes.Equal(a[len(a)-1-suf], b[len(b)-1-suf]) {
- suf++
- }
- am, bm := a[pre:len(a)-suf], b[pre:len(b)-suf]
- n, m := len(am), len(bm)
- if n == 0 && m == 0 {
- return nil, true
- }
- w := m + 1
- if (n+1)*w > landHunkMaxCells {
- return nil, false
- }
-
- // lcs[i*w+j] is the LCS length of am[i:] and bm[j:].
- lcs := make([]int32, (n+1)*w)
- for i := n - 1; i >= 0; i-- {
- for j := m - 1; j >= 0; j-- {
- switch {
- case bytes.Equal(am[i], bm[j]):
- lcs[i*w+j] = lcs[(i+1)*w+j+1] + 1
- case lcs[(i+1)*w+j] >= lcs[i*w+j+1]:
- lcs[i*w+j] = lcs[(i+1)*w+j]
- default:
- lcs[i*w+j] = lcs[i*w+j+1]
- }
- }
- }
-
- var edits []landLineEdit
- cur := -1
- for i, j := 0, 0; i < n || j < m; {
- if i < n && j < m && bytes.Equal(am[i], bm[j]) {
- cur = -1
- i++
- j++
- continue
- }
- if cur < 0 {
- edits = append(edits, landLineEdit{start: pre + i, end: pre + i})
- cur = len(edits) - 1
- }
- if i < n && (j == m || lcs[(i+1)*w+j] >= lcs[i*w+j+1]) {
- i++
- edits[cur].end = pre + i
- } else {
- edits[cur].n++
- j++
- }
- }
- return edits, true
+// landRange returns the 1-based half-open range of the 0-based range r.
+func landRange(r merge3.Range) *gitalypb.LineRange {
+ return &gitalypb.LineRange{Start: uint32(r.Start + 1), End: uint32(r.End + 1)}
}
diff --git a/internal/gitaly/service/operations/land_package.go b/internal/gitaly/service/operations/land_package.go
index da99f2c..03c9dba 100644
--- a/internal/gitaly/service/operations/land_package.go
+++ b/internal/gitaly/service/operations/land_package.go
@@ -48,6 +48,8 @@ type landFileState struct {
read bool
outcome gitalypb.LandConflictFile_Outcome
reason string
+ // syntaxUnchecked is set when a check accepted the file without a syntax verdict.
+ syntaxUnchecked bool
}
// sent reports whether the file is sent to the resolver.
@@ -152,13 +154,14 @@ func landPackage(tip, commitID, base git.ObjectID, tipMessage, commitMessage str
break
}
pf := &gitalypb.LandConflictFile{
- Path: []byte(f.conflict.path),
- Kind: landKindProto(f.kind),
- Base: landSideProto(f.conflict.base),
- Ours: landSideProto(f.conflict.ours),
- Theirs: landSideProto(f.conflict.theirs),
- Outcome: f.outcome,
- Reason: landCutString(f.reason, landPackageReasonBytes),
+ Path: []byte(f.conflict.path),
+ Kind: landKindProto(f.kind),
+ Base: landSideProto(f.conflict.base),
+ Ours: landSideProto(f.conflict.ours),
+ Theirs: landSideProto(f.conflict.theirs),
+ Outcome: f.outcome,
+ Reason: landCutString(f.reason, landPackageReasonBytes),
+ SyntaxUnchecked: f.syntaxUnchecked,
}
if f.textRead() && (f.kind == resolver.KindContent || f.kind == resolver.KindAddAdd) {
pf.Hunks = landConflictHunks(f.sides[0], f.sides[1], f.sides[2])
diff --git a/internal/gitaly/service/operations/land_package_test.go b/internal/gitaly/service/operations/land_package_test.go
index cd03967..d9b72b5 100644
--- a/internal/gitaly/service/operations/land_package_test.go
+++ b/internal/gitaly/service/operations/land_package_test.go
@@ -203,6 +203,8 @@ func TestUserLand_conflictPackage(t *testing.T) {
require.Contains(t, pkg.GetReason(), "not enabled")
for _, f := range pkg.GetFiles() {
require.Equal(t, gitalypb.LandConflictFile_OUTCOME_NOT_ATTEMPTED, f.GetOutcome())
+ // The agent gets the hunks even though no file was read for a resolver.
+ require.Len(t, f.GetHunks(), 1, string(f.GetPath()))
}
})
@@ -288,7 +290,7 @@ func TestUserLand_reland(t *testing.T) {
dir, argv := resolverScript(t, "")
writeRawAnswer(t, dir, resolver.CheckResponse{
Version: resolver.ProtocolVersion, Operation: resolver.OperationCheck, Resolver: "graft-resolve",
- Files: []resolver.CheckFile{{Path: "a", OK: true, Syntax: resolver.SyntaxNone}, {Path: "b", OK: false, Reason: "check failed: tests", Syntax: resolver.SyntaxNone}},
+ Files: []resolver.CheckFile{{Path: "a", OK: true, Syntax: resolver.SyntaxUnchecked}, {Path: "b", OK: false, Reason: "check failed: tests", Syntax: resolver.SyntaxNone}},
})
fx := newResolveFixture(t, enabledResolver(argv))
req := fx.request("Land")
@@ -298,7 +300,9 @@ func TestUserLand_reland(t *testing.T) {
requireMergeConflict(t, err)
pkg := landConflictDetail(err)
require.NotNil(t, pkg)
- require.Equal(t, gitalypb.LandConflictFile_OUTCOME_RESOLVED, packageFile(t, pkg, "a").GetOutcome())
+ a := packageFile(t, pkg, "a")
+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_RESOLVED, a.GetOutcome())
+ require.True(t, a.GetSyntaxUnchecked(), "a passed without a syntax verdict, and the package says so")
b := packageFile(t, pkg, "b")
require.Equal(t, gitalypb.LandConflictFile_OUTCOME_REJECTED, b.GetOutcome())
require.Equal(t, "check failed: tests", b.GetReason())
diff --git a/internal/gitaly/service/operations/land_reland.go b/internal/gitaly/service/operations/land_reland.go
index 1a0e4a7..a281769 100644
--- a/internal/gitaly/service/operations/land_reland.go
+++ b/internal/gitaly/service/operations/land_reland.go
@@ -56,7 +56,7 @@ func (s *Server) landWithResolution(
return landResolution{}, structerr.NewInvalidArgument("resolution is for commit %q, not commit_id %q", r.GetCommit(), commitID)
}
- l, err := landListConflicts(ctx, repo, tip, commitID)
+ l, err := landListConflicts(ctx, repo, tip, commitID, s.resolveCfg.MaxFileBytesOrDefault())
if errors.Is(err, errLandNoConflicts) {
return landResolution{}, structerr.NewFailedPrecondition("the merge of tip %s and commit %s has no conflicts, so there is nothing to resolve: land without a resolution", tip, commitID)
}
@@ -65,15 +65,15 @@ func (s *Server) landWithResolution(
}
maxFiles := s.resolveCfg.MaxFilesOrDefault()
if r.GetTip() != tip.String() {
- return landResolution{}, l.notAttempted(maxFiles, fmt.Sprintf("the branch tip moved from %s to %s since the resolution was made: resolve the conflicts of this package", r.GetTip(), tip), nil)
+ return landResolution{}, l.notAttempted(ctx, maxFiles, fmt.Sprintf("the branch tip moved from %s to %s since the resolution was made: resolve the conflicts of this package", r.GetTip(), tip), nil)
}
if l.bases > 1 {
- return landResolution{}, l.notAttempted(maxFiles, fmt.Sprintf("the change has %d merge bases (a criss-cross history), which are not resolved", l.bases), nil)
+ return landResolution{}, l.notAttempted(ctx, maxFiles, fmt.Sprintf("the change has %d merge bases (a criss-cross history), which are not resolved", l.bases), nil)
}
resolved, reason := landResolutionFiles(r, l.files)
if reason != "" {
- return landResolution{}, l.notAttempted(maxFiles, reason, nil)
+ return landResolution{}, l.notAttempted(ctx, maxFiles, reason, nil)
}
maxBytes := s.resolveCfg.MaxFileBytesOrDefault()
@@ -103,7 +103,7 @@ func (s *Server) landWithResolution(
f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_RESOLVED, ""
}
}
- return landResolution{}, l.unresolved(maxFiles, "", "the resolution was rejected: "+landUnresolvedCause(l.files), nil)
+ return landResolution{}, l.unresolved(ctx, maxFiles, "", "the resolution was rejected: "+landUnresolvedCause(l.files), nil)
}
resp := &resolver.Response{Version: resolver.ProtocolVersion, Resolver: landAgentResolver(actor)}
@@ -209,10 +209,10 @@ func (s *Server) landCheckResolution(
maxFiles := s.resolveCfg.MaxFilesOrDefault()
resp, err := s.conflictResolver.Check(ctx, req)
if err != nil {
- return "", l.notAttempted(maxFiles, fmt.Sprintf("the resolution could not be checked: %v", err), err)
+ return "", l.notAttempted(ctx, maxFiles, fmt.Sprintf("the resolution could not be checked: %v", err), err)
}
if !landResolverNameValid(resp.Resolver) {
- return "", l.notAttempted(maxFiles, fmt.Sprintf("the resolution could not be checked: the check names an invalid resolver %q", resp.Resolver), nil)
+ return "", l.notAttempted(ctx, maxFiles, fmt.Sprintf("the resolution could not be checked: the check names an invalid resolver %q", resp.Resolver), nil)
}
syntaxUnchecked := 0
for i, v := range resp.Files {
@@ -222,6 +222,7 @@ func (s *Server) landCheckResolution(
continue
}
if v.Syntax == resolver.SyntaxUnchecked {
+ f.syntaxUnchecked = true
syntaxUnchecked++
}
}
diff --git a/internal/gitaly/service/operations/land_resolve.go b/internal/gitaly/service/operations/land_resolve.go
index 6a19124..975afc8 100644
--- a/internal/gitaly/service/operations/land_resolve.go
+++ b/internal/gitaly/service/operations/land_resolve.go
@@ -78,14 +78,14 @@ func (s *Server) resolveLandConflicts(
tip, commitID git.ObjectID,
committer git.Signature,
) (landResolution, error) {
- l, err := landListConflicts(ctx, repo, tip, commitID)
+ l, err := landListConflicts(ctx, repo, tip, commitID, s.resolveCfg.MaxFileBytesOrDefault())
if err != nil {
return landResolution{}, err
}
base, hasBase, conflicts, files := l.base, l.hasBase, l.conflicts, l.files
tipMessage, commitMessage := l.tipMessage, l.commitMessage
maxFiles := s.resolveCfg.MaxFilesOrDefault()
- notAttempted := func(reason string) error { return l.notAttempted(maxFiles, reason, nil) }
+ notAttempted := func(reason string) error { return l.notAttempted(ctx, maxFiles, reason, nil) }
criss := l.bases
// The actor is the authenticated identity only. The name in the request is chosen by the
@@ -154,7 +154,7 @@ func (s *Server) resolveLandConflicts(
for _, f := range files {
if f.outcome != gitalypb.LandConflictFile_OUTCOME_RESOLVED {
- return landResolution{}, l.unresolved(maxFiles, "", landUnresolvedCause(files), resolveErr)
+ return landResolution{}, l.unresolved(ctx, maxFiles, "", landUnresolvedCause(files), resolveErr)
}
}
@@ -164,6 +164,8 @@ func (s *Server) resolveLandConflicts(
// landListing is the conflicting files of the merge of a tip and a change, with what the conflict
// package needs.
type landListing struct {
+ repo *localrepo.Repo
+ maxFileBytes int64
tip, commitID git.ObjectID
base git.ObjectID
hasBase bool
@@ -182,8 +184,8 @@ var errLandNoConflicts = errors.New("the merge of the tip and the change reports
// error: when rebasing, the conflict may come from an intermediate commit that a later commit of
// the change undoes, so the merge of the two ends is clean and the landing reports the merge
// conflict. This is a documented limitation.
-func landListConflicts(ctx context.Context, repo *localrepo.Repo, tip, commitID git.ObjectID) (landListing, error) {
- l := landListing{tip: tip, commitID: commitID}
+func landListConflicts(ctx context.Context, repo *localrepo.Repo, tip, commitID git.ObjectID, maxFileBytes int64) (landListing, error) {
+ l := landListing{repo: repo, maxFileBytes: maxFileBytes, tip: tip, commitID: commitID}
var err error
if l.base, l.hasBase, l.bases, err = landMergeBase(ctx, repo, tip, commitID); err != nil {
return l, err
@@ -207,8 +209,12 @@ func landListConflicts(ctx context.Context, repo *localrepo.Repo, tip, commitID
}
// unresolved returns the error of a land left unresolved, with its conflict package. err is the
-// error of the resolver or of the check that caused it, if any.
-func (l landListing) unresolved(maxFiles int, reason, cause string, err error) error {
+// error of the resolver or of the check that caused it, if any. The sides that the hunks of the
+// package need and that were not read yet are read here, whatever the outcome of the file.
+func (l landListing) unresolved(ctx context.Context, maxFiles int, reason, cause string, err error) error {
+ if readErr := l.readForHunks(ctx, maxFiles); readErr != nil {
+ return readErr
+ }
return &landUnresolvedError{
pkg: landPackage(l.tip, l.commitID, l.base, l.tipMessage, l.commitMessage, l.files, maxFiles, reason),
cause: cause,
@@ -216,13 +222,51 @@ func (l landListing) unresolved(maxFiles int, reason, cause string, err error) e
}
}
+// readForHunks reads the sides of the content and add/add conflicts of the package that are not
+// read yet and fit max_file_bytes, so that the package has their hunks. A larger side is not read:
+// its file gets no hunks, as a diff of that size is not computed anyway.
+func (l landListing) readForHunks(ctx context.Context, maxFiles int) error {
+ for i, f := range l.files {
+ if i == maxFiles {
+ break
+ }
+ if f.read || (f.kind != resolver.KindContent && f.kind != resolver.KindAddAdd) {
+ continue
+ }
+ var sides [3][]byte
+ fits := true
+ for j, b := range []*landBlob{f.conflict.base, f.conflict.ours, f.conflict.theirs} {
+ if b == nil {
+ continue
+ }
+ info, err := l.repo.ReadObjectInfo(ctx, b.oid.Revision())
+ if err != nil {
+ return fmt.Errorf("reading size of %q: %w", f.conflict.path, err)
+ }
+ if info.Size > l.maxFileBytes {
+ fits = false
+ break
+ }
+ content, err := l.repo.ReadObject(ctx, b.oid)
+ if err != nil {
+ return fmt.Errorf("reading blob of %q: %w", f.conflict.path, err)
+ }
+ sides[j] = content
+ }
+ if fits {
+ f.sides, f.read = sides, true
+ }
+ }
+ return nil
+}
+
// notAttempted returns the error of a land the server did not try to resolve at all, every file
// NOT_ATTEMPTED and the package carrying the reason.
-func (l landListing) notAttempted(maxFiles int, reason string, err error) error {
+func (l landListing) notAttempted(ctx context.Context, maxFiles int, reason string, err error) error {
for _, f := range l.files {
f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_NOT_ATTEMPTED, ""
}
- return l.unresolved(maxFiles, reason, reason, err)
+ return l.unresolved(ctx, maxFiles, reason, reason, err)
}
// landRequestFile is the file of the resolve request for a classified file that is sent.
diff --git a/internal/graft/merge3/merge3.go b/internal/graft/merge3/merge3.go
new file mode 100644
index 0000000..0c24f37
--- /dev/null
+++ b/internal/graft/merge3/merge3.go
@@ -0,0 +1,268 @@
+// Package merge3 is a three-way merge of text by lines. It finds the regions where the two sides
+// changed the base, merges the regions where only one side changed it (or both the same way), and
+// reports the others as conflicts: as line ranges of each side (the hunks of the conflict package)
+// or as a file with git's conflict markers around them.
+//
+// It is the merge of the conflict package of UserLand: the server computes the hunks with it, and
+// the SDK the file with markers that an agent edits, from the sides it reads by object ID.
+package merge3
+
+import (
+ "bytes"
+ "sort"
+)
+
+// MaxCells bounds the table of the line diff of one side against the base (the changed middle of
+// the files, after the common prefix and suffix): about 2800 changed lines on each side. Merge of
+// files whose diff is larger fails.
+const MaxCells = 8 << 20
+
+// Range is a half-open range of 0-based lines of one side, [Start, End).
+type Range struct {
+ Start, End int
+}
+
+// Hunk is a conflicting region as a line range of each side. Each range counts the lines of the
+// side it names; an empty range is an insertion point before line Start.
+type Hunk struct {
+ Base, Ours, Theirs Range
+}
+
+// region is a stretch of the base that one or both sides changed.
+type region struct {
+ base, ours, theirs Range
+ // changedOurs and changedTheirs say which sides changed it.
+ changedOurs, changedTheirs bool
+ // conflict is set when both sides changed it, differently.
+ conflict bool
+}
+
+// Result is the merge of three versions of a text.
+type Result struct {
+ base, ours, theirs [][]byte
+ regions []region
+}
+
+// Merge merges ours and theirs, both changed from base. An absent base (an add/add conflict) is
+// empty. It returns false when a diff exceeds MaxCells.
+func Merge(base, ours, theirs []byte) (*Result, bool) {
+ r := &Result{base: SplitLines(base), ours: SplitLines(ours), theirs: SplitLines(theirs)}
+ oursEdits, ok := lineDiff(r.base, r.ours)
+ if !ok {
+ return nil, false
+ }
+ theirsEdits, ok := lineDiff(r.base, r.theirs)
+ if !ok {
+ return nil, false
+ }
+
+ type sideEdit struct {
+ edit
+ theirs bool
+ }
+ all := make([]sideEdit, 0, len(oursEdits)+len(theirsEdits))
+ for _, e := range oursEdits {
+ all = append(all, sideEdit{edit: e})
+ }
+ for _, e := range theirsEdits {
+ all = append(all, sideEdit{edit: e, theirs: true})
+ }
+ sort.SliceStable(all, func(i, j int) bool {
+ if all[i].start != all[j].start {
+ return all[i].start < all[j].start
+ }
+ return all[i].end < all[j].end
+ })
+
+ // delta is, per side, the lines added minus the lines removed by the edits before the region,
+ // which maps a base line to the line of that side.
+ var oursDelta, theirsDelta int
+ for i := 0; i < len(all); {
+ start, end := all[i].start, all[i].end
+ j := i
+ var oursLines, theirsLines, oursCovered, theirsCovered int
+ var changedOurs, changedTheirs bool
+ // Edits that touch or overlap are one region.
+ for ; j < len(all) && (j == i || all[j].start <= end); j++ {
+ e := all[j]
+ end = max(end, e.end)
+ if e.theirs {
+ changedTheirs = true
+ theirsLines += e.n
+ theirsCovered += e.end - e.start
+ } else {
+ changedOurs = true
+ oursLines += e.n
+ oursCovered += e.end - e.start
+ }
+ }
+ // A side's text of the region is its edits plus the base lines of the region it kept.
+ oursLen := oursLines + (end - start) - oursCovered
+ theirsLen := theirsLines + (end - start) - theirsCovered
+ reg := region{
+ base: Range{start, end},
+ ours: Range{start + oursDelta, start + oursDelta + oursLen},
+ theirs: Range{start + theirsDelta, start + theirsDelta + theirsLen},
+ changedOurs: changedOurs, changedTheirs: changedTheirs,
+ }
+ reg.conflict = changedOurs && changedTheirs && !sameLines(r.ours[reg.ours.Start:reg.ours.End], r.theirs[reg.theirs.Start:reg.theirs.End])
+ r.regions = append(r.regions, reg)
+ oursDelta += oursLen - (end - start)
+ theirsDelta += theirsLen - (end - start)
+ i = j
+ }
+ return r, true
+}
+
+// Hunks returns the conflicting regions, in order.
+func (r *Result) Hunks() []Hunk {
+ var hunks []Hunk
+ for _, reg := range r.regions {
+ if reg.conflict {
+ hunks = append(hunks, Hunk{Base: reg.base, Ours: reg.ours, Theirs: reg.theirs})
+ }
+ }
+ return hunks
+}
+
+// Labels name the sides in the conflict markers.
+type Labels struct {
+ Ours, Base, Theirs string
+}
+
+// WithMarkers returns the merged text: the regions that only one side changed (or both the same
+// way) take that change, and every conflicting region is written between git's diff3 conflict
+// markers, "<<<<<<< ours", "||||||| base", "=======" and ">>>>>>> theirs", followed by the labels.
+// A side of a conflict that does not end with a newline gets one before the next marker.
+func (r *Result) WithMarkers(l Labels) []byte {
+ var out bytes.Buffer
+ pos := 0
+ write := func(lines [][]byte) {
+ for _, line := range lines {
+ out.Write(line)
+ }
+ }
+ writeSide := func(lines [][]byte) {
+ write(lines)
+ if out.Len() > 0 && out.Bytes()[out.Len()-1] != '\n' {
+ out.WriteByte('\n')
+ }
+ }
+ marker := func(m, label string) {
+ out.WriteString(m)
+ if label != "" {
+ out.WriteString(" " + label)
+ }
+ out.WriteByte('\n')
+ }
+ for _, reg := range r.regions {
+ write(r.base[pos:reg.base.Start])
+ pos = reg.base.End
+ switch {
+ case reg.conflict:
+ marker("<<<<<<<", l.Ours)
+ writeSide(r.ours[reg.ours.Start:reg.ours.End])
+ marker("|||||||", l.Base)
+ writeSide(r.base[reg.base.Start:reg.base.End])
+ marker("=======", "")
+ writeSide(r.theirs[reg.theirs.Start:reg.theirs.End])
+ marker(">>>>>>>", l.Theirs)
+ case reg.changedOurs:
+ write(r.ours[reg.ours.Start:reg.ours.End])
+ default:
+ write(r.theirs[reg.theirs.Start:reg.theirs.End])
+ }
+ }
+ write(r.base[pos:])
+ return out.Bytes()
+}
+
+func sameLines(a, b [][]byte) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if !bytes.Equal(a[i], b[i]) {
+ return false
+ }
+ }
+ return true
+}
+
+// SplitLines splits b into lines that keep their terminator.
+func SplitLines(b []byte) [][]byte {
+ if len(b) == 0 {
+ return nil
+ }
+ parts := bytes.SplitAfter(b, []byte("\n"))
+ if len(parts[len(parts)-1]) == 0 {
+ parts = parts[:len(parts)-1]
+ }
+ return parts
+}
+
+// edit replaces the base lines [start, end) with n lines of a side.
+type edit struct {
+ start, end int
+ n int
+}
+
+// lineDiff returns the line edits that turn a into b, from a longest common subsequence of the
+// lines after the common prefix and suffix. It returns false when the table would exceed MaxCells.
+func lineDiff(a, b [][]byte) ([]edit, bool) {
+ pre := 0
+ for pre < len(a) && pre < len(b) && bytes.Equal(a[pre], b[pre]) {
+ pre++
+ }
+ suf := 0
+ for suf < len(a)-pre && suf < len(b)-pre && bytes.Equal(a[len(a)-1-suf], b[len(b)-1-suf]) {
+ suf++
+ }
+ am, bm := a[pre:len(a)-suf], b[pre:len(b)-suf]
+ n, m := len(am), len(bm)
+ if n == 0 && m == 0 {
+ return nil, true
+ }
+ w := m + 1
+ if (n+1)*w > MaxCells {
+ return nil, false
+ }
+
+ // lcs[i*w+j] is the LCS length of am[i:] and bm[j:].
+ lcs := make([]int32, (n+1)*w)
+ for i := n - 1; i >= 0; i-- {
+ for j := m - 1; j >= 0; j-- {
+ switch {
+ case bytes.Equal(am[i], bm[j]):
+ lcs[i*w+j] = lcs[(i+1)*w+j+1] + 1
+ case lcs[(i+1)*w+j] >= lcs[i*w+j+1]:
+ lcs[i*w+j] = lcs[(i+1)*w+j]
+ default:
+ lcs[i*w+j] = lcs[i*w+j+1]
+ }
+ }
+ }
+
+ var edits []edit
+ cur := -1
+ for i, j := 0, 0; i < n || j < m; {
+ if i < n && j < m && bytes.Equal(am[i], bm[j]) {
+ cur = -1
+ i++
+ j++
+ continue
+ }
+ if cur < 0 {
+ edits = append(edits, edit{start: pre + i, end: pre + i})
+ cur = len(edits) - 1
+ }
+ if i < n && (j == m || lcs[(i+1)*w+j] >= lcs[i*w+j+1]) {
+ i++
+ edits[cur].end = pre + i
+ } else {
+ edits[cur].n++
+ j++
+ }
+ }
+ return edits, true
+}
diff --git a/internal/graft/merge3/merge3_test.go b/internal/graft/merge3/merge3_test.go
new file mode 100644
index 0000000..758f5fe
--- /dev/null
+++ b/internal/graft/merge3/merge3_test.go
@@ -0,0 +1,110 @@
+package merge3
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+var labels = Labels{Ours: "ours", Base: "base", Theirs: "theirs"}
+
+func TestMerge(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ base, ours, theirs string
+ hunks []Hunk
+ markers string
+ }{
+ {
+ name: "one line changed on both sides",
+ base: "1\n2\n3\n", ours: "1\nO\n3\n", theirs: "1\nT\n3\n",
+ hunks: []Hunk{{Base: Range{1, 2}, Ours: Range{1, 2}, Theirs: Range{1, 2}}},
+ markers: "1\n<<<<<<< ours\nO\n||||||| base\n2\n=======\nT\n>>>>>>> theirs\n3\n",
+ },
+ {
+ // Ours adds two lines at the top and changes line 3; theirs changes the end. The
+ // clean changes of both sides are applied around the conflict.
+ name: "clean changes around a conflict",
+ base: "1\n2\n3\n4\n5\n", ours: "a\nb\n1\n2\nO\n4\n5\n", theirs: "1\n2\nT\n4\nfive\n",
+ hunks: []Hunk{{Base: Range{2, 3}, Ours: Range{4, 5}, Theirs: Range{2, 3}}},
+ markers: "a\nb\n1\n2\n<<<<<<< ours\nO\n||||||| base\n3\n=======\nT\n>>>>>>> theirs\n4\nfive\n",
+ },
+ {
+ name: "non-overlapping changes merge cleanly",
+ base: "1\n2\n3\n4\n5\n", ours: "O\n2\n3\n4\n5\n", theirs: "1\n2\n3\n4\nT\n",
+ markers: "O\n2\n3\n4\nT\n",
+ },
+ {
+ name: "the same change on both sides is no conflict",
+ base: "1\n2\n", ours: "1\nX\n", theirs: "1\nX\n",
+ markers: "1\nX\n",
+ },
+ {
+ name: "both insert at the same point",
+ base: "1\n2\n", ours: "1\nO\n2\n", theirs: "1\nT\n2\n",
+ hunks: []Hunk{{Base: Range{1, 1}, Ours: Range{1, 2}, Theirs: Range{1, 2}}},
+ markers: "1\n<<<<<<< ours\nO\n||||||| base\n=======\nT\n>>>>>>> theirs\n2\n",
+ },
+ {
+ name: "add/add: no base",
+ base: "", ours: "o1\no2\n", theirs: "t1\n",
+ hunks: []Hunk{{Base: Range{0, 0}, Ours: Range{0, 2}, Theirs: Range{0, 1}}},
+ markers: "<<<<<<< ours\no1\no2\n||||||| base\n=======\nt1\n>>>>>>> theirs\n",
+ },
+ {
+ name: "a side without a final newline gets one before the marker",
+ base: "1\n2", ours: "1\nO", theirs: "1\nT",
+ hunks: []Hunk{{Base: Range{1, 2}, Ours: Range{1, 2}, Theirs: Range{1, 2}}},
+ markers: "1\n<<<<<<< ours\nO\n||||||| base\n2\n=======\nT\n>>>>>>> theirs\n",
+ },
+ {
+ name: "two conflicts",
+ base: "1\n2\n3\n4\n5\n", ours: "O1\n2\n3\n4\nO5\n", theirs: "T1\n2\n3\n4\nT5\n",
+ hunks: []Hunk{
+ {Base: Range{0, 1}, Ours: Range{0, 1}, Theirs: Range{0, 1}},
+ {Base: Range{4, 5}, Ours: Range{4, 5}, Theirs: Range{4, 5}},
+ },
+ markers: "<<<<<<< ours\nO1\n||||||| base\n1\n=======\nT1\n>>>>>>> theirs\n2\n3\n4\n<<<<<<< ours\nO5\n||||||| base\n5\n=======\nT5\n>>>>>>> theirs\n",
+ },
+ {
+ name: "a deletion against an edit",
+ base: "1\n2\n3\n", ours: "1\n3\n", theirs: "1\nT\n3\n",
+ hunks: []Hunk{{Base: Range{1, 2}, Ours: Range{1, 1}, Theirs: Range{1, 2}}},
+ markers: "1\n<<<<<<< ours\n||||||| base\n2\n=======\nT\n>>>>>>> theirs\n3\n",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ r, ok := Merge([]byte(tc.base), []byte(tc.ours), []byte(tc.theirs))
+ require.True(t, ok)
+ require.Equal(t, tc.hunks, r.Hunks())
+ require.Equal(t, tc.markers, string(r.WithMarkers(labels)))
+ })
+ }
+}
+
+func TestMergeTooLarge(t *testing.T) {
+ t.Parallel()
+
+ var a, b strings.Builder
+ for i := 0; i < 3000; i++ {
+ a.WriteString("a\n")
+ b.WriteString("b\n")
+ }
+ _, ok := Merge([]byte(a.String()), []byte(b.String()), []byte("x\n"))
+ require.False(t, ok)
+}
+
+func TestWithMarkersRoundTripsACleanMerge(t *testing.T) {
+ t.Parallel()
+
+ // With no conflict, the merge holds every change of both sides and no marker.
+ r, ok := Merge([]byte("a\nb\nc\nd\n"), []byte("A\nb\nc\nd\n"), []byte("a\nb\nc\nD\ne\n"))
+ require.True(t, ok)
+ require.Empty(t, r.Hunks())
+ require.Equal(t, "A\nb\nc\nD\ne\n", string(r.WithMarkers(labels)))
+}
diff --git a/internal/graft/workspace/backend.go b/internal/graft/workspace/backend.go
index d5a8296..580c8b1 100644
--- a/internal/graft/workspace/backend.go
+++ b/internal/graft/workspace/backend.go
@@ -155,6 +155,26 @@ type LandOptions struct {
// ResolveConflicts asks the server to resolve merge conflicts with its
// conflict resolver.
ResolveConflicts bool
+ // Resolution lands Commit with the caller's resolution of the conflicts of
+ // the merge with the branch tip Resolution.Tip, as a merge commit. It must
+ // resolve exactly the conflicting paths. Strategy is then not used.
+ Resolution *Resolution
+}
+
+// Resolution is a caller's resolution of the conflicts of landing Commit onto
+// the branch tip Tip.
+type Resolution struct {
+ Tip, Commit string
+ Files []ResolvedFile
+}
+
+// ResolvedFile resolves one conflicting path: Delete it, or write Content with
+// Mode.
+type ResolvedFile struct {
+ Path string
+ Delete bool
+ Mode string
+ Content []byte
}
// LandResult is the outcome of a land.
diff --git a/internal/graft/workspace/land_resolve_test.go b/internal/graft/workspace/land_resolve_test.go
index 94538ec..b61e662 100644
--- a/internal/graft/workspace/land_resolve_test.go
+++ b/internal/graft/workspace/land_resolve_test.go
@@ -104,3 +104,42 @@ func TestLandResolvingPassesOptionThrough(t *testing.T) {
require.Len(t, b.lands, 1)
require.True(t, b.lands[0].ResolveConflicts)
}
+
+// TestLandResolutionLandsTheResolvedFiles drives LandResolution over the memory backend: the
+// pending commit conflicts with the tip on a.txt, and a resolution of a.txt made against that tip
+// lands it; a resolution against another tip, or one that names a path without a conflict, fails
+// as a merge conflict and keeps the commit pending.
+func TestLandResolutionLandsTheResolvedFiles(t *testing.T) {
+ t.Parallel()
+
+ b := seedBackend(t, []string{"a.txt", "b.txt"}, []string{"base", "b"})
+ ws := cloneTestWorkspace(t, b)
+ require.NoError(t, os.WriteFile(filepath.Join(ws.Root(), "a.txt"), []byte("local"), 0o644))
+ _, err := ws.Commit(context.Background(), CommitRequest{Message: "local a", Author: Signature{Name: "Ada", Email: "[email protected]"}})
+ require.NoError(t, err)
+ pending := ws.state.Pending.Commit
+
+ // Another writer changes a.txt on main.
+ tip := b.Put("main", "a.txt", []byte("remote"))
+ committer := Signature{Name: "Ada", Email: "[email protected]"}
+
+ _, err = ws.LandResolution(context.Background(), "", committer, &Resolution{Tip: "stale", Commit: pending,
+ Files: []ResolvedFile{{Path: "a.txt", Mode: "100644", Content: []byte("both")}}})
+ require.ErrorIs(t, err, ErrMergeConflict, "a resolution against another tip")
+
+ _, err = ws.LandResolution(context.Background(), "", committer, &Resolution{Tip: tip, Commit: pending,
+ Files: []ResolvedFile{{Path: "a.txt", Mode: "100644", Content: []byte("both")}, {Path: "b.txt", Mode: "100644", Content: []byte("x")}}})
+ require.ErrorIs(t, err, ErrMergeConflict, "a resolution of a path without a conflict")
+ require.NotNil(t, ws.state.Pending, "a failed land keeps the commit pending")
+
+ _, err = ws.LandResolution(context.Background(), "", committer, &Resolution{Tip: tip, Commit: "other", Files: nil})
+ require.ErrorContains(t, err, "not the pending commit")
+
+ res, err := ws.LandResolution(context.Background(), "", committer, &Resolution{Tip: tip, Commit: pending,
+ Files: []ResolvedFile{{Path: "a.txt", Mode: "100644", Content: []byte("both")}}})
+ require.NoError(t, err)
+ require.True(t, res.Rewritten)
+ require.Equal(t, "both", readRemote(t, b, "main", "a.txt"))
+ require.Equal(t, "b", readRemote(t, b, "main", "b.txt"))
+ require.Nil(t, ws.state.Pending)
+}
diff --git a/internal/graft/workspace/memory.go b/internal/graft/workspace/memory.go
index 4df38c1..decbb99 100644
--- a/internal/graft/workspace/memory.go
+++ b/internal/graft/workspace/memory.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"sort"
+ "strconv"
"strings"
"sync"
"time"
@@ -291,7 +292,19 @@ func (m *MemoryBackend) Land(_ context.Context, opts LandOptions) (LandResult, e
if commit.parent != "" {
base = m.commits[commit.parent].files
}
- // Three-way merge of the commit's changes (relative to its parent) onto the tip.
+ // Three-way merge of the commit's changes (relative to its parent) onto the tip. With a
+ // resolution, the conflicting names take the resolved files, as the server's merge commit
+ // does; the resolution must be made against this tip and resolve exactly those names.
+ if opts.Resolution != nil && opts.Resolution.Tip != tip {
+ return LandResult{}, fmt.Errorf("the resolution was made against tip %s, the branch is at %s: %w", opts.Resolution.Tip, tip, ErrMergeConflict)
+ }
+ resolved := map[string]ResolvedFile{}
+ if opts.Resolution != nil {
+ for _, f := range opts.Resolution.Files {
+ resolved[f.Path] = f
+ }
+ }
+ conflicting := map[string]bool{}
files := cloneFiles(m.commits[tip].files)
names := map[string]bool{}
for name := range commit.files {
@@ -308,7 +321,24 @@ func (m *MemoryBackend) Land(_ context.Context, opts LandOptions) (LandResult, e
}
tipFile, tipHas := files[name]
if !sameFile(tipFile, tipHas, baseFile, baseHas) && !sameFile(tipFile, tipHas, commitFile, commitHasFile) {
- return LandResult{}, fmt.Errorf("%s: %w", name, ErrMergeConflict)
+ if opts.Resolution == nil {
+ return LandResult{}, fmt.Errorf("%s: %w", name, ErrMergeConflict)
+ }
+ r, ok := resolved[name]
+ if !ok {
+ return LandResult{}, fmt.Errorf("%s is not resolved: %w", name, ErrMergeConflict)
+ }
+ conflicting[name] = true
+ if r.Delete {
+ delete(files, name)
+ continue
+ }
+ mode, err := strconv.ParseUint(r.Mode, 8, 32)
+ if err != nil {
+ return LandResult{}, fmt.Errorf("the resolution of %s has the mode %q: %w", name, r.Mode, err)
+ }
+ files[name] = memFile{content: r.Content, mode: uint32(mode)}
+ continue
}
if commitHasFile {
files[name] = commitFile
@@ -316,6 +346,11 @@ func (m *MemoryBackend) Land(_ context.Context, opts LandOptions) (LandResult, e
delete(files, name)
}
}
+ for name := range resolved {
+ if !conflicting[name] {
+ return LandResult{}, fmt.Errorf("the resolution names %s, which does not conflict: %w", name, ErrMergeConflict)
+ }
+ }
newID := m.newCommit(tip, files, commit.author, commit.subject)
m.setBranch(opts.Branch, newID, "land", true)
return LandResult{Commit: newID, Rewritten: true}, nil
diff --git a/internal/graft/workspace/workspace.go b/internal/graft/workspace/workspace.go
index a54fb18..366d5b7 100644
--- a/internal/graft/workspace/workspace.go
+++ b/internal/graft/workspace/workspace.go
@@ -482,7 +482,7 @@ func (w *Workspace) Commit(ctx context.Context, req CommitRequest) (CommitResult
if req.LandBranch == "" {
return res, nil
}
- lres, err := w.land(ctx, req.LandBranch, req.Strategy, req.Author, req.Resolve)
+ lres, err := w.land(ctx, req.LandBranch, req.Strategy, req.Author, req.Resolve, nil)
if err != nil {
if w.state.Pending != nil && w.state.Pending.Landed != "" {
// The land succeeded; only the refresh failed, and err explains it.
@@ -514,11 +514,34 @@ func (w *Workspace) LandResolving(ctx context.Context, branch, strategy string,
return LandResult{}, err
}
defer unlock()
- return w.land(ctx, branch, strategy, committer, resolve)
+ return w.land(ctx, branch, strategy, committer, resolve, nil)
+}
+
+// GetObjects returns the contents of the requested blobs from the workspace's
+// server, such as the sides of a conflict. Missing objects are absent from the
+// result.
+func (w *Workspace) GetObjects(ctx context.Context, oids []string) (map[string][]byte, error) {
+ return w.backend.GetObjects(ctx, oids)
+}
+
+// LandResolution lands the pending commit with the caller's resolution of the
+// conflicts of its merge with the branch tip, as a merge commit, and then
+// refreshes the workspace as Land does. The resolution must be for the pending
+// commit.
+func (w *Workspace) LandResolution(ctx context.Context, branch string, committer Signature, resolution *Resolution) (LandResult, error) {
+ unlock, err := w.lockAndLoad()
+ if err != nil {
+ return LandResult{}, err
+ }
+ defer unlock()
+ if w.state.Pending != nil && resolution.Commit != w.state.Pending.Commit {
+ return LandResult{}, fmt.Errorf("the resolution is for commit %s, not the pending commit %s", resolution.Commit, w.state.Pending.Commit)
+ }
+ return w.land(ctx, branch, StrategyMerge, committer, false, resolution)
}
// land is Land without taking the workspace lock.
-func (w *Workspace) land(ctx context.Context, branch, strategy string, committer Signature, resolve bool) (LandResult, error) {
+func (w *Workspace) land(ctx context.Context, branch, strategy string, committer Signature, resolve bool, resolution *Resolution) (LandResult, error) {
if w.state.Pending == nil {
return LandResult{}, errors.New("nothing to land: no pending commit")
}
@@ -551,6 +574,7 @@ func (w *Workspace) land(ctx context.Context, branch, strategy string, committer
CreateBranch: branch == w.state.Branch,
Committer: committer,
ResolveConflicts: resolve,
+ Resolution: resolution,
})
if err != nil {
return LandResult{}, err
diff --git a/sdk/conflict.go b/sdk/conflict.go
new file mode 100644
index 0000000..96b1f77
--- /dev/null
+++ b/sdk/conflict.go
@@ -0,0 +1,112 @@
+package sdk
+
+import (
+ "context"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/feder-cr/git-ai/proto/go/gitalypb"
+)
+
+// MaxLandRequestBytes is the gRPC message limit of the server (4 MiB). A Land request with a
+// Resolution must fit in it; Land refuses a larger one before sending it.
+const MaxLandRequestBytes = 4 << 20
+
+// LandConflict returns the conflict package of a Land call that failed on its conflicts: every
+// conflicting file with its sides, its conflicting hunks and what the server did with it (see
+// doc/graft/RESOLVE.md). The server sends it when the call set ResolveConflicts or Resolution.
+// Resolve the files and land again with LandOptions.Resolution (see ResolutionFor).
+func LandConflict(err error) (*gitalypb.LandConflict, bool) {
+ return detailOf[*gitalypb.LandConflict](err)
+}
+
+// ConflictSides are the contents of the sides of a conflicting file; an absent side is nil.
+type ConflictSides struct {
+ Base, Ours, Theirs []byte
+}
+
+// ConflictSides reads the sides of every file of a conflict package, by path, with GetObjects.
+func (r *Repo) ConflictSides(ctx context.Context, c *gitalypb.LandConflict) (map[string]ConflictSides, error) {
+ var oids []string
+ for _, f := range c.GetFiles() {
+ for _, s := range []*gitalypb.LandConflictSide{f.GetBase(), f.GetOurs(), f.GetTheirs()} {
+ if s != nil {
+ oids = append(oids, s.GetOid())
+ }
+ }
+ }
+ objects, err := r.GetObjects(ctx, oids)
+ if err != nil {
+ return nil, err
+ }
+ data := make(map[string][]byte, len(objects))
+ for _, o := range objects {
+ if o.Missing {
+ return nil, status.Errorf(codes.NotFound, "conflict side %s is missing from the repository", o.OID)
+ }
+ data[o.OID] = o.Data
+ }
+ read := func(s *gitalypb.LandConflictSide) []byte {
+ if s == nil {
+ return nil
+ }
+ if b := data[s.GetOid()]; b != nil {
+ return b
+ }
+ return []byte{}
+ }
+ out := make(map[string]ConflictSides, len(c.GetFiles()))
+ for _, f := range c.GetFiles() {
+ out[string(f.GetPath())] = ConflictSides{Base: read(f.GetBase()), Ours: read(f.GetOurs()), Theirs: read(f.GetTheirs())}
+ }
+ return out, nil
+}
+
+// Resolution is the caller's resolution of the conflicts of a conflict package, for
+// LandOptions.Resolution. It must resolve every conflicting path exactly once.
+type Resolution struct {
+ // Tip and Commit are the tip and the landed commit of the package (LandConflict.Tip and
+ // LandConflict.Commit).
+ Tip, Commit string
+ // Files resolve the conflicting paths.
+ Files []ResolvedFile
+}
+
+// ResolvedFile resolves one conflicting path: Delete it, or write Content with Mode.
+type ResolvedFile struct {
+ Path string
+ Delete bool
+ Mode string
+ Content []byte
+}
+
+// ResolutionFor returns an empty resolution of the conflicts of c: its tip and commit, and no
+// file yet.
+func ResolutionFor(c *gitalypb.LandConflict) *Resolution {
+ return &Resolution{Tip: c.GetTip(), Commit: c.GetCommit()}
+}
+
+// toProto returns the resolution as the request field.
+func (r *Resolution) toProto() *gitalypb.LandResolution {
+ out := &gitalypb.LandResolution{Tip: r.Tip, Commit: r.Commit}
+ for _, f := range r.Files {
+ rf := &gitalypb.LandResolvedFile{Path: []byte(f.Path), Action: gitalypb.LandResolvedFile_ACTION_WRITE, Mode: f.Mode, Content: f.Content}
+ if f.Delete {
+ rf.Action, rf.Mode, rf.Content = gitalypb.LandResolvedFile_ACTION_DELETE, "", nil
+ }
+ out.Files = append(out.Files, rf)
+ }
+ return out
+}
+
+// checkLandRequestSize refuses a request that the server's 4 MiB message limit would refuse,
+// with a clear error instead of a transport failure.
+func checkLandRequestSize(req *gitalypb.UserLandRequest) error {
+ if n := proto.Size(req); n > MaxLandRequestBytes {
+ return status.Errorf(codes.InvalidArgument,
+ "the land request with its resolution is %d bytes, more than the server's 4 MiB message limit: resolve fewer or smaller files per land", n)
+ }
+ return nil
+}
diff --git a/sdk/integration_test.go b/sdk/integration_test.go
index 6c8fb57..c027cf5 100644
--- a/sdk/integration_test.go
+++ b/sdk/integration_test.go
@@ -793,6 +793,47 @@ func TestIntegration_Land(t *testing.T) {
require.True(t, sdk.IsMergeConflict(err), "got %v", err)
require.Equal(t, codes.FailedPrecondition, sdk.Code(err))
require.Equal(t, tip.String(), env.mustResolve(t, "main"), "branch is unchanged")
+ _, ok := sdk.LandConflict(err)
+ require.False(t, ok, "no package without ResolveConflicts")
+ })
+
+ t.Run("the conflict package and the re-land", func(t *testing.T) {
+ t.Parallel()
+
+ env := startIntegration(t, nil) // no resolver: the agent resolves
+ base := env.writeCommit(t, "main", map[string]string{"f.txt": "1\nbase\n3\n", "g.txt": "g\n"})
+ tip := env.writeCommit(t, "main", map[string]string{"f.txt": "1\ntip\n3\n", "g.txt": "g\n"}, base)
+ change := env.writeCommit(t, "", map[string]string{"f.txt": "1\nchange\n3\n", "g.txt": "g\n", "h.txt": "h\n"}, base)
+
+ _, err := env.repo.Land(env.ctx, sdk.LandOptions{Branch: "main", Commit: change.String(), User: user, ResolveConflicts: true})
+ require.True(t, sdk.IsMergeConflict(err), "got %v", err)
+ pkg, ok := sdk.LandConflict(err)
+ require.True(t, ok, "the merge conflict carries the package")
+ require.Equal(t, tip.String(), pkg.GetTip())
+ require.Equal(t, change.String(), pkg.GetCommit())
+ require.Equal(t, base.String(), pkg.GetMergeBase())
+ require.Len(t, pkg.GetFiles(), 1)
+ f := pkg.GetFiles()[0]
+ require.Equal(t, "f.txt", string(f.GetPath()))
+ require.Len(t, f.GetHunks(), 1)
+ require.Equal(t, uint32(2), f.GetHunks()[0].GetOurs().GetStart())
+
+ sides, err := env.repo.ConflictSides(env.ctx, pkg)
+ require.NoError(t, err)
+ require.Equal(t, sdk.ConflictSides{Base: []byte("1\nbase\n3\n"), Ours: []byte("1\ntip\n3\n"), Theirs: []byte("1\nchange\n3\n")}, sides["f.txt"])
+
+ resolution := sdk.ResolutionFor(pkg)
+ resolution.Files = []sdk.ResolvedFile{{Path: "f.txt", Mode: "100644", Content: []byte("1\ntip and change\n3\n")}}
+ result, err := env.repo.Land(env.ctx, sdk.LandOptions{Branch: "main", Commit: change.String(), User: user, Resolution: resolution})
+ require.NoError(t, err)
+ require.True(t, result.Rewritten)
+ require.Equal(t, "agent", result.Resolver)
+ require.Equal(t, []string{"f.txt"}, result.ResolvedPaths)
+ require.Equal(t, "1\ntip and change\n3\n", env.readString(t, "main", "f.txt"))
+ require.Equal(t, "h\n", env.readString(t, "main", "h.txt"))
+ body := env.git(t, "log", "-1", "--format=%B", "main")
+ require.Contains(t, body, "Graft-Resolved-By: agent\n")
+ require.NotContains(t, body, "Graft-Checked-By:")
})
t.Run("create branch", func(t *testing.T) {
diff --git a/sdk/land.go b/sdk/land.go
index 7361485..17eab29 100644
--- a/sdk/land.go
+++ b/sdk/land.go
@@ -54,8 +54,16 @@ type LandOptions struct {
// configured conflict resolver (see doc/graft/RESOLVE.md). A resolved
// landing is a merge commit of the branch tip and the change. If the
// resolver is disabled, refuses a file or fails, the landing fails with a
- // merge conflict as without this option.
+ // merge conflict as without this option, and the error carries the
+ // conflict package (see LandConflict).
ResolveConflicts bool
+ // Resolution lands Commit with the caller's resolution of the conflicts of
+ // a conflict package (see LandConflict and ResolutionFor), as a merge
+ // commit of the branch tip and the change. The server accepts it only when
+ // it was made against the current tip and resolves exactly the conflicting
+ // paths; otherwise Land fails with a fresh package. The request must fit in
+ // MaxLandRequestBytes.
+ Resolution *Resolution
}
// LandResult describes the outcome of a successful Land call.
@@ -101,7 +109,8 @@ func oldTip(oid string) string {
// without a merge queue.
//
// Failures carry structured details: use IsMergeConflict, IsNotAncestor,
-// IsReferenceUpdateConflict, IsRejectedByHook or LandError.
+// IsReferenceUpdateConflict, IsRejectedByHook or LandError, and LandConflict
+// for the conflict package of a land that asked for resolution.
func (r *Repo) Land(ctx context.Context, opts LandOptions) (*LandResult, error) {
switch {
case trimBranchPrefix(opts.Branch) == "":
@@ -126,6 +135,12 @@ func (r *Repo) Land(ctx context.Context, opts LandOptions) (*LandResult, error)
if !opts.Timestamp.IsZero() {
req.Timestamp = timestamppb.New(opts.Timestamp)
}
+ if opts.Resolution != nil {
+ req.Resolution = opts.Resolution.toProto()
+ if err := checkLandRequestSize(req); err != nil {
+ return nil, err
+ }
+ }
resp, err := r.client.operations.UserLand(ctx, req)
if err != nil {
diff --git a/sdk/land_test.go b/sdk/land_test.go
index 1e29c01..82ce4ab 100644
--- a/sdk/land_test.go
+++ b/sdk/land_test.go
@@ -261,3 +261,46 @@ func TestRepo_Land_Validation(t *testing.T) {
})
}
}
+
+func TestRepo_Land_SendsTheResolution(t *testing.T) {
+ t.Parallel()
+
+ fakes := newFakeServices()
+ fakes.operations.landResponse = &gitalypb.UserLandResponse{LandedCommitId: "merged", Rewritten: true}
+ repo := dialFake(t, fakes.register).Repo("repo")
+
+ opts := validLand()
+ opts.Resolution = &sdk.Resolution{Tip: "tip-sha", Commit: "change-sha", Files: []sdk.ResolvedFile{
+ {Path: "a.go", Mode: "100644", Content: []byte("merged\n")},
+ {Path: "old.go", Delete: true, Mode: "100644", Content: []byte("ignored")},
+ }}
+ _, err := repo.Land(t.Context(), opts)
+ require.NoError(t, err)
+
+ req := fakes.operations.landRequests[0].GetResolution()
+ require.Equal(t, "tip-sha", req.GetTip())
+ require.Equal(t, "change-sha", req.GetCommit())
+ require.Len(t, req.GetFiles(), 2)
+ require.Equal(t, gitalypb.LandResolvedFile_ACTION_WRITE, req.GetFiles()[0].GetAction())
+ require.Equal(t, "merged\n", string(req.GetFiles()[0].GetContent()))
+ del := req.GetFiles()[1]
+ require.Equal(t, gitalypb.LandResolvedFile_ACTION_DELETE, del.GetAction())
+ require.Empty(t, del.GetMode(), "a deletion carries no mode")
+ require.Nil(t, del.GetContent(), "a deletion carries no content")
+}
+
+func TestRepo_Land_RefusesAResolutionOverTheMessageLimit(t *testing.T) {
+ t.Parallel()
+
+ fakes := newFakeServices()
+ repo := dialFake(t, fakes.register).Repo("repo")
+
+ opts := validLand()
+ opts.Resolution = &sdk.Resolution{Tip: "t", Commit: "c", Files: []sdk.ResolvedFile{
+ {Path: "big.bin", Mode: "100644", Content: make([]byte, sdk.MaxLandRequestBytes)},
+ }}
+ _, err := repo.Land(t.Context(), opts)
+ require.Equal(t, codes.InvalidArgument, status.Code(err))
+ require.Contains(t, err.Error(), "4 MiB message limit")
+ require.Empty(t, fakes.operations.landRequests, "the request is not sent")
+}