Skip to content
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
5 changes: 3 additions & 2 deletions crates/wright-bench/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::process::ExitCode;
use std::time::{Duration, Instant};

use wright_driver::CompilerSession;
use wright_driver::FindingSelection;
use wright_driver::Profile;
use wright_driver::config::{InputSpec, SessionConfig, SourceKind};
use wright_driver::service::{ToolRequest, ToolResponse, ToolService};
Expand Down Expand Up @@ -283,9 +284,9 @@ fn semantic_query_trial(
ToolRequest::References { symbol: 0 },
ToolRequest::Usage { symbol: 0 },
ToolRequest::Cfg { rule: 0 },
ToolRequest::Findings,
ToolRequest::Findings(FindingSelection::default()),
ToolRequest::PersistentObjects,
ToolRequest::Lint,
ToolRequest::Lint(FindingSelection::default()),
ToolRequest::LintRules,
];
let start = Instant::now();
Expand Down
53 changes: 51 additions & 2 deletions crates/wright-cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ LINT OPTIONS:
--disable-rule <ID> Disable a lint rule (repeatable)
--rule-severity <ID>:<SEV> Override a lint rule severity (repeatable)

FINDING SELECTION (check, analyze, lint):
--severity <LEVEL> Report findings at or above a severity: error|warning|info
--rule-id <ID> Report findings from one lint rule id only
--file <PATH> Report findings in one source file (any spelling that resolves to it)
--max <N> Report at most N findings (withheld counts are shown)

UPDATE OPTIONS:
--check Check for an update without modifying the installation
--version <VERSION> Install an exact version instead of the latest stable release";
Expand All @@ -67,9 +73,9 @@ pub(crate) enum Command {
/// currently shipped.
Convert(ConvertArgs),
/// Check frontend, project, semantic, and validation correctness.
Check(CommonArgs),
Check(ReportArgs),
/// Summarize semantic structure, CFG hotspots, and cross-cutting state.
Analyze(CommonArgs),
Analyze(ReportArgs),
/// Parse, lower, and report lint findings.
Lint(LintArgs),
/// Parse, lower, and show exhaustive structural/semantic facts.
Expand Down Expand Up @@ -117,6 +123,39 @@ pub(crate) struct SemanticCompareArgs {
pub(crate) actual: PathBuf,
}

/// Arguments of commands that report findings: shared workflow options plus
/// the finding-selection options (#430).
#[derive(Debug, Args)]
pub(crate) struct ReportArgs {
#[command(flatten)]
pub(crate) common: CommonArgs,
#[command(flatten)]
pub(crate) select: SelectArgs,
}

/// Finding-selection options shared by `check`, `analyze`, and `lint`
/// (`cost` joins with the query surface, #429). Selection narrows reported
/// output only — verdicts and exit codes always reflect the complete set.
#[derive(Debug, Args, Default)]
pub(crate) struct SelectArgs {
/// Report findings at or above this severity only.
#[arg(long, value_enum, value_name = "LEVEL")]
pub(crate) severity: Option<SeverityArg>,
/// Report findings produced by this lint rule id only; an unknown id is
/// a usage error.
#[arg(long, value_name = "ID")]
pub(crate) rule_id: Option<String>,
/// Report findings located in this source file only; any spelling that
/// resolves to the same file (as passed, root-relative, or absolute)
/// selects it.
#[arg(long, value_name = "PATH")]
pub(crate) file: Option<String>,
/// Report at most N findings; withheld findings are reported, never
/// silently dropped.
#[arg(long, value_name = "N")]
pub(crate) max: Option<usize>,
}

#[derive(Debug, Args)]
pub(crate) struct CommonArgs {
/// Input path; `-` reads standard input and an omitted path uses the current directory.
Expand Down Expand Up @@ -152,6 +191,8 @@ pub(crate) struct CommonArgs {
pub(crate) struct LintArgs {
#[command(flatten)]
pub(crate) common: CommonArgs,
#[command(flatten)]
pub(crate) select: SelectArgs,
/// Read project lint configuration YAML.
#[arg(long = "lint-config", value_name = "PATH")]
pub(crate) lint_config: Option<PathBuf>,
Expand Down Expand Up @@ -299,6 +340,14 @@ pub(crate) enum ColorArg {
Never,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub(crate) enum SeverityArg {
Error,
#[value(alias = "warn")]
Warning,
Info,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub(crate) enum ShellArg {
Bash,
Expand Down
44 changes: 34 additions & 10 deletions crates/wright-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,18 +139,27 @@ fn run_workflow(command: Command) -> ExitCode {
move |session: &mut wright_driver::CompilerSession| session.convert(target),
)
}
Command::Check(args) => run_configured(
config_from_common(&args, true),
present::Presentation::from_common(&args),
wright_driver::CompilerSession::check,
),
Command::Analyze(args) => run_configured(
config_from_common(&args, true),
present::Presentation::from_common(&args),
wright_driver::CompilerSession::analyze,
),
Command::Check(args) => {
let mut config = config_from_common(&args.common, true);
config.selection = selection_from_args(&args.select);
run_configured(
config,
present::Presentation::from_common(&args.common),
wright_driver::CompilerSession::check,
)
}
Command::Analyze(args) => {
let mut config = config_from_common(&args.common, true);
config.selection = selection_from_args(&args.select);
run_configured(
config,
present::Presentation::from_common(&args.common),
wright_driver::CompilerSession::analyze,
)
}
Command::Lint(args) => {
let mut config = config_from_common(&args.common, true);
config.selection = selection_from_args(&args.select);
if let Some(path) = &args.lint_config {
config.lint = match LintConfig::from_yaml_path(path) {
Ok(config) => config,
Expand Down Expand Up @@ -301,6 +310,21 @@ fn config_from_common(common: &CommonArgs, provider_workflow: bool) -> SessionCo
}
}

/// Map the CLI finding-selection flags onto the shared driver selection
/// model; the driver applies it to diagnostics and lint findings alike (#430).
fn selection_from_args(select: &cli::SelectArgs) -> wright_driver::FindingSelection {
wright_driver::FindingSelection {
severity: select.severity.map(|severity| match severity {
cli::SeverityArg::Error => wright_driver::Severity::Error,
cli::SeverityArg::Warning => wright_driver::Severity::Warning,
cli::SeverityArg::Info => wright_driver::Severity::Info,
}),
rule: select.rule_id.clone(),
file: select.file.clone(),
max: select.max,
}
}

fn is_opy_input(common: &CommonArgs) -> bool {
match common.kind {
cli::SourceKindArg::Opy => true,
Expand Down
133 changes: 111 additions & 22 deletions crates/wright-cli/src/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,14 @@ fn render_text<T: serde::Serialize + ResultPresentation>(envelope: &Envelope<T>,
for diag in &envelope.diagnostics {
render_diagnostic(diag, color);
}
if let Some(selection) = &envelope.selection {
if selection.withheld > 0 {
eprintln!(
" ... {} diagnostic(s) withheld (--max)",
selection.withheld
);
}
}
if !envelope.ok {
if envelope.diagnostics.is_empty() {
eprintln!("{}: failed", envelope.command);
Expand All @@ -296,7 +304,13 @@ fn render_verdict<T: serde::Serialize + ResultPresentation>(envelope: &Envelope<
};
println!("{label} {}", envelope.command);
let metadata = match envelope.command.as_str() {
"check" => format!("{} diagnostic(s)", envelope.diagnostics.len()),
"check" => format!(
"{} diagnostic(s)",
envelope
.selection
.as_ref()
.map_or(envelope.diagnostics.len(), |selection| selection.total)
),
_ => envelope.result.metadata().unwrap_or_default(),
};
println!(" {}", dim(&metadata, color));
Expand Down Expand Up @@ -470,11 +484,21 @@ impl ResultPresentation for AnalyzeResult {

impl ResultPresentation for LintResult {
fn metadata(&self) -> Option<String> {
Some(format!(
let total = self
.selection
.as_ref()
.map_or_else(|| array_len(&self.findings), |selection| selection.total);
let mut metadata = format!(
"{} finding(s) across {} rule(s)",
array_len(&self.findings),
total,
array_len(&self.rules)
))
);
if let Some(selection) = &self.selection {
if selection.withheld > 0 {
metadata.push_str(&format!(", {} withheld", selection.withheld));
}
}
Some(metadata)
}
fn render_body(&self) {
render_lint(self);
Expand All @@ -487,10 +511,24 @@ impl ResultPresentation for LintResult {
}
}
fn update_summary_status(&self, status: &mut SummaryStatus) {
if let Some(findings) = self.findings.as_array() {
for finding in findings {
if let Some(sev) = finding.get("severity").and_then(serde_json::Value::as_str) {
*status = (*status).max(SummaryStatus::from_finding_severity(sev));
match &self.selection {
// Selection narrows the reported list only; the verdict keeps the
// full set's highest severity (#430).
Some(selection) => {
if let Some(severity) = selection.max_severity {
*status =
(*status).max(SummaryStatus::from_finding_severity(severity.as_str()));
}
}
None => {
if let Some(findings) = self.findings.as_array() {
for finding in findings {
if let Some(sev) =
finding.get("severity").and_then(serde_json::Value::as_str)
{
*status = (*status).max(SummaryStatus::from_finding_severity(sev));
}
}
}
}
}
Expand Down Expand Up @@ -518,12 +556,27 @@ fn summary_status<T: serde::Serialize + ResultPresentation>(
} else {
SummaryStatus::Error
};
for diag in &envelope.diagnostics {
status = status.max(match diag.severity {
Severity::Error => SummaryStatus::Error,
Severity::Warning => SummaryStatus::Warn,
Severity::Info => SummaryStatus::Pass,
});
match &envelope.selection {
// The verdict reflects the full diagnostic set, not the selected
// remainder (#430).
Some(selection) => {
if let Some(severity) = selection.max_severity {
status = status.max(match severity {
Severity::Error => SummaryStatus::Error,
Severity::Warning => SummaryStatus::Warn,
Severity::Info => SummaryStatus::Pass,
});
}
}
None => {
for diag in &envelope.diagnostics {
status = status.max(match diag.severity {
Severity::Error => SummaryStatus::Error,
Severity::Warning => SummaryStatus::Warn,
Severity::Info => SummaryStatus::Pass,
});
}
}
}
envelope.result.update_summary_status(&mut status);
status.as_str()
Expand Down Expand Up @@ -700,17 +753,42 @@ fn render_lint(result: &LintResult) {
if findings.is_empty() {
println!(" none");
}
for f in &findings {
let code = f["code"].as_str().unwrap_or("finding");
let sev = f["severity"].as_str().unwrap_or("info");
let ev = f["evidence"].as_str().unwrap_or("exact");
let msg = f["message"].as_str().unwrap_or_default();
match f.get("boundedness").and_then(serde_json::Value::as_str) {
// Consecutive findings sharing a rule id and message collapse into one
// entry that lists its locations (#430).
let mut index = 0;
while index < findings.len() {
let first = &findings[index];
let mut end = index + 1;
while end < findings.len()
&& findings[end]["code"] == first["code"]
&& findings[end]["message"] == first["message"]
{
end += 1;
}
let code = first["code"].as_str().unwrap_or("finding");
let sev = first["severity"].as_str().unwrap_or("info");
let ev = first["evidence"].as_str().unwrap_or("exact");
let msg = first["message"].as_str().unwrap_or_default();
match first.get("boundedness").and_then(serde_json::Value::as_str) {
Some(v) => println!(" {sev}[{code}] (evidence: {ev}) (boundedness: {v}): {msg}"),
None => println!(" {sev}[{code}] (evidence: {ev}): {msg}"),
}
if let Some(span) = f.get("span") {
print_span(span, " ");
if end == index + 1 {
if let Some(span) = first.get("span") {
print_span(span, " ");
}
} else {
for finding in &findings[index..end] {
if let Some(span) = finding.get("span") {
print_location(span, " ");
}
}
}
index = end;
}
if let Some(selection) = &result.selection {
if selection.withheld > 0 {
println!(" ... {} finding(s) withheld (--max)", selection.withheld);
}
}
}
Expand Down Expand Up @@ -764,6 +842,16 @@ fn render_diagnostic(diagnostic: &wright_driver::Diagnostic, color: bool) {
}
}

fn print_location(span: &serde_json::Value, indent: &str) {
let path = span
.get("path")
.and_then(serde_json::Value::as_str)
.unwrap_or("<span>");
let line = span_position(span, "start", "line").unwrap_or(0);
let col = span_position(span, "start", "col").unwrap_or(0);
println!("{indent}--> {path}:{line}:{col}");
}

fn print_span(span: &serde_json::Value, indent: &str) {
let path = span
.get("path")
Expand Down Expand Up @@ -957,6 +1045,7 @@ mod tests {
ok,
exit: if ok { 0 } else { 1 },
diagnostics,
selection: None,
result: LintResult {
findings,
..LintResult::default()
Expand Down
Loading
Loading