Skip to content

WIP use vscode.workspace.fs APIs #1770

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"argsIgnorePattern": "^_",
"caughtErrors": "none"
}
]
],
"no-restricted-imports": ["warn", "fs", "fs/promises", "node:fs"]
},
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"ignorePatterns": ["assets", "out", "dist", "**/*.d.ts"]
Expand Down
12 changes: 7 additions & 5 deletions .vscode-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,24 +55,25 @@ if (vsixPath) {
if (!path.isAbsolute(vsixPath)) {
vsixPath = path.join(__dirname, vsixPath);
}
console.log("Installing VSIX " + vsixPath);
!isDebugRun && console.log("Installing VSIX " + vsixPath);
installExtensions.push(vsixPath);

// Determine version to use
const match = /swift-vscode-(\d+.\d+.\d+(-dev)?)(-\d+)?.vsix/g.exec(path.basename(vsixPath));
if (match) {
versionStr = match[1];
}
console.log("Running tests against extension version " + versionStr);
!isDebugRun && console.log("Running tests against extension version " + versionStr);

extensionDevelopmentPath = `${__dirname}/.vscode-test/extensions/${publisher}.${name}-${versionStr}`;
console.log("Running tests against extension development path " + extensionDevelopmentPath);
!isDebugRun &&
console.log("Running tests against extension development path " + extensionDevelopmentPath);
} else {
extensionDependencies.push("vadimcn.vscode-lldb", "llvm-vs-code-extensions.lldb-dap");
}

const vscodeVersion = process.env["VSCODE_VERSION"] ?? "stable";
console.log("Running tests against VS Code version " + vscodeVersion);
!isDebugRun && console.log("Running tests against VS Code version " + vscodeVersion);

const installConfigs = [];
for (const ext of installExtensions) {
Expand All @@ -91,7 +92,8 @@ const env = {
...process.env,
RUNNING_UNDER_VSCODE_TEST_CLI: "1",
};
console.log("Running tests against environment:\n" + JSON.stringify(env, undefined, 2));
!isDebugRun &&
console.log("Running tests against environment:\n" + JSON.stringify(env, undefined, 2));

module.exports = defineConfig({
tests: [
Expand Down
12 changes: 7 additions & 5 deletions docs/contributor/writing-tests-for-vscode-swift.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,9 @@ Mocking file system access can be a challenging endeavor that is prone to fail w
The [`mock-fs`](https://github.com/tschaub/mock-fs) module is a well-maintained library that can be used to mitigate these issues by temporarily replacing Node's built-in `fs` module with an in-memory file system. This can be useful for testing logic that uses the `fs` module without actually reaching out to the file system. Just a single function call can be used to configure what the fake file system will contain:

```typescript
import * as chai from "chai";
import { expect } from "chai";
import * as mockFS from "mock-fs";
import * as fs from "fs/promises";
import * as vscode from "vscode";

suite("mock-fs example", () => {
// This teardown step is also important to make sure your tests clean up the
Expand All @@ -137,8 +137,9 @@ suite("mock-fs example", () => {
mockFS({
"/path/to/some/file": "Some really cool file contents",
});
await expect(fs.readFile("/path/to/some/file", "utf-8"))
.to.eventually.equal("Some really cool file contents");
const uri = vscode.Uri.file("/path/to/some/file");
expect(Buffer.from(await vscode.workspace.fs.readFile(uri)).toString("utf-8"))
.to.equal("Some really cool file contents");
});
});
```
Expand All @@ -148,7 +149,8 @@ In order to test failure paths, you can either create an empty file system or us
```typescript
test("file is not readable by the current user", async () => {
mockFS({ "/path/to/file": mockFS.file({ mode: 0o000 }) });
await expect(fs.readFile("/path/to/file", "utf-8")).to.eventually.be.rejected;
const uri = vscode.Uri.file("/path/to/file");
await expect(vscode.workspace.fs.readFile(uri)).to.eventually.be.rejected;
});
```

Expand Down
9 changes: 5 additions & 4 deletions src/PackageWatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
//===----------------------------------------------------------------------===//

import * as path from "path";
import * as fs from "fs/promises";
import * as vscode from "vscode";
import { FolderContext } from "./FolderContext";
import { FolderOperation, WorkspaceContext } from "./WorkspaceContext";
Expand Down Expand Up @@ -151,10 +150,12 @@ export class PackageWatcher {
private async readSwiftVersionFile() {
const versionFile = path.join(this.folderContext.folder.fsPath, ".swift-version");
try {
const contents = await fs.readFile(versionFile);
return Version.fromString(contents.toString().trim());
const contents = Buffer.from(
await vscode.workspace.fs.readFile(vscode.Uri.file(versionFile))
);
return Version.fromString(contents.toString("utf-8").trim());
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
if ((error as vscode.FileSystemError).code !== "FileNotFound") {
this.workspaceContext.logger.error(
`Failed to read .swift-version file at ${versionFile}: ${error}`
);
Expand Down
9 changes: 4 additions & 5 deletions src/SwiftPackage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
//===----------------------------------------------------------------------===//

import * as vscode from "vscode";
import * as fs from "fs/promises";
import * as path from "path";
import { execSwift, getErrorDescription, hashString } from "./utilities/utilities";
import { isPathInsidePath } from "./utilities/filesystem";
Expand Down Expand Up @@ -301,8 +300,8 @@ export class SwiftPackage {
): Promise<PackageResolved | undefined> {
try {
const uri = vscode.Uri.joinPath(folder, "Package.resolved");
const contents = await fs.readFile(uri.fsPath, "utf8");
return new PackageResolved(contents);
const contents = Buffer.from(await vscode.workspace.fs.readFile(uri));
return new PackageResolved(contents.toString("utf-8"));
} catch {
// failed to load resolved file return undefined
return undefined;
Expand Down Expand Up @@ -351,8 +350,8 @@ export class SwiftPackage {
vscode.Uri.file(BuildFlags.buildDirectoryFromWorkspacePath(folder.fsPath, true)),
"workspace-state.json"
);
const contents = await fs.readFile(uri.fsPath, "utf8");
return JSON.parse(contents);
const contents = Buffer.from(await vscode.workspace.fs.readFile(uri));
return JSON.parse(contents.toString("utf8"));
} catch {
// failed to load resolved file return undefined
return undefined;
Expand Down
15 changes: 10 additions & 5 deletions src/TestExplorer/TestRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import * as vscode from "vscode";
import * as path from "path";
import * as stream from "stream";
import * as os from "os";
import * as asyncfs from "fs/promises";
import { FolderContext } from "../FolderContext";
import { compactMap, execFile, getErrorDescription } from "../utilities/utilities";
import { createSwiftTask } from "../tasks/SwiftTaskProvider";
Expand Down Expand Up @@ -695,7 +694,7 @@ export class TestRunner {
);
const swiftTestingArgs = SwiftTestingBuildAguments.build(
fifoPipePath,
attachmentFolder
attachmentFolder?.fsPath
);
const testBuildConfig = await TestingConfigurationFactory.swiftTestingConfig(
this.folderContext,
Expand Down Expand Up @@ -919,11 +918,17 @@ export class TestRunner {
}
}

const buffer = await asyncfs.readFile(filename, "utf8");
const buffer = Buffer.from(
await vscode.workspace.fs.readFile(vscode.Uri.file(filename))
);
const xUnitParser = new TestXUnitParser(
this.folderContext.toolchain.hasMultiLineParallelTestOutput
);
const results = await xUnitParser.parse(buffer, runState, this.workspaceContext.logger);
const results = await xUnitParser.parse(
buffer.toString("utf-8"),
runState,
this.workspaceContext.logger
);
if (results) {
this.testRun.appendOutput(
`\r\nExecuted ${results.tests} tests, with ${results.failures} failures and ${results.errors} errors.\r\n`
Expand Down Expand Up @@ -978,7 +983,7 @@ export class TestRunner {
);
const swiftTestingArgs = SwiftTestingBuildAguments.build(
fifoPipePath,
attachmentFolder
attachmentFolder?.fsPath
);

const swiftTestBuildConfig = await TestingConfigurationFactory.swiftTestingConfig(
Expand Down
Loading