Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
30 changes: 23 additions & 7 deletions crates/ruff/src/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ use itertools::{Itertools, iterate};
use ruff_linter::linter::FixTable;
use serde::Serialize;

use ruff_db::diagnostic::{Diagnostic, DisplayDiagnosticConfig, SecondaryCode};
use ruff_db::diagnostic::{
Diagnostic, DisplayDiagnosticConfig, HyperlinkMode, SecondaryCode, fmt_with_hyperlink,
};
use ruff_linter::fs::relativize_path;
use ruff_linter::logging::LogLevel;
use ruff_linter::message::{EmitterContext, render_diagnostics};
Expand All @@ -33,6 +35,10 @@ bitflags! {
#[derive(Serialize)]
struct ExpandedStatistics<'a> {
code: Option<&'a SecondaryCode>,
/// Skipped when serializing to keep the JSON output unchanged; it only exists to hyperlink
/// the code in terminal output.
#[serde(skip)]
url: Option<&'a str>,
name: &'static str,
count: usize,
#[serde(rename = "fixable")]
Expand Down Expand Up @@ -297,6 +303,7 @@ impl Printer {
.map(
|&(code, message, count, fixable_count)| ExpandedStatistics {
code,
url: message.documentation_url(),
name: message.name(),
count,
// Backward compatibility: `fixable` is true only when all violations are fixable.
Expand Down Expand Up @@ -330,6 +337,11 @@ impl Printer {
.unwrap();
let any_fixable = statistics.iter().any(ExpandedStatistics::any_fixable);

// Turning colors off also turns hyperlinks off, matching how the full and concise
// output formats build their stylesheets.
let hyperlink = colored::control::SHOULD_COLORIZE.should_colorize()
&& HyperlinkMode::Auto.is_enabled();
Comment thread
alonfaraj marked this conversation as resolved.
Resolved

let all_fixable = format!("[{}] ", "*".cyan());
let partially_fixable = format!("[{}] ", "-".cyan());
let unfixable = "[ ] ";
Expand All @@ -340,12 +352,16 @@ impl Printer {
writer,
"{:>count_width$}\t{:<code_width$}\t{}{}",
statistic.count.to_string().bold(),
statistic
.code
.map(SecondaryCode::as_str)
.unwrap_or_default()
.red()
.bold(),
fmt_with_hyperlink(
statistic
.code
.map(SecondaryCode::as_str)
.unwrap_or_default()
.red()
.bold(),
statistic.url,
hyperlink,
),
if any_fixable {
if statistic.all_fixable {
&all_fixable
Expand Down
29 changes: 29 additions & 0 deletions crates/ruff/tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,35 @@ def mvce(keys, values):
");
}

/// Rule codes in `--statistics` output link to the rule documentation, as they do in the concise
/// and full output formats.
#[test]
fn show_statistics_hyperlinks() -> Result<()> {
Comment thread
alonfaraj marked this conversation as resolved.
Resolved
let tempdir = TempDir::new()?;
let input = tempdir.path().join("main.py");
fs::write(
&input,
"def mvce(keys, values):\n return {key: value for key, value in zip(keys, values)}\n",
)?;

let mut cmd = RuffCheck::default()
.filename(input.to_str().unwrap())
.args(["--select", "C416", "--statistics", "--color", "always"])
.build();
// Force hyperlink support so that the test does not depend on the terminal it runs in.
let output = cmd.env("FORCE_HYPERLINK", "1").output()?;
let stdout = str::from_utf8(&output.stdout)?;

assert!(
stdout.contains(
"\u{1b}]8;;https://docs.astral.sh/ruff/rules/unnecessary-comprehension\u{1b}\\"
),
Comment thread
alonfaraj marked this conversation as resolved.
Resolved
"expected the `C416` code to be hyperlinked, got: {stdout:?}"
);

Ok(())
}

#[test]
fn show_statistics_unsafe_fixes() {
let mut cmd = RuffCheck::default()
Expand Down
12 changes: 12 additions & 0 deletions crates/ruff_db/src/diagnostic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use serde::Serialize;
pub use self::render::{
DisplayDiagnostic, DisplayDiagnostics, DummyFileResolver, FileResolver, Input,
};
pub use self::stylesheet::fmt_with_hyperlink;
use crate::cancellation::CancellationToken;
use crate::{Db, files::File};

Expand Down Expand Up @@ -1393,6 +1394,17 @@ pub enum HyperlinkMode {
Never,
}

impl HyperlinkMode {
/// Returns whether hyperlinks should be emitted, detecting terminal support for [`Self::Auto`].
pub fn is_enabled(self) -> bool {
match self {
HyperlinkMode::Auto => supports_hyperlinks::supports_hyperlinks(),
HyperlinkMode::Always => true,
HyperlinkMode::Never => false,
}
}
}

/// Configuration for rendering diagnostics.
#[derive(Clone, Debug)]
pub struct DisplayDiagnosticConfig {
Expand Down
12 changes: 8 additions & 4 deletions crates/ruff_db/src/diagnostic/render/concise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl<'a> ConciseRenderer<'a> {
diagnostics: &[Diagnostic],
) -> std::fmt::Result {
let stylesheet = if self.config.color {
DiagnosticStylesheet::styled().hyperlinks(self.config.hyperlinks)
DiagnosticStylesheet::styled().hyperlink(self.config.hyperlinks.is_enabled())
Comment thread
alonfaraj marked this conversation as resolved.
Resolved
} else {
DiagnosticStylesheet::plain()
};
Expand Down Expand Up @@ -74,7 +74,11 @@ impl<'a> ConciseRenderer<'a> {
f,
"{code} ",
code = fmt_styled(
fmt_with_hyperlink(&code, diag.documentation_url(), &stylesheet),
fmt_with_hyperlink(
&code,
diag.documentation_url(),
stylesheet.hyperlink
),
stylesheet.secondary_code
)
)?;
Expand All @@ -86,7 +90,7 @@ impl<'a> ConciseRenderer<'a> {
fmt_with_hyperlink(
&diag.inner.id,
diag.documentation_url(),
&stylesheet
stylesheet.hyperlink
),
stylesheet.secondary_code
)
Expand All @@ -109,7 +113,7 @@ impl<'a> ConciseRenderer<'a> {
"{severity}[{id}] ",
severity = fmt_styled(severity, severity_style),
id = fmt_styled(
fmt_with_hyperlink(id, diag.documentation_url(), &stylesheet),
fmt_with_hyperlink(id, diag.documentation_url(), stylesheet.hyperlink),
stylesheet.emphasis
)
)?;
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_db/src/diagnostic/render/full.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl<'a> FullRenderer<'a> {
diagnostics: &[Diagnostic],
) -> std::fmt::Result {
let stylesheet = if self.config.color {
DiagnosticStylesheet::styled().hyperlinks(self.config.hyperlinks)
DiagnosticStylesheet::styled().hyperlink(self.config.hyperlinks.is_enabled())
} else {
DiagnosticStylesheet::plain()
};
Expand Down
20 changes: 7 additions & 13 deletions crates/ruff_db/src/diagnostic/stylesheet.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use anstyle::{AnsiColor, Effects, Style};
use std::fmt::Formatter;

use crate::diagnostic::HyperlinkMode;

pub(super) const fn fmt_styled<'a, T>(
content: T,
style: anstyle::Style,
Expand Down Expand Up @@ -33,15 +31,16 @@ where
FmtStyled { content, style }
}

pub(super) fn fmt_with_hyperlink<'a, T>(
/// Renders `content`, wrapped in an OSC 8 terminal hyperlink to `url` when `hyperlink` is enabled.
pub fn fmt_with_hyperlink<'a, T>(
content: T,
url: Option<&'a str>,
stylesheet: &DiagnosticStylesheet,
hyperlink: bool,
) -> impl std::fmt::Display + 'a
where
T: std::fmt::Display + 'a,
{
let url = if stylesheet.hyperlink { url } else { None };
let url = if hyperlink { url } else { None };

std::fmt::from_fn(move |f| {
if let Some(url) = url {
Expand Down Expand Up @@ -88,7 +87,6 @@ impl DiagnosticStylesheet {
pub fn styled() -> Self {
let bright_blue = AnsiColor::BrightBlue.on_default();

let hyperlink = supports_hyperlinks::supports_hyperlinks();
Self {
error: AnsiColor::BrightRed.on_default().effects(Effects::BOLD),
warning: AnsiColor::Yellow.on_default().effects(Effects::BOLD),
Expand All @@ -104,16 +102,12 @@ impl DiagnosticStylesheet {
deletion: AnsiColor::Red.on_default(),
insertion_line_no: AnsiColor::Green.on_default().effects(Effects::BOLD),
deletion_line_no: AnsiColor::Red.on_default().effects(Effects::BOLD),
hyperlink,
hyperlink: false,
}
}

pub(super) fn hyperlinks(mut self, mode: HyperlinkMode) -> Self {
match mode {
HyperlinkMode::Auto => {}
HyperlinkMode::Always => self.hyperlink = true,
HyperlinkMode::Never => self.hyperlink = false,
}
pub(super) fn hyperlink(mut self, yes: bool) -> Self {
self.hyperlink = yes;
self
}

Expand Down
Loading