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

feat(lint): add support for config file and CLI flags for rules #11776

Merged
merged 20 commits into from
Sep 3, 2021
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
69 changes: 64 additions & 5 deletions cli/config_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ impl TsConfig {
maybe_config_file: Option<&ConfigFile>,
) -> Result<Option<IgnoredCompilerOptions>, AnyError> {
if let Some(config_file) = maybe_config_file {
let (value, maybe_ignored_options) = config_file.as_compiler_options()?;
let (value, maybe_ignored_options) = config_file.to_compiler_options()?;
self.merge(&value);
Ok(maybe_ignored_options)
} else {
Expand Down Expand Up @@ -266,10 +266,33 @@ impl Serialize for TsConfig {
}
}

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LintRulesConfig {
pub tags: Option<Vec<String>>,
bartlomieju marked this conversation as resolved.
Show resolved Hide resolved
pub include: Option<Vec<String>>,
pub exclude: Option<Vec<String>>,
bartlomieju marked this conversation as resolved.
Show resolved Hide resolved
}

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LintFilesConfig {
pub include: Vec<String>,
pub exclude: Vec<String>,
}

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LintConfig {
pub rules: LintRulesConfig,
pub files: LintFilesConfig,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfigFileJson {
pub compiler_options: Option<Value>,
pub lint: Option<Value>,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -328,7 +351,7 @@ impl ConfigFile {

/// Parse `compilerOptions` and return a serde `Value`.
/// The result also contains any options that were ignored.
pub fn as_compiler_options(
pub fn to_compiler_options(
&self,
) -> Result<(Value, Option<IgnoredCompilerOptions>), AnyError> {
if let Some(compiler_options) = self.json.compiler_options.clone() {
Expand All @@ -340,6 +363,16 @@ impl ConfigFile {
Ok((json!({}), None))
}
}

pub fn to_lint_config(&self) -> Result<Option<LintConfig>, AnyError> {
if let Some(config) = self.json.lint.clone() {
let lint_config: LintConfig = serde_json::from_value(config)
.context("Failed to parse \"lint\" configuration")?;
Ok(Some(lint_config))
} else {
Ok(None)
}
}
}

#[cfg(test)]
Expand Down Expand Up @@ -397,12 +430,22 @@ mod tests {
"build": true,
// comments are allowed
"strict": true
},
"lint": {
"files": {
"include": ["src/"],
"exclude": ["src/testdata/"]
},
"rules": {
"tags": ["recommended"],
"include": ["ban-untagged-todo"]
}
}
}"#;
let config_path = PathBuf::from("/deno/tsconfig.json");
let config_file = ConfigFile::new(config_text, &config_path).unwrap();
let (options_value, ignored) =
config_file.as_compiler_options().expect("error parsing");
config_file.to_compiler_options().expect("error parsing");
assert!(options_value.is_object());
let options = options_value.as_object().unwrap();
assert!(options.contains_key("strict"));
Expand All @@ -414,6 +457,22 @@ mod tests {
maybe_path: Some(config_path),
}),
);

let lint_config = config_file
.to_lint_config()
.expect("error parsing lint object")
.expect("lint object should be defined");
assert_eq!(lint_config.files.include, vec!["src/"]);
assert_eq!(lint_config.files.exclude, vec!["src/testdata/"]);
assert_eq!(
lint_config.rules.include,
Some(vec!["ban-untagged-todo".to_string()])
);
assert_eq!(
lint_config.rules.tags,
Some(vec!["recommended".to_string()])
);
assert!(lint_config.rules.exclude.is_none());
}

#[test]
Expand All @@ -422,7 +481,7 @@ mod tests {
let config_path = PathBuf::from("/deno/tsconfig.json");
let config_file = ConfigFile::new(config_text, &config_path).unwrap();
let (options_value, _) =
config_file.as_compiler_options().expect("error parsing");
config_file.to_compiler_options().expect("error parsing");
assert!(options_value.is_object());
}

Expand All @@ -432,7 +491,7 @@ mod tests {
let config_path = PathBuf::from("/deno/tsconfig.json");
let config_file = ConfigFile::new(config_text, &config_path).unwrap();
let (options_value, _) =
config_file.as_compiler_options().expect("error parsing");
config_file.to_compiler_options().expect("error parsing");
assert!(options_value.is_object());
}

Expand Down
108 changes: 108 additions & 0 deletions cli/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ pub enum DenoSubcommand {
files: Vec<PathBuf>,
ignore: Vec<PathBuf>,
rules: bool,
rules_tags: Vec<String>,
rules_include: Vec<String>,
rules_exclude: Vec<String>,
json: bool,
},
Repl {
Expand Down Expand Up @@ -952,6 +955,35 @@ Ignore linting a file by adding an ignore comment at the top of the file:
.long("rules")
.help("List available rules"),
)
.arg(
Arg::with_name("rules-tags")
.long("rules-tags")
.require_equals(true)
.takes_value(true)
.use_delimiter(true)
.empty_values(true)
.conflicts_with("rules")
.help("Use set of rules with a tag"),
)
.arg(
Arg::with_name("rules-include")
.long("rules-include")
.require_equals(true)
.takes_value(true)
.use_delimiter(true)
.conflicts_with("rules")
.help("Include lint rules"),
)
.arg(
Arg::with_name("rules-exclude")
.long("rules-exclude")
.require_equals(true)
.takes_value(true)
.use_delimiter(true)
.conflicts_with("rules")
.help("Exclude lint rules"),
)
.arg(config_arg())
.arg(
Arg::with_name("ignore")
.long("ignore")
Expand Down Expand Up @@ -1722,6 +1754,7 @@ fn lsp_parse(flags: &mut Flags, _matches: &clap::ArgMatches) {
}

fn lint_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
config_arg_parse(flags, matches);
let files = match matches.values_of("files") {
Some(f) => f.map(PathBuf::from).collect(),
None => vec![],
Expand All @@ -1731,10 +1764,25 @@ fn lint_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
None => vec![],
};
let rules = matches.is_present("rules");
let rules_tags = match matches.values_of("rules-tags") {
Some(f) => f.map(String::from).collect(),
None => vec![],
};
let rules_include = match matches.values_of("rules-include") {
Some(f) => f.map(String::from).collect(),
None => vec![],
};
let rules_exclude = match matches.values_of("rules-exclude") {
Some(f) => f.map(String::from).collect(),
None => vec![],
};
let json = matches.is_present("json");
flags.subcommand = DenoSubcommand::Lint {
files,
rules,
rules_tags,
rules_include,
rules_exclude,
ignore,
json,
};
Expand Down Expand Up @@ -2456,6 +2504,9 @@ mod tests {
PathBuf::from("script_2.ts")
],
rules: false,
rules_tags: vec![],
rules_include: vec![],
rules_exclude: vec![],
json: false,
ignore: vec![],
},
Expand All @@ -2471,6 +2522,9 @@ mod tests {
subcommand: DenoSubcommand::Lint {
files: vec![],
rules: false,
rules_tags: vec![],
rules_include: vec![],
rules_exclude: vec![],
json: false,
ignore: vec![
PathBuf::from("script_1.ts"),
Expand All @@ -2488,6 +2542,32 @@ mod tests {
subcommand: DenoSubcommand::Lint {
files: vec![],
rules: true,
rules_tags: vec![],
rules_include: vec![],
rules_exclude: vec![],
json: false,
ignore: vec![],
},
..Flags::default()
}
);

let r = flags_from_vec(svec![
"deno",
"lint",
"--rules-tags=",
"--rules-include=ban-untagged-todo,no-undef",
"--rules-exclude=no-const-assign"
]);
assert_eq!(
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Lint {
files: vec![],
rules: false,
rules_tags: svec![""],
rules_include: svec!["ban-untagged-todo", "no-undef"],
rules_exclude: svec!["no-const-assign"],
json: false,
ignore: vec![],
},
Expand All @@ -2502,9 +2582,37 @@ mod tests {
subcommand: DenoSubcommand::Lint {
files: vec![PathBuf::from("script_1.ts")],
rules: false,
rules_tags: vec![],
rules_include: vec![],
rules_exclude: vec![],
json: true,
ignore: vec![],
},
..Flags::default()
}
);

let r = flags_from_vec(svec![
"deno",
"lint",
"--config",
"Deno.jsonc",
"--json",
"script_1.ts"
]);
assert_eq!(
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Lint {
files: vec![PathBuf::from("script_1.ts")],
rules: false,
rules_tags: vec![],
rules_include: vec![],
rules_exclude: vec![],
json: true,
ignore: vec![],
},
config_path: Some("Deno.jsonc".to_string()),
..Flags::default()
}
);
Expand Down
2 changes: 1 addition & 1 deletion cli/lsp/language_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ impl Inner {
ConfigFile::read(path)?
};
let (value, maybe_ignored_options) =
config_file.as_compiler_options()?;
config_file.to_compiler_options()?;
tsconfig.merge(&value);
self.maybe_config_file = Some(config_file);
self.maybe_config_uri = Some(config_url);
Expand Down
40 changes: 37 additions & 3 deletions cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,10 +489,14 @@ async fn lsp_command() -> Result<(), AnyError> {
lsp::start().await
}

#[allow(clippy::too_many_arguments)]
async fn lint_command(
_flags: Flags,
flags: Flags,
files: Vec<PathBuf>,
list_rules: bool,
rules_tags: Vec<String>,
rules_include: Vec<String>,
rules_exclude: Vec<String>,
ignore: Vec<PathBuf>,
json: bool,
) -> Result<(), AnyError> {
Expand All @@ -501,7 +505,24 @@ async fn lint_command(
return Ok(());
}

tools::lint::lint_files(files, ignore, json).await
let program_state = ProgramState::build(flags.clone()).await?;
let maybe_lint_config =
if let Some(config_file) = &program_state.maybe_config_file {
config_file.to_lint_config()?
} else {
None
};

tools::lint::lint_files(
maybe_lint_config,
rules_tags,
rules_include,
rules_exclude,
files,
ignore,
json,
)
.await
}

async fn cache_command(
Expand Down Expand Up @@ -1183,9 +1204,22 @@ fn get_subcommand(
DenoSubcommand::Lint {
files,
rules,
rules_tags,
rules_include,
rules_exclude,
ignore,
json,
} => lint_command(flags, files, rules, ignore, json).boxed_local(),
} => lint_command(
flags,
files,
rules,
rules_tags,
rules_include,
rules_exclude,
ignore,
json,
)
.boxed_local(),
bartlomieju marked this conversation as resolved.
Show resolved Hide resolved
DenoSubcommand::Repl { eval } => run_repl(flags, eval).boxed_local(),
DenoSubcommand::Run { script } => run_command(flags, script).boxed_local(),
DenoSubcommand::Test {
Expand Down
Loading