MCPcopy Create free account
hub / github.com/alibaba/open-code-review / loadBackgroundFile

Function loadBackgroundFile

cmd/opencodereview/background_file.go:49–97  ·  view source on GitHub ↗
(path string)

Source from the content-addressed store, hash-verified

47}
48
49func loadBackgroundFile(path string) (string, error) {
50 info, err := os.Stat(path)
51 if err != nil {
52 return "", fmt.Errorf("read background file %q: %w", path, err)
53 }
54 if info.IsDir() {
55 return "", fmt.Errorf("background file %q is a directory, not a file", path)
56 }
57 if info.Size() > maxBackgroundFileBytes {
58 return "", fmt.Errorf(
59 "background file %q is %d bytes, exceeding the maximum of %d bytes; please provide a smaller file",
60 path, info.Size(), maxBackgroundFileBytes,
61 )
62 }
63
64 raw, err := os.ReadFile(path)
65 if err != nil {
66 return "", fmt.Errorf("read background file %q: %w", path, err)
67 }
68
69 cleaned := sanitizeMarkdown(string(raw))
70 if cleaned == "" {
71 return "", fmt.Errorf("background file %q is empty after sanitisation", path)
72 }
73
74 if strings.Contains(cleaned, backgroundOpenTag) || strings.Contains(cleaned, backgroundCloseTag) {
75 return "", fmt.Errorf(
76 "background file %q must not contain the reserved delimiters %q or %q",
77 path, backgroundOpenTag, backgroundCloseTag,
78 )
79 }
80
81 // Enforce the limits on the cleaned content only: the wrapper delimiters add
82 // overhead the user cannot control, so counting them would make the reported
83 // character count misleading.
84 if n := len([]rune(cleaned)); n > backgroundHardLimit {
85 return "", fmt.Errorf(
86 "background content is %d characters, exceeding the hard limit of %d (aborting)",
87 n, backgroundHardLimit,
88 )
89 } else if n > backgroundSoftLimit {
90 fmt.Fprintf(os.Stderr,
91 "[ocr] --background-file content is %d characters, exceeding the recommended %d (continuing but review quality might be impacted)\n",
92 n, backgroundSoftLimit,
93 )
94 }
95
96 return backgroundOpenTag + "\n" + cleaned + "\n" + backgroundCloseTag, nil
97}
98
99func sanitizeMarkdown(s string) string {
100 var b strings.Builder

Calls 1

sanitizeMarkdownFunction · 0.85