package lint import ( "sort" "git.warky.dev/wdevs/pgtidy/pkg/diagnostics" ) // ApplyFixes applies all autofixes from diags to src and returns the result. // Fixes are applied in reverse-offset order so earlier edits do not shift the // byte positions of later ones. Overlapping fixes are skipped. func ApplyFixes(src string, diags []diagnostics.Diagnostic) string { type fix struct { offset, end int new string } var fixes []fix for _, d := range diags { if d.Fix != nil { fixes = append(fixes, fix{d.Fix.Offset, d.Fix.End, d.Fix.New}) } } if len(fixes) == 0 { return src } sort.Slice(fixes, func(i, j int) bool { return fixes[i].offset > fixes[j].offset }) b := []byte(src) last := len(b) + 1 // sentinel: no fix applied yet for _, f := range fixes { if f.end > last { continue // overlaps a previously applied fix; skip } last = f.offset b = append(b[:f.offset], append([]byte(f.new), b[f.end:]...)...) } return string(b) }