From c5b3f0ae19ff30abfe3d6e36e1dddd64251f4f9d Mon Sep 17 00:00:00 2001 From: Takashi Tamura Date: Sun, 1 Oct 2023 09:06:43 +0900 Subject: [PATCH 1/3] Use util.inspect(). --- .../components/locatorlib/synctex.test.ts | 12 +++---- test/utils/decycle.ts | 31 ------------------- 2 files changed, 5 insertions(+), 38 deletions(-) delete mode 100644 test/utils/decycle.ts diff --git a/test/unittests/components/locatorlib/synctex.test.ts b/test/unittests/components/locatorlib/synctex.test.ts index ef1696851..d8d56f649 100644 --- a/test/unittests/components/locatorlib/synctex.test.ts +++ b/test/unittests/components/locatorlib/synctex.test.ts @@ -1,11 +1,9 @@ import * as assert from 'assert' import * as path from 'path' - -import {getFixtureDir, runUnitTestWithFixture} from '../../../utils/ciutils' -import {FakeLogger} from '../../../utils/fakecomponents' - -import {SyncTexJs} from '../../../../src/components/locatorlib/synctex' -import {decycle} from '../../../utils/decycle' +import { getFixtureDir, runUnitTestWithFixture } from '../../../utils/ciutils' +import { FakeLogger } from '../../../utils/fakecomponents' +import { SyncTexJs } from '../../../../src/components/locatorlib/synctex' +import { inspect } from 'util' suite('unit test suite', () => { @@ -21,7 +19,7 @@ suite('unit test suite', () => { } const synctexjs = new SyncTexJs(fakeExtension) const ret = synctexjs.parseSyncTexForPdf(pdfFilePath) - const output = JSON.stringify(decycle(ret), null, ' ') + const output = inspect(ret, {showHidden: true}) // console.log(output) assert.ok(output) }) diff --git a/test/utils/decycle.ts b/test/utils/decycle.ts deleted file mode 100644 index 3adaba018..000000000 --- a/test/utils/decycle.ts +++ /dev/null @@ -1,31 +0,0 @@ -export function decycle(obj: unknown, memo = new Set()): any { - if (!obj) { - return obj - } - if (typeof obj !== 'object') { - return obj - } - memo.add(obj) - if (obj instanceof Array) { - return obj.map(e => decycle(e, memo)) - } - const ret = Object.create(null) - Object.entries(obj).forEach(([key, val]) => { - if (typeof val === 'object') { - if (memo.has(val)) { - if (Object.values(val).every(e => typeof e !== 'object')) { - ret[key] = val - } else { - ret[key] = `(cyclic ref)` - } - } else { - memo.add(val) - ret[key] = decycle(val, memo) - } - } else { - ret[key] = decycle(val, memo) - } - - }) - return ret -} From 5604b0ad516fcfb0fbbf64cd5d803981e645263b Mon Sep 17 00:00:00 2001 From: Takashi Tamura Date: Sun, 1 Oct 2023 10:51:36 +0900 Subject: [PATCH 2/3] Uset util.inspect() instead of JSON.stringify() for logging. --- src/components/builder.ts | 3 ++- src/components/configuration.ts | 3 ++- src/components/eventbus.ts | 3 ++- src/components/locator.ts | 5 +++-- src/components/locatorlib/synctex.ts | 9 +++++---- src/components/logger.ts | 3 ++- src/components/manager.ts | 3 ++- src/components/managerlib/bibwatcher.ts | 3 ++- src/components/managerlib/managerwatcher.ts | 3 ++- src/components/managerlib/pdfwatcher.ts | 5 +++-- src/components/server.ts | 13 +++++++------ src/components/viewer.ts | 19 ++++++++++--------- src/components/viewerlib/pdfviewerpanel.ts | 3 ++- src/providers/completionlib/command.ts | 3 ++- src/providers/completionlib/environment.ts | 3 ++- src/providersmanager.ts | 3 ++- src/utils/inspect.ts | 9 +++++++++ 17 files changed, 59 insertions(+), 34 deletions(-) create mode 100644 src/utils/inspect.ts diff --git a/src/components/builder.ts b/src/components/builder.ts index e022240ef..037c6079d 100644 --- a/src/components/builder.ts +++ b/src/components/builder.ts @@ -12,6 +12,7 @@ import type { Manager } from './manager' import type { LwStatusBarItem } from './statusbaritem' import { statPath } from '../lib/lwfs/lwfs' import { ExternalPromise } from '../utils/externalpromise' +import { inspectCompact } from '../utils/inspect' const maxPrintLine = '10000' @@ -245,7 +246,7 @@ export class Builder { private buildStep(rootFile: string, step: StepCommand, {stepIndex, totalStepsLength}: {stepIndex: number, totalStepsLength: number}) { this.extension.logger.logCommand(`Recipe step ${stepIndex}`, step.command, step.args) - this.extension.logger.info(`Recipe step env: ${JSON.stringify(step.env)}`) + this.extension.logger.info(`Recipe step env: ${inspectCompact(step.env)}`) const envVars = Object.create(null) as ProcessEnv Object.keys(process.env).forEach(key => envVars[key] = process.env[key]) const currentEnv = step.env diff --git a/src/components/configuration.ts b/src/components/configuration.ts index 1c355fb10..da18568e1 100644 --- a/src/components/configuration.ts +++ b/src/components/configuration.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode' import { Logger } from './logger' +import { inspectReadable } from '../utils/inspect' export class Configuration { @@ -35,7 +36,7 @@ export class Configuration { const configuration = vscode.workspace.getConfiguration(undefined, workspace) for(const config of this.configurationsToLog) { const value = configuration.get(config) - this.extension.logger.info(`${config}: ${JSON.stringify(value, null, ' ')}`) + this.extension.logger.info(`${config}: ${inspectReadable(value)}`) } } } diff --git a/src/components/eventbus.ts b/src/components/eventbus.ts index 47845f247..eda403413 100644 --- a/src/components/eventbus.ts +++ b/src/components/eventbus.ts @@ -2,6 +2,7 @@ import type * as vscode from 'vscode' import type {PdfViewerState} from '../../types/latex-toybox-protocol-types/index' import { AwaitableEventEmitter } from './eventbuslib/awaitableeventemitter' import type { Logger } from './logger' +import { inspectCompact } from '../utils/inspect' export type EventName = 'auxupdated' | @@ -41,7 +42,7 @@ export class EventBus { }) { this.allEmitters.forEach((emitter) => { emitter.event((arg) => { - extension.logger.debug(`Event ${emitter.eventName} triggered. Payload: ${JSON.stringify(arg)}`) + extension.logger.debug(`Event ${emitter.eventName} triggered. Payload: ${inspectCompact(arg)}`) }) }) } diff --git a/src/components/locator.ts b/src/components/locator.ts index 0ddec716a..c0688680b 100644 --- a/src/components/locator.ts +++ b/src/components/locator.ts @@ -12,6 +12,7 @@ import type { Logger } from './logger' import type { Manager } from './manager' import type { Viewer } from './viewer' import { ExternalPromise } from '../utils/externalpromise' +import { inspectCompact } from '../utils/inspect' export type SyncTeXRecordForward = { page: number, @@ -177,7 +178,7 @@ export class Locator { private invokeSyncTeXCommandForward(line: number, col: number, filePath: string, pdfFile: string): Thenable { const configuration = vscode.workspace.getConfiguration('latex-toybox') const args = ['view', '-i', `${line}:${col + 1}:${filePath}`, '-o', pdfFile] - this.extension.logger.info(`Execute synctex with args ${JSON.stringify(args)}`) + this.extension.logger.info(`Execute synctex with args ${inspectCompact(args)}`) const command = configuration.get('synctex.path') as string const proc = cp.spawn(command, args, {cwd: path.dirname(pdfFile)}) @@ -227,7 +228,7 @@ export class Locator { const configuration = vscode.workspace.getConfiguration('latex-toybox') const args = ['edit', '-o', `${page}:${x}:${y}:${pdfPath}`] - this.extension.logger.info(`Executing synctex with args ${JSON.stringify(args)}`) + this.extension.logger.info(`Executing synctex with args: ${inspectCompact(args)}`) const command = configuration.get('synctex.path') as string const proc = cp.spawn(command, args, {cwd: path.dirname(pdfPath)}) diff --git a/src/components/locatorlib/synctex.ts b/src/components/locatorlib/synctex.ts index cade6588f..fd72fab43 100644 --- a/src/components/locatorlib/synctex.ts +++ b/src/components/locatorlib/synctex.ts @@ -7,6 +7,7 @@ import {iconvLiteSupportedEncodings} from '../../utils/convertfilename' import {isSameRealPath} from '../../utils/pathnormalize' import { existsPath, readFileAsBuffer } from '../../lib/lwfs/lwfs' import type { ILogger } from '../../interfaces' +import { inspectCompact } from '../../utils/inspect' class Rectangle { @@ -110,7 +111,7 @@ export class SyncTexJs { } if (!await existsPath(synctexFile) && !await existsPath(synctexFileGz)) { - this.extension.logger.error(`[SyncTexJs] .synctex and .synctex.gz file not found: ${JSON.stringify({synctexFile, synctexFileGz})}`) + this.extension.logger.error(`[SyncTexJs] .synctex and .synctex.gz file not found: ${inspectCompact({synctexFile, synctexFileGz})}`) } throw new SyncTexJsError(`parseSyncTexForPdf failed with: ${pdfFile}`) @@ -139,13 +140,13 @@ export class SyncTexJs { } async syncTexJsForward(line: number, filePath: string, pdfFile: string) { - this.extension.logger.info(`[SyncTexJs] Execute syncTexJsForward: ${JSON.stringify({pdfFile, filePath, line})}`) + this.extension.logger.info(`[SyncTexJs] Execute syncTexJsForward: ${inspectCompact({pdfFile, filePath, line})}`) const pdfSyncObject = await this.parseSyncTexForPdf(pdfFile) const inputFilePath = await this.findInputFilePathForward(filePath, pdfSyncObject) if (inputFilePath === undefined) { const inputFiles = Object.keys(pdfSyncObject.blockNumberLine) const inputFilesStr = JSON.stringify(inputFiles, null, ' ') - throw new SyncTexJsError(`[SyncTexJs] No relevant entry of the tex file found in the synctex file: ${JSON.stringify({filePath, pdfFile, line, inputFilesStr})}`) + throw new SyncTexJsError(`[SyncTexJs] No relevant entry of the tex file found in the synctex file: ${inspectCompact({filePath, pdfFile, line, inputFilesStr})}`) } const linePageBlocks = pdfSyncObject.blockNumberLine[inputFilePath] @@ -183,7 +184,7 @@ export class SyncTexJs { } async syncTexJsBackward(page: number, x: number, y: number, pdfPath: string) { - this.extension.logger.info(`[SyncTexJs] Execute syncTexJsBackward: ${JSON.stringify({pdfPath, page, x, y})}`) + this.extension.logger.info(`[SyncTexJs] Execute syncTexJsBackward: ${inspectCompact({pdfPath, page, x, y})}`) const pdfSyncObject = await this.parseSyncTexForPdf(pdfPath) const y0 = y - pdfSyncObject.offset.y const x0 = x - pdfSyncObject.offset.x diff --git a/src/components/logger.ts b/src/components/logger.ts index 1ad483972..5e2bcc227 100644 --- a/src/components/logger.ts +++ b/src/components/logger.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode' import { ILogger } from '../interfaces' +import { inspectCompact } from '../utils/inspect' export class Logger implements ILogger { @@ -16,7 +17,7 @@ export class Logger implements ILogger { logCommand(message: string, command: string, args: readonly string[] = []) { this.info(message + ': ' + command) - this.info(message + ' args: ' + JSON.stringify(args)) + this.info(message + ' args: ' + inspectCompact(args)) } debug(message: string) { diff --git a/src/components/manager.ts b/src/components/manager.ts index 24a8da2db..27eda9505 100644 --- a/src/components/manager.ts +++ b/src/components/manager.ts @@ -31,6 +31,7 @@ import type { Commander } from '../commander' import type { DuplicateLabels } from './duplicatelabels' import type { CompletionUpdater } from './completionupdater' import { ManagerWatcher } from './managerlib/managerwatcher' +import { inspectReadable } from '../utils/inspect' /** @@ -385,7 +386,7 @@ export class Manager { try { this.#rootFilePromise = rootFilePromise const wsfolders = vscode.workspace.workspaceFolders?.map(e => e.uri.toString(true)) - this.extension.logger.info(`Current workspace folders: ${JSON.stringify(wsfolders)}`) + this.extension.logger.info(`Current workspace folders: ${inspectReadable(wsfolders)}`) this.localRootFile = undefined const findMethods = [ () => this.finderUtils.findRootFromMagic(), diff --git a/src/components/managerlib/bibwatcher.ts b/src/components/managerlib/bibwatcher.ts index dac6e10d2..7999f3159 100644 --- a/src/components/managerlib/bibwatcher.ts +++ b/src/components/managerlib/bibwatcher.ts @@ -4,6 +4,7 @@ import { toKey } from '../../utils/tokey' import type { LwFileWatcher } from './lwfilewatcher' import type { Completer } from '../../providers/completion' import type { Logger } from '../logger' +import { inspectReadable } from '../../utils/inspect' export class BibWatcher { @@ -66,7 +67,7 @@ export class BibWatcher { } logWatchedFiles() { - this.extension.logger.debug(`BibWatcher.bibsWatched: ${JSON.stringify(Array.from(this.watchedBibs))}`) + this.extension.logger.debug(`BibWatcher.bibsWatched: ${inspectReadable(this.watchedBibs)}`) } } diff --git a/src/components/managerlib/managerwatcher.ts b/src/components/managerlib/managerwatcher.ts index fb1080970..e5b057687 100644 --- a/src/components/managerlib/managerwatcher.ts +++ b/src/components/managerlib/managerwatcher.ts @@ -2,6 +2,7 @@ import * as vscode from 'vscode' import { toKey } from '../../utils/tokey' import type { LwFileWatcher } from './lwfilewatcher' import type { Logger } from '../logger' +import { inspectReadable } from '../../utils/inspect' export class ManagerWatcher { @@ -68,7 +69,7 @@ export class ManagerWatcher { } logWatchedFiles() { - this.extension.logger.debug(`ManagerWatcher.watchedFiles: ${JSON.stringify(Array.from(this.watchedFiles))}`) + this.extension.logger.debug(`ManagerWatcher.watchedFiles: ${inspectReadable(this.watchedFiles)}`) } } diff --git a/src/components/managerlib/pdfwatcher.ts b/src/components/managerlib/pdfwatcher.ts index ff5e9f088..0f1217d36 100644 --- a/src/components/managerlib/pdfwatcher.ts +++ b/src/components/managerlib/pdfwatcher.ts @@ -4,6 +4,7 @@ import type { LwFileWatcher } from './lwfilewatcher' import type { Logger } from '../logger' import type { Viewer } from '../viewer' import { sleep } from '../../utils/utils' +import { inspectReadable } from '../../utils/inspect' export class PdfWatcher { @@ -65,8 +66,8 @@ export class PdfWatcher { } logWatchedFiles() { - this.extension.logger.debug(`PdfWatcher.pdfsWatched: ${JSON.stringify(Array.from(this.watchedPdfs))}`) - this.extension.logger.debug(`PdfWatcher.ignoredPdfUris: ${JSON.stringify(Array.from(this.ignoredPdfUris))}`) + this.extension.logger.debug(`PdfWatcher.pdfsWatched: ${inspectReadable(this.watchedPdfs)}`) + this.extension.logger.debug(`PdfWatcher.ignoredPdfUris: ${inspectReadable(this.ignoredPdfUris)}`) } } diff --git a/src/components/server.ts b/src/components/server.ts index 6ba934ce9..3ab3e06dd 100644 --- a/src/components/server.ts +++ b/src/components/server.ts @@ -10,6 +10,7 @@ import { readFileAsBuffer } from '../lib/lwfs/lwfs' import { ExternalPromise } from '../utils/externalpromise' import type { Logger } from './logger' import type { Viewer } from './viewer' +import { inspectCompact, inspectReadable } from '../utils/inspect' class WsServer extends ws.Server { private readonly validOrigin: string @@ -32,7 +33,7 @@ class WsServer extends ws.Server { shouldHandle(req: http.IncomingMessage): boolean { const reqOrigin = req.headers['origin'] if (reqOrigin !== undefined && reqOrigin !== this.validOrigin) { - this.extension.logger.info(`[Server] Origin in WebSocket upgrade request is invalid: ${JSON.stringify(req.headers)}`) + this.extension.logger.info(`[Server] Origin in WebSocket upgrade request is invalid: ${inspectReadable(req.headers)}`) this.extension.logger.info(`[Server] Valid origin: ${this.validOrigin}`) return false } else { @@ -96,17 +97,17 @@ export class Server { const address = this.httpServer.address() if (address && typeof address !== 'string') { this.address = address - this.extension.logger.info(`[Server] Server successfully started: ${JSON.stringify(address)}`) + this.extension.logger.info(`[Server] Server successfully started: ${inspectCompact(address)}`) this.validOriginUri = await this.obtainValidOrigin(address.port) this.extension.logger.info(`[Server] valdOrigin is ${this.validOrigin}`) this.initializeWsServer() this.#serverStarted.resolve() } else { - this.extension.logger.error(`[Server] Server failed to start. Address is invalid: ${JSON.stringify(address)}`) + this.extension.logger.error(`[Server] Server failed to start. Address is invalid: ${inspectCompact(address)}`) } }) this.httpServer.on('error', (err) => { - this.extension.logger.error(`[Server] Error creating LaTeX Toybox http server: ${JSON.stringify(err)}.`) + this.extension.logger.error(`[Server] Error creating LaTeX Toybox http server: ${inspectReadable(err)}.`) }) } @@ -120,7 +121,7 @@ export class Server { const wsServer = new WsServer(this.httpServer, this.extension, this.validOrigin) wsServer.on('connection', (websocket) => { websocket.on('message', (msg: string) => this.extension.viewer.handler(websocket, msg)) - websocket.on('error', (err) => this.extension.logger.error(`[Server] Error on WebSocket connection. ${JSON.stringify(err)}`)) + websocket.on('error', (err) => this.extension.logger.error(`[Server] Error on WebSocket connection. ${inspectReadable(err)}`)) }) } @@ -133,7 +134,7 @@ export class Server { private checkHttpOrigin(req: http.IncomingMessage, response: http.ServerResponse): boolean { const reqOrigin = req.headers['origin'] if (reqOrigin !== undefined && reqOrigin !== this.validOrigin) { - this.extension.logger.info(`[Server] Origin in http request is invalid: ${JSON.stringify(req.headers)}`) + this.extension.logger.info(`[Server] Origin in http request is invalid: ${inspectReadable(req.headers)}`) this.extension.logger.info(`[Server] Valid origin: ${this.validOrigin}`) response.writeHead(403) response.end() diff --git a/src/components/viewer.ts b/src/components/viewer.ts index b18d2f77b..192298aef 100644 --- a/src/components/viewer.ts +++ b/src/components/viewer.ts @@ -3,15 +3,15 @@ import type ws from 'ws' import * as path from 'path' import * as cs from 'cross-spawn' -import type {Locator, SyncTeXRecordForward} from './locator' -import {openWebviewPanel} from '../utils/webview' -import {getCurrentThemeLightness} from '../utils/theme' +import type { Locator, SyncTeXRecordForward } from './locator' +import { openWebviewPanel } from '../utils/webview' +import { getCurrentThemeLightness } from '../utils/theme' -import type {ClientRequest, PdfViewerParams, PdfViewerState} from '../../types/latex-toybox-protocol-types/index' +import type { ClientRequest, PdfViewerParams, PdfViewerState } from '../../types/latex-toybox-protocol-types/index' -import {Client} from './viewerlib/client' -import {PdfViewerPanel, PdfViewerPanelSerializer, PdfViewerPanelService} from './viewerlib/pdfviewerpanel' -import {PdfViewerManagerService} from './viewerlib/pdfviewermanager' +import { Client } from './viewerlib/client' +import { PdfViewerPanel, PdfViewerPanelSerializer, PdfViewerPanelService } from './viewerlib/pdfviewerpanel' +import { PdfViewerManagerService } from './viewerlib/pdfviewermanager' import * as lwfs from '../lib/lwfs/lwfs' import { encodePathWithPrefix } from '../utils/encodepdffilepath' import type { EventBus } from './eventbus' @@ -20,7 +20,8 @@ import type { Manager } from './manager' import type { Server } from './server' import type { LwStatusBarItem } from './statusbaritem' import { ExternalPromise } from '../utils/externalpromise' -export {PdfViewerHookProvider} from './viewerlib/pdfviewerhook' +import { inspectCompact } from '../utils/inspect' +export { PdfViewerHookProvider } from './viewerlib/pdfviewerhook' export class Viewer { @@ -100,7 +101,7 @@ export class Viewer { * refreshes all the PDF viewers. */ refreshExistingViewer(sourceFile?: string, pdfFileUri?: vscode.Uri): void { - this.extension.logger.info(`Call refreshExistingViewer: ${JSON.stringify({sourceFile})}`) + this.extension.logger.info(`Call refreshExistingViewer: ${inspectCompact({sourceFile})}`) const pdfFile = pdfFileUri || (sourceFile ? this.tex2pdf(sourceFile, true) : undefined) if (pdfFile === undefined) { this.clientMap.forEach(clientSet => { diff --git a/src/components/viewerlib/pdfviewerpanel.ts b/src/components/viewerlib/pdfviewerpanel.ts index cc247d36b..37abec327 100644 --- a/src/components/viewerlib/pdfviewerpanel.ts +++ b/src/components/viewerlib/pdfviewerpanel.ts @@ -10,6 +10,7 @@ import { encodePathWithPrefix } from '../../utils/encodepdffilepath' import { EventBus } from '../eventbus' import { Logger } from '../logger' import { Server } from '../server' +import { inspectCompact } from '../../utils/inspect' export class PdfViewerPanel { @@ -81,7 +82,7 @@ export class PdfViewerPanelSerializer implements vscode.WebviewPanelSerializer { localResourceRoots: [vscode.Uri.file(resourceFolder)] } await this.extension.server.serverStarted - this.extension.logger.info(`Restoring the PDF viewer at the column ${panel.viewColumn} from the state: ${JSON.stringify(argState)}`) + this.extension.logger.info(`Restoring the PDF viewer at the column ${panel.viewColumn} from the state: ${inspectCompact(argState)}`) const state = argState.state let pdfFileUri: vscode.Uri | undefined if (state.path) { diff --git a/src/providers/completionlib/command.ts b/src/providers/completionlib/command.ts index 6849f3090..6d89df8d5 100644 --- a/src/providers/completionlib/command.ts +++ b/src/providers/completionlib/command.ts @@ -10,6 +10,7 @@ import type { Completer } from '../completion' import type { Logger } from '../../components/logger' import type { Manager } from '../../components/manager' import { CommandKind } from './completionkind' +import { inspectCompact } from '../../utils/inspect' type DataUnimathSymbolsJsonType = typeof import('../../../data/unimathsymbols.json') @@ -178,7 +179,7 @@ export class Command implements IProvider, ICommand { pkgEntry.push(this.entryCmdToCompletion(key, cmds[key])) } else { this.extension.logger.info(`Cannot parse intellisense file: ${filePathUri}`) - this.extension.logger.info(`Missing field in entry: "${key}": ${JSON.stringify(cmds[key])}`) + this.extension.logger.info(`Missing field in entry: "${key}": ${inspectCompact(cmds[key])}`) } }) } catch (e) { diff --git a/src/providers/completionlib/environment.ts b/src/providers/completionlib/environment.ts index 8975ec26b..12b607f57 100644 --- a/src/providers/completionlib/environment.ts +++ b/src/providers/completionlib/environment.ts @@ -9,6 +9,7 @@ import type { Logger } from '../../components/logger' import type { Manager } from '../../components/manager' import type { Completer } from '../completion' import { EnvAsCmdKind, EnvKind } from './completionkind' +import { inspectCompact } from '../../utils/inspect' type DataEnvsJsonType = typeof import('../../../data/environments.json') @@ -73,7 +74,7 @@ export class Environment implements IProvider { Object.keys(envs).forEach(key => { if (! isEnvItemEntry(envs[key])) { this.extension.logger.info(`Cannot parse intellisense file: ${filePathUri}`) - this.extension.logger.info(`Missing field in entry: "${key}": ${JSON.stringify(envs[key])}`) + this.extension.logger.info(`Missing field in entry: "${key}": ${inspectCompact(envs[key])}`) delete envs[key] } }) diff --git a/src/providersmanager.ts b/src/providersmanager.ts index a23fa67d8..2f8330461 100644 --- a/src/providersmanager.ts +++ b/src/providersmanager.ts @@ -14,6 +14,7 @@ import { BibtexFormatterProvider } from './providers/bibtexformatter' import type { Extension } from './main' import { MathPreviewPanelSerializer } from './components/mathpreviewpanel' import { AtSuggestionCompleter } from './providers/atsuggestion' +import { inspectCompact } from './utils/inspect' abstract class SingleProviderManager implements vscode.Disposable { @@ -74,7 +75,7 @@ export class ProvidersManager { const configuration = vscode.workspace.getConfiguration('latex-toybox') const userTriggersLatex = configuration.get('intellisense.triggers.latex', ['{']) const latexTriggers = ['\\', ','].concat(userTriggersLatex) - extension.logger.info(`Trigger characters for intellisense of LaTeX documents: ${JSON.stringify(latexTriggers)}`) + extension.logger.info(`Trigger characters for intellisense of LaTeX documents: ${inspectCompact(latexTriggers)}`) return vscode.languages.registerCompletionItemProvider(latexDoctexSelector, extension.completer, ...latexTriggers) } }, diff --git a/src/utils/inspect.ts b/src/utils/inspect.ts new file mode 100644 index 000000000..16778d8ea --- /dev/null +++ b/src/utils/inspect.ts @@ -0,0 +1,9 @@ +import { inspect } from 'util' + +export function inspectReadable(obj: unknown): string { + return inspect(obj, { compact: false, depth: null, breakLength: Infinity }) +} + +export function inspectCompact(obj: unknown): string { + return inspect(obj, { compact: true, depth: null, breakLength: Infinity }) +} From d91eb8984cc31de74c34df8ac4ffc4de27ae2abd Mon Sep 17 00:00:00 2001 From: Takashi Tamura Date: Sun, 1 Oct 2023 11:13:38 +0900 Subject: [PATCH 3/3] Use util.inspect() for Logger.logError() --- src/commander.ts | 6 ++---- src/components/builder.ts | 12 ++++-------- src/components/compilerloglib/biblogparser.ts | 5 ++--- src/components/compilerloglib/latexlogparser.ts | 5 ++--- src/components/locator.ts | 13 +++++-------- src/components/logger.ts | 17 +++-------------- src/components/managerlib/pathutils.ts | 3 ++- src/components/mathpreview.ts | 2 +- .../mathpreviewlib/hoverpreviewonref.ts | 4 ++-- src/components/server.ts | 4 +--- src/components/viewer.ts | 4 +--- src/interfaces.ts | 2 +- src/providers/completionlib/command.ts | 1 + test/utils/fakecomponents.ts | 1 - 14 files changed, 27 insertions(+), 52 deletions(-) diff --git a/src/commander.ts b/src/commander.ts index f0d81bc3c..9fda96769 100644 --- a/src/commander.ts +++ b/src/commander.ts @@ -221,10 +221,8 @@ export class Commander { pdfFile = this.extension.manager.tex2pdf(this.extension.manager.rootFile) } return this.extension.locator.syncTeX(undefined, undefined, pdfFile) - } catch(e) { - if (e instanceof Error) { - this.extension.logger.logError(e) - } + } catch (e) { + this.extension.logger.logError(e) throw e } } diff --git a/src/components/builder.ts b/src/components/builder.ts index 037c6079d..4ca8bdde6 100644 --- a/src/components/builder.ts +++ b/src/components/builder.ts @@ -12,7 +12,7 @@ import type { Manager } from './manager' import type { LwStatusBarItem } from './statusbaritem' import { statPath } from '../lib/lwfs/lwfs' import { ExternalPromise } from '../utils/externalpromise' -import { inspectCompact } from '../utils/inspect' +import { inspectCompact, inspectReadable } from '../utils/inspect' const maxPrintLine = '10000' @@ -61,9 +61,7 @@ export class Builder { cp.execSync(`taskkill /F /T /PID ${pid}`, { timeout: 1000 }) } } catch (e) { - if (e instanceof Error) { - this.extension.logger.error(`Error when killing child processes of the current process. ${e.message}`) - } + this.extension.logger.error(`Error when killing child processes of the current process. ${inspectReadable(e)}`) } finally { proc.kill() this.extension.logger.info(`Kill the current process. PID: ${pid}`) @@ -209,9 +207,7 @@ export class Builder { await this.buildFinished(rootFile) } catch (e) { this.extension.statusbaritem.displayStatus('fail', 'Build failed.') - if (e instanceof Error) { - this.extension.logger.logError(e) - } + this.extension.logger.logError(e) } finally { releaseBuildMutex() } @@ -306,7 +302,7 @@ export class Builder { this.currentProcess = undefined resultPromise.resolve() } - } catch(e) { + } catch (e) { resultPromise.reject(e) } }) diff --git a/src/components/compilerloglib/biblogparser.ts b/src/components/compilerloglib/biblogparser.ts index 4bd66174e..84a8d049e 100644 --- a/src/components/compilerloglib/biblogparser.ts +++ b/src/components/compilerloglib/biblogparser.ts @@ -4,6 +4,7 @@ import type { CompilerLog } from '../compilerlog' import type { Completer } from '../../providers/completion' import type { Logger } from '../logger' import type { Manager } from '../manager' +import { inspectReadable } from '../../utils/inspect' const multiLineWarning = /^Warning--(.+)\n--line (\d+) of file (.+)$/gm const singleLineWarning = /^Warning--(.+) in ([^\s]+)\s*$/gm @@ -38,9 +39,7 @@ export class BibLogParser { try { excludeRegexp = (configuration.get('message.bibtexlog.exclude') as string[]).map(regexp => new RegExp(regexp)) } catch (e) { - if (e instanceof Error) { - this.extension.logger.info(`latex-toybox.message.bibtexlog.exclude is invalid: ${e.message}`) - } + this.extension.logger.info(`latex-toybox.message.bibtexlog.exclude is invalid: ${inspectReadable(e)}`) return } this.buildLog = [] diff --git a/src/components/compilerloglib/latexlogparser.ts b/src/components/compilerloglib/latexlogparser.ts index 98e640d94..f7b71f733 100644 --- a/src/components/compilerloglib/latexlogparser.ts +++ b/src/components/compilerloglib/latexlogparser.ts @@ -5,6 +5,7 @@ import type { LogEntry } from './core' import type { CompilerLog } from '../compilerlog' import type { Manager } from '../manager' import type { Logger } from '../logger' +import { inspectReadable } from '../../utils/inspect' const latexError = /^(?:(.*):(\d+):|!)(?: (.+) Error:)? (.+?)$/ const latexBox = /^((?:Over|Under)full \\[vh]box \([^)]*\)) in paragraph at lines (\d+)--(\d+)$/ @@ -80,9 +81,7 @@ export class LatexLogParser { try { excludeRegexp = (configuration.get('message.latexlog.exclude') as string[]).map(regexp => new RegExp(regexp)) } catch (e) { - if (e instanceof Error) { - this.extension.logger.info(`latex-toybox.message.latexlog.exclude is invalid: ${e.message}`) - } + this.extension.logger.info(`latex-toybox.message.latexlog.exclude is invalid: ${inspectReadable(e)}`) return } // Compose the current file diff --git a/src/components/locator.ts b/src/components/locator.ts index c0688680b..68ceef155 100644 --- a/src/components/locator.ts +++ b/src/components/locator.ts @@ -165,9 +165,7 @@ export class Locator { this.extension.viewer.syncTeX(pdfFile, record) } catch (e) { this.extension.logger.info('[SyncTexJs] Forward SyncTeX failed.') - if (e instanceof Error) { - this.extension.logger.logError(e) - } + this.extension.logger.logError(e) } } else { const record = await this.invokeSyncTeXCommandForward(line, character, filePath, pdfFile) @@ -280,9 +278,7 @@ export class Locator { record = await this.synctexjs.syncTexJsBackward(Number(data.page), data.pos[0], data.pos[1], pdfPath) } catch (e) { this.extension.logger.info('[SyncTexJs] Backward SyncTeX failed.') - if (e instanceof Error) { - this.extension.logger.logError(e) - } + this.extension.logger.logError(e) return } } else { @@ -299,8 +295,9 @@ export class Locator { record.input = ed break } - } catch(e) { + } catch (e) { this.extension.logger.error(`[SyncTexJs] isSameRealPath throws error: ${record.input} and ${ed}`) + this.extension.logger.logError(e) } } @@ -326,7 +323,7 @@ export class Locator { editor.selection = new vscode.Selection(pos, pos) await vscode.commands.executeCommand('revealLine', {lineNumber: row, at: 'center'}) this.animateToNotify(editor, pos) - } catch(e: unknown) { + } catch (e: unknown) { if (e instanceof Error) { this.extension.logger.logError(e) } diff --git a/src/components/logger.ts b/src/components/logger.ts index 5e2bcc227..6fde5468e 100644 --- a/src/components/logger.ts +++ b/src/components/logger.ts @@ -1,6 +1,6 @@ import * as vscode from 'vscode' import { ILogger } from '../interfaces' -import { inspectCompact } from '../utils/inspect' +import { inspectCompact, inspectReadable } from '../utils/inspect' export class Logger implements ILogger { @@ -28,19 +28,8 @@ export class Logger implements ILogger { this.logPanel.error(message) } - logError(e: Error) { - this.error(e.message) - if (e.stack) { - this.error(e.stack) - } - } - - logOnRejected(e: unknown) { - if (e instanceof Error) { - this.logError(e) - } else { - this.error(String(e)) - } + logError(e: unknown) { + this.error(inspectReadable(e)) } showLog() { diff --git a/src/components/managerlib/pathutils.ts b/src/components/managerlib/pathutils.ts index e0ed8b67b..ee163bb21 100644 --- a/src/components/managerlib/pathutils.ts +++ b/src/components/managerlib/pathutils.ts @@ -83,8 +83,9 @@ export class PathUtils { return bibPath } } - } catch(e) { + } catch (e) { this.extension.logger.info(`Cannot run kpsewhich to resolve .bib file: ${bib}`) + this.extension.logger.logError(e) } return undefined } diff --git a/src/components/mathpreview.ts b/src/components/mathpreview.ts index 72772adad..83d9dd752 100644 --- a/src/components/mathpreview.ts +++ b/src/components/mathpreview.ts @@ -62,7 +62,7 @@ export class MathPreview { return new vscode.Hover(new vscode.MarkdownString(this.mputils.addDummyCodeBlock(`![equation](${md})`)), tex.range ) } catch(e) { this.extension.logger.error(`Error while MathJax is rendering: ${typesetArg}`) - this.extension.logger.logOnRejected(e) + this.extension.logger.logError(e) throw e } } diff --git a/src/components/mathpreviewlib/hoverpreviewonref.ts b/src/components/mathpreviewlib/hoverpreviewonref.ts index c3dd4a1ce..dd0fded2d 100644 --- a/src/components/mathpreviewlib/hoverpreviewonref.ts +++ b/src/components/mathpreviewlib/hoverpreviewonref.ts @@ -49,8 +49,8 @@ export class HoverPreviewOnRefProvider { const xml = await this.mj.typeset(typesetArg, typesetOpts) const svg = utils.svgToDataUrl(xml) return svg - } catch(e) { - this.extension.logger.logOnRejected(e) + } catch (e) { + this.extension.logger.logError(e) this.extension.logger.error(`Error when MathJax is rendering ${typesetArg}`) throw e } diff --git a/src/components/server.ts b/src/components/server.ts index 3ab3e06dd..2e416e168 100644 --- a/src/components/server.ts +++ b/src/components/server.ts @@ -190,9 +190,7 @@ export class Server { this.extension.logger.info(`[Server] Preview PDF file: ${fileUri.toString(true)}`) } catch (e) { this.extension.logger.error(`[Server] Error reading PDF file: ${fileUri.toString(true)}`) - if (e instanceof Error) { - this.extension.logger.logError(e) - } + this.extension.logger.logError(e) response.writeHead(404) response.end() } diff --git a/src/components/viewer.ts b/src/components/viewer.ts index 192298aef..7b32b3157 100644 --- a/src/components/viewer.ts +++ b/src/components/viewer.ts @@ -156,9 +156,7 @@ export class Viewer { value: url }) this.extension.logger.info(`Something bad happened when opening PDF viewer for ${pdfFileUri.toString(true)}`) - if (e instanceof Error) { - this.extension.logger.logError(e) - } + this.extension.logger.logError(e) } } diff --git a/src/interfaces.ts b/src/interfaces.ts index 235899d6f..6d1e004d4 100644 --- a/src/interfaces.ts +++ b/src/interfaces.ts @@ -8,6 +8,6 @@ export interface ILogger { debug(message: string): void, error(message: string): void, logError(e: Error): void, - logOnRejected(e: unknown): void, + logError(e: unknown): void, showLog(): void } diff --git a/src/providers/completionlib/command.ts b/src/providers/completionlib/command.ts index 6d89df8d5..1825d56eb 100644 --- a/src/providers/completionlib/command.ts +++ b/src/providers/completionlib/command.ts @@ -184,6 +184,7 @@ export class Command implements IProvider, ICommand { }) } catch (e) { this.extension.logger.error(`Cannot parse intellisense file: ${filePathUri}`) + this.extension.logger.logError(e) } } this.packageCmds.set(pkg, pkgEntry) diff --git a/test/utils/fakecomponents.ts b/test/utils/fakecomponents.ts index 6b46ef5ec..437ed431a 100644 --- a/test/utils/fakecomponents.ts +++ b/test/utils/fakecomponents.ts @@ -6,6 +6,5 @@ export class FakeLogger implements ILogger { debug(){} error(){} logError() {} - logOnRejected() {} showLog() {} }