Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions tsc/internal/api/requestfilesystem/filechanges.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func (s *requestFileSystem) ExpandFileChanges(summary project.FileChangeSummary)
expand(&summary.Changed)
expand(&summary.Created)
expand(&summary.Deleted)
expand(&summary.DiskChanged)
return summary
}

Expand Down
21 changes: 21 additions & 0 deletions tsc/internal/api/requestfilesystem/requestfilesystem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,27 @@ func newLayeredRequestFileSystem(params *RequestFileSystem, base vfs.FS, current
return fileSystem.(*requestFileSystem), nil
}

func TestRequestFileSystemExpandDiskChangedAliases(t *testing.T) {
t.Parallel()
fileSystem, err := newRequestFileSystem(&RequestFileSystem{
Kind: KindFull,
Files: map[string]string{
"/packages/pkg/package.json": `{"name":"pkg"}`,
},
Symlinks: map[string]RequestSymlink{
"/project/node_modules/pkg": {Target: "../../../packages/pkg"},
},
}, vfstest.FromMap(map[string]string{}, tspath.CaseSensitive), "/")
assert.NilError(t, err)

var change project.FileChangeSummary
change.DiskChanged.Add("file:///packages/pkg/package.json")
expanded := fileSystem.ExpandFileChanges(change)

assert.Assert(t, expanded.DiskChanged.Has("file:///packages/pkg/package.json"))
assert.Assert(t, expanded.DiskChanged.Has("file:///project/node_modules/pkg/package.json"))
}

func verifyCompactionWithoutHostReads(t *testing.T, layer *requestFileSystem, host *trackingvfs.FS, paths []string) {
t.Helper()
compacted, err := newRequestFileSystem(&RequestFileSystem{Kind: KindLayer}, layer, layer.currentDirectory.AsString())
Expand Down
159 changes: 159 additions & 0 deletions tsc/internal/project/contentmapper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,165 @@ func TestDynamicContentMapperInProject(t *testing.T) {
assert.Assert(t, !mappedFile.IsContentMapperFailureStub())
}

func TestDynamicContentMapperRefreshesForSavedOverlay(t *testing.T) {
t.Parallel()
for _, test := range []struct {
name string
save bool
watch bool
editAfterSave bool
openAfterWatch bool
closeAfterSave bool
}{
{name: "save", save: true},
{name: "watch", watch: true},
{name: "save and watch", save: true, watch: true},
{name: "save then edit", save: true, editAfterSave: true},
{name: "watch then open", watch: true, openAfterWatch: true},
{name: "save then close", save: true, closeAfterSave: true},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
files := map[string]any{
"/home/project/tsconfig.json": `{ "contentMappers": [{ "package": "mapper", "extensions": [".box"] }] }`,
"/home/project/node_modules/mapper/package.json": contentmappertest.PackageJSON(contentmappertest.DynamicVerbatimMapper),
"/home/project/mapper.config.json": `{ "version": 1 }`,
"/home/project/app.box": "export const value = 1;\n",
"/home/project/main.ts": `import { value } from "./app.box"; value;`,
}
init, utils := projecttestutil.GetSessionInitOptions(files, &project.SessionOptions{
CurrentDirectory: "/home/project",
DefaultLibraryPath: bundled.LibPath(),
TypingsLocation: projecttestutil.TestTypingsLocation,
PositionEncoding: lsproto.PositionEncodingKindUTF8,
RunExternalCode: true,
}, nil)
lifecycle := &contentmappertest.ProjectLifecycle{}
init.Spawner = contentmappertest.NewSpawnerWithProjectLifecycle(lifecycle)
session := project.NewSession(init)
defer session.Close()

ctx := context.Background()
mainURI := lsproto.DocumentUri("file:///home/project/main.ts")
configURI := lsproto.DocumentUri("file:///home/project/mapper.config.json")
session.DidOpenFile(ctx, mainURI, 1, files["/home/project/main.ts"].(string), lsproto.LanguageKindTypeScript)
if !test.openAfterWatch {
session.DidOpenFile(ctx, configURI, 1, files["/home/project/mapper.config.json"].(string), lsproto.LanguageKindJSON)
}
languageService, err := session.GetLanguageService(ctx, mainURI)
assert.NilError(t, err)
opens := lifecycle.Opens.Load()
closes := lifecycle.Closes.Load()
assert.Assert(t, opens > 0)

const savedContent = `{ "version": 2 }`
if !test.openAfterWatch {
session.DidChangeFile(ctx, configURI, 2, []lsproto.TextDocumentContentChangePartialOrWholeDocument{{
WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{Text: savedContent},
}})
// Flush the edit before saving; the mapper cannot observe unsaved overlay content.
languageService, err = session.GetLanguageService(ctx, mainURI)
assert.NilError(t, err)
}
assert.Equal(t, lifecycle.Opens.Load(), opens)
assert.Equal(t, lifecycle.Closes.Load(), closes)
program := languageService.GetProgram()

assert.NilError(t, utils.FS().WriteFile(configURI.FileName(), savedContent))
if test.save {
session.DidSaveFile(ctx, configURI)
}
if test.watch {
session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{{Uri: configURI, Type: lsproto.FileChangeTypeChanged}})
}
if test.editAfterSave {
session.DidChangeFile(ctx, configURI, 3, []lsproto.TextDocumentContentChangePartialOrWholeDocument{{
WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{Text: `{ "version": 3 }`},
}})
}
if test.openAfterWatch {
session.DidOpenFile(ctx, configURI, 1, savedContent, lsproto.LanguageKindJSON)
}
if test.closeAfterSave {
session.DidCloseFile(ctx, configURI)
}
session.WaitForBackgroundTasks()
languageService, err = session.GetLanguageService(ctx, mainURI)
assert.NilError(t, err)
assert.Equal(t, lifecycle.Closes.Load(), closes+1)
assert.Equal(t, lifecycle.Opens.Load(), opens+1)
assert.Assert(t, languageService.GetProgram() != program)

session.DidSaveFile(ctx, mainURI)
session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{{Uri: mainURI, Type: lsproto.FileChangeTypeChanged}})
session.WaitForBackgroundTasks()
_, err = session.GetLanguageService(ctx, mainURI)
assert.NilError(t, err)
assert.Equal(t, lifecycle.Opens.Load(), opens+1)
})
}
}

func TestDynamicContentMapperRefreshesForWatchedOverlayAlias(t *testing.T) {
t.Parallel()
const projectDirectory = "/home/project/node_modules/pkg"
const configContent = `{ "version": 1 }`
const mainContent = `import { value } from "./app.box"; value;`
files := map[string]any{
projectDirectory: vfstest.Symlink("/packages/pkg"),
"/home/project/node_modules/mapper/package.json": contentmappertest.PackageJSON(contentmappertest.DynamicVerbatimMapper),
"/packages/pkg/tsconfig.json": `{ "compilerOptions": { "resolveJsonModule": true }, "files": ["main.ts", "mapper.config.json"], "contentMappers": [{ "package": "mapper", "extensions": [".box"] }] }`,
"/packages/pkg/mapper.config.json": configContent,
"/packages/pkg/app.box": "export const value = 1;\n",
"/packages/pkg/main.ts": mainContent,
}
init, utils := projecttestutil.GetSessionInitOptions(files, &project.SessionOptions{
CurrentDirectory: projectDirectory,
DefaultLibraryPath: bundled.LibPath(),
PositionEncoding: lsproto.PositionEncodingKindUTF8,
RunExternalCode: true,
}, nil)
lifecycle := &contentmappertest.ProjectLifecycle{}
init.Spawner = contentmappertest.NewSpawnerWithProjectLifecycle(lifecycle)
session := project.NewSession(init)
defer session.Close()

ctx := t.Context()
mainURI := lsproto.DocumentUri("file://" + projectDirectory + "/main.ts")
configURI := lsproto.DocumentUri("file://" + projectDirectory + "/mapper.config.json")
session.DidOpenFile(ctx, mainURI, 1, mainContent, lsproto.LanguageKindTypeScript)
_, err := session.GetLanguageService(ctx, mainURI)
assert.NilError(t, err)
session.DidOpenFile(ctx, configURI, 1, configContent, lsproto.LanguageKindJSON)
_, err = session.GetLanguageService(ctx, mainURI)
assert.NilError(t, err)
opens := lifecycle.Opens.Load()
closes := lifecycle.Closes.Load()
assert.Assert(t, opens > 0)

session.DidChangeFile(ctx, configURI, 2, []lsproto.TextDocumentContentChangePartialOrWholeDocument{{
WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{Text: `{ "version": 3 }`},
}})
_, err = session.GetLanguageService(ctx, mainURI)
assert.NilError(t, err)
assert.Equal(t, lifecycle.Opens.Load(), opens)
assert.Equal(t, lifecycle.Closes.Load(), closes)

assert.NilError(t, utils.FS().WriteFile("/packages/pkg/mapper.config.json", `{ "version": 2 }`))
session.DidChangeWatchedFiles(ctx, []*lsproto.FileEvent{{
Uri: "file:///packages/pkg/mapper.config.json",
Type: lsproto.FileChangeTypeChanged,
}})
session.WaitForBackgroundTasks()
_, err = session.GetLanguageService(ctx, mainURI)
assert.NilError(t, err)
assert.Equal(t, lifecycle.Opens.Load(), opens+1)
assert.Equal(t, lifecycle.Closes.Load(), closes+1)
content, ok := session.Snapshot().ReadFile(configURI.FileName())
assert.Assert(t, ok)
assert.Equal(t, content, `{ "version": 3 }`)
}

func TestDynamicContentMapperRefreshesForMixedWatchBatches(t *testing.T) {
t.Parallel()
for _, test := range []struct {
Expand Down
9 changes: 8 additions & 1 deletion tsc/internal/project/filechange.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ type FileChangeSummary struct {
// Only set when file watching is enabled
Deleted collections.Set[lsproto.DocumentUri]

// DiskChanged records disk changes, including those hidden by overlays, for consumers that read directly from disk.
DiskChanged collections.Set[lsproto.DocumentUri]

// IncludesWatchChangeOutsideNodeModules is true if the summary includes a create, change, or delete watch
// event of a file outside a node_modules directory.
IncludesWatchChangeOutsideNodeModules bool
Expand All @@ -60,11 +63,12 @@ func (f FileChangeSummary) Clone() FileChangeSummary {
f.Changed = *f.Changed.Clone()
f.Created = *f.Created.Clone()
f.Deleted = *f.Deleted.Clone()
f.DiskChanged = *f.DiskChanged.Clone()
return f
}

func (f FileChangeSummary) IsEmpty() bool {
return !f.InvalidateAll && f.Opened == "" && f.Reopened == "" && f.Closed.Len() == 0 && f.Changed.Len() == 0 && f.Created.Len() == 0 && f.Deleted.Len() == 0
return !f.InvalidateAll && f.Opened == "" && f.Reopened == "" && f.Closed.Len() == 0 && f.Changed.Len() == 0 && f.Created.Len() == 0 && f.Deleted.Len() == 0 && f.DiskChanged.Len() == 0
}

func (f FileChangeSummary) HasExcessiveWatchEvents() bool {
Expand Down Expand Up @@ -92,6 +96,9 @@ func mergeFileChangeSummary(dst *FileChangeSummary, src FileChangeSummary) {
for uri := range src.Deleted.Keys() {
dst.Deleted.Add(uri)
}
for uri := range src.DiskChanged.Keys() {
dst.DiskChanged.Add(uri)
}
if src.IncludesWatchChangeOutsideNodeModules {
dst.IncludesWatchChangeOutsideNodeModules = true
}
Expand Down
8 changes: 7 additions & 1 deletion tsc/internal/project/overlayfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,7 @@ func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, ma
watchChanged bool
changes []*FileChange
saved bool
saveObserved bool
created bool
deleted bool
watchObserved bool
Expand Down Expand Up @@ -474,6 +475,7 @@ func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, ma
events.watchChanged = false
case FileChangeKindSave:
events.saved = true
events.saveObserved = true
case FileChangeKindWatchCreate:
if events.deleted {
// Delete followed by create becomes a change
Expand Down Expand Up @@ -504,6 +506,10 @@ func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, ma
path := uri.PathKey(fs.caseSensitivity)
o := newOverlays[path]

if events.saveObserved || events.watchChanged || (o != nil || events.openChange != nil) && events.watchObserved {
result.DiskChanged.Add(uri)
}

if events.openChange != nil {
if result.Opened != "" || result.Reopened != "" {
panic("can only process one file open event at a time")
Expand Down Expand Up @@ -564,7 +570,7 @@ func (fs *overlayFS) processChanges(changes []FileChange) (FileChangeSummary, ma
}
}

if o != nil && (events.watchObserved || events.saved) {
if o != nil && (events.watchObserved || events.saveObserved) {
if matchesDiskText, _ := o.computeMatchesDiskText(fs.host); matchesDiskText != o.MatchesDiskText() {
o = newOverlay(o.FileName(), o.Content(), o.Version(), o.kind)
o.matchesDiskText = matchesDiskText
Expand Down
82 changes: 78 additions & 4 deletions tsc/internal/project/overlayfs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ func TestProcessChanges(t *testing.T) {

assert.Assert(t, result.Changed.Has(testURI1))
assert.Equal(t, result.Changed.Len(), 1)
assert.Assert(t, result.DiskChanged.Has(testURI1))
})

t.Run("save marks overlay as matching disk", func(t *testing.T) {
Expand All @@ -153,16 +154,87 @@ func TestProcessChanges(t *testing.T) {
URI: testURI1,
},
})
// We don't observe saves for snapshot changes,
// so they're not included in the summary
assert.Assert(t, result.IsEmpty())
assert.Equal(t, result.Changed.Len(), 0)
assert.Assert(t, result.DiskChanged.Has(testURI1))
assert.Assert(t, !result.IsEmpty())

// Check that the overlay is marked as matching disk text
fh := fs.GetFile(testURI1.FileName())
assert.Assert(t, fh != nil)
assert.Assert(t, fh.MatchesDiskText())
})

t.Run("save followed by edit records disk change", func(t *testing.T) {
t.Parallel()
fs := createOverlayFS()
const savedContent = "const x = 1;"
fs.processChanges([]FileChange{
{
Kind: FileChangeKindOpen,
URI: testURI1,
Version: 1,
Content: savedContent,
LanguageKind: lsproto.LanguageKindTypeScript,
},
})
assert.NilError(t, fs.host.WriteFile(testURI1.FileName(), savedContent))

result, _ := fs.processChanges([]FileChange{
{Kind: FileChangeKindSave, URI: testURI1},
{
Kind: FileChangeKindChange,
URI: testURI1,
Version: 2,
Changes: []lsproto.TextDocumentContentChangePartialOrWholeDocument{{
WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{Text: "const x = 2;"},
}},
},
})

assert.Assert(t, result.DiskChanged.Has(testURI1))
assert.Assert(t, !fs.GetFile(testURI1.FileName()).MatchesDiskText())
})

for _, test := range []struct {
name string
diskChange FileChangeKind
transition FileChangeKind
}{
{name: "watch then open", diskChange: FileChangeKindWatchChange, transition: FileChangeKindOpen},
{name: "save then reopen", diskChange: FileChangeKindSave, transition: FileChangeKindOpen},
{name: "save then close", diskChange: FileChangeKindSave, transition: FileChangeKindClose},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
fs := createOverlayFS()
const savedContent = "const x = 1;"
if test.diskChange == FileChangeKindSave {
fs.processChanges([]FileChange{{
Kind: FileChangeKindOpen,
URI: testURI1,
Version: 1,
Content: savedContent,
LanguageKind: lsproto.LanguageKindTypeScript,
}})
}
assert.NilError(t, fs.host.WriteFile(testURI1.FileName(), savedContent))

result, _ := fs.processChanges([]FileChange{
{Kind: test.diskChange, URI: testURI1},
{
Kind: test.transition,
URI: testURI1,
Version: 2,
Content: savedContent,
LanguageKind: lsproto.LanguageKindTypeScript,
},
})

assert.Assert(t, result.DiskChanged.Has(testURI1))
assert.Equal(t, result.Changed.Len(), 0)
})
}

t.Run("open falls back to file extension for unknown language kind", func(t *testing.T) {
t.Parallel()
fs := createOverlayFS()
Expand Down Expand Up @@ -240,12 +312,14 @@ func TestProcessChanges(t *testing.T) {

// Now process a watch change
assert.NilError(t, fs.host.WriteFile(testURI1.FileName(), "const x = 2;"))
fs.processChanges([]FileChange{
result, _ := fs.processChanges([]FileChange{
{
Kind: FileChangeKindWatchChange,
URI: testURI1,
},
})
assert.Equal(t, result.Changed.Len(), 0)
assert.Assert(t, result.DiskChanged.Has(testURI1))
assert.Assert(t, !fs.GetFile(testURI1.FileName()).MatchesDiskText())
})

Expand Down
Loading
Loading