Skip to content

Commit

Permalink
馃敤 Major refactor of code
Browse files Browse the repository at this point in the history
  • Loading branch information
dkundel committed May 18, 2017
1 parent 8102201 commit b3dd6e3
Show file tree
Hide file tree
Showing 18 changed files with 1,898 additions and 853 deletions.
61 changes: 34 additions & 27 deletions .vscode/launch.json
@@ -1,28 +1,35 @@
// A launch configuration that compiles the extension and then opens it inside a new window
{
"version": "0.1.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/src",
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/test",
"preLaunchTask": "npm"
}
]
}
"version": "0.1.0",
"configurations": [{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/out/src/**/*.js"
],
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}",
"--extensionTestsPath=${workspaceRoot}/out/test"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/out/test/**/*.js"
],
"preLaunchTask": "npm"
}
]
}
3 changes: 1 addition & 2 deletions .vscode/settings.json
Expand Up @@ -5,6 +5,5 @@
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
"typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version
}
}
2 changes: 1 addition & 1 deletion .vscode/tasks.json
Expand Up @@ -23,7 +23,7 @@
"args": ["run", "compile", "--loglevel", "silent"],

// The tsc compiler is started in watching mode
"isWatching": true,
"isBackground": true,

// use the standard tsc in watch mode problem matcher to find compile problems in the output.
"problemMatcher": "$tsc-watch"
Expand Down
32 changes: 22 additions & 10 deletions package.json
Expand Up @@ -11,7 +11,7 @@
"license": "MIT",
"publisher": "dkundel",
"engines": {
"vscode": "^0.10.1"
"vscode": "^1.0.0"
},
"categories": [
"Other"
Expand All @@ -24,7 +24,7 @@
"url": "https://github.com/dkundel/vscode-new-file.git"
},
"activationEvents": [
"onCommand:extension.createNewFile"
"onCommand:newFile.createNewFile"
],
"main": "./out/src/extension",
"contributes": {
Expand Down Expand Up @@ -61,31 +61,43 @@
},
"commands": [
{
"command": "extension.createNewFile",
"command": "newFile.createNewFile",
"title": "Files: Advanced New File"
}
],
"keybindings": [
{
"command": "extension.createNewFile",
"command": "newFile.createNewFile",
"key": "alt+ctrl+n",
"mac": "alt+cmd+`"
"mac": "alt+cmd+n"
}
]
},
"scripts": {
"vscode:prepublish": "node ./node_modules/vscode/bin/compile",
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./"
"vscode:prepublish": "tsc -p ./",
"compile": "tsc -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install",
"test": "node ./node_modules/vscode/bin/test"
},
"devDependencies": {
"@types/expect.js": "^0.3.29",
"@types/mocha": "^2.2.41",
"@types/mockery": "^1.4.29",
"@types/node": "^7.0.18",
"@types/rimraf": "^0.0.28",
"expect.js": "^0.3.1",
"mocha": "^3.4.1",
"mockery": "^1.4.0",
"rimraf": "^2.4.4",
"typescript": "^1.6.2",
"vscode": "0.10.x"
"typescript": "^2.3.2",
"vscode": "^1.1.0"
},
"dependencies": {
"@types/debug": "^0.0.29",
"@types/mkdirp": "^0.3.29",
"@types/q": "^1.0.0",
"debug": "^2.6.7",
"mkdirp": "^0.5.1",
"q": "^1.4.1"
}
}
}
188 changes: 22 additions & 166 deletions src/extension.ts
@@ -1,16 +1,18 @@
/// <reference path="../typings/tsd.d.ts" />
import {
commands,
ExtensionContext,
window
} from 'vscode'
import * as Debug from 'debug';

import { ExtensionContext, commands, window, workspace, QuickPickItem, QuickPickOptions, TextEditor } from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import * as Q from 'q';
import * as mkdirp from 'mkdirp';
import { FileController } from './file-controller';

export function activate(context: ExtensionContext) {
const debug = Debug('vscode-new-file');

console.log('Your extension "vscode-new-file" is now active!');
export function activate(context: ExtensionContext) {
debug('Your extension "vscode-new-file" is now active!');

let disposable = commands.registerCommand('extension.createNewFile', () => {
let disposable = commands.registerCommand('newFile.createNewFile', () => {

const File = new FileController().readSettings();

Expand All @@ -25,166 +27,20 @@ export function activate(context: ExtensionContext) {
});

context.subscriptions.push(disposable);
}

export interface NewFileSettings {
showFullPath: boolean;
relativeTo: string;
rootDirectory: string;
defaultFileExtension: string;
defaultBaseFileName: string;
}

export class FileController {
private settings: NewFileSettings;

public readSettings(): FileController{
let config = workspace.getConfiguration('newFile');

this.settings = {
showFullPath: config.get('showFullPath', true),
relativeTo: config.get('relativeTo', 'file'),
rootDirectory: config.get('rootDirectory', this.homedir()),
defaultFileExtension: config.get('defaultFileExtension', '.ts'),
defaultBaseFileName: config.get('defaultBaseFileName', 'newFile')
};

return this;
}

public determineRoot(): string {
let root: string;

if (this.settings.relativeTo === 'project') {
root = workspace.rootPath;
} else if (this.settings.relativeTo === 'file') {
if (window.activeTextEditor) {
root = path.dirname(window.activeTextEditor.document.fileName);
} else if (workspace.rootPath) {
root = workspace.rootPath;
}
}

if (!root) {
this.settings.relativeTo === 'root';
root = this.settings.rootDirectory;

if (root.indexOf('~') === 0) {
root = path.join(this.homedir(), root.substr(1));
}
}

return root;
}

public getDefaultFileValue(root): string {
const newFileName = this.settings.defaultBaseFileName;
const defaultExtension = this.settings.defaultFileExtension;

const currentFileName: string = window.activeTextEditor ? window.activeTextEditor.document.fileName : '';
const ext: string = path.extname(currentFileName) || defaultExtension;

if (this.settings.showFullPath) {
return path.join(root, `${newFileName}${ext}`);
} else {
return `${newFileName}${ext}`;
}
}

public showFileNameDialog(): Q.Promise<string> {
const deferred: Q.Deferred<string> = Q.defer<string>();
let question = `What's the path and name of the new file?`;

if (!this.settings.showFullPath) {
if (this.settings.relativeTo === 'project') {
question += ' (Relative to project root)';
} else if (this.settings.relativeTo === 'file') {
question += ' (Relative to current file)';
}
}

let rootPath = this.determineRoot();
let defaultFileValue = this.getDefaultFileValue(rootPath);

window.showInputBox({
prompt: question,
value: defaultFileValue
}).then(selectedFilePath => {
if (selectedFilePath === null || typeof selectedFilePath === 'undefined') {
deferred.reject(undefined);
return;
}
selectedFilePath = selectedFilePath || defaultFileValue;
if (selectedFilePath) {
if (this.settings.showFullPath) {
deferred.resolve(selectedFilePath);
} else {
deferred.resolve(this.getFullPath(rootPath, selectedFilePath));
}
}
});

return deferred.promise;
}

public createFile(newFileName): Q.Promise<string> {
const deferred: Q.Deferred<string> = Q.defer<string>();
let dirname: string = path.dirname(newFileName);
let fileExists: boolean = fs.existsSync(newFileName);

if (!fileExists) {
mkdirp.sync(dirname);

fs.appendFile(newFileName, '', (err) => {
if (err) {
deferred.reject(err);
return;
}

deferred.resolve(newFileName);
});
} else {
deferred.resolve(newFileName);
}

return deferred.promise;
}

public openFileInEditor(fileName): Q.Promise<TextEditor> {
const deferred: Q.Deferred<TextEditor> = Q.defer<TextEditor>();

workspace.openTextDocument(fileName).then((textDocument) => {
if (!textDocument) {
deferred.reject(new Error('Could not open file!'));
return;
}
let disposableDeprecated = commands.registerCommand('extension.createNewFile', () => {
window.showWarningMessage('You are using a deprecated event. Please switch your keyboard shortcut to use "newFile.createNewFile"');
const File = new FileController().readSettings();

window.showTextDocument(textDocument).then((editor) => {
if (!editor) {
deferred.reject(new Error('Could not show document!'));
return;
File.showFileNameDialog()
.then(File.createFile)
.then(File.openFileInEditor)
.catch((err) => {
if (err.message) {
window.showErrorMessage(err.message);
}

deferred.resolve(editor);
});
});

return deferred.promise;
}

private getFullPath(root: string, filePath: string): string {
if (filePath.indexOf('/') === 0) {
return filePath;
}

if (filePath.indexOf('~') === 0) {
return path.join(this.homedir(), filePath.substr(1));
}
});

return path.resolve(root, filePath);
}

private homedir(): string {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
context.subscriptions.push(disposableDeprecated);
}

0 comments on commit b3dd6e3

Please sign in to comment.