Skip to content

Commit

Permalink
Fix parsing maxAllowedComplexity (#646)
Browse files Browse the repository at this point in the history
  • Loading branch information
arendjr authored and ematipico committed May 24, 2024
1 parent a49bd8d commit 9f3427d
Show file tree
Hide file tree
Showing 12 changed files with 229 additions and 5 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ bitflags = "2.5.0"
bpaf = { version = "0.9.9", features = ["derive"] }
countme = "3.0.1"
crossbeam = "0.8.4"
crossbeam = "0.8.2"
dashmap = "5.4.0"
enumflags2 = "0.7.9"
getrandom = "0.2.15"
Expand All @@ -184,6 +185,7 @@ syn = "1.0.109"
termcolor = "1.4.1"
tokio = "1.36.0"
tracing = { version = "0.1.40", default-features = false, features = ["std"] }

tracing-subscriber = "0.3.18"
unicode-bom = "2.0.3"
unicode-width = "0.1.12"
Expand Down
1 change: 1 addition & 0 deletions crates/biome_cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ tracing = { workspace = true }
tracing-appender = "0.2.3"
tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
tracing-tree = "0.3.0"
ratatui = "0.23.1-alpha.0"

[target.'cfg(unix)'.dependencies]
libc = "0.2.154"
Expand Down
15 changes: 13 additions & 2 deletions crates/biome_cli/src/commands/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ pub(crate) struct LintCommandPayload {
pub(crate) javascript_linter: Option<PartialJavascriptLinter>,
pub(crate) json_linter: Option<PartialJsonLinter>,
pub(crate) css_linter: Option<PartialCssLinter>,
pub(crate) review: bool,
}

/// Handler for the "lint" command of the Biome CLI
Expand All @@ -64,9 +65,19 @@ pub(crate) fn lint(session: CliSession, payload: LintCommandPayload) -> Result<(
javascript_linter,
css_linter,
json_linter,
review,
} = payload;

setup_cli_subscriber(cli_options.log_level, cli_options.log_kind);

if review && (!apply_unsafe && !apply) {
if !apply_unsafe {
return Err(CliDiagnostic::missing_argument("apply-unsafe", "lint"));
} else if !apply {
return Err(CliDiagnostic::missing_argument("apply", "lint"));
}
}
// no point in doing the traversal if all the checks have been disabled
let fix_file_mode = determine_fix_file_mode(
FixFileModeOptions {
apply,
Expand Down Expand Up @@ -162,8 +173,8 @@ pub(crate) fn lint(session: CliSession, payload: LintCommandPayload) -> Result<(
fix_file_mode,
stdin,
rule,
})
.set_report(&cli_options),
review
}),
session,
&cli_options,
paths,
Expand Down
4 changes: 4 additions & 0 deletions crates/biome_cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ pub enum BiomeCommand {
#[bpaf(long("apply-unsafe"), switch, hide_usage)]
apply_unsafe: bool,

/// It runs the lint command in interactive mode, where fixes are chose manually
#[bpaf(long("review"), switch)]
review: bool,

#[bpaf(external(partial_linter_configuration), hide_usage, optional)]
linter_configuration: Option<PartialLinterConfiguration>,

Expand Down
13 changes: 13 additions & 0 deletions crates/biome_cli/src/execute/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ pub enum TraversalMode {
/// - When a rule is passed, its severity level is set to `error' if it is a recommended rule, or `warn' otherwise.
/// - When a rule group is passed, the `recommended` flag is enabled, but if the `all` flag is enabled.
rule: Option<RuleSelector>,

/// Whether the user wants to review the changes using the `--review` argument
review: bool,
},
/// This mode is enabled when running the command `biome ci`
CI {
Expand Down Expand Up @@ -270,6 +273,16 @@ impl Execution {
}
}

pub(crate) fn interactive(&self) -> bool {
match &self.traversal_mode {
TraversalMode::Lint { review, .. } => *review,
TraversalMode::Format { .. }
| TraversalMode::CI
| TraversalMode::Migrate { .. }
| TraversalMode::Check { .. } => false,
}
}

pub(crate) fn as_diagnostic_category(&self) -> &'static Category {
match self.traversal_mode {
TraversalMode::Check { .. } => category!("check"),
Expand Down
2 changes: 2 additions & 0 deletions crates/biome_cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ impl<'app> CliSession<'app> {
css_linter,
javascript_linter,
json_linter,
review,
} => commands::lint::lint(
self,
LintCommandPayload {
Expand All @@ -155,6 +156,7 @@ impl<'app> CliSession<'app> {
css_linter,
javascript_linter,
json_linter,
review,
},
),
BiomeCommand::Ci {
Expand Down
93 changes: 92 additions & 1 deletion crates/biome_service/src/file_handlers/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use crate::configuration::to_analyzer_rules;
use crate::diagnostics::extension_error;
use crate::file_handlers::{is_diagnostic_error, FixAllParams};
use crate::settings::{LinterSettings, OverrideSettings, Settings};
use crate::workspace::{DocumentFileSource, OrganizeImportsResult};
use crate::workspace::{
DocumentFileSource, OrganizeImportsResult, PullDiagnosticsAndActionsResult,
};
use crate::{
settings::{
FormatSettings, LanguageListSettings, LanguageSettings, ServiceLanguage,
Expand Down Expand Up @@ -906,3 +908,92 @@ pub(crate) fn organize_imports(parse: AnyParse) -> Result<OrganizeImportsResult,
})
}
}

fn diagnostics_and_actions(params: LintParams) -> PullDiagnosticsAndActionsResult {
if params.parse.has_errors() {
return PullDiagnosticsAndActionsResult {
errors: 0,
diagnostics_with_actions: vec![],
skipped_diagnostics: 0,
};
}
let Ok(file_source) = params.parse.file_source(params.path) else {
return PullDiagnosticsAndActionsResult {
errors: 0,
diagnostics_with_actions: vec![],
skipped_diagnostics: 0,
};
};
let tree = params.parse.tree();
let mut diagnostics = vec![];
let mut errors = 0;
let analyzer_options =
compute_analyzer_options(&params.settings, PathBuf::from(params.path.as_path()));

let mut diagnostic_count = diagnostics.len() as u64;

let has_lint = params.filter.categories.contains(RuleCategories::LINT);

info!("Analyze file {}", params.path.display());
let (_, _) = analyze(
&tree,
params.filter,
&analyzer_options,
file_source,
|signal| {
if let Some(mut diagnostic) = signal.diagnostic() {
// Do not report unused suppression comment diagnostics if this is a syntax-only analyzer pass
if !has_lint && diagnostic.category() == Some(category!("suppressions/unused")) {
return ControlFlow::<Never>::Continue(());
}

diagnostic_count += 1;

// We do now check if the severity of the diagnostics should be changed.
// The configuration allows to change the severity of the diagnostics emitted by rules.
let severity = diagnostic
.category()
.filter(|category| category.name().starts_with("lint/"))
.map(|category| {
params
.rules
.and_then(|rules| rules.get_severity_from_code(category))
.unwrap_or(Severity::Warning)
})
.unwrap_or_else(|| diagnostic.severity());

if severity >= Severity::Error {
errors += 1;
}

if diagnostic_count <= params.max_diagnostics {
let actions: Vec<_> = signal
.actions()
.into_code_action_iter()
.map(|item| CodeAction {
category: item.category.clone(),
rule_name: item
.rule_name
.map(|(group, name)| (Cow::Borrowed(group), Cow::Borrowed(name))),
suggestion: item.suggestion,
})
.collect();

let error = diagnostic.with_severity(severity);

diagnostics.push((biome_diagnostics::serde::Diagnostic::new(error), actions));
}
}

ControlFlow::<Never>::Continue(())
},
);

let skipped_diagnostics = diagnostic_count.saturating_sub(diagnostics.len() as u64);

PullDiagnosticsAndActionsResult {
diagnostics_with_actions: diagnostics,
errors,
skipped_diagnostics,
}
}
1 change: 1 addition & 0 deletions crates/biome_service/src/file_handlers/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ impl ExtensionHandler for JsonFileHandler {
rename: None,
fix_all: Some(fix_all),
organize_imports: Some(organize_imports),
diagnostics_and_actions: None,
},
formatter: FormatterCapabilities {
format: Some(format),
Expand Down
8 changes: 7 additions & 1 deletion crates/biome_service/src/file_handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use self::{
pub use crate::file_handlers::astro::{AstroFileHandler, ASTRO_FENCE};
pub use crate::file_handlers::svelte::{SvelteFileHandler, SVELTE_FENCE};
pub use crate::file_handlers::vue::{VueFileHandler, VUE_FENCE};
use crate::workspace::{FixFileMode, OrganizeImportsResult};
use crate::workspace::{
CodeAction, FixFileMode, OrganizeImportsResult, PullDiagnosticsAndActionsResult,
};
use crate::{
settings::WorkspaceSettingsHandle,
workspace::{FixFileResult, GetSyntaxTreeResult, PullActionsResult, RenameResult},
Expand Down Expand Up @@ -387,6 +389,8 @@ pub(crate) struct CodeActionsParams<'a> {
}

type Lint = fn(LintParams) -> LintResults;
type DiagnosticsAndActions = fn(LintParams) -> PullDiagnosticsAndActionsResult;

type CodeActions = fn(CodeActionsParams) -> PullActionsResult;
type FixAll = fn(FixAllParams) -> Result<FixFileResult, WorkspaceError>;
type Rename = fn(&BiomePath, AnyParse, TextSize, String) -> Result<RenameResult, WorkspaceError>;
Expand All @@ -396,6 +400,8 @@ type OrganizeImports = fn(AnyParse) -> Result<OrganizeImportsResult, WorkspaceEr
pub struct AnalyzerCapabilities {
/// It lints a file
pub(crate) lint: Option<Lint>,
/// Extract diagnostics and relative actions
pub(crate) diagnostics_and_actions: Option<DiagnosticsAndActions>,
/// It extracts code actions for a file
pub(crate) code_actions: Option<CodeActions>,
/// Applies fixes to a file
Expand Down
26 changes: 26 additions & 0 deletions crates/biome_service/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,14 @@ pub struct PullActionsResult {
pub actions: Vec<CodeAction>,
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PullDiagnosticsAndActionsResult {
pub diagnostics_with_actions: Vec<(biome_diagnostics::serde::Diagnostic, Vec<CodeAction>)>,
pub errors: usize,
pub skipped_diagnostics: u64,
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CodeAction {
Expand Down Expand Up @@ -833,6 +841,11 @@ pub trait Workspace: Send + Sync + RefUnwindSafe {
/// position within a file
fn pull_actions(&self, params: PullActionsParams) -> Result<PullActionsResult, WorkspaceError>;

fn pull_diagnostics_and_actions(
&self,
params: PullDiagnosticsParams,
) -> Result<PullDiagnosticsAndActionsResult, WorkspaceError>;

/// Runs the given file through the formatter using the provided options
/// and returns the resulting source code
fn format_file(&self, params: FormatFileParams) -> Result<Printed, WorkspaceError>;
Expand Down Expand Up @@ -952,6 +965,19 @@ impl<'app, W: Workspace + ?Sized> FileGuard<'app, W> {
})
}

pub fn pull_diagnostics_and_actions(
&self,
categories: RuleCategories,
max_diagnostics: u64,
) -> Result<PullDiagnosticsAndActionsResult, WorkspaceError> {
self.workspace
.pull_diagnostics_and_actions(PullDiagnosticsParams {
path: self.path.clone(),
categories,
max_diagnostics,
})
}

pub fn pull_actions(&self, range: TextRange) -> Result<PullActionsResult, WorkspaceError> {
self.workspace.pull_actions(PullActionsParams {
path: self.path.clone(),
Expand Down
8 changes: 8 additions & 0 deletions crates/biome_service/src/workspace/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::workspace::{
FileFeaturesResult, GetFileContentParams, IsPathIgnoredParams, OpenProjectParams,
OrganizeImportsParams, OrganizeImportsResult, ProjectKey, RageParams, RageResult,
RegisterProjectFolderParams, ServerInfo, UnregisterProjectFolderParams, UpdateProjectParams,
PullDiagnosticsAndActionsResult
};
use crate::{TransportError, Workspace, WorkspaceError};
use biome_formatter::Printed;
Expand Down Expand Up @@ -181,6 +182,13 @@ where
self.request("biome/pull_actions", params)
}

fn pull_diagnostics_and_actions(
&self,
params: PullDiagnosticsParams,
) -> Result<PullDiagnosticsAndActionsResult, WorkspaceError> {
self.request("biome/pull_diagnostics_and_actions", params)
}

fn format_file(&self, params: FormatFileParams) -> Result<Printed, WorkspaceError> {
self.request("biome/format_file", params)
}
Expand Down
Loading

0 comments on commit 9f3427d

Please sign in to comment.