Skip to content

Commit

Permalink
feat: create templates
Browse files Browse the repository at this point in the history
  • Loading branch information
Bajdzis committed Oct 6, 2019
1 parent 2d363cc commit fdaee59
Show file tree
Hide file tree
Showing 10 changed files with 176 additions and 27 deletions.
7 changes: 7 additions & 0 deletions icons/awesome-template.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 9 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 21 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,26 @@
},
"main": "./out/extension.js",
"contributes": {
"commands": [],
"commands": [
{
"command": "extension.saveAsTemplate",
"title": "Save file as awesome template",
"category": "FILE",
"icon": {
"dark": "icons/awesome-template.svg",
"light": "icons/awesome-template.svg"
}
}
],
"menus": {
"editor/title": [
{
"command": "extension.saveAsTemplate",
"group": "navigation@1",
"when": "resourceScheme == file"
}
]
},
"configuration": {
"title": "Awesome Tree",
"properties": {
Expand Down Expand Up @@ -80,6 +99,7 @@
"vscode-test": "^1.2.0"
},
"dependencies": {
"@types/uuid": "^3.4.5",
"lodash": "^4.17.15"
}
}
4 changes: 4 additions & 0 deletions src/__mocks__/vscode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ export const window = {
createOutputChannel: jest.fn(() => outputChanelMock),
showInformationMessage: jest.fn(),
} as {[key in keyof typeof vscode.window]: jest.Mock};

export const commands = {
registerCommand: jest.fn(),
} as {[key in keyof typeof vscode.commands]: jest.Mock};
66 changes: 66 additions & 0 deletions src/commands/saveAsTemplate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import * as fs from 'fs';
import * as vscode from 'vscode';
import * as path from 'path';
import * as uuid from 'uuid/v4';
import { getRelativePath } from '../fileSystem/getRelativePath';
import { getInfoAboutPath } from '../fileInfo/getInfoAboutPath';
import { createVariableTemplate } from '../variableTemplate/createVariableTemplate';
import { createDocument } from '../fileSystem/createDocument';
import { addExtensionToRecommendations } from '../fileSystem/addExtensionToRecommendations';

const DIRECTORY_FOR_TEMPLATES = 'awesome-tree-templates';

function findWorkspacePath(searchFsPath:string): string | undefined {
const { workspaceFolders } = vscode.workspace;
if(!workspaceFolders){
return;
}
for (let i = 0; i < workspaceFolders.length; i++) {
const {fsPath} = workspaceFolders[i].uri;
if(searchFsPath.indexOf(fsPath) === 0){
return fsPath;
}
}
}

export function saveAsTemplate(file: vscode.Uri) {
const workspacePath = findWorkspacePath(file.fsPath);
if (workspacePath === undefined) {
vscode.window.showWarningMessage(`Can't find workspace directory for file: '${file.fsPath}'`);
return;
}

const relativePath = getRelativePath(file.fsPath);
const templateId = uuid();
const templatePath = path.join(workspacePath, DIRECTORY_FOR_TEMPLATES, 'templates', `template-${templateId}.json` );
const templateDatabasePath = path.join(workspacePath, DIRECTORY_FOR_TEMPLATES, 'database-awesome.json' );
const infoAboutNewFile = getInfoAboutPath(relativePath);
const lines = fs.readFileSync(file.fsPath).toString().split('\n');
const templateLines = lines.map(line => createVariableTemplate(line, [infoAboutNewFile]));

const template = {
baseFilePath: relativePath,
pathsTemplate: [
createVariableTemplate(relativePath, [infoAboutNewFile])
],
templateId
};

let currentSavedTemplates: Array<any>;

try {
currentSavedTemplates = JSON.parse(fs.readFileSync(templateDatabasePath).toString());
} catch (error) {
currentSavedTemplates = [];
}

currentSavedTemplates.push(template);

Promise.all([
createDocument(templatePath, JSON.stringify(templateLines, null, 4)),
createDocument(templateDatabasePath, JSON.stringify(currentSavedTemplates, null, 4))
]).then(() => {
vscode.window.showInformationMessage('Saved success!');
addExtensionToRecommendations(workspacePath);
});
}
27 changes: 5 additions & 22 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ import { getRelativePath } from './fileSystem/getRelativePath';
import { getSiblingInfo, DirectoriesInfo } from './fileInfo/getSiblingInfo';
import { getPathTemplates } from './fileSystem/getPathTemplates';
import { getFilesContentAsTemplate } from './fileSystem/getFilesContentAsTemplate';
import { saveAsTemplate } from './commands/saveAsTemplate';
import { createDocument } from './fileSystem/createDocument';

export function activate() {
export function activate(context: vscode.ExtensionContext) {
const settingProvider = vscode.workspace.getConfiguration('awesomeTree');
const fileSystemWatcher = vscode.workspace.createFileSystemWatcher('**/*',false, true, true);
const outputChannel = vscode.window.createOutputChannel('Awesome tree');


context.subscriptions.push(vscode.commands.registerCommand('extension.saveAsTemplate', saveAsTemplate));
outputChannel.appendLine('Listening for file changes started!');

fileSystemWatcher.onDidCreate(async(createdItemUri: vscode.Uri) => {
Expand Down Expand Up @@ -120,17 +123,6 @@ export function activate() {
}
});

function createDocument(filePath: string, content: string): Promise<vscode.TextDocument> {
return new Promise((resolve, reject) => {
ensureDirectoryExistence(filePath);
fs.writeFile(filePath, content, {}, async (err) => {
if(err){
return reject(err);
}
vscode.workspace.openTextDocument(filePath).then(resolve);
});
});
}

function createGithubIssue(error: Error) {
const MAX_CHARACTERS_IN_URI: number = 4000;
Expand Down Expand Up @@ -193,15 +185,6 @@ export function activate() {
}, [] as string[]);
}

function ensureDirectoryExistence(filePath:string) {
const dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}

function isDirectory(uri: vscode.Uri): boolean {
return fs.lstatSync(uri.fsPath).isDirectory();
}
Expand Down
10 changes: 8 additions & 2 deletions src/extenstion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,24 @@ describe('extenstion', () => {
let mockWatcher: {
[key in keyof vscode.FileSystemWatcher]?: jest.Mock
};
let mockContext: vscode.ExtensionContext;

beforeEach(() => {
mockWatcher = {
onDidCreate: jest.fn()
};
mockContext = {
subscriptions: {
push: jest.fn()
}
} as any as vscode.ExtensionContext;
const createSystemWatcher = vscode.workspace.createFileSystemWatcher as jest.Mock;
createSystemWatcher.mockReturnValueOnce(mockWatcher);
});

it('should start listen for create file', () => {
expect(vscode.workspace.createFileSystemWatcher).not.toHaveBeenCalled();
activate();
activate(mockContext);

expect(vscode.workspace.createFileSystemWatcher).toHaveBeenCalled();
expect(mockWatcher.onDidCreate).toHaveBeenCalled();
Expand All @@ -47,7 +53,7 @@ describe('extenstion', () => {
});
});

activate();
activate(mockContext);
});

});
30 changes: 30 additions & 0 deletions src/fileSystem/addExtensionToRecommendations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as fs from 'fs';
import * as path from 'path';
import * as process from 'child_process';

export function addExtensionToRecommendations(workspaceDirectory: string){
try {
const extensionsPath = path.join(workspaceDirectory, '.vscode', 'extensions.json');
let fileData;
if (fs.existsSync(extensionsPath)) {
fileData = JSON.parse(fs.readFileSync(extensionsPath).toString());
if (!Array.isArray(fileData.recommendations)) {
fileData.recommendations = [];
}
if (fileData.recommendations.includes('bajdzis.awesome-tree')) {
return;
}
} else {
fileData = {
recommendations: []
};
}
fileData.recommendations.push('bajdzis.awesome-tree');

fs.writeFileSync(extensionsPath, JSON.stringify(fileData, null, 2));

process.spawn('git add ".vscode/extensions.json" -f');
} catch (error) {
console.log(error);
}
}
15 changes: 15 additions & 0 deletions src/fileSystem/createDocument.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as fs from 'fs';
import * as vscode from 'vscode';
import { ensureDirectoryExistence } from './ensureDirectoryExistence';

export function createDocument(filePath: string, content: string): Promise<vscode.TextDocument> {
return new Promise((resolve, reject) => {
ensureDirectoryExistence(filePath);
fs.writeFile(filePath, content, {}, async (err) => {
if(err){
return reject(err);
}
vscode.workspace.openTextDocument(filePath).then(resolve);
});
});
}
11 changes: 11 additions & 0 deletions src/fileSystem/ensureDirectoryExistence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as fs from 'fs';
import * as path from 'path';

export function ensureDirectoryExistence(filePath:string) {
const dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}

0 comments on commit fdaee59

Please sign in to comment.