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 templates #4

Merged
merged 3 commits into from
Oct 6, 2019
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
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';

export const DIRECTORY_FOR_TEMPLATES = 'awesome-tree-templates';

export 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);
});
}
59 changes: 36 additions & 23 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ 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';
import { getMatchingTemplate } from './savedTemplates/getMatchingTemplate';

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 @@ -55,16 +59,37 @@ export function activate() {

uniquePathFiles.forEach(async (filePathTemplate) => {
const filePath: string = path.join(createdItemUri.fsPath, renderVariableTemplate(filePathTemplate, [infoAboutNewDirectory]));
const content = createFileContent(filePathTemplate, infoAboutSiblingDirectories, [infoAboutNewDirectory]);
const savedTemplate = getMatchingTemplate(filePath);

let content: string;
if (savedTemplate === null) {
content = createFileContent(filePathTemplate, infoAboutSiblingDirectories, [infoAboutNewDirectory]);
} else {
content = savedTemplate.map(line =>
renderVariableTemplate(line, [infoAboutNewDirectory])
).join('\n');
}

const textDocument = await createDocument(filePath, content);

vscode.window.showTextDocument(textDocument);
});


} else if(isEmptyFile(createdItemUri, outputChannel)) {
const savedTemplate = getMatchingTemplate(createdItemUri.fsPath);
const relativePath = getRelativePath(createdItemUri.fsPath);
const infoAboutNewFile = getInfoAboutPath(relativePath);
if (savedTemplate!==null) {

const content = savedTemplate.map(line =>
renderVariableTemplate(line, [infoAboutNewFile])
).join('\n');

createDocument(createdItemUri.fsPath, content);
return;
}

const parentDir = path.dirname(createdItemUri.fsPath);

const fileToSkip = path.basename(createdItemUri.fsPath);
Expand All @@ -75,6 +100,10 @@ export function activate() {
return fs.readFileSync(filePath).toString().split('\n');
});

if (contents.length < 2) {
return;
}

const [baseFile, ...otherFiles] = contents;
const lineToGenerate: string[] = [];

Expand Down Expand Up @@ -120,22 +149,15 @@ 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;
let uri: string = `https://github.com/Bajdzis/vscode-awesome-tree/issues/new?title=${error.toString()}`;

if (error instanceof Error) {
uri = `https://github.com/Bajdzis/vscode-awesome-tree/issues/new?title=${error.toString()}&body=\`\`\`${error.stack}\`\`\``;
}

if (error instanceof AwesomeTreeError) {
uri = `https://github.com/Bajdzis/vscode-awesome-tree/issues/new?title=${error.getTitle()}&body=${error.getBody()}`;
}
Expand Down Expand Up @@ -193,15 +215,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);
}
Loading