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

Function readWorkspaceFileForDiff

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

Source from the content-addressed store, hash-verified

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

Calls 2

CanonicalPathFunction · 0.92
WithinBaseFunction · 0.92