gunk-dev/the-valley

text.go

source601b054bc28emain's published tip history
1.6 KiB
1package git
2
3import (
4 "strings"
5 "unicode/utf8"
6)
7
8// NotText replaces the hunks of a file that isn't valid UTF-8 in TextDiff.
9const NotText = "[the content of this file is not text and was left out]"
10
11// TextDiff returns a unified diff as valid UTF-8, for a model's prompt: the
12// CLIs refuse any other input. A file whose hunks aren't valid UTF-8 keeps
13// its header, so the reader still sees that it changed, and has its hunks
14// replaced with the line NotText.
15func TextDiff(diff string) string {
16 if utf8.ValidString(diff) {
17 return diff
18 }
19 var b strings.Builder
20 for _, file := range splitFiles(diff) {
21 if utf8.ValidString(file) {
22 b.WriteString(file)
23 continue
24 }
25 header, hunks := file, ""
26 if strings.HasPrefix(file, "@@ ") {
27 header, hunks = "", file
28 } else if i := strings.Index(file, "\n@@ "); i >= 0 {
29 header, hunks = file[:i+1], file[i+1:]
30 }
31 // Only a path can make a header invalid; keep it, marked.
32 b.WriteString(strings.ToValidUTF8(header, "�"))
33 if utf8.ValidString(hunks) {
34 b.WriteString(hunks)
35 } else {
36 b.WriteString(NotText + "\n")
37 }
38 }
39 return b.String()
40}
41
42// splitFiles splits a diff before each "diff --git" line.
43func splitFiles(diff string) []string {
44 var files []string
45 for diff != "" {
46 end := strings.Index(diff, "\ndiff --git ")
47 if end < 0 {
48 return append(files, diff)
49 }
50 files = append(files, diff[:end+1])
51 diff = diff[end+1:]
52 }
53 return files
54}
55
56// TruncateText cuts s to at most n bytes at a rune boundary, so valid UTF-8
57// stays valid.
58func TruncateText(s string, n int) string {
59 if len(s) <= n {
60 return s
61 }
62 for n > 0 && !utf8.RuneStart(s[n]) {
63 n--
64 }
65 return s[:n]
66}