Skip to content

Commit 68bbb6d

Browse files
committed
feat(cwc): exclude binary files from context window
1 parent 8990c58 commit 68bbb6d

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

pkg/filetree/filetree.go

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
package filetree
22

33
import (
4+
"github.com/emilkje/cwc/pkg/ui"
5+
"io"
46
"os"
57
"path/filepath"
68
"regexp"
79
"sort"
810
"strings"
11+
"unicode/utf8"
912
)
1013

1114
type FileNode struct {
@@ -40,14 +43,34 @@ func GatherFiles(re *regexp.Regexp, paths []string, ignorePatterns []*regexp.Reg
4043
return nil
4144
}
4245

43-
var file []byte
44-
file, err = os.ReadFile(path) // #nosec
46+
var f []byte
4547

48+
file, err := os.OpenFile(path, os.O_RDONLY, 0) // #nosec
4649
if err != nil {
4750
return err
4851
}
4952

50-
fileMap[path] = file
53+
defer file.Close()
54+
buffer := make([]byte, 512)
55+
for {
56+
if _, err := file.Read(buffer); err == io.EOF {
57+
break
58+
}
59+
// check if the file is binary
60+
if !utf8.Valid(buffer) {
61+
ui.PrintMessage("Skipping binary file: "+path+"\n", ui.MessageTypeWarning)
62+
return nil
63+
}
64+
f = append(f, buffer...)
65+
}
66+
67+
//file, err = os.ReadFile(path) // #nosec
68+
69+
if err != nil {
70+
return err
71+
}
72+
73+
fileMap[path] = f
5174

5275
// Construct the file tree
5376
parts := strings.Split(path, string(os.PathSeparator))

0 commit comments

Comments
 (0)