Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into chore/update-deps-audit
Browse files Browse the repository at this point in the history
  • Loading branch information
Klaus-Keller committed Sep 15, 2023
2 parents 3630284 + 807f94a commit 5ac8c1d
Show file tree
Hide file tree
Showing 29 changed files with 426 additions and 184 deletions.
11 changes: 11 additions & 0 deletions packages/core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# @sap/guided-answers-extension-core

## 1.31.0

### Minor Changes

- 3976fd5: Enhanced output log with log levels

### Patch Changes

- Updated dependencies [3976fd5]
- @sap/guided-answers-extension-types@1.31.0

## 1.30.1

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@sap/guided-answers-extension-core",
"description": "Guided Answers extension core module",
"version": "1.30.1",
"version": "1.31.0",
"license": "Apache-2.0",
"private": true,
"main": "dist/index.js",
Expand Down
30 changes: 20 additions & 10 deletions packages/core/src/guided-answers-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,7 @@ export function getGuidedAnswerApi(options?: APIOptions): GuidedAnswerAPI {
const apiHost = options?.apiHost ?? API_HOST;
const ide = options?.ide;
const extensions = options?.extensions ?? new Set<string>();
const logger = options?.logger ?? {
logString: (m) => {
console.log(m);
}
};
const logger = options?.logger ?? getConsoleLogger();

return {
getApiInfo: () => ({ host: apiHost, version: VERSION }),
Expand All @@ -70,6 +66,21 @@ export function getGuidedAnswerApi(options?: APIOptions): GuidedAnswerAPI {
};
}

/**
* Return logger for console logging.
*
* @returns - logger to log to console
*/
function getConsoleLogger(): Logger {
return {
logTrace: console.trace,
logDebug: console.debug,
logInfo: console.info,
logWarn: console.warn,
logError: console.error
};
}

/**
* Convert <img src="...">-tags in body to point to absolute path.
*
Expand Down Expand Up @@ -185,10 +196,9 @@ function convertCommand(command: GuidedAnswersEnhancement['command'], logger: Lo
try {
argument = command.exec.args ? JSON.parse(command.exec.args) : undefined;
} catch (error) {
logger.logString(
`Error when parsing argument '${
command.exec.args
}' for HTML enhancement. Extension id: '${extensionId}', command id: '${commandId}', ${error?.toString()}`
logger.logError(
`Error when parsing argument '${command.exec.args}' for HTML enhancement. Extension id: '${extensionId}', command id: '${commandId}'.`,
error
);
}
return { extensionId, commandId, argument } as VSCodeCommand;
Expand Down Expand Up @@ -244,7 +254,7 @@ function getEnhancements(
}
}
} catch (error) {
logger.logString(`Error processing enhancements, ${error?.toString()}`);
logger.logError('Error processing enhancements', error);
}
return { htmlEnhancements, nodeCommands };
}
Expand Down
35 changes: 24 additions & 11 deletions packages/core/test/guided-answers-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import type {
FeedbackOutcomePayload,
GuidedAnswerNode,
GuidedAnswersQueryOptions,
GuidedAnswerTreeSearchResult
GuidedAnswerTreeSearchResult,
Logger
} from '@sap/guided-answers-extension-types';
import { getGuidedAnswerApi } from '../src';

Expand Down Expand Up @@ -632,7 +633,7 @@ describe('Guided Answers Api: getNodeById()', () => {
const options: APIOptions = {
ide: 'SBAS',
extensions: new Set(['sbas.ext']),
logger: { logString: jest.fn() }
logger: { logError: jest.fn() } as Partial<Logger> as Logger
};
mockedAxios.get.mockImplementation(() => Promise.resolve({ data }));

Expand All @@ -641,7 +642,10 @@ describe('Guided Answers Api: getNodeById()', () => {

// Result check
expect(result.COMMANDS).toBe(undefined);
expect(options.logger?.logString).toBeCalledWith(expect.stringContaining('WRONG'));
expect(options.logger?.logError).toBeCalledWith(
expect.stringContaining('Error'),
expect.objectContaining({ message: expect.stringContaining('WRONG') })
);
});

test('Get node with different images, should add host to src where applicable', async () => {
Expand Down Expand Up @@ -935,7 +939,7 @@ describe('Guided Answers Api: getNodePath()', () => {
const options: APIOptions = {
ide: 'SBAS',
extensions: new Set(['my.ext.id']),
logger: { logString: jest.fn() }
logger: { logError: jest.fn() } as Partial<Logger> as Logger
};
mockedAxios.get.mockImplementation((url: string) => {
const data = nodes.find((n) => url.endsWith(`/${n.NODE_ID}`));
Expand All @@ -953,7 +957,10 @@ describe('Guided Answers Api: getNodePath()', () => {
expect(result.length).toBe(2);
expect(result[0].BODY).toBe('<p>Should not be modified at all</p>');
expect(result[1].BODY).toBe('<p>Also should not be modified at all</p>');
expect(options.logger?.logString).toBeCalledWith(expect.stringContaining('Error when parsing argument'));
expect(options.logger?.logError).toBeCalledWith(
expect.stringContaining('Error when parsing argument'),
expect.objectContaining({ message: expect.stringContaining('JSON') })
);
});

test('Get node path, error in getEnhancements()', async () => {
Expand All @@ -965,15 +972,18 @@ describe('Guided Answers Api: getNodePath()', () => {
};
const options: APIOptions = {
ide: 'SBAS',
logger: { logString: jest.fn() }
logger: { logError: jest.fn() } as Partial<Logger> as Logger
};
mockedAxios.get.mockResolvedValue({ data });

// Test execution
const result = await getGuidedAnswerApi(options).getNodePath([1]);

// Result check
expect(options.logger?.logString).toBeCalledWith(expect.stringContaining('Error'));
expect(options.logger?.logError).toBeCalledWith(
expect.stringContaining('Error'),
expect.objectContaining({ message: expect.stringContaining('enhancements') })
);
expect(result[0]?.BODY).toBe('<p>Should remain</p>');
});

Expand Down Expand Up @@ -1158,14 +1168,14 @@ describe('Guided Answers Api: sendFeedbackOutcome()', () => {
});

describe('Guided Answers Api: console logger', () => {
const originalLog = console.log;
const originalConsoleError = console.error;

beforeEach(() => {
console.log = jest.fn();
console.error = jest.fn();
});

afterEach(() => {
console.log = originalLog;
console.error = originalConsoleError;
});

test('Get node by id: Fallback to console logger for erroneous enhancement', async () => {
Expand Down Expand Up @@ -1200,6 +1210,9 @@ describe('Guided Answers Api: console logger', () => {

// Result check
expect(result?.BODY).toMatchSnapshot();
expect(console.log).toBeCalledWith(expect.stringContaining(`Error when parsing argument '{'`));
expect(console.error).toBeCalledWith(
expect.stringContaining(`Error when parsing argument '{'`),
expect.objectContaining({ message: expect.stringContaining('JSON') })
);
});
});
6 changes: 6 additions & 0 deletions packages/ide-extension/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# sap-guided-answer-extension

## 1.31.0

### Minor Changes

- 3976fd5: Enhanced output log with log levels

## 1.30.1

## 1.30.0
Expand Down
6 changes: 3 additions & 3 deletions packages/ide-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "%guidedAnswer.description%",
"publisher": "SAPOSS",
"license": "Apache-2.0",
"version": "1.30.1",
"version": "1.31.0",
"icon": "media/guided-answers-extension.png",
"categories": [
"Education"
Expand All @@ -22,7 +22,7 @@
"url": "https://github.com/SAP/guided-answers-extension.git"
},
"engines": {
"vscode": "^1.73.1"
"vscode": "^1.74.1"
},
"main": "./dist/extension-min.js",
"private": false,
Expand Down Expand Up @@ -83,7 +83,7 @@
"@sap/guided-answers-extension-core": "workspace:*",
"@sap/guided-answers-extension-types": "workspace:*",
"@types/uuid": "9.0.4",
"@types/vscode": "1.73.1",
"@types/vscode": "1.74.1",
"@vscode/vsce": "2.21.0",
"applicationinsights": "2.5.0",
"esbuild": "0.19.3",
Expand Down
4 changes: 2 additions & 2 deletions packages/ide-extension/src/bookmarks/bookmarks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Memento } from 'vscode';
import type { Bookmarks, GuidedAnswerTree } from '@sap/guided-answers-extension-types';
import { logString } from '../logger/logger';
import { logError } from '../logger/logger';

let globalStateApi: Memento;

Expand Down Expand Up @@ -37,6 +37,6 @@ export function updateBookmarks(bookmarks: Bookmarks): void {
}
globalStateApi
.update('bookmark', newBookmarks)
.then(undefined, (error) => logString(`Error updating bookmarks.\n${error?.toString()}`));
.then(undefined, (error) => logError(`Error updating bookmarks.`, error));
}
}
18 changes: 4 additions & 14 deletions packages/ide-extension/src/enhancement/commandHandler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { commands, window } from 'vscode';
import type { Command } from '@sap/guided-answers-extension-types';
import { isTerminalCommand, isVSCodeCommand } from '@sap/guided-answers-extension-types';
import { logString } from '../logger/logger';
import { logError, logInfo } from '../logger/logger';

/**
* Execute command execution requests.
Expand All @@ -12,27 +12,17 @@ export function handleCommand(command: Command): void {
if (isVSCodeCommand(command.exec)) {
const commandId = command.exec.commandId;
const argument = command.exec.argument;
logString(
`Executing VSCode command '${commandId}'. Full command info including arguments:\n${JSON.stringify(
command,
null,
2
)} `
);
logInfo(`Executing VSCode command '${commandId}'. Full command info including arguments:`, command);
commands
.executeCommand(commandId, argument)
?.then(undefined, (error) =>
logString(`Error while executing command '${commandId}'\n${error?.toString()}`)
);
?.then(undefined, (error) => logError(`Error while executing command '${commandId}'`, error));
}
if (isTerminalCommand(command.exec)) {
const terminal = window.createTerminal(`Guided Answers extension by SAP`);
if (terminal) {
const commandString = command.exec.arguments.join(' ');
terminal.show();
logString(
`Executing terminal command '${commandString}'. Full command info:\n${JSON.stringify(command, null, 2)}`
);
logInfo(`Executing terminal command '${commandString}'. Full command info:`, command);
if (command.exec.cwd) {
terminal.sendText(`cd "${command.exec.cwd}"`);
}
Expand Down
10 changes: 4 additions & 6 deletions packages/ide-extension/src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ExtensionContext } from 'vscode';
import { commands, window, workspace } from 'vscode';
import { getDevSpace, getIde } from '@sap/guided-answers-extension-core';
import { logString } from './logger/logger';
import { logError, logInfo } from './logger/logger';
import { GuidedAnswersPanel, GuidedAnswersSerializer } from './panel/guidedAnswersPanel';
import { initTelemetry } from './telemetry';
import { GuidedAnswersUriHandler } from './links';
Expand All @@ -18,15 +18,13 @@ export function activate(context: ExtensionContext): void {
try {
context.subscriptions.push(initTelemetry());
} catch (error) {
logString(`Error during initialization of telemetry.\n${error?.toString()}`);
logError(`Error during initialization of telemetry.`, error);
}
try {
initBookmarks(context.globalState);
initLastVisited(context.globalState);
} catch (error) {
logString(
`Error during initialization of functionality that relies on VSCode's global state storage.\n${error?.toString()}`
);
logError(`Error during initialization of functionality that relies on VSCode's global state storage.`, error);
}
context.subscriptions.push(
commands.registerCommand('sap.ux.guidedAnswer.openGuidedAnswer', async (startOptions?: StartOptions) => {
Expand All @@ -39,7 +37,7 @@ export function activate(context: ExtensionContext): void {
ide: await getIde(),
startOptions
};
logString(`Guided Answers command called. Options: ${JSON.stringify(options)}`);
logInfo(`Guided Answers command called. Options:`, options);
let guidedAnswersPanel: GuidedAnswersPanel | undefined = GuidedAnswersPanel.getInstance();
if (openInNewTab || !guidedAnswersPanel) {
guidedAnswersPanel = new GuidedAnswersPanel(options);
Expand Down
4 changes: 2 additions & 2 deletions packages/ide-extension/src/last-visited/lastVisited.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Memento } from 'vscode';
import type { LastVisitedGuide } from '@sap/guided-answers-extension-types';
import { logString } from '../logger/logger';
import { logError } from '../logger/logger';

let globalStateApi: Memento;

Expand Down Expand Up @@ -30,5 +30,5 @@ export function getAllLastVisitedGuides(): LastVisitedGuide[] {
export function updateLastVisitedGuides(lastVisitedGuides: LastVisitedGuide[]): void {
globalStateApi
.update('lastVisitedGuides', lastVisitedGuides)
.then(undefined, (error) => logString(`Error updating lastVisitedGuides.\n${error?.toString()}`));
.then(undefined, (error) => logError(`Error updating lastVisitedGuides.`, error));
}
10 changes: 4 additions & 6 deletions packages/ide-extension/src/links/guided-answers-uri-handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { commands } from 'vscode';
import type { ProviderResult, Uri, UriHandler } from 'vscode';
import { logString } from '../logger/logger';
import { logError, logInfo } from '../logger/logger';
import { extractLinkInfo } from './link-info';

/**
Expand All @@ -16,16 +16,14 @@ export class GuidedAnswersUriHandler implements UriHandler {
*/
handleUri(uri: Uri): ProviderResult<void> {
const link = decodeURIComponent(uri.toString());
logString(`Guided Answers extension called from URI: ${link}`);
logInfo(`Guided Answers extension called from URI: ${link}`);
const startOptions = extractLinkInfo(link);
logString(`Extracted information from link: ${startOptions ? JSON.stringify(startOptions) : ''}`);
logInfo(`Extracted information from link:`, startOptions);
if (startOptions?.treeId) {
commands
.executeCommand('sap.ux.guidedAnswer.openGuidedAnswer', startOptions)
?.then(undefined, (error) =>
logString(
`Error while executing start command 'sap.ux.guidedAnswer.openGuidedAnswer'.\n${error?.toString()}`
)
logError(`Error while executing start command 'sap.ux.guidedAnswer.openGuidedAnswer'`, error)
);
}
}
Expand Down
Loading

0 comments on commit 5ac8c1d

Please sign in to comment.