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

Function readWorkspaceFileForDiff

internal/diff/workspace_file.go:11–60  ·  view source on GitHub ↗
(repoDir, relPath string)

Source from the content-addressed store, hash-verified

9)
10
11func readWorkspaceFileForDiff(repoDir, relPath string) ([]byte, error) {
12 repoRoot, err := pathutil.CanonicalPath(repoDir)
13 if err != nil {
14 return nil, fmt.Errorf("resolve repository path %q: %w", repoDir, err)
15 }
16 if filepath.IsAbs(relPath) {
17 return nil, fmt.Errorf("file path %q must be relative, not absolute", relPath)
18 }
19
20 fullPath := filepath.Join(repoRoot, relPath)
21 if !pathutil.WithinBase(repoRoot, fullPath) {
22 return nil, fmt.Errorf("file path %q is outside repository", relPath)
23 }
24
25 parent, err := filepath.EvalSymlinks(filepath.Dir(fullPath))
26 if err != nil {
27 return nil, fmt.Errorf("resolve parent path for %q: %w", relPath, err)
28 }
29 if !pathutil.WithinBase(repoRoot, parent) {
30 return nil, fmt.Errorf("file path %q is outside repository", relPath)
31 }
32
33 info, err := os.Lstat(fullPath)
34 if err != nil {
35 return nil, fmt.Errorf("stat file %q: %w", relPath, err)
36 }
37 if info.IsDir() {
38 return nil, fmt.Errorf("file path %q is a directory", relPath)
39 }
40 if info.Mode()&os.ModeSymlink != 0 {
41 target, err := os.Readlink(fullPath)
42 if err != nil {
43 return nil, fmt.Errorf("read symlink %q: %w", relPath, err)
44 }
45 return []byte(target), nil
46 }
47
48 resolvedPath, err := filepath.EvalSymlinks(fullPath)
49 if err != nil {
50 return nil, fmt.Errorf("resolve file %q: %w", relPath, err)
51 }
52 if !pathutil.WithinBase(repoRoot, resolvedPath) {
53 return nil, fmt.Errorf("file path %q is outside repository", relPath)
54 }
55 content, err := os.ReadFile(resolvedPath)
56 if err != nil {
57 return nil, fmt.Errorf("read file %q: %w", relPath, err)
58 }
59 return content, nil
60}

Calls 2

CanonicalPathFunction · 0.92
WithinBaseFunction · 0.92