@@ -1,740 +0,0 @@
11−type ActionType string
14− ActionAdd ActionType = "add"
15− ActionDelete ActionType = "delete"
16− ActionUpdate ActionType = "update"
19−type FileChange struct {
27− Changes map[string]FileChange
31− OrigIndex int // line index of the first line in the original file
32− DelLines []string // lines to delete
33− InsLines []string // lines to insert
36−type PatchAction struct {
44− Actions map[string]PatchAction
47−type DiffError struct {
51−func (e DiffError) Error() string {
55−// Helper functions for error handling
56−func NewDiffError(message string) DiffError {
57− return DiffError{message: message}
60−func fileError(action, reason, path string) DiffError {
61− return NewDiffError(fmt.Sprintf("%s File Error: %s: %s", action, reason, path))
64−func contextError(index int, context string, isEOF bool) DiffError {
65− prefix := "Invalid Context"
67− prefix = "Invalid EOF Context"
69− return NewDiffError(fmt.Sprintf("%s %d:\n%s", prefix, index, context))
73− currentFiles map[string]string
80−func NewParser(currentFiles map[string]string, lines []string) *Parser {
82− currentFiles: currentFiles,
85− patch: Patch{Actions: make(map[string]PatchAction, len(currentFiles))},
90−func (p *Parser) isDone(prefixes []string) bool {
91− if p.index >= len(p.lines) {
94− for _, prefix := range prefixes {
95− if strings.HasPrefix(p.lines[p.index], prefix) {
102−func (p *Parser) startsWith(prefix any) bool {
103− var prefixes []string
104− switch v := prefix.(type) {
106− prefixes = []string{v}
111− for _, pfx := range prefixes {
112− if strings.HasPrefix(p.lines[p.index], pfx) {
119−func (p *Parser) readStr(prefix string, returnEverything bool) string {
120− if p.index >= len(p.lines) {
121− return "" // Changed from panic to return empty string for safer operation
123− if strings.HasPrefix(p.lines[p.index], prefix) {
125− if returnEverything {
126− text = p.lines[p.index]
128− text = p.lines[p.index][len(prefix):]
136−func (p *Parser) Parse() error {
137− endPatchPrefixes := []string{"*** End Patch"}
139− for !p.isDone(endPatchPrefixes) {
140− path := p.readStr("*** Update File: ", false)
142− if _, exists := p.patch.Actions[path]; exists {
143− return fileError("Update", "Duplicate Path", path)
145− moveTo := p.readStr("*** Move to: ", false)
146− if _, exists := p.currentFiles[path]; !exists {
147− return fileError("Update", "Missing File", path)
149− text := p.currentFiles[path]
150− action, err := p.parseUpdateFile(text)
155− action.MovePath = &moveTo
157− p.patch.Actions[path] = action
161− path = p.readStr("*** Delete File: ", false)
163− if _, exists := p.patch.Actions[path]; exists {
164− return fileError("Delete", "Duplicate Path", path)
166− if _, exists := p.currentFiles[path]; !exists {
167− return fileError("Delete", "Missing File", path)
169− p.patch.Actions[path] = PatchAction{Type: ActionDelete, Chunks: []Chunk{}}
173− path = p.readStr("*** Add File: ", false)
175− if _, exists := p.patch.Actions[path]; exists {
176− return fileError("Add", "Duplicate Path", path)
178− if _, exists := p.currentFiles[path]; exists {
179− return fileError("Add", "File already exists", path)
181− action, err := p.parseAddFile()
185− p.patch.Actions[path] = action
189− return NewDiffError(fmt.Sprintf("Unknown Line: %s", p.lines[p.index]))
192− if !p.startsWith("*** End Patch") {
193− return NewDiffError("Missing End Patch")
200−func (p *Parser) parseUpdateFile(text string) (PatchAction, error) {
201− action := PatchAction{Type: ActionUpdate, Chunks: []Chunk{}}
202− fileLines := strings.Split(text, "\n")
205− endPrefixes := []string{
213− for !p.isDone(endPrefixes) {
214− defStr := p.readStr("@@ ", false)
216− if defStr == "" && p.index < len(p.lines) && p.lines[p.index] == "@@" {
217− sectionStr = p.lines[p.index]
220− if defStr == "" && sectionStr == "" && index != 0 {
221− return action, NewDiffError(fmt.Sprintf("Invalid Line:\n%s", p.lines[p.index]))
223− if strings.TrimSpace(defStr) != "" {
225− for i := range fileLines[:index] {
226− if fileLines[i] == defStr {
233− for i := index; i < len(fileLines); i++ {
234− if fileLines[i] == defStr {
243− for i := range fileLines[:index] {
244− if strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {
252− for i := index; i < len(fileLines); i++ {
253− if strings.TrimSpace(fileLines[i]) == strings.TrimSpace(defStr) {
263− nextChunkContext, chunks, endPatchIndex, eof := peekNextSection(p.lines, p.index)
264− newIndex, fuzz := findContext(fileLines, nextChunkContext, index, eof)
266− ctxText := strings.Join(nextChunkContext, "\n")
267− return action, contextError(index, ctxText, eof)
271− for _, ch := range chunks {
272− ch.OrigIndex += newIndex
273− action.Chunks = append(action.Chunks, ch)
275− index = newIndex + len(nextChunkContext)
276− p.index = endPatchIndex
281−func (p *Parser) parseAddFile() (PatchAction, error) {
282− lines := make([]string, 0, 16) // Preallocate space for better performance
283− endPrefixes := []string{
290− for !p.isDone(endPrefixes) {
291− s := p.readStr("", true)
292− if !strings.HasPrefix(s, "+") {
293− return PatchAction{}, NewDiffError(fmt.Sprintf("Invalid Add File Line: %s", s))
295− lines = append(lines, s[1:])
298− newFile := strings.Join(lines, "\n")
306−// Refactored to use a matcher function for each comparison type
307−func findContextCore(lines []string, context []string, start int) (int, int) {
308− if len(context) == 0 {
313− if idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {
319− // Try trimming right whitespace
320− if idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {
321− return strings.TrimRight(a, " \t") == strings.TrimRight(b, " \t")
326− // Try trimming all whitespace
327− if idx, fuzz := tryFindMatch(lines, context, start, func(a, b string) bool {
328− return strings.TrimSpace(a) == strings.TrimSpace(b)
336−// Helper function to DRY up the match logic
337−func tryFindMatch(lines []string, context []string, start int,
338− compareFunc func(string, string) bool,
340− for i := start; i < len(lines); i++ {
341− if i+len(context) <= len(lines) {
343− for j := range context {
344− if !compareFunc(lines[i+j], context[j]) {
350− // Return fuzz level: 0 for exact, 1 for trimRight, 100 for trimSpace
352− if compareFunc("a ", "a") && !compareFunc("a", "b") {
354− } else if compareFunc("a ", "a") {
364−func findContext(lines []string, context []string, start int, eof bool) (int, int) {
366− newIndex, fuzz := findContextCore(lines, context, len(lines)-len(context))
368− return newIndex, fuzz
370− newIndex, fuzz = findContextCore(lines, context, start)
371− return newIndex, fuzz + 10000
373− return findContextCore(lines, context, start)
376−func peekNextSection(lines []string, initialIndex int) ([]string, []Chunk, int, bool) {
377− index := initialIndex
378− old := make([]string, 0, 32) // Preallocate for better performance
379− delLines := make([]string, 0, 8)
380− insLines := make([]string, 0, 8)
381− chunks := make([]Chunk, 0, 4)
384− // End conditions for the section
385− endSectionConditions := func(s string) bool {
386− return strings.HasPrefix(s, "@@") ||
387− strings.HasPrefix(s, "*** End Patch") ||
388− strings.HasPrefix(s, "*** Update File:") ||
389− strings.HasPrefix(s, "*** Delete File:") ||
390− strings.HasPrefix(s, "*** Add File:") ||
391− strings.HasPrefix(s, "*** End of File") ||
393− strings.HasPrefix(s, "***")
396− for index < len(lines) {
398− if endSectionConditions(s) {
423− if mode == "keep" && lastMode != mode {
424− if len(insLines) > 0 || len(delLines) > 0 {
425− chunks = append(chunks, Chunk{
426− OrigIndex: len(old) - len(delLines),
431− delLines = make([]string, 0, 8)
432− insLines = make([]string, 0, 8)
436− delLines = append(delLines, line)
437− old = append(old, line)
439− insLines = append(insLines, line)
441− old = append(old, line)
445− if len(insLines) > 0 || len(delLines) > 0 {
446− chunks = append(chunks, Chunk{
447− OrigIndex: len(old) - len(delLines),
453− if index < len(lines) && lines[index] == "*** End of File" {
455− return old, chunks, index, true
457− return old, chunks, index, false
460−func TextToPatch(text string, orig map[string]string) (Patch, int, error) {
461− text = strings.TrimSpace(text)
462− lines := strings.Split(text, "\n")
463− if len(lines) < 2 || !strings.HasPrefix(lines[0], "*** Begin Patch") || lines[len(lines)-1] != "*** End Patch" {
464− return Patch{}, 0, NewDiffError("Invalid patch text")
466− parser := NewParser(orig, lines)
468− if err := parser.Parse(); err != nil {
469− return Patch{}, 0, err
471− return parser.patch, parser.fuzz, nil
474−func IdentifyFilesNeeded(text string) []string {
475− text = strings.TrimSpace(text)
476− lines := strings.Split(text, "\n")
477− result := make(map[string]bool)
479− for _, line := range lines {
480− if strings.HasPrefix(line, "*** Update File: ") {
481− result[line[len("*** Update File: "):]] = true
483− if strings.HasPrefix(line, "*** Delete File: ") {
484− result[line[len("*** Delete File: "):]] = true
488− files := make([]string, 0, len(result))
489− for file := range result {
490− files = append(files, file)
495−func IdentifyFilesAdded(text string) []string {
496− text = strings.TrimSpace(text)
497− lines := strings.Split(text, "\n")
498− result := make(map[string]bool)
500− for _, line := range lines {
501− if strings.HasPrefix(line, "*** Add File: ") {
502− result[line[len("*** Add File: "):]] = true
506− files := make([]string, 0, len(result))
507− for file := range result {
508− files = append(files, file)
513−func getUpdatedFile(text string, action PatchAction, path string) (string, error) {
514− if action.Type != ActionUpdate {
515− return "", errors.New("expected UPDATE action")
517− origLines := strings.Split(text, "\n")
518− destLines := make([]string, 0, len(origLines)) // Preallocate with capacity
521− for _, chunk := range action.Chunks {
522− if chunk.OrigIndex > len(origLines) {
523− return "", NewDiffError(fmt.Sprintf("%s: chunk.orig_index %d > len(lines) %d", path, chunk.OrigIndex, len(origLines)))
525− if origIndex > chunk.OrigIndex {
526− return "", NewDiffError(fmt.Sprintf("%s: orig_index %d > chunk.orig_index %d", path, origIndex, chunk.OrigIndex))
528− destLines = append(destLines, origLines[origIndex:chunk.OrigIndex]...)
529− delta := chunk.OrigIndex - origIndex
532− if len(chunk.InsLines) > 0 {
533− destLines = append(destLines, chunk.InsLines...)
535− origIndex += len(chunk.DelLines)
538− destLines = append(destLines, origLines[origIndex:]...)
539− return strings.Join(destLines, "\n"), nil
542−func PatchToCommit(patch Patch, orig map[string]string) (Commit, error) {
543− commit := Commit{Changes: make(map[string]FileChange, len(patch.Actions))}
544− for pathKey, action := range patch.Actions {
545− switch action.Type {
547− oldContent := orig[pathKey]
548− commit.Changes[pathKey] = FileChange{
550− OldContent: &oldContent,
553− commit.Changes[pathKey] = FileChange{
555− NewContent: action.NewFile,
558− newContent, err := getUpdatedFile(orig[pathKey], action, pathKey)
560− return Commit{}, err
562− oldContent := orig[pathKey]
563− fileChange := FileChange{
565− OldContent: &oldContent,
566− NewContent: &newContent,
568− if action.MovePath != nil {
569− fileChange.MovePath = action.MovePath
571− commit.Changes[pathKey] = fileChange
577−func AssembleChanges(orig map[string]string, updatedFiles map[string]string) Commit {
578− commit := Commit{Changes: make(map[string]FileChange, len(updatedFiles))}
579− for p, newContent := range updatedFiles {
580− oldContent, exists := orig[p]
581− if exists && oldContent == newContent {
585− if exists && newContent != "" {
586− commit.Changes[p] = FileChange{
588− OldContent: &oldContent,
589− NewContent: &newContent,
591− } else if newContent != "" {
592− commit.Changes[p] = FileChange{
594− NewContent: &newContent,
597− commit.Changes[p] = FileChange{
599− OldContent: &oldContent,
602− return commit // Changed from panic to simply return current commit
608−func LoadFiles(paths []string, openFn func(string) (string, error)) (map[string]string, error) {
609− orig := make(map[string]string, len(paths))
610− for _, p := range paths {
611− content, err := openFn(p)
613− return nil, fileError("Open", "File not found", p)
620−func ApplyCommit(commit Commit, writeFn func(string, string) error, removeFn func(string) error) error {
621− for p, change := range commit.Changes {
622− switch change.Type {
624− if err := removeFn(p); err != nil {
628− if change.NewContent == nil {
629− return NewDiffError(fmt.Sprintf("Add action for %s has nil new_content", p))
631− if err := writeFn(p, *change.NewContent); err != nil {
635− if change.NewContent == nil {
636− return NewDiffError(fmt.Sprintf("Update action for %s has nil new_content", p))
638− if change.MovePath != nil {
639− if err := writeFn(*change.MovePath, *change.NewContent); err != nil {
642− if err := removeFn(p); err != nil {
646− if err := writeFn(p, *change.NewContent); err != nil {
655−func ProcessPatch(text string, openFn func(string) (string, error), writeFn func(string, string) error, removeFn func(string) error) (string, error) {
656− if !strings.HasPrefix(text, "*** Begin Patch") {
657− return "", NewDiffError("Patch must start with *** Begin Patch")
659− paths := IdentifyFilesNeeded(text)
660− orig, err := LoadFiles(paths, openFn)
665− patch, fuzz, err := TextToPatch(text, orig)
671− return "", NewDiffError(fmt.Sprintf("Patch contains fuzzy matches (fuzz level: %d)", fuzz))
674− commit, err := PatchToCommit(patch, orig)
679− if err := ApplyCommit(commit, writeFn, removeFn); err != nil {
683− return "Patch applied successfully", nil
686−func OpenFile(p string) (string, error) {
687− data, err := os.ReadFile(p)
691− return string(data), nil
694−func WriteFile(p string, content string) error {
695− if filepath.IsAbs(p) {
696− return NewDiffError("We do not support absolute paths.")
699− dir := filepath.Dir(p)
701− if err := os.MkdirAll(dir, 0o755); err != nil {
706− return os.WriteFile(p, []byte(content), 0o644)
709−func RemoveFile(p string) error {
713−func ValidatePatch(patchText string, files map[string]string) (bool, string, error) {
714− if !strings.HasPrefix(patchText, "*** Begin Patch") {
715− return false, "Patch must start with *** Begin Patch", nil
718− neededFiles := IdentifyFilesNeeded(patchText)
719− for _, filePath := range neededFiles {
720− if _, exists := files[filePath]; !exists {
721− return false, fmt.Sprintf("File not found: %s", filePath), nil
725− patch, fuzz, err := TextToPatch(patchText, files)
727− return false, err.Error(), nil
731− return false, fmt.Sprintf("Patch contains fuzzy matches (fuzz level: %d)", fuzz), nil
734− _, err = PatchToCommit(patch, files)
736− return false, err.Error(), nil
739− return true, "Patch is valid", nil