Skip to content

Commit

Permalink
Merge 16e59f3 into 35f9dd5
Browse files Browse the repository at this point in the history
  • Loading branch information
Ken Howard committed Dec 2, 2018
2 parents 35f9dd5 + 16e59f3 commit ddd2426
Show file tree
Hide file tree
Showing 14 changed files with 236 additions and 133 deletions.
18 changes: 17 additions & 1 deletion __mocks__/@octokit/rest.ts
@@ -1,6 +1,10 @@
// tslint:disable:no-any no-unsafe-any
// tslint:disable:no-any no-unsafe-any no-magic-numbers
jest.genMockFromModule<object>('@octokit/rest');

const gistId = Math.random()
.toString(36)
.slice(7);

const gistsResponseData = [
{
created_at: new Date().toString(),
Expand Down Expand Up @@ -54,6 +58,18 @@ const gistsResponse = (): Promise<any> =>
});

const mockedGists = {
create: jest.fn((params) =>
Promise.resolve({
data: {
created_at: new Date().toString(),
description: params.description,
files: params.files,
id: gistId,
public: params.public,
updated_at: new Date().toString()
}
})
),
get: jest.fn((options) =>
Promise.resolve({
data: { ...gistsResponseData[0], id: options.gist_id }
Expand Down
2 changes: 1 addition & 1 deletion jest.config.js
Expand Up @@ -4,7 +4,7 @@ module.exports = {
testMatch: ['**/__tests__/**/(*.)+(spec|test).ts?(x)'],
coverageThreshold: {
global: {
branches: 60, // TODO: adjust this back to 80%
branches: 70, // TODO: adjust this back to 80%
functions: 80,
lines: 80,
statements: -30 // TODO: adjust this back to 10
Expand Down
40 changes: 20 additions & 20 deletions package.json
Expand Up @@ -19,53 +19,53 @@
"commands": [
{
"command": "extension.openCodeBlock",
"title": "GIST: Open Block",
"category": "Gist"
"title": "Open Block",
"category": "GIST"
},
{
"command": "extension.openFavoriteCodeBlock",
"title": "GIST: Open Favorite Block",
"category": "Gist"
"title": "Open Favorite Block",
"category": "GIST"
},
{
"command": "extension.createCodeBlock",
"title": "GIST: Create New Block",
"category": "Gist"
"title": "Create New Block",
"category": "GIST"
},
{
"command": "extension.openCodeBlockInBrowser",
"title": "GIST: Open Block In Browser",
"category": "Gist"
"title": "Open Block In Browser",
"category": "GIST"
},
{
"command": "extension.deleteCodeBlock",
"title": "GIST: Delete Block",
"category": "Gist"
"title": "Delete Block",
"category": "GIST"
},
{
"command": "extension.removeFileFromCodeBlock",
"title": "GIST: Remove From Block",
"category": "Gist"
"title": "Remove From Block",
"category": "GIST"
},
{
"command": "extension.addToCodeBlock",
"title": "GIST: Add To Block",
"category": "Gist"
"title": "Add To Block",
"category": "GIST"
},
{
"command": "extension.changeCodeBlockDescription",
"title": "GIST: Change Block Description",
"category": "Gist"
"title": "Change Block Description",
"category": "GIST"
},
{
"command": "extension.insertCode",
"title": "GIST: Insert Code Into Current File",
"category": "Gist"
"title": "Insert Code Into Current File",
"category": "GIST"
},
{
"command": "extension.toggleProfile",
"title": "GIST: Toggle Profile",
"category": "Gist"
"title": "Toggle Profile",
"category": "GIST"
}
],
"keybindings": [
Expand Down
31 changes: 31 additions & 0 deletions src/commands/__tests__/gists.commands.test.ts
Expand Up @@ -6,6 +6,7 @@ import { gists } from '../../gists/gists-service';
import { logger } from '../../logger';
import { profiles } from '../../profiles';
import {
createCodeBlock,
openCodeBlock,
openFavoriteCodeBlock,
updateCodeBlock,
Expand All @@ -14,6 +15,8 @@ import {

jest.mock('fs');
jest.mock('path');
const promptMock: any = jest.genMockFromModule('../../utils/prompt');
jest.mock('../../utils/prompt', promptMock);

const executeCommandSpy = jest.spyOn(commands, 'executeCommand');
const configureSpy = jest.spyOn(gists, 'configure');
Expand Down Expand Up @@ -132,4 +135,32 @@ describe('Gists Commands Tests', () => {
});
});
});
describe('#createCodeBlock', () => {
test('should create a code block and open the files', async () => {
expect.assertions(2);

promptMock.prompt.mockImplementation(
(_msg: string, defaultValue: string) => Promise.resolve(defaultValue)
);

const codeBlock = {
fileName: `${TMP_DIRECTORY_PREFIX}_123456789abcdefg_random_string/test-file-name.md`,
getText: jest.fn(() => 'test-file-content')
};

const editor = {
document: codeBlock,
selection: { isEmpty: true }
};

(<any>window).activeTextEditor = editor;

await createCodeBlock();

expect(editor.document.getText.mock.calls).toHaveLength(2);
expect(executeCommandSpy.mock.calls[0][0]).toStrictEqual(
'workbench.action.keepEditor'
);
});
});
});
73 changes: 64 additions & 9 deletions src/commands/gists.commands.ts
@@ -1,10 +1,15 @@
import { commands, window, workspace } from 'vscode';

import { configure, getGist, getGists, updateGist } from '../gists';
import { configure, createGist, getGist, getGists, updateGist } from '../gists';
import { insights } from '../insights';
import { logger } from '../logger';
import { profiles } from '../profiles';
import { extractTextDocumentDetails, filesSync, notify } from '../utils';
import {
extractTextDocumentDetails,
filesSync,
notify,
prompt
} from '../utils';

const _formatGistsForQuickPick = (gists: Gist[]): QuickPickGist[] =>
gists.map((item, i, j) => ({
Expand All @@ -27,6 +32,24 @@ const _openDocument = async (file: string): Promise<void> => {
commands.executeCommand('workbench.action.keepEditor');
};

const _openCodeBlock = async (
gistId: string
): Promise<{
fileCount: number;
files: { [x: string]: { content: string } };
id: string;
}> => {
const { id, files, fileCount } = await getGist(gistId);
const filePaths = filesSync(id, files);

// await is not available not available in forEach
for (const filePath of filePaths) {
await _openDocument(filePath);
}

return { id, files, fileCount };
};

const openCodeBlock = async (favorite = false): Promise<void> => {
let gistName = '';
try {
Expand All @@ -41,13 +64,7 @@ const openCodeBlock = async (favorite = false): Promise<void> => {
gistName = `"${selected.block.name}"`;
logger.info(`User Selected Gist: "${selected.label}"`);

const { id, files, fileCount } = await getGist(selected.block.id);
const filePaths = filesSync(id, files);

// await is not available not available in forEach
for (const filePath of filePaths) {
await _openDocument(filePath);
}
const { fileCount } = await _openCodeBlock(selected.block.id);

logger.info('Opened Gist');
insights.track('open', undefined, {
Expand Down Expand Up @@ -105,7 +122,45 @@ const updateGistAccessKey = (): void => {
insights.track('updateGistAccessKey', { url });
};

const createCodeBlock = async (): Promise<void> => {
let gistName = '';
try {
const editor = window.activeTextEditor;
if (!editor) {
throw new Error('Open a file before creating');
}
const selection = editor.selection;
const content = editor.document.getText(
selection.isEmpty ? undefined : selection
);
const details = extractTextDocumentDetails(editor.document);
const filename = (details && details.filename) || 'untitled.txt';
const description = await prompt('Enter description');
const isPublic =
((await prompt('Public? Y = Yes, N = No', 'Y')) || 'Y') // TODO: add configuration for default value
.slice(0, 1)
.toLowerCase() === 'y';

gistName = description || filename;

const gist = await createGist(
{ [filename]: { content } },
description,
isPublic
);

await _openCodeBlock(gist.id);
} catch (err) {
const context = gistName ? ` ${gistName}` : '';
const error: Error = err as Error;
logger.error(`createCodeBlock > ${error && error.message}`);
insights.exception('createCodeBlock', { messsage: error.message });
notify.error(`Could Not Create${context}`, `Reason: ${error.message}`);
}
};

export {
createCodeBlock,
updateGistAccessKey,
openCodeBlock,
openFavoriteCodeBlock,
Expand Down
8 changes: 2 additions & 6 deletions src/extension.ts
@@ -1,6 +1,7 @@
import { commands, ExtensionContext, workspace } from 'vscode';

import {
createCodeBlock,
createProfile,
openCodeBlock,
openFavoriteCodeBlock,
Expand Down Expand Up @@ -45,6 +46,7 @@ export function activate(context: ExtensionContext): void {
'extension.openFavoriteCodeBlock',
openFavoriteCodeBlock
);
commands.registerCommand('extension.createCodeBlock', createCodeBlock);
workspace.onDidSaveTextDocument(updateCodeBlock);
commands.registerCommand(
'extension.updateGistAccessKey',
Expand Down Expand Up @@ -78,12 +80,6 @@ export function activate(context: ExtensionContext): void {
});
});

commands.registerCommand(
'extension.createCodeBlock',
(): void => {
// intentionally left blank
}
);
commands.registerCommand(
'extension.openCodeBlockInBrowser',
(): void => {
Expand Down

0 comments on commit ddd2426

Please sign in to comment.