-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
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
Improve astro check #3906
Merged
Merged
Improve astro check #3906
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
753f5a3
Improve astro check
Princesseuh 8132127
Fix lockfile
Princesseuh 19a2bfa
Update to latest language-server version
Princesseuh cb905ba
Add simple tests
Princesseuh 4a6524e
Fix lock file, again
Princesseuh 091b09b
Fix `astro check` not working on Windows, speeds up tests
Princesseuh 4586ca5
Merge branch 'main' into astro-check-improvements
Princesseuh 4c0494a
Add changeest
Princesseuh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
/* eslint-disable no-console */ | ||
import { AstroCheck, DiagnosticSeverity } from '@astrojs/language-server'; | ||
import type { AstroConfig } from '../../@types/astro'; | ||
|
||
import glob from 'fast-glob'; | ||
import * as fs from 'fs'; | ||
import { bold, dim, red, yellow } from 'kleur/colors'; | ||
import ora from 'ora'; | ||
import { fileURLToPath, pathToFileURL } from 'url'; | ||
import { printDiagnostic } from './print.js'; | ||
|
||
interface Result { | ||
errors: number; | ||
// The language server cannot actually return any warnings at the moment, but we'll keep this here for future use | ||
warnings: number; | ||
hints: number; | ||
} | ||
|
||
export async function check(astroConfig: AstroConfig) { | ||
console.log(bold('astro check')); | ||
|
||
const root = astroConfig.root; | ||
|
||
const spinner = ora(` Getting diagnostics for Astro files in ${fileURLToPath(root)}…`).start(); | ||
|
||
let checker = new AstroCheck(root.toString()); | ||
const filesCount = await openAllDocuments(root, [], checker); | ||
|
||
let diagnostics = await checker.getDiagnostics(); | ||
|
||
spinner.succeed(); | ||
|
||
let result: Result = { | ||
errors: 0, | ||
warnings: 0, | ||
hints: 0, | ||
}; | ||
|
||
diagnostics.forEach((diag) => { | ||
diag.diagnostics.forEach((d) => { | ||
console.log(printDiagnostic(diag.filePath, diag.text, d)); | ||
|
||
switch (d.severity) { | ||
case DiagnosticSeverity.Error: { | ||
result.errors++; | ||
break; | ||
} | ||
case DiagnosticSeverity.Warning: { | ||
result.warnings++; | ||
break; | ||
} | ||
case DiagnosticSeverity.Hint: { | ||
result.hints++; | ||
break; | ||
} | ||
} | ||
}); | ||
}); | ||
|
||
console.log( | ||
[ | ||
bold(`Result (${filesCount} file${filesCount === 1 ? '' : 's'}): `), | ||
bold(red(`${result.errors} ${result.errors === 1 ? 'error' : 'errors'}`)), | ||
bold(yellow(`${result.warnings} ${result.warnings === 1 ? 'warning' : 'warnings'}`)), | ||
dim(`${result.hints} ${result.hints === 1 ? 'hint' : 'hints'}\n`), | ||
].join(`\n${dim('-')} `) | ||
); | ||
|
||
const exitCode = result.errors ? 1 : 0; | ||
return exitCode; | ||
} | ||
|
||
/** | ||
* Open all Astro files in the given directory and return the number of files found. | ||
*/ | ||
async function openAllDocuments( | ||
workspaceUri: URL, | ||
filePathsToIgnore: string[], | ||
checker: AstroCheck | ||
): Promise<number> { | ||
const files = await glob('**/*.astro', { | ||
cwd: fileURLToPath(workspaceUri), | ||
ignore: ['node_modules/**'].concat(filePathsToIgnore.map((ignore) => `${ignore}/**`)), | ||
absolute: true, | ||
}); | ||
|
||
for (const file of files) { | ||
const text = fs.readFileSync(file, 'utf-8'); | ||
checker.upsertDocument({ | ||
uri: pathToFileURL(file).toString(), | ||
text, | ||
}); | ||
} | ||
|
||
return files.length; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
import { Diagnostic, DiagnosticSeverity, offsetAt } from '@astrojs/language-server'; | ||
import { | ||
bgRed, | ||
bgWhite, | ||
bgYellow, | ||
black, | ||
bold, | ||
cyan, | ||
gray, | ||
red, | ||
white, | ||
yellow | ||
} from 'kleur/colors'; | ||
import stringWidth from 'string-width'; | ||
|
||
export function printDiagnostic(filePath: string, text: string, diag: Diagnostic): string { | ||
let result = []; | ||
|
||
// Lines and characters are 0-indexed, so we need to add 1 to the offset to get the actual line and character | ||
const realStartLine = diag.range.start.line + 1; | ||
const realStartCharacter = diag.range.start.character + 1; | ||
|
||
// IDE friendly path that user can CTRL+Click to open the file at a specific line / character | ||
const IDEFilePath = `${bold(cyan(filePath))}:${bold(yellow(realStartLine))}:${bold( | ||
yellow(realStartCharacter) | ||
)}`; | ||
result.push( | ||
`${IDEFilePath} ${bold(getColorForSeverity(diag, getStringForSeverity(diag)))}: ${diag.message}` | ||
); | ||
|
||
// Optionally add the before the error to add context if not empty | ||
const previousLine = getLine(diag.range.start.line - 1, text); | ||
if (previousLine) { | ||
result.push(`${getPrintableLineNumber(realStartLine - 1)} ${gray(previousLine)}`); | ||
} | ||
|
||
// Add the line with the error | ||
const str = getLine(diag.range.start.line, text); | ||
const lineNumStr = realStartLine.toString().padStart(2, '0'); | ||
const lineNumLen = lineNumStr.length; | ||
result.push(`${getBackgroundForSeverity(diag, lineNumStr)} ${str}`); | ||
|
||
// Adds tildes under the specific range where the diagnostic is | ||
const tildes = generateString('~', diag.range.end.character - diag.range.start.character); | ||
|
||
// NOTE: This is not perfect, if the line include any characters that is made of multiple characters, for example | ||
// regionals flags, but the terminal can't display it, then the number of spaces will be wrong. Not sure how to fix. | ||
const beforeChars = stringWidth(str.substring(0, diag.range.start.character)); | ||
const spaces = generateString(' ', beforeChars + lineNumLen - 1); | ||
result.push(` ${spaces}${bold(getColorForSeverity(diag, tildes))}`); | ||
|
||
const nextLine = getLine(diag.range.start.line + 1, text); | ||
if (nextLine) { | ||
result.push(`${getPrintableLineNumber(realStartLine + 1)} ${gray(nextLine)}`); | ||
} | ||
|
||
// Force a new line at the end | ||
result.push(''); | ||
|
||
return result.join('\n'); | ||
} | ||
|
||
function generateString(str: string, len: number): string { | ||
return Array.from({ length: len }, () => str).join(''); | ||
} | ||
|
||
function getStringForSeverity(diag: Diagnostic): string { | ||
switch (diag.severity) { | ||
case DiagnosticSeverity.Error: | ||
return 'Error'; | ||
case DiagnosticSeverity.Warning: | ||
return 'Warning'; | ||
case DiagnosticSeverity.Hint: | ||
return 'Hint'; | ||
default: | ||
return 'Unknown'; | ||
} | ||
} | ||
|
||
function getColorForSeverity(diag: Diagnostic, text: string): string { | ||
switch (diag.severity) { | ||
case DiagnosticSeverity.Error: | ||
return red(text); | ||
case DiagnosticSeverity.Warning: | ||
return yellow(text); | ||
case DiagnosticSeverity.Hint: | ||
return gray(text); | ||
default: | ||
return text; | ||
} | ||
} | ||
|
||
function getBackgroundForSeverity(diag: Diagnostic, text: string): string { | ||
switch (diag.severity) { | ||
case DiagnosticSeverity.Error: | ||
return bgRed(white(text)); | ||
case DiagnosticSeverity.Warning: | ||
return bgYellow(white(text)); | ||
case DiagnosticSeverity.Hint: | ||
return bgWhite(black(text)); | ||
default: | ||
return text; | ||
} | ||
} | ||
|
||
function getPrintableLineNumber(line: number): string { | ||
return bgWhite(black(line.toString().padStart(2, '0'))); | ||
} | ||
|
||
function getLine(line: number, text: string): string { | ||
return text | ||
.substring( | ||
offsetAt({ line, character: 0 }, text), | ||
offsetAt({ line, character: Number.MAX_SAFE_INTEGER }, text) | ||
) | ||
.replace(/\t/g, ' ') | ||
.trimEnd(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
6 changes: 6 additions & 0 deletions
6
packages/astro/test/fixtures/astro-check-errors/astro.config.mjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import { defineConfig } from 'astro/config'; | ||
|
||
// https://astro.build/config | ||
export default defineConfig({ | ||
integrations: [], | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"name": "@test/astro-check-errors", | ||
"version": "0.0.0", | ||
"private": true, | ||
"dependencies": { | ||
"astro": "workspace:*" | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Love the summary section