Skip to content

Commit f73f09b

Browse files
committed
Fix nil pointer dereference in snapshotFS.GetFile for non-existent files
1 parent 8cf32b4 commit f73f09b

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

internal/project/snapshot_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,4 +101,28 @@ func TestSnapshot(t *testing.T) {
101101
assert.Check(t, snapshotAfter.fs.diskFiles["/home/projects/ts/p1/a.ts"] == nil)
102102
assert.Check(t, snapshotAfter.fs.diskFiles["/home/projects/ts/p2/b.ts"] != nil)
103103
})
104+
105+
t.Run("GetFile returns nil for non-existent files", func(t *testing.T) {
106+
t.Parallel()
107+
files := map[string]any{
108+
"/home/projects/TS/p1/tsconfig.json": "{}",
109+
"/home/projects/TS/p1/index.ts": "console.log('Hello, world!');",
110+
}
111+
session := setup(files)
112+
session.DidOpenFile(context.Background(), "file:///home/projects/TS/p1/index.ts", 1, files["/home/projects/TS/p1/index.ts"].(string), lsproto.LanguageKindTypeScript)
113+
snapshot, release := session.Snapshot()
114+
defer release()
115+
116+
// Test that GetFile returns nil for non-existent file (first call)
117+
handle := snapshot.GetFile("/home/projects/TS/p1/nonexistent.ts")
118+
assert.Check(t, handle == nil, "GetFile should return nil for non-existent file on first call")
119+
120+
// Test that GetFile returns nil for non-existent file (second call - triggers the cached path)
121+
handle2 := snapshot.GetFile("/home/projects/TS/p1/nonexistent.ts")
122+
assert.Check(t, handle2 == nil, "GetFile should return nil for non-existent file on second call")
123+
124+
// Test that ReadFile returns false for non-existent file
125+
_, ok := snapshot.ReadFile("/home/projects/TS/p1/nonexistent.ts")
126+
assert.Check(t, !ok, "ReadFile should return false for non-existent file")
127+
})
104128
}

internal/project/snapshotfs.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,12 @@ func (s *snapshotFS) GetFile(fileName string) FileHandle {
4949
}
5050
return nil
5151
}))
52-
if entry, ok := s.readFiles.LoadOrStore(s.toPath(fileName), newEntry); ok {
53-
return entry()
52+
entry, _ := s.readFiles.LoadOrStore(s.toPath(fileName), newEntry)
53+
file := entry()
54+
if file == nil {
55+
return nil
5456
}
55-
return nil
57+
return file
5658
}
5759

5860
type snapshotFSBuilder struct {

0 commit comments

Comments
 (0)