Skip to content

Add New Swift File command #1018

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

Merged
merged 2 commits into from
Aug 27, 2024
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
23 changes: 23 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@
"title": "Create New Project...",
"category": "Swift"
},
{
"command": "swift.newFile",
"title": "Create New Swift File...",
"shortTitle": "Swift File",
"category": "Swift"
},
{
"command": "swift.updateDependencies",
"title": "Update Package Dependencies",
Expand Down Expand Up @@ -600,6 +606,10 @@
}
],
"keybindings": [
{
"command": "swift.newFile",
"key": "Alt+S Alt+N"
},
{
"command": "swift.insertFunctionComment",
"key": "Alt+Ctrl+/",
Expand All @@ -620,6 +630,19 @@
"when": "testId"
}
],
"file/newFile": [
{
"command": "swift.newFile",
"group": "file"
}
],
"explorer/context": [
{
"command": "swift.newFile",
"group": "swift",
"when": "swift.isActivated"
}
],
"commandPalette": [
{
"command": "swift.createNewProject",
Expand Down
2 changes: 2 additions & 0 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { resetPackage } from "./commands/resetPackage";
import { updateDependencies } from "./commands/dependencies/update";
import { runPluginTask } from "./commands/runPluginTask";
import { runTestMultipleTimes } from "./commands/testMultipleTimes";
import { newSwiftFile } from "./commands/newFile";

/**
* References:
Expand Down Expand Up @@ -67,6 +68,7 @@ export function registerToolchainCommands(
*/
export function register(ctx: WorkspaceContext): vscode.Disposable[] {
return [
vscode.commands.registerCommand("swift.newFile", uri => newSwiftFile(uri)),
vscode.commands.registerCommand("swift.resolveDependencies", () =>
resolveDependencies(ctx)
),
Expand Down
56 changes: 56 additions & 0 deletions src/commands/newFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2021-2024 the VS Code Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VS Code Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import * as fs from "fs/promises";
import * as path from "path";
import * as vscode from "vscode";

const extension = "swift";
const defaultFileName = `Untitled.${extension}`;

export async function newSwiftFile(
uri?: vscode.Uri,
isDirectory: (uri: vscode.Uri) => Promise<boolean> = async uri => {
return (await vscode.workspace.fs.stat(uri)).type === vscode.FileType.Directory;
}
) {
if (uri) {
// Attempt to create the file at the given directory.
const dir = (await isDirectory(uri)) ? uri.fsPath : path.dirname(uri.fsPath);
const defaultName = vscode.Uri.file(path.join(dir, defaultFileName));
const targetUri = await vscode.window.showSaveDialog({
defaultUri: defaultName,
title: "Enter a file path to be created",
});

if (!targetUri) {
return;
}

try {
await fs.writeFile(targetUri.fsPath, "", "utf-8");
const document = await vscode.workspace.openTextDocument(targetUri);
await vscode.languages.setTextDocumentLanguage(document, "swift");
await vscode.window.showTextDocument(document);
} catch (err) {
vscode.window.showErrorMessage(`Failed to create ${targetUri.fsPath}`);
}
} else {
// If no path is supplied then open an untitled editor w/ Swift language type
const document = await vscode.workspace.openTextDocument({
language: "swift",
});
await vscode.window.showTextDocument(document);
}
}
53 changes: 53 additions & 0 deletions test/suite/commands/NewFile.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2024 the VS Code Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VS Code Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

// import * as assert from "assert";
import * as vscode from "vscode";
import * as assert from "assert";
import * as path from "path";
import { anything, deepEqual, verify, when } from "ts-mockito";
import { newSwiftFile } from "../../../src/commands/newFile";
import { mockNamespace } from "../../unit-tests/MockUtils";
import { TemporaryFolder } from "../../../src/utilities/tempFolder";
import { fileExists } from "../../../src/utilities/filesystem";

suite("NewFile Command Test Suite", () => {
const workspaceMock = mockNamespace(vscode, "workspace");
const windowMock = mockNamespace(vscode, "window");
const languagesMock = mockNamespace(vscode, "languages");

test("Creates a blank file if no URI is provided", async () => {
await newSwiftFile(undefined);

verify(workspaceMock.openTextDocument(deepEqual({ language: "swift" }))).once();
verify(windowMock.showTextDocument(anything())).once();
});

test("Creates file at provided directory", async () => {
const folder = await TemporaryFolder.create();
const file = path.join(folder.path, "MyFile.swift");

when(windowMock.showSaveDialog(anything())).thenReturn(
Promise.resolve(vscode.Uri.file(file))
);

await newSwiftFile(vscode.Uri.file(folder.path), () => Promise.resolve(true));

assert.ok(await fileExists(file));

verify(workspaceMock.openTextDocument(anything())).once();
verify(languagesMock.setTextDocumentLanguage(anything(), "swift")).once();
verify(windowMock.showTextDocument(anything())).once();
});
});