Skip to content
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

feat: create file if file does not exist. closes #2274 #2392

Merged
merged 2 commits into from
Feb 23, 2018
Merged
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
37 changes: 17 additions & 20 deletions src/cmd_line/commands/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,23 +86,28 @@ export class FileCommand extends node.CommandBase {
return;
}

let currentFilePath = vscode.window.activeTextEditor!.document.uri.path;
let editorFilePath = vscode.window.activeTextEditor!.document.uri.path;
this._arguments.name = <string>untildify(this._arguments.name);
let newFilePath = path.isAbsolute(this._arguments.name)
let filePath = path.isAbsolute(this._arguments.name)
? this._arguments.name
: path.join(path.dirname(currentFilePath), this._arguments.name);

if (newFilePath !== currentFilePath) {
const newFileDoesntExist = !await this.fileExists(newFilePath);
const newFileHasNoExtname = path.extname(newFilePath) === '';
if (newFileDoesntExist && newFileHasNoExtname) {
const pathWithExtname = newFilePath + path.extname(currentFilePath);
if (await this.fileExists(pathWithExtname)) {
newFilePath = pathWithExtname;
: path.join(path.dirname(editorFilePath), this._arguments.name);

if (filePath !== editorFilePath) {
if (!fs.existsSync(filePath)) {
// if file does not exist and does not have an extension
// try to find it with the same extension
if (path.extname(filePath) === '') {
const pathWithExt = filePath + path.extname(editorFilePath);
if (fs.existsSync(pathWithExt)) {
filePath = pathWithExt;
}
}

// create file
fs.closeSync(fs.openSync(filePath, 'w'));
}

let folder = vscode.Uri.file(newFilePath);
let folder = vscode.Uri.file(filePath);
await vscode.commands.executeCommand(
'vscode.open',
folder,
Expand All @@ -121,12 +126,4 @@ export class FileCommand extends node.CommandBase {
}
}
}

protected fileExists(filePath: string) {
return new Promise<boolean>((resolve, reject) => {
fs.stat(filePath, async (error, stat) => {
resolve(!error);
});
});
}
}