Skip to content
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

Add hyperlinks to diagnostic documentation url #4148

Merged
merged 7 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking
changeKind: feature
packages:
- "@typespec/compiler"
---

Diagnostics logged to the terminal now have a clickable hyperlink to the diagnostic documentation url if applicable.
2 changes: 2 additions & 0 deletions packages/compiler/src/core/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export function logDiagnostics(diagnostics: readonly Diagnostic[], logger: LogSi
level: diagnostic.severity,
message: diagnostic.message,
code: diagnostic.code,
url: diagnostic.url,
sourceLocation: getSourceLocation(diagnostic.target, { locateId: true }),
});
}
Expand All @@ -46,6 +47,7 @@ export function formatDiagnostic(diagnostic: Diagnostic) {
code: diagnostic.code,
level: diagnostic.severity,
message: diagnostic.message,
url: diagnostic.url,
sourceLocation: getSourceLocation(diagnostic.target, { locateId: true }),
},
{ pretty: false }
Expand Down
9 changes: 1 addition & 8 deletions packages/compiler/src/core/linter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ import {
export interface Linter {
extendRuleSet(ruleSet: LinterRuleSet): Promise<readonly Diagnostic[]>;
lint(): readonly Diagnostic[];

/** @internal */
getRuleUrl(ruleId: string): string | undefined;
markcowl marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down Expand Up @@ -67,13 +64,8 @@ export function createLinter(
return {
extendRuleSet,
lint,
getRuleUrl,
};

function getRuleUrl(ruleId: string): string | undefined {
return ruleMap.get(ruleId)?.url;
}

async function extendRuleSet(ruleSet: LinterRuleSet): Promise<readonly Diagnostic[]> {
tracer.trace("extend-rule-set.start", JSON.stringify(ruleSet, null, 2));
const diagnostics = createDiagnosticCollector();
Expand Down Expand Up @@ -244,6 +236,7 @@ export function createLinterRuleContext<N extends string, DM extends DiagnosticM
severity: rule.severity,
message: messageStr,
target: diag.target,
url: rule.url,
codefixes: diag.codefixes,
};
}
Expand Down
11 changes: 10 additions & 1 deletion packages/compiler/src/core/logger/console-sink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { codeFrameColumns } from "@babel/code-frame";
import pc from "picocolors";
import { Formatter } from "picocolors/types.js";
import { LogLevel, LogSink, ProcessedLog, SourceLocation } from "../types.js";
import { supportsHyperlink } from "./support-hyperlinks.js";

export interface FormatLogOptions {
pretty?: boolean;
Expand All @@ -20,8 +21,16 @@ export function createConsoleSink(options: ConsoleSinkOptions = {}): LogSink {
};
}

const supportHyperLinks = supportsHyperlink(process.stdout);
function hyperlink(text: string, url: string | undefined, options: FormatLogOptions) {
if (supportHyperLinks && url && options.pretty) {
return `\u001B]8;;${url}\u0007${text}\u001B]8;;\u0007`;
}
return text;
}

export function formatLog(log: ProcessedLog, options: FormatLogOptions): string {
const code = color(options, log.code ? ` ${log.code}` : "", pc.gray);
const code = log.code ? hyperlink(color(options, ` ${log.code}`, pc.gray), log.url, options) : "";
const level = formatLevel(options, log.level);
const content = `${level}${code}: ${log.message}`;
const location = log.sourceLocation;
Expand Down
100 changes: 100 additions & 0 deletions packages/compiler/src/core/logger/support-hyperlinks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// FORK of https://github.com/jamestalmage/supports-hyperlinks that work on new windows terminal and some more unix terminals.
// and doesn't include some of the cli flags that won't work with our strict cli.

/**
* Check if the terminal supports hyperlink.
*/
export function supportsHyperlink(stream: NodeJS.WriteStream) {
const {
CI,
TERM,
TERM_PROGRAM,
TERM_PROGRAM_VERSION,
VTE_VERSION,
FORCE_HYPERLINK,
COLORTERM,
TERMINAL_EMULATOR,
} = process.env;

if (FORCE_HYPERLINK) {
return !(FORCE_HYPERLINK.length > 0 && parseInt(FORCE_HYPERLINK, 10) === 0);
}

if (stream && !stream.isTTY) {
return false;
}

if ("WT_SESSION" in process.env) {
return true;
}

if (process.platform === "win32") {
return false;
}

if (CI) {
return false;
}

if (TERM_PROGRAM) {
const version = parseVersion(TERM_PROGRAM_VERSION || "");

switch (TERM_PROGRAM) {
case "iTerm.app":
if (version.major === 3) {
return version.minor >= 1;
}

return version.major > 3;
case "WezTerm":
return version.major >= 20200620;
case "vscode":
// eslint-disable-next-line no-mixed-operators
return version.major > 1 || (version.major === 1 && version.minor >= 72);
// No default
}
}

/* cspell:disable-next-line */
if (TERM && ["xterm-kitty", "alacritty", "alacritty-direct"].includes(TERM)) {
return true;
}

if (COLORTERM === "xfce4-terminal") {
return true;
}
if (TERMINAL_EMULATOR === "JetBrains-JediTerm") {
return true;
}

if (VTE_VERSION) {
// 0.50.0 was supposed to support hyperlinks, but throws a segfault
if (VTE_VERSION === "0.50.0") {
return false;
}

const version = parseVersion(VTE_VERSION);
return version.major > 0 || version.minor >= 50;
}

return false;
}

function parseVersion(versionString: string): { major: number; minor: number; patch: number } {
if (/^\d{3,4}$/.test(versionString)) {
// Env var doesn't always use dots. example: 4601 => 46.1.0
const m = /(\d{1,2})(\d{2})/.exec(versionString) || [];
return {
major: 0,
minor: parseInt(m[1], 10),
patch: parseInt(m[2], 10),
};
}

const versions = (versionString || "").split(".").map((n) => parseInt(n, 10));
return {
major: versions[0],
minor: versions[1],
patch: versions[2],
};
}
8 changes: 0 additions & 8 deletions packages/compiler/src/core/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,6 @@ export interface Program {
* Project root. If a tsconfig was found/specified this is the directory for the tsconfig.json. Otherwise directory where the entrypoint is located.
*/
readonly projectRoot: string;

/** @internal */
getDiagnosticUrl(diagnostic: Diagnostic): string | undefined;
}

interface EmitterRef {
Expand Down Expand Up @@ -195,7 +192,6 @@ export async function compile(
resolveTypeReference,
getSourceFileLocationContext,
projectRoot: getDirectoryPath(options.config ?? resolvedMain ?? ""),
getDiagnosticUrl,
};

trace("compiler.options", JSON.stringify(options, null, 2));
Expand All @@ -210,10 +206,6 @@ export async function compile(
await loadStandardLibrary();
}

function getDiagnosticUrl(diagnostic: Diagnostic): string | undefined {
return linter.getRuleUrl(diagnostic.code);
}

// Load additional imports prior to compilation
if (resolvedMain && options.additionalImports) {
const importScript = options.additionalImports.map((i) => `import "${i}";`).join("\n");
Expand Down
4 changes: 4 additions & 0 deletions packages/compiler/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2148,6 +2148,8 @@ export type DiagnosticSeverity = "error" | "warning";

export interface Diagnostic {
code: string;
/** @internal Diagnostic documentation url */
readonly url?: string;
severity: DiagnosticSeverity;
message: string;
target: DiagnosticTarget | typeof NoTarget;
Expand Down Expand Up @@ -2678,6 +2680,8 @@ export interface ProcessedLog {
level: LogLevel;
message: string;
code?: string;
/** Documentation for the error code. */
url?: string;
sourceLocation?: SourceLocation;
}

Expand Down
5 changes: 2 additions & 3 deletions packages/compiler/src/server/serverlib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,10 +398,9 @@ export function createServer(host: ServerHost): Server {
const severity = convertSeverity(each.severity);
const diagnostic = VSDiagnostic.create(range, each.message, severity, each.code, "TypeSpec");

const url = program.getDiagnosticUrl(each);
if (url) {
if (each.url) {
diagnostic.codeDescription = {
href: url,
href: each.url,
};
}
if (each.code === "deprecated") {
Expand Down
Loading