Skip to content

Commit

Permalink
fix: do not wrap log
Browse files Browse the repository at this point in the history
  • Loading branch information
fi3ework committed Jul 3, 2021
1 parent 20c95e9 commit 2bb6cbd
Show file tree
Hide file tree
Showing 13 changed files with 234 additions and 78 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ module.exports = {
env: {
jest: true,
},
globals: {
globalThis: 'readable',
},
rules: {
'@typescript-eslint/consistent-type-assertions': 'off',
'@typescript-eslint/no-require-imports': 'off',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"semver": "^7.3.5",
"ts-jest": "^27.0.3",
"typescript": "^4.2.2",
"vite": "^2.1.3",
"vite": "^2.3.8",
"vite-plugin-checker": "workspace:*",
"vite-plugin-checker-vls": "workspace:*",
"zx": "^1.14.2"
Expand Down
1 change: 0 additions & 1 deletion packages/checker-vls/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"chokidar": "^3.5.1",
"commander": "^7.2.0",
"glob": "^7.1.7",
"log-update": "^4.0.0",
"vite-plugin-checker": "workspace:*",
"vls": "^0.7.2",
"vscode-languageclient": "^7.0.0",
Expand Down
123 changes: 77 additions & 46 deletions packages/checker-vls/src/commands/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import chalk from 'chalk'
import chokidar from 'chokidar'
import fs from 'fs'
import glob from 'glob'
import logUpdate from 'log-update'
import os from 'os'
import path from 'path'
import { Duplex } from 'stream'
Expand Down Expand Up @@ -31,12 +30,16 @@ import { codeFrameColumns } from '@babel/code-frame'
import { getInitParams } from '../initParams'

import type { TextDocument } from 'vscode-languageserver-textdocument'

enum DOC_VERSION {
init = -1,
}

export type LogLevel = typeof logLevels[number]
export const logLevels = ['ERROR', 'WARN', 'INFO', 'HINT'] as const

let disposeSuppressConsole: ReturnType<typeof suppressConsole>

const logLevel2Severity = {
ERROR: DiagnosticSeverity.Error,
WARN: DiagnosticSeverity.Warning,
Expand Down Expand Up @@ -81,7 +84,6 @@ export async function diagnostics(
}

// initial report
console.log(os.EOL)
if (!errCount) {
console.log(chalk.green(`[VLS checker] No error found`))
if (!watch) {
Expand All @@ -107,10 +109,22 @@ class TestStream extends Duplex {
this.emit('data', chunk)
done()
}

public _read(_size: number) {}
}

function suppressConsole() {
let disposed = false
const rawConsoleLog = globalThis.console.log
globalThis.console.log = () => {}

return () => {
if (disposed) return

disposed = true
globalThis.console.log = rawConsoleLog
}
}

async function prepareClientConnection(workspaceUri: URI, options: DiagnosticOptions) {
const up = new TestStream()
const down = new TestStream()
Expand All @@ -129,22 +143,29 @@ async function prepareClientConnection(workspaceUri: URI, options: DiagnosticOpt

// hijack sendDiagnostics
serverConnection.sendDiagnostics = (diagnostics) => {
if (diagnostics.version === DOC_VERSION.init) return
disposeSuppressConsole?.()
if (diagnostics.version === DOC_VERSION.init) {
return
}

if (!diagnostics.diagnostics.length) {
prettyDiagnosticsLog({
ds: [],
diagnostics: [],
absFilePath: '',
fileText: '',
showNoError: false,
})
return
}

const overlayErr = lspDiagnosticToViteError(diagnostics)
if (!overlayErr) return

prettyDiagnosticsLog({
ds: diagnostics.diagnostics,
diagnostics: diagnostics.diagnostics,
absFilePath: uriToAbsPath(diagnostics.uri),
fileText: overlayErr.fileText,
showNoError: false,
})

options.errorCallback?.(diagnostics, overlayErr)
Expand Down Expand Up @@ -212,6 +233,11 @@ async function getDiagnostics(
// watch mode will run this full diagnostic at starting
let initialErrCount = 0
let logChunk = ''

if (options.watch) {
disposeSuppressConsole = suppressConsole()
}

for (const absFilePath of absFilePaths) {
const fileText = fs.readFileSync(absFilePath, 'utf-8')
clientConnection.sendNotification(DidOpenTextDocumentNotification.type, {
Expand All @@ -223,35 +249,38 @@ async function getDiagnostics(
},
})

try {
let diagnostics = (await clientConnection.sendRequest('$/getDiagnostics', {
uri: URI.file(absFilePath).toString(),
version: DOC_VERSION.init,
})) as Diagnostic[]

/**
* Ignore eslint errors for now
*/
diagnostics = diagnostics
.filter((r) => r.source !== 'eslint-plugin-vue')
.filter((r) => r.severity && r.severity <= severity)

if (diagnostics.length > 0) {
logChunk += prettyDiagnosticsLog({
absFilePath,
fileText,
ds: diagnostics,
doLog: false,
})

diagnostics.forEach((d) => {
if (d.severity === DiagnosticSeverity.Error) {
initialErrCount++
}
})
// logout in build mode
if (!options.watch) {
try {
let diagnostics = (await clientConnection.sendRequest('$/getDiagnostics', {
uri: URI.file(absFilePath).toString(),
version: DOC_VERSION.init,
})) as Diagnostic[]

/**
* Ignore eslint errors for now
*/
diagnostics = diagnostics
.filter((r) => r.source !== 'eslint-plugin-vue')
.filter((r) => r.severity && r.severity <= severity)

if (diagnostics.length > 0) {
logChunk += prettyDiagnosticsLog({
absFilePath,
fileText,
diagnostics: diagnostics,
doLog: false,
})

diagnostics.forEach((d) => {
if (d.severity === DiagnosticSeverity.Error) {
initialErrCount++
}
})
}
} catch (err) {
console.error(err.stack)
}
} catch (err) {
console.error(err.stack)
}
}

Expand All @@ -274,7 +303,7 @@ async function getDiagnostics(
})
}

logUpdate(logChunk)
console.log(logChunk)
return initialErrCount
}

Expand All @@ -289,46 +318,48 @@ function composeLspLog({
}) {
let logChunk = ''
const location = range2Location(diagnostic.range)
logChunk += `${chalk.green('File')}: ${chalk.green(absFilePath)}:${location.start.line}:${
logChunk += `${os.EOL}${chalk.green.bold('FILE ')} ${absFilePath}:${location.start.line}:${
location.start.column
}`
}${os.EOL}`

if (diagnostic.severity === DiagnosticSeverity.Error) {
logChunk += `${chalk.red('Error')}: ${diagnostic.message.trim()}`
logChunk += `${chalk.red.bold('ERROR ')} ${diagnostic.message.trim()}`
} else {
logChunk += `${chalk.yellow('Warn')} : ${diagnostic.message.trim()}`
logChunk += `${chalk.yellow.bold('WARN ')} ${diagnostic.message.trim()}`
}

logChunk += codeFrameColumns(fileText, location)
return logChunk
}

export function prettyDiagnosticsLog({
ds,
diagnostics,
fileText,
absFilePath,
doLog = true,
showNoError = true,
}: {
ds: Diagnostic[]
diagnostics: Diagnostic[]
fileText: string
absFilePath: string
/** does log to terminal */
doLog?: boolean
showNoError?: boolean
}) {
if (!ds.length) {
doLog && logUpdate(chalk.green(`[VLS checker] No error found`))
if (!diagnostics.length && showNoError) {
doLog && console.log(chalk.green(`[VLS checker] No error found`))
return ''
}

const logs = ds.map((d) => {
const logs = diagnostics.map((d) => {
return composeLspLog({
diagnostic: d,
absFilePath,
fileText,
})
})

const logChunk = logs.join(os.EOL)
doLog && logUpdate(logChunk)
let logChunk = logs.join(os.EOL) + os.EOL
doLog && console.log(logChunk)
return logChunk
}
6 changes: 5 additions & 1 deletion packages/vite-plugin-checker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,19 @@
"@babel/code-frame": "^7.12.13",
"@types/lodash.omit": "^4.5.6",
"@types/lodash.pick": "^4.4.6",
"ansi-escapes": "^4.3.0",
"lodash.omit": "^4.5.0",
"lodash.pick": "^4.4.0",
"log-update": "^4.0.0",
"npm-run-path": "^4.0.1",
"slice-ansi": "^4.0.0",
"strip-ansi": "^6.0.0",
"tiny-invariant": "^1.1.0",
"vscode-languageclient": "^7.0.0"
},
"peerDependencies": {
"vite": "^2.0.0"
},
"devDependencies": {
"@types/slice-ansi": "^4.0.0"
}
}
8 changes: 5 additions & 3 deletions packages/vite-plugin-checker/src/checkers/tsc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import invariant from 'tiny-invariant'
import ts from 'typescript'
import { ErrorPayload } from 'vite'
import { isMainThread, parentPort } from 'worker_threads'
import logUpdate from 'log-update'

import { ensureCall, formatHost, tsDiagnosticToViteError } from '../utils'
import { createScript } from '../worker'
Expand Down Expand Up @@ -72,7 +71,9 @@ const createDiagnostic: CreateDiagnostic<Pick<PluginConfig, 'typescript'>> = (ch
errorCount
// eslint-disable-next-line max-params
) => {
// logChunk = []
// https://github.com/microsoft/TypeScript/blob/dc237b317ed4bbccd043ddda802ffde00362a387/src/compiler/diagnosticMessages.json#L4086-L4088
if (diagnostic.code === 6031) return

// https://github.com/microsoft/TypeScript/issues/32542
switch (diagnostic.code) {
case 6032: // Incremental build
Expand All @@ -99,13 +100,14 @@ const createDiagnostic: CreateDiagnostic<Pick<PluginConfig, 'typescript'>> = (ch
logChunk.diagnostics = null
}
const d = logChunk.diagnostics === null ? '' : logChunk.diagnostics + os.EOL
logUpdate(d + logChunk.message)
console.log(d + logChunk.message)
})
}

// https://github.com/microsoft/TypeScript/issues/32385
// https://github.com/microsoft/TypeScript/pull/33082/files
const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram

const host = ts.createWatchCompilerHost(
configFile,
{ noEmit: true },
Expand Down

0 comments on commit 2bb6cbd

Please sign in to comment.