adde 'marker' type
This commit is contained in:
parent
1e8fea4287
commit
30881f4710
4 changed files with 98 additions and 0 deletions
81
marker.go
Normal file
81
marker.go
Normal file
|
@ -0,0 +1,81 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func applyMarkerPatch(targetFilePath string, modifications []string) error {
|
||||
// Parse patch content
|
||||
var marker string
|
||||
var entriesToAdd []string
|
||||
var entriesToRemove []string
|
||||
collecting := false
|
||||
|
||||
for _, line := range modifications {
|
||||
switch {
|
||||
case strings.HasPrefix(line, "#"):
|
||||
// Capture marker line (first # line only)
|
||||
if marker == "" {
|
||||
marker = strings.TrimSpace(strings.TrimPrefix(line, "#"))
|
||||
collecting = true
|
||||
}
|
||||
case collecting && strings.HasPrefix(line, "+"):
|
||||
entriesToAdd = append(entriesToAdd, strings.TrimPrefix(line, "+"))
|
||||
case collecting && strings.HasPrefix(line, "-"):
|
||||
entriesToRemove = append(entriesToRemove, strings.TrimPrefix(line, "-"))
|
||||
}
|
||||
}
|
||||
|
||||
// Validate input
|
||||
if marker == "" {
|
||||
return fmt.Errorf("missing marker line starting with #")
|
||||
}
|
||||
|
||||
// Read entire file
|
||||
content, err := os.ReadFile(targetFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read file: %v", err)
|
||||
}
|
||||
|
||||
lines := strings.Split(string(content), "\n")
|
||||
var modifiedLines []string
|
||||
markerFound := false
|
||||
|
||||
for _, line := range lines {
|
||||
// Check if current line is our marker
|
||||
if !markerFound && strings.TrimSpace(line) == marker {
|
||||
markerFound = true
|
||||
modifiedLines = append(modifiedLines, line)
|
||||
// Add new entries immediately after marker
|
||||
modifiedLines = append(modifiedLines, entriesToAdd...)
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if line should be removed
|
||||
keep := true
|
||||
for _, removeLine := range entriesToRemove {
|
||||
if line == removeLine {
|
||||
keep = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if keep {
|
||||
modifiedLines = append(modifiedLines, line)
|
||||
}
|
||||
}
|
||||
|
||||
if !markerFound {
|
||||
return fmt.Errorf("marker line not found: %q", marker)
|
||||
}
|
||||
|
||||
// Write directly to target file
|
||||
err = os.WriteFile(targetFilePath, []byte(strings.Join(modifiedLines, "\n")), 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write changes: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue