JacobHawley's picture
download
raw
30.4 kB
diff --git a/worktree.go b/worktree.go index df86532a..0673094f 100644 --- a/worktree.go +++ b/worktree.go @@ -1,6 +1,7 @@ package git import ( + "bytes" "context" "errors" "fmt" @@ -49,6 +50,10 @@ var ( ErrRestoreWorktreeOnlyNotSupported = errors.New("worktree only is not supported") // ErrSparseResetDirectoryNotFound is returned when a sparse-reset directory is not found. ErrSparseResetDirectoryNotFound = errors.New("sparse-reset directory not found on commit") + // ErrMergeConflicts is returned when a merge encounters conflicts. + ErrMergeConflicts = errors.New("merge conflicts detected") + // ErrUncommittedChanges is returned when uncommitted changes prevent an operation. + ErrUncommittedChanges = errors.New("uncommitted changes present") ) // Worktree represents a git worktree. @@ -176,6 +181,1034 @@ func (w *Worktree) updateSubmodules(ctx context.Context, o *SubmoduleUpdateOptio return s.UpdateContext(ctx, o) } +func (w *Worktree) Merge(commit plumbing.Hash, opts *MergeOptions) error { + if opts == nil { + opts = &MergeOptions{} + } + + status, err := w.Status() + if err != nil { + return err + } + if !status.IsClean() { + return ErrUncommittedChanges + } + + head, err := w.r.Head() + if err != nil { + return err + } + + headCommit, err := w.r.CommitObject(head.Hash()) + if err != nil { + return err + } + + theirCommit, err := w.r.CommitObject(commit) + if err != nil { + return err + } + + mergeBases, err := headCommit.MergeBase(theirCommit) + if err != nil { + return err + } + + if len(mergeBases) == 0 { + return fmt.Errorf("no common ancestor found") + } + + baseCommit := mergeBases[0] + + if baseCommit.Hash == commit { + return nil + } + + if baseCommit.Hash == head.Hash() { + return w.updateHEAD(commit) + } + + oursTree, err := headCommit.Tree() + if err != nil { + return err + } + + theirsTree, err := theirCommit.Tree() + if err != nil { + return err + } + + idx, err := w.r.Storer.Index() + if err != nil { + return err + } + + baseTree, err := baseCommit.Tree() + if err != nil { + return err + } + + mergeState, err := w.performThreeWayMerge(baseTree, oursTree, theirsTree, idx) + if err != nil { + return err + } + + if len(mergeState.conflicts) > 0 { + if err := w.applyMergeChanges(mergeState, idx); err != nil { + return err + } + if err := w.writeConflictMarkers(mergeState); err != nil { + return err + } + if err := w.updateIndexWithConflicts(idx, mergeState); err != nil { + return err + } + if err := w.r.Storer.SetIndex(idx); err != nil { + return err + } + if err := w.writeMergeHead(commit); err != nil { + return err + } + return ErrMergeConflicts + } + + if err := w.applyMergeChanges(mergeState, idx); err != nil { + return err + } + + for path, change := range mergeState.changes { + if change.deleted { + idx.Remove(path) + } else { + idx.Remove(path) + e := idx.Add(path) + e.Hash = change.hash + e.Mode = change.mode + } + } + + if err := w.r.Storer.SetIndex(idx); err != nil { + return err + } + + tree, err := w.buildTreeFromIndex(idx) + if err != nil { + return err + } + + mergeCommit := &object.Commit{ + Author: headCommit.Author, + Committer: headCommit.Author, + Message: fmt.Sprintf("Merge commit %s", commit.String()[:7]), + TreeHash: tree, + ParentHashes: []plumbing.Hash{ + head.Hash(), + commit, + }, + } + + obj := w.r.Storer.NewEncodedObject() + if err := mergeCommit.Encode(obj); err != nil { + return err + } + + commitHash, err := w.r.Storer.SetEncodedObject(obj) + if err != nil { + return err + } + + return w.updateHEAD(commitHash) +} + +func (w *Worktree) writeMergeHead(hash plumbing.Hash) error { + return util.WriteFile(w.Filesystem, ".git/MERGE_HEAD", []byte(hash.String()+"\n"), 0644) +} + +func (w *Worktree) readMergeHead() (plumbing.Hash, error) { + data, err := util.ReadFile(w.Filesystem, ".git/MERGE_HEAD") + if err != nil { + if os.IsNotExist(err) { + return plumbing.ZeroHash, nil + } + return plumbing.ZeroHash, err + } + return plumbing.NewHash(strings.TrimSpace(string(data))), nil +} + +func (w *Worktree) clearMergeHead() error { + err := w.Filesystem.Remove(".git/MERGE_HEAD") + if err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + +func (w *Worktree) buildTreeFromIndex(idx *index.Index) (plumbing.Hash, error) { + trees := make(map[string]*object.Tree) + trees[""] = &object.Tree{} + + for _, entry := range idx.Entries { + if entry.Stage != 0 { + continue + } + + // Ensure every ancestor directory has a Tree node. + dir := filepath.ToSlash(filepath.Dir(entry.Name)) + if dir == "." { + dir = "" + } + for seg := dir; seg != ""; seg = func() string { + p := filepath.ToSlash(filepath.Dir(seg)) + if p == "." { + return "" + } + return p + }() { + if _, exists := trees[seg]; !exists { + trees[seg] = &object.Tree{} + } + } + if _, exists := trees[dir]; !exists { + trees[dir] = &object.Tree{} + } + + trees[dir].Entries = append(trees[dir].Entries, object.TreeEntry{ + Name: filepath.Base(entry.Name), + Mode: entry.Mode, + Hash: entry.Hash, + }) + } + + // Collect and sort subdirectory keys so parent trees are built deterministically. + subdirs := make([]string, 0, len(trees)) + for dir := range trees { + if dir != "" { + subdirs = append(subdirs, dir) + } + } + // Process deepest paths first so child hashes are available when building parents. + slices.SortFunc(subdirs, func(a, b string) int { + if len(a) > len(b) { + return -1 + } + if len(a) < len(b) { + return 1 + } + if a < b { + return -1 + } + if a > b { + return 1 + } + return 0 + }) + + for _, dir := range subdirs { + tree := trees[dir] + slices.SortFunc(tree.Entries, func(a, b object.TreeEntry) int { + nameA, nameB := a.Name, b.Name + if a.Mode == filemode.Dir { + nameA += "/" + } + if b.Mode == filemode.Dir { + nameB += "/" + } + if nameA < nameB { + return -1 + } + if nameA > nameB { + return 1 + } + return 0 + }) + + obj := w.r.Storer.NewEncodedObject() + if err := tree.Encode(obj); err != nil { + return plumbing.ZeroHash, err + } + + hash, err := w.r.Storer.SetEncodedObject(obj) + if err != nil { + return plumbing.ZeroHash, err + } + + parentDir := filepath.Dir(dir) + if parentDir == "." { + parentDir = "" + } + + trees[parentDir].Entries = append(trees[parentDir].Entries, object.TreeEntry{ + Name: filepath.Base(dir), + Mode: filemode.Dir, + Hash: hash, + }) + } + + rootTree := trees[""] + slices.SortFunc(rootTree.Entries, func(a, b object.TreeEntry) int { + nameA, nameB := a.Name, b.Name + if a.Mode == filemode.Dir { + nameA += "/" + } + if b.Mode == filemode.Dir { + nameB += "/" + } + if nameA < nameB { + return -1 + } + if nameA > nameB { + return 1 + } + return 0 + }) + obj := w.r.Storer.NewEncodedObject() + if err := rootTree.Encode(obj); err != nil { + return plumbing.ZeroHash, err + } + + return w.r.Storer.SetEncodedObject(obj) +} + +type mergeState struct { + conflicts map[string]*conflictInfo + changes map[string]*mergeChange +} + +type conflictInfo struct { + baseHash plumbing.Hash + oursHash plumbing.Hash + theirsHash plumbing.Hash + path string + isTree bool +} + +type mergeChange struct { + path string + hash plumbing.Hash + mode filemode.FileMode + deleted bool +} + +func (w *Worktree) performThreeWayMerge(base, ours, theirs *object.Tree, idx *index.Index) (*mergeState, error) { + state := &mergeState{ + conflicts: make(map[string]*conflictInfo), + changes: make(map[string]*mergeChange), + } + + baseFiles := make(map[string]*object.TreeEntry) + base.Files().ForEach(func(f *object.File) error { + baseFiles[f.Name] = &object.TreeEntry{Name: f.Name, Hash: f.Hash, Mode: f.Mode} + return nil + }) + + oursFiles := make(map[string]*object.TreeEntry) + ours.Files().ForEach(func(f *object.File) error { + oursFiles[f.Name] = &object.TreeEntry{Name: f.Name, Hash: f.Hash, Mode: f.Mode} + return nil + }) + + theirsFiles := make(map[string]*object.TreeEntry) + theirs.Files().ForEach(func(f *object.File) error { + theirsFiles[f.Name] = &object.TreeEntry{Name: f.Name, Hash: f.Hash, Mode: f.Mode} + return nil + }) + + oursTreeMap := treeToMap(ours, w.r.Storer) + theirsTreeMap := treeToMap(theirs, w.r.Storer) + + allPaths := make(map[string]bool) + for path := range baseFiles { + allPaths[path] = true + } + for path := range oursFiles { + allPaths[path] = true + } + for path := range theirsFiles { + allPaths[path] = true + } + + for path := range allPaths { + baseEntry := baseFiles[path] + oursEntry := oursFiles[path] + theirsEntry := theirsFiles[path] + + oursIsFile := oursEntry != nil && oursEntry.Mode.IsFile() + theirsIsFile := theirsEntry != nil && theirsEntry.Mode.IsFile() + oursIsDir := oursTreeMap[path] + theirsIsDir := theirsTreeMap[path] + + if (oursIsFile && theirsIsDir) || (oursIsDir && theirsIsFile) { + state.conflicts[path] = &conflictInfo{ + path: path, + isTree: true, + } + if oursEntry != nil { + state.conflicts[path].oursHash = oursEntry.Hash + } + if theirsEntry != nil { + state.conflicts[path].theirsHash = theirsEntry.Hash + } + continue + } + + if baseEntry == nil { + if oursEntry != nil && theirsEntry != nil { + if oursEntry.Hash != theirsEntry.Hash { + if err := w.detectContentConflict(path, baseEntry, oursEntry, theirsEntry, state); err != nil { + return nil, err + } + } else { + state.changes[path] = &mergeChange{ + path: path, + hash: oursEntry.Hash, + mode: oursEntry.Mode, + } + } + } else if oursEntry != nil { + state.changes[path] = &mergeChange{ + path: path, + hash: oursEntry.Hash, + mode: oursEntry.Mode, + } + } else if theirsEntry != nil { + state.changes[path] = &mergeChange{ + path: path, + hash: theirsEntry.Hash, + mode: theirsEntry.Mode, + } + } + } else { + baseHash := baseEntry.Hash + oursHash := plumbing.ZeroHash + if oursEntry != nil { + oursHash = oursEntry.Hash + } + theirsHash := plumbing.ZeroHash + if theirsEntry != nil { + theirsHash = theirsEntry.Hash + } + + if oursHash == theirsHash { + if oursEntry != nil { + state.changes[path] = &mergeChange{ + path: path, + hash: oursEntry.Hash, + mode: oursEntry.Mode, + } + } else { + state.changes[path] = &mergeChange{ + path: path, + deleted: true, + } + } + } else if oursHash == baseHash && theirsHash != baseHash { + if theirsEntry != nil { + state.changes[path] = &mergeChange{ + path: path, + hash: theirsEntry.Hash, + mode: theirsEntry.Mode, + } + } else { + state.changes[path] = &mergeChange{ + path: path, + deleted: true, + } + } + } else if theirsHash == baseHash && oursHash != baseHash { + if oursEntry != nil { + state.changes[path] = &mergeChange{ + path: path, + hash: oursEntry.Hash, + mode: oursEntry.Mode, + } + } else { + state.changes[path] = &mergeChange{ + path: path, + deleted: true, + } + } + } else { + if err := w.detectContentConflict(path, baseEntry, oursEntry, theirsEntry, state); err != nil { + return nil, err + } + } + } + } + + return state, nil +} + +// treeToMap returns a set of all directory paths (relative, slash-separated) +// that exist anywhere in the tree, including nested subdirectories. +// This is used to detect file-vs-directory conflicts at any depth. +func treeToMap(tree *object.Tree, s storer.EncodedObjectStorer) map[string]bool { + m := make(map[string]bool) + var walk func(t *object.Tree, prefix string) + walk = func(t *object.Tree, prefix string) { + for _, entry := range t.Entries { + fullPath := entry.Name + if prefix != "" { + fullPath = prefix + "/" + entry.Name + } + if entry.Mode == filemode.Dir { + m[fullPath] = true + sub, err := object.GetTree(s, entry.Hash) + if err == nil { + walk(sub, fullPath) + } + } + } + } + walk(tree, "") + return m +} + +func (w *Worktree) detectContentConflict(path string, base, ours, theirs *object.TreeEntry, state *mergeState) error { + if (ours == nil && theirs != nil) || (ours != nil && theirs == nil) { + state.conflicts[path] = &conflictInfo{ + path: path, + } + if base != nil { + state.conflicts[path].baseHash = base.Hash + } + if ours != nil { + state.conflicts[path].oursHash = ours.Hash + } + if theirs != nil { + state.conflicts[path].theirsHash = theirs.Hash + } + return nil + } + + if ours == nil && theirs == nil { + return nil + } + + oursFile, err := w.r.BlobObject(ours.Hash) + if err != nil { + return err + } + + theirsFile, err := w.r.BlobObject(theirs.Hash) + if err != nil { + return err + } + + oursContent, err := oursFile.Reader() + if err != nil { + return err + } + defer oursContent.Close() + + theirsContent, err := theirsFile.Reader() + if err != nil { + return err + } + defer theirsContent.Close() + + oursBytes, err := io.ReadAll(oursContent) + if err != nil { + return err + } + + theirsBytes, err := io.ReadAll(theirsContent) + if err != nil { + return err + } + + var baseBytes []byte + if base != nil { + baseFile, err := w.r.BlobObject(base.Hash) + if err != nil { + return err + } + baseContent, err := baseFile.Reader() + if err != nil { + return err + } + defer baseContent.Close() + baseBytes, err = io.ReadAll(baseContent) + if err != nil { + return err + } + } + + merged, err := mergeContent(baseBytes, oursBytes, theirsBytes) + if err != nil { + state.conflicts[path] = &conflictInfo{ + path: path, + } + if base != nil { + state.conflicts[path].baseHash = base.Hash + } + state.conflicts[path].oursHash = ours.Hash + state.conflicts[path].theirsHash = theirs.Hash + } else { + hash, err := w.writeBlob(merged) + if err != nil { + return err + } + state.changes[path] = &mergeChange{ + path: path, + hash: hash, + mode: ours.Mode, + } + } + + return nil +} + + +func splitLines(s string) []string { + if s == "" { + return []string{} + } + lines := strings.Split(s, "\n") + if len(lines) > 0 && lines[len(lines)-1] == "" { + lines = lines[:len(lines)-1] + } + return lines +} + +// lcs computes the Longest Common Subsequence of two line slices and returns +// a list of (i, j) index pairs where a[i] == b[j] in the LCS. +func lcs(a, b []string) [][2]int { + m, n := len(a), len(b) + // dp[i][j] = length of LCS of a[:i] and b[:j] + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + if a[i-1] == b[j-1] { + dp[i][j] = dp[i-1][j-1] + 1 + } else if dp[i-1][j] >= dp[i][j-1] { + dp[i][j] = dp[i-1][j] + } else { + dp[i][j] = dp[i][j-1] + } + } + } + // Backtrack to recover pairs. + pairs := make([][2]int, 0, dp[m][n]) + i, j := m, n + for i > 0 && j > 0 { + if a[i-1] == b[j-1] { + pairs = append(pairs, [2]int{i - 1, j - 1}) + i-- + j-- + } else if dp[i-1][j] >= dp[i][j-1] { + i-- + } else { + j-- + } + } + // Reverse to get forward order. + for lo, hi := 0, len(pairs)-1; lo < hi; lo, hi = lo+1, hi-1 { + pairs[lo], pairs[hi] = pairs[hi], pairs[lo] + } + return pairs +} + +// diff3Hunk represents one hunk produced by the diff3 algorithm. +type diff3Hunk struct { + kind int // 0 = unchanged, 1 = ours-only, 2 = theirs-only, 3 = conflict + base []string + ours []string + theirs []string +} + +// diff3Hunks performs a 3-way diff of base, ours, theirs and returns a list +// of hunks that cover every line. The algorithm: +// 1. Compute LCS(base, ours) → alignment A +// 2. Compute LCS(base, theirs) → alignment B +// 3. Walk forward through base positions, collecting changed regions from +// each side, then classifying them. +func diff3Hunks(base, ours, theirs []string) []diff3Hunk { + lcsA := lcs(base, ours) // base[ai] == ours[ai2] + lcsB := lcs(base, theirs) // base[bi] == theirs[bi2] + + // Build lookup: baseIdx -> oursIdx for matched lines. + oursMatch := make(map[int]int, len(lcsA)) + for _, p := range lcsA { + oursMatch[p[0]] = p[1] + } + theirsMatch := make(map[int]int, len(lcsB)) + for _, p := range lcsB { + theirsMatch[p[0]] = p[1] + } + + hunks := make([]diff3Hunk, 0) + bi := 0 // current base index + oi := 0 // current ours index + ti := 0 // current theirs index + lcsa := 0 // next index into lcsA + lcsb := 0 // next index into lcsB + + for bi < len(base) || oi < len(ours) || ti < len(theirs) { + // Find next base line that is matched in both sides. + nextBaseBoth := len(base) // default: no such line + for k := bi; k < len(base); k++ { + _, inA := oursMatch[k] + _, inB := theirsMatch[k] + if inA && inB { + nextBaseBoth = k + break + } + } + + if nextBaseBoth == len(base) { + // No more base lines matched on both sides — gather remaining lines. + remainBase := base[bi:] + remainOurs := ours[oi:] + remainTheirs := theirs[ti:] + if len(remainOurs) == 0 && len(remainTheirs) == 0 { + // Both deleted trailing base lines — nothing to emit. + } else if len(remainOurs) == 0 { + hunks = append(hunks, diff3Hunk{kind: 2, base: remainBase, theirs: remainTheirs}) + } else if len(remainTheirs) == 0 { + hunks = append(hunks, diff3Hunk{kind: 1, base: remainBase, ours: remainOurs}) + } else { + // Check if both sides agree. + if slices.Equal(remainOurs, remainTheirs) { + hunks = append(hunks, diff3Hunk{kind: 0, base: remainBase, ours: remainOurs, theirs: remainTheirs}) + } else { + hunks = append(hunks, diff3Hunk{kind: 3, base: remainBase, ours: remainOurs, theirs: remainTheirs}) + } + } + break + } + + // Lines before nextBaseBoth are differing regions on one or both sides. + oursNext := oursMatch[nextBaseBoth] + theirsNext := theirsMatch[nextBaseBoth] + + changedOurs := ours[oi:oursNext] + changedTheirs := theirs[ti:theirsNext] + changedBase := base[bi:nextBaseBoth] + + if len(changedOurs) > 0 || len(changedBase) > 0 || len(changedTheirs) > 0 { + oursChanged := !slices.Equal(changedOurs, changedBase) + theirsChanged := !slices.Equal(changedTheirs, changedBase) + + switch { + case !oursChanged && !theirsChanged: + // Both sides kept base unchanged — but this shouldn't happen + // since nextBaseBoth would have been earlier. Emit as unchanged. + hunks = append(hunks, diff3Hunk{kind: 0, base: changedBase, ours: changedOurs, theirs: changedTheirs}) + case oursChanged && !theirsChanged: + hunks = append(hunks, diff3Hunk{kind: 1, base: changedBase, ours: changedOurs, theirs: changedTheirs}) + case !oursChanged && theirsChanged: + hunks = append(hunks, diff3Hunk{kind: 2, base: changedBase, ours: changedOurs, theirs: changedTheirs}) + default: + if slices.Equal(changedOurs, changedTheirs) { + // Both sides made the same change — accept it. + hunks = append(hunks, diff3Hunk{kind: 1, base: changedBase, ours: changedOurs, theirs: changedTheirs}) + } else { + hunks = append(hunks, diff3Hunk{kind: 3, base: changedBase, ours: changedOurs, theirs: changedTheirs}) + } + } + } + + // Emit the matched line itself as unchanged. + hunks = append(hunks, diff3Hunk{ + kind: 0, + base: base[nextBaseBoth : nextBaseBoth+1], + ours: ours[oursNext : oursNext+1], + theirs: theirs[theirsNext : theirsNext+1], + }) + + bi = nextBaseBoth + 1 + oi = oursNext + 1 + ti = theirsNext + 1 + lcsa++ + lcsb++ + _ = lcsa + _ = lcsb + } + + return hunks +} + +// mergeContent attempts a 3-way merge of base, ours, and theirs. +// Returns the merged content on success, or an error if there are conflicts. +func mergeContent(base, ours, theirs []byte) ([]byte, error) { + baseLines := splitLines(string(base)) + oursLines := splitLines(string(ours)) + theirsLines := splitLines(string(theirs)) + + hunks := diff3Hunks(baseLines, oursLines, theirsLines) + result := make([]string, 0) + for _, h := range hunks { + switch h.kind { + case 0: // unchanged + result = append(result, h.ours...) + case 1: // ours-only change + result = append(result, h.ours...) + case 2: // theirs-only change + result = append(result, h.theirs...) + case 3: // conflict — cannot auto-merge + return nil, fmt.Errorf("conflict") + } + } + return []byte(strings.Join(result, "\n") + "\n"), nil +} + +// mergeContentWithMarkers performs a 3-way merge and writes conflict markers +// for any regions that could not be resolved automatically. It always succeeds +// and never returns an error -- conflict sections are written with <<<<<<< / ======= / >>>>>>> markers. +func mergeContentWithMarkers(base, ours, theirs []byte) []byte { + baseLines := splitLines(string(base)) + oursLines := splitLines(string(ours)) + theirsLines := splitLines(string(theirs)) + + hunks := diff3Hunks(baseLines, oursLines, theirsLines) + result := make([]string, 0) + for _, h := range hunks { + switch h.kind { + case 0: + result = append(result, h.ours...) + case 1: + result = append(result, h.ours...) + case 2: + result = append(result, h.theirs...) + case 3: + result = append(result, "<<<<<<< HEAD") + result = append(result, h.ours...) + result = append(result, "=======") + result = append(result, h.theirs...) + result = append(result, ">>>>>>>") + } + } + return []byte(strings.Join(result, "\n") + "\n") +} + +func (w *Worktree) writeBlob(content []byte) (plumbing.Hash, error) { + obj := w.r.Storer.NewEncodedObject() + obj.SetType(plumbing.BlobObject) + obj.SetSize(int64(len(content))) + + writer, err := obj.Writer() + if err != nil { + return plumbing.ZeroHash, err + } + + _, err = writer.Write(content) + if err != nil { + writer.Close() + return plumbing.ZeroHash, err + } + + if err := writer.Close(); err != nil { + return plumbing.ZeroHash, err + } + + return w.r.Storer.SetEncodedObject(obj) +} + +func (w *Worktree) writeConflictMarkers(state *mergeState) error { + for path, conflict := range state.conflicts { + if conflict.isTree { + continue + } + + var baseContent, oursContent, theirsContent []byte + var err error + + if !conflict.baseHash.IsZero() { + baseBlob, err := w.r.BlobObject(conflict.baseHash) + if err != nil { + return err + } + reader, err := baseBlob.Reader() + if err != nil { + return err + } + baseContent, err = io.ReadAll(reader) + reader.Close() + if err != nil { + return err + } + } + + if !conflict.oursHash.IsZero() { + oursBlob, err := w.r.BlobObject(conflict.oursHash) + if err != nil { + return err + } + reader, err := oursBlob.Reader() + if err != nil { + return err + } + oursContent, err = io.ReadAll(reader) + reader.Close() + if err != nil { + return err + } + } + + if !conflict.theirsHash.IsZero() { + theirsBlob, err := w.r.BlobObject(conflict.theirsHash) + if err != nil { + return err + } + reader, err := theirsBlob.Reader() + if err != nil { + return err + } + theirsContent, err = io.ReadAll(reader) + reader.Close() + if err != nil { + return err + } + } + + isDeleteModify := (conflict.oursHash.IsZero() && !conflict.theirsHash.IsZero()) || + (!conflict.oursHash.IsZero() && conflict.theirsHash.IsZero()) + isAddAdd := conflict.baseHash.IsZero() && !conflict.oursHash.IsZero() && !conflict.theirsHash.IsZero() + + var conflictContent bytes.Buffer + + if isDeleteModify || isAddAdd { + conflictContent.WriteString("<<<<<<< HEAD\n") + if len(oursContent) > 0 { + conflictContent.Write(oursContent) + if oursContent[len(oursContent)-1] != '\n' { + conflictContent.WriteByte('\n') + } + } + conflictContent.WriteString("=======\n") + if len(theirsContent) > 0 { + conflictContent.Write(theirsContent) + if theirsContent[len(theirsContent)-1] != '\n' { + conflictContent.WriteByte('\n') + } + } + conflictContent.WriteString(">>>>>>>\n") + } else { + conflictContent.Write(mergeContentWithMarkers(baseContent, oursContent, theirsContent)) + } + + err = util.WriteFile(w.Filesystem, path, conflictContent.Bytes(), 0644) + if err != nil { + return err + } + } + + return nil +} + +func (w *Worktree) updateIndexWithConflicts(idx *index.Index, state *mergeState) error { + toRemove := make([]string, 0) + for _, entry := range idx.Entries { + if _, hasConflict := state.conflicts[entry.Name]; hasConflict { + toRemove = append(toRemove, entry.Name) + } + if _, hasChange := state.changes[entry.Name]; hasChange { + toRemove = append(toRemove, entry.Name) + } + } + + for _, path := range toRemove { + idx.Remove(path) + } + + for path, conflict := range state.conflicts { + if conflict.isTree { + continue + } + + if !conflict.baseHash.IsZero() { + e := idx.Add(path) + e.Hash = conflict.baseHash + e.Stage = index.AncestorMode + e.Mode = filemode.Regular + } + + if !conflict.oursHash.IsZero() { + e := idx.Add(path) + e.Hash = conflict.oursHash + e.Stage = index.OurMode + e.Mode = filemode.Regular + } + + if !conflict.theirsHash.IsZero() { + e := idx.Add(path) + e.Hash = conflict.theirsHash + e.Stage = index.TheirMode + e.Mode = filemode.Regular + } + } + + for path, change := range state.changes { + if change.deleted { + idx.Remove(path) + } else { + e := idx.Add(path) + e.Hash = change.hash + e.Mode = change.mode + } + } + + return nil +} + +func (w *Worktree) applyMergeChanges(state *mergeState, idx *index.Index) error { + for path, change := range state.changes { + skipDueToTreeConflict := false + for conflictPath, conflict := range state.conflicts { + if conflict.isTree { + if path == conflictPath || strings.HasPrefix(path, conflictPath+"/") { + skipDueToTreeConflict = true + break + } + } + } + if skipDueToTreeConflict { + continue + } + + if change.deleted { + // Validate path before removal to prevent removing base/root directory + cleanPath := filepath.Clean(path) + fileName := filepath.Base(cleanPath) + + // Only remove if we have a valid file/directory name + if path != "" && fileName != "" && fileName != "." && fileName != ".." && + cleanPath != "." && cleanPath != "/" && cleanPath != string(filepath.Separator) { + err := w.Filesystem.Remove(path) + if err != nil && !os.IsNotExist(err) { + return err + } + } + } else { + blob, err := w.r.BlobObject(change.hash) + if err != nil { + return err + } + + reader, err := blob.Reader() + if err != nil { + return err + } + defer reader.Close() + + content, err := io.ReadAll(reader) + if err != nil { + return err + } + + err = util.WriteFile(w.Filesystem, path, content, 0644) + if err != nil { + return err + } + } + } + + return nil +} + // Checkout switch branches or restore working tree files. func (w *Worktree) Checkout(opts *CheckoutOptions) error { if err := opts.Validate(); err != nil { diff --git a/worktree_commit.go b/worktree_commit.go index 8a662ce1..ec32bb65 100644 --- a/worktree_commit.go +++ b/worktree_commit.go @@ -3,6 +3,7 @@ package git import ( "bytes" "errors" + "fmt" "io" "path" "regexp" @@ -40,6 +41,11 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error return plumbing.ZeroHash, err } + mergeHead, err := w.readMergeHead() + if err != nil { + return plumbing.ZeroHash, err + } + if opts.All { if err := w.autoAddModifiedAndDeleted(); err != nil { return plumbing.ZeroHash, err @@ -64,6 +70,12 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error return plumbing.ZeroHash, err } + for _, entry := range idx.Entries { + if entry.Stage != 0 { + return plumbing.ZeroHash, fmt.Errorf("unresolved conflicts in index") + } + } + // First handle the case of the first commit in the repository being empty. if len(opts.Parents) == 0 && len(idx.Entries) == 0 && !opts.AllowEmptyCommits { return plumbing.ZeroHash, ErrEmptyCommit @@ -97,6 +109,28 @@ func (w *Worktree) Commit(msg string, opts *CommitOptions) (plumbing.Hash, error return plumbing.ZeroHash, err } + if !mergeHead.IsZero() { + commitObj, err := w.r.CommitObject(commit) + if err != nil { + return plumbing.ZeroHash, err + } + commitObj.ParentHashes = append(commitObj.ParentHashes, mergeHead) + + obj := w.r.Storer.NewEncodedObject() + if err := commitObj.Encode(obj); err != nil { + return plumbing.ZeroHash, err + } + + commit, err = w.r.Storer.SetEncodedObject(obj) + if err != nil { + return plumbing.ZeroHash, err + } + + if err := w.clearMergeHead(); err != nil { + return plumbing.ZeroHash, err + } + } + return commit, w.updateHEAD(commit) } diff --git a/worktree_status.go b/worktree_status.go index 296530e1..0613aaff 100644 --- a/worktree_status.go +++ b/worktree_status.go @@ -566,7 +566,41 @@ func (w *Worktree) fillEncodedObjectFromSymlink(dst io.Writer, path string, _ os return err } +// clearConflictStages removes all conflict stage entries (stages 1/2/3) for +// the given filename from the index. Returns true if any were removed. +func clearConflictStages(idx *index.Index, filename string) bool { + hasConflict := false + for _, e := range idx.Entries { + if e.Name == filename && (e.Stage == index.AncestorMode || e.Stage == index.OurMode || e.Stage == index.TheirMode) { + hasConflict = true + break + } + } + if hasConflict { + for { + _, err := idx.Remove(filename) + if err != nil { + break + } + } + } + return hasConflict +} + func (w *Worktree) addOrUpdateFileToIndex(idx *index.Index, filename string, h plumbing.Hash) error { + cleared := clearConflictStages(idx, filename) + + count := 0 + for _, e := range idx.Entries { + if e.Name == filename { + count++ + } + } + + if cleared || count > 1 { + return w.doAddFileToIndex(idx, filename, h) + } + e, err := idx.Entry(filename) if err != nil && !errors.Is(err, index.ErrEntryNotFound) { return err @@ -580,6 +614,7 @@ func (w *Worktree) addOrUpdateFileToIndex(idx *index.Index, filename string, h p } func (w *Worktree) doAddFileToIndex(idx *index.Index, filename string, h plumbing.Hash) error { + clearConflictStages(idx, filename) return w.doUpdateFileToIndex(idx.Add(filename), filename, h) }
diff --git a/worktree.go b/worktree.go
index df86532a..0673094f 100644
--- a/worktree.go
+++ b/worktree.go
@@ -1,6 +1,7 @@
package git
import (
+ "bytes"
"context"
"errors"
"fmt"
@@ -49,6 +50,10 @@ var (
ErrRestoreWorktreeOnlyNotSupported = errors.New("worktree only is not supported")
// ErrSparseResetDirectoryNotFound is returned when a sparse-reset directory is not found.
ErrSparseResetDirectoryNotFound = errors.New("sparse-reset directory not found on commit")
+ // ErrMergeConflicts is returned when a merge encounters conflicts.
+ ErrMergeConflicts = errors.New("merge conflicts detected")
+ // ErrUncommittedChanges is returned when uncommitted changes prevent an operation.
+ ErrUncommittedChanges = errors.New("uncommitted changes present")
)
// Worktree represents a git worktree.
@@ -176,6 +181,1034 @@ func (w *Worktree) updateSubmodules(ctx context.Context, o *SubmoduleUpdateOptio
return s.UpdateContext(ctx, o)
}
+func (w *Worktree) Merge(commit plumbing.Hash, opts *MergeOptions) error {
+ if opts == nil {
+ opts = &MergeOptions{}
+ }
+
+ status, err := w.Status()
+ if err != nil {
+ return err
+ }
+ if !status.IsClean() {
+ return ErrUncommittedChanges
+ }
+
+ head, err := w.r.Head()
+ if err != nil {
+ return err
+ }
+
+ headCommit, err := w.r.CommitObject(head.Hash())
+ if err != nil {
+ return err
+ }
+
+ theirCommit, err := w.r.CommitObject(commit)
+ if err != nil {
+ return err
+ }
+
+ mergeBases, err := headCommit.MergeBase(theirCommit)
+ if err != nil {
+ return err
+ }
+
+ if len(mergeBases) == 0 {
+ return fmt.Errorf("no common ancestor found")
+ }
+
+ baseCommit := mergeBases[0]
+
+ if baseCommit.Hash == commit {
+ return nil
+ }
+
+ if baseCommit.Hash == head.Hash() {
+ return w.updateHEAD(commit)
+ }
+
+ oursTree, err := headCommit.Tree()
+ if err != nil {
+ return err
+ }
+
+ theirsTree, err := theirCommit.Tree()
+ if err != nil {
+ return err
+ }
+
+ idx, err := w.r.Storer.Index()
+ if err != nil {
+ return err
+ }
+
+ baseTree, err := baseCommit.Tree()
+ if err != nil {
+ return err
+ }
+
+ mergeState, err := w.performThreeWayMerge(baseTree, oursTree, theirsTree, idx)
+ if err != nil {
+ return err
+ }
+
+ if len(mergeState.conflicts) > 0 {

Xet Storage Details

Size:
30.4 kB
·
Xet hash:
e02b5835a40cc20d5baac404d6288a59239acee443498a93bebcc390e078122b

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.