Skip to content

Commit 82b2807

Browse files
author
Aqsa Aqeel
committed
Refactor: Improve diff truncation for large changes
1 parent 3f987b8 commit 82b2807

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

cmd/cli/createMsg.go

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ func CreateCommitMsg(Store *store.StoreMethods, dryRun bool, autoCommit bool) {
9393

9494
// Large diff handling
9595
const maxDiffChars = 8000 // can change as needed
96-
const maxDiffLines = 300
96+
const maxDiffLines = 300
9797

9898
diffLines := strings.Split(changes, "\n")
9999
diffTooLarge := len(changes) > maxDiffChars || len(diffLines) > maxDiffLines
@@ -103,18 +103,26 @@ func CreateCommitMsg(Store *store.StoreMethods, dryRun bool, autoCommit bool) {
103103
pterm.Info.Printf("Diff size: %d lines, %d characters.\n", len(diffLines), len(changes))
104104
pterm.Info.Println("Only the first part of the diff will be used for commit message generation.")
105105

106-
// Truncate the diff for LLM input
107-
truncatedLines := diffLines
108-
if len(diffLines) > maxDiffLines {
109-
truncatedLines = diffLines[:maxDiffLines]
110-
}
111-
truncatedDiff := strings.Join(truncatedLines, "\n")
112-
if len(truncatedDiff) > maxDiffChars {
113-
truncatedDiff = truncatedDiff[:maxDiffChars]
106+
// Truncate the diff for LLM input, preserving whole lines and UTF-8 safety
107+
truncatedLines := make([]string, 0, len(diffLines))
108+
totalChars := 0
109+
110+
for i, line := range diffLines {
111+
lineLen := len([]rune(line)) + 1 // +1 for newline, using rune count for UTF-8 safety
112+
113+
// Stop if we've reached max lines or adding this line would exceed max chars
114+
if i >= maxDiffLines || (totalChars+lineLen) > maxDiffChars {
115+
break
116+
}
117+
118+
truncatedLines = append(truncatedLines, line)
119+
totalChars += lineLen
114120
}
115-
changes = truncatedDiff
116121

117-
pterm.Info.Printf("Truncated diff to %d lines, %d characters.\n", len(strings.Split(changes, "\n")), len(changes))
122+
changes = strings.Join(truncatedLines, "\n")
123+
actualLineCount := len(truncatedLines)
124+
125+
pterm.Info.Printf("Truncated diff to %d lines, %d characters.\n", actualLineCount, len(changes))
118126
pterm.Info.Println("Consider committing smaller changes for more accurate commit messages.")
119127
}
120128

0 commit comments

Comments
 (0)