Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357// Package diff manages temp files for diff-review and applies Edit/Write hook// operations to the real file while keeping a backup for restoration.package diff
import ( "bytes" "fmt" "io" "os" "path/filepath" "strings"
"git.sr.ht/~jcmuller/claude-plugins/transcript")
// Dir wraps a per-invocation temp directory with 0700 permissions.// Call Close when done to remove it and all its contents.type Dir struct { dir string}
// New creates a fresh temp directory under /tmp with 0700 permissions.func New() (*Dir, error) { dir, err := os.MkdirTemp("", "claude-diff-*") if err != nil { return nil, fmt.Errorf("creating temp dir: %w", err) } if err := os.Chmod(dir, 0o700); err != nil { _ = os.RemoveAll(dir) return nil, fmt.Errorf("setting temp dir permissions: %w", err) } return &Dir{dir: dir}, nil}
// Dir returns the absolute path of the temp directory.func (d *Dir) Dir() string { return d.dir }
// Close removes the temp directory and all its contents.func (d *Dir) Close() error { return os.RemoveAll(d.dir)}
// MakeTemp creates an empty 0600 file inside the temp directory.// label is a human-readable name (e.g., "backup"); ext is the file extension.func (d *Dir) MakeTemp(ext, label string) (string, error) { path := filepath.Join(d.dir, label+ext) f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) //nolint:gosec // G304: path is inside our own temp dir if err != nil { return "", fmt.Errorf("creating temp file %s: %w", label, err) } return path, f.Close()}
// Backup copies src into a new 0600 temp file and returns its path.// If src does not exist the backup is created empty (new-file case).func (d *Dir) Backup(src, ext string) (string, error) { backup, err := d.MakeTemp(ext, "backup") if err != nil { return "", err }
in, err := os.Open(src) //nolint:gosec // G304: src is the hook-provided file path if err != nil { // Source does not exist — empty backup is correct for new files. return backup, nil //nolint:nilerr } defer in.Close() //nolint:errcheck
out, err := os.OpenFile(backup, os.O_WRONLY|os.O_TRUNC, 0o600) //nolint:gosec // G304: backup is inside our own temp dir if err != nil { return "", fmt.Errorf("opening backup for write: %w", err) } defer out.Close() //nolint:errcheck
if _, err := io.Copy(out, in); err != nil { return "", fmt.Errorf("copying to backup: %w", err) }
// Stamp the backup with the original file's mtime so RestoreOriginal can recover it. if srcInfo, statErr := in.Stat(); statErr == nil { _ = os.Chtimes(backup, srcInfo.ModTime(), srcInfo.ModTime()) }
return backup, nil}
// ApplyWrite writes content to filePath, creating parent directories as needed.func ApplyWrite(filePath, content string) error { if err := os.MkdirAll(filepath.Dir(filePath), 0o755); err != nil { //nolint:gosec // G301: 0755 is standard for dirs return fmt.Errorf("creating parent dirs: %w", err) } return os.WriteFile(filePath, []byte(content), 0o600)}
// ApplyEdit applies a string replacement to filePath in-place.// When replaceAll is false only the first occurrence is replaced.func ApplyEdit(filePath, oldStr, newStr string, replaceAll bool) error { data, err := os.ReadFile(filePath) //nolint:gosec // G304: file path from hook input if err != nil { return fmt.Errorf("reading file for edit: %w", err) } var updated string if replaceAll { updated = strings.ReplaceAll(string(data), oldStr, newStr) } else { updated = strings.Replace(string(data), oldStr, newStr, 1) } return os.WriteFile(filePath, []byte(updated), 0o600)}
// FindEditLine returns the 1-based line number of the first occurrence of oldStr// in the file at path, or 1 if oldStr is empty, not found, or the file cannot be read.// For multi-line oldStr, returns the line where the match begins.func FindEditLine(path, oldStr string) int { if oldStr == "" { return 1 } data, err := os.ReadFile(path) //nolint:gosec // G304: internal temp file if err != nil { return 1 } idx := strings.Index(string(data), oldStr) if idx < 0 { return 1 } return strings.Count(string(data[:idx]), "\n") + 1}
// ContentChanged reports whether the files at paths a and b differ byte-for-byte.func ContentChanged(a, b string) (bool, error) { ab, err := os.ReadFile(a) //nolint:gosec // G304: paths are internal temp files if err != nil { return false, fmt.Errorf("reading %s: %w", a, err) } bb, err := os.ReadFile(b) //nolint:gosec // G304: paths are internal temp files if err != nil { return false, fmt.Errorf("reading %s: %w", b, err) } return !bytes.Equal(ab, bb), nil}
// RestoreOriginal reverts filePath to its pre-hook state.// For new files (isNewFile=true) the file is deleted.// For existing files the backup is copied back preserving permissions.func RestoreOriginal(filePath, backup string, isNewFile bool) error { if isNewFile { if err := os.Remove(filePath); err != nil && !os.IsNotExist(err) { return fmt.Errorf("removing new file on restore: %w", err) } return nil } if backup == "" { return nil } backupInfo, statErr := os.Stat(backup)
data, err := os.ReadFile(backup) //nolint:gosec // G304: backup is our own temp file if err != nil { return fmt.Errorf("reading backup: %w", err) } if err := os.WriteFile(filePath, data, 0o600); err != nil { return fmt.Errorf("writing restored file: %w", err) }
// Recover the original mtime (stamped onto backup during Backup). if statErr == nil { _ = os.Chtimes(filePath, backupInfo.ModTime(), backupInfo.ModTime()) }
return nil}
// AppendContextBlock writes one separator newline, the block, and a// terminating newline to the end of path. The block argument should already// be comment-prefixed and wrapped in transcript.BeginMarker /// transcript.EndMarker sentinel lines. StripContextBlock recovers the body// verbatim regardless of whether the body originally ended with a newline.func AppendContextBlock(path, block string) error { f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600) //nolint:gosec // G304: caller supplies a trusted path if err != nil { return fmt.Errorf("opening %s for append: %w", path, err) } if _, err := io.WriteString(f, "\n"+block+"\n"); err != nil { _ = f.Close() return fmt.Errorf("appending to %s: %w", path, err) } return f.Close()}
// StripContextBlock removes the last begin/end sentinel pair from path// and reports whether anything was removed. Scans line by line so the// strip survives harmless external modifications to the block that would// defeat an exact-byte match. When either sentinel is absent, the file// is left untouched and (false, nil) is returned. Idempotent: a second// call finds no markers and no-ops.//// The block argument is retained for API stability with earlier callers// but is not consulted; detection relies solely on the sentinel markers.// The separator newline AppendContextBlock placed before the block is// consumed together with the block lines.func StripContextBlock(path, _ string) (bool, error) { data, err := os.ReadFile(path) //nolint:gosec // G304: caller supplies a trusted path if err != nil { return false, fmt.Errorf("reading %s: %w", path, err) } start, end, ok := findLastSentinelPair(data) if !ok { return false, nil } // Consume the 1 separator newline AppendContextBlock writes before the block. for i := 0; i < 1 && start > 0 && data[start-1] == '\n'; i++ { start-- } remainder := append([]byte{}, data[:start]...) remainder = append(remainder, data[end:]...) if err := os.WriteFile(path, remainder, 0o600); err != nil { return false, fmt.Errorf("writing %s: %w", path, err) } return true, nil}
// findLastSentinelPair returns the byte range [start, end) covering the// last begin-marker line through and including the trailing newline of// its matching end-marker line, or ok=false if no complete pair exists.func findLastSentinelPair(data []byte) (start, end int, ok bool) { lines := splitLinesKeepTerminators(data) endIdx := -1 for i := len(lines) - 1; i >= 0; i-- { if bytes.Contains(lines[i], []byte(transcript.EndMarker)) { endIdx = i break } } if endIdx < 0 { return 0, 0, false } for i := endIdx - 1; i >= 0; i-- { if bytes.Contains(lines[i], []byte(transcript.BeginMarker)) { s := 0 for _, ln := range lines[:i] { s += len(ln) } e := s for _, ln := range lines[i : endIdx+1] { e += len(ln) } return s, e, true } } return 0, 0, false}
// PrependContextBlock writes block followed by two newlines at the very// beginning of path, producing a blank line between the block and the// first line of code. The block argument should already be comment-// prefixed and wrapped in transcript.BeginMarker / transcript.EndMarker// sentinel lines. StripContextBlockTop removes exactly what// PrependContextBlock wrote, leaving the body byte-identical.func PrependContextBlock(path, block string) error { data, err := os.ReadFile(path) //nolint:gosec // G304: caller supplies a trusted path if err != nil { return fmt.Errorf("reading %s: %w", path, err) } out := make([]byte, 0, len(block)+2+len(data)) out = append(out, block...) out = append(out, '\n', '\n') out = append(out, data...) return os.WriteFile(path, out, 0o600)}
// StripContextBlockTop removes the first begin/end sentinel pair from the// start of path and reports whether anything was removed. Scans line by// line so the strip survives harmless external modifications to the block// (trailing whitespace normalization, inserted blank lines, and so on)// that would defeat an exact-byte match. When either sentinel is absent,// the file is left untouched and (false, nil) is returned. Idempotent:// a second call finds no markers and no-ops.//// The block argument is retained for API stability with earlier callers// but is not consulted; detection relies solely on the sentinel markers.func StripContextBlockTop(path, _ string) (bool, error) { data, err := os.ReadFile(path) //nolint:gosec // G304: caller supplies a trusted path if err != nil { return false, fmt.Errorf("reading %s: %w", path, err) } start, end, ok := findFirstSentinelPair(data) if !ok { return false, nil } // Consume the extra separator newline PrependContextBlock writes after the block. if end < len(data) && data[end] == '\n' { end++ } remainder := append([]byte{}, data[:start]...) remainder = append(remainder, data[end:]...) if err := os.WriteFile(path, remainder, 0o600); err != nil { return false, fmt.Errorf("writing %s: %w", path, err) } return true, nil}
// findFirstSentinelPair returns the byte range [start, end) covering the// first begin-marker line through and including the trailing newline of// the matching end-marker line, or ok=false if no complete pair exists.func findFirstSentinelPair(data []byte) (start, end int, ok bool) { lines := splitLinesKeepTerminators(data) beginIdx := -1 for i, ln := range lines { if bytes.Contains(ln, []byte(transcript.BeginMarker)) { beginIdx = i break } } if beginIdx < 0 { return 0, 0, false } for i := beginIdx + 1; i < len(lines); i++ { if bytes.Contains(lines[i], []byte(transcript.EndMarker)) { s := 0 for _, ln := range lines[:beginIdx] { s += len(ln) } e := s for _, ln := range lines[beginIdx : i+1] { e += len(ln) } return s, e, true } } return 0, 0, false}
// splitLinesKeepTerminators splits data into lines while preserving the// trailing "\n" on each line. The final line may lack a terminator.func splitLinesKeepTerminators(data []byte) [][]byte { var lines [][]byte i := 0 for i < len(data) { j := bytes.IndexByte(data[i:], '\n') if j < 0 { lines = append(lines, data[i:]) break } lines = append(lines, data[i:i+j+1]) i += j + 1 } return lines}
// ContextLineCount returns the number of lines PrependContextBlock adds when// writing block to the top of a file. Callers that jump the diff tool to a// specific body line must shift that line number by this count when a block// has been prepended.func ContextLineCount(block string) int { return strings.Count(block, "\n") + 1}