use std::{
borrow::Cow,
collections::BTreeSet,
env,
fmt::Write as _,
fs,
io::{self, Read as _, Write as IoWrite},
path::{Path, PathBuf},
process::ExitCode,
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
use adotenv::{
parse_strict_with_options, parse_with_options, ColumnEncoding, Dialect, Document, EditOptions,
LineBreaks, LineIndex, ParseOptions, Severity,
};
use adotenv_lint::{
apply_batch_with_policy, discover_config, lint_with_options, load_effective_config,
parse_dialect, parse_equals_spacing as parse_spacing, parse_key_case,
parse_output_format as parse_format, parse_quote_style, BatchOptions, ConfigExplicit, Finding,
Fix, IgnoredPaths, LintConfig, LintOptions, LintPolicy, OutputFormat, Rule, Schema,
SchemaConfig,
};
const SUCCESS: u8 = 0;
const FINDINGS: u8 = 1;
const FAILURE: u8 = 2;
const USAGE: &str = r"adotenv-lint [options] <file-or-directory>...
Lint .env files using adotenv's literal document model.
Options:
--dialect <portable|node|python|compose|docker>
--format <human|json|github|sarif>
-r, --recursive Search directories for .env and .env.* files
--key-order Require sorted declarations
--key-case <lower|upper> Require key case
--quote-style <double|single|unquoted|preserve>
--equals-spacing <none|spaces|preserve>
--trim-trailing-whitespace Require trimmed trailing whitespace
--example <path> Require keys declared in a .env.example file
--no-unknown-keys Report keys absent from the schema or --example
--no-empty-values Report empty or bare values
--config <path> Read policy from a TOML file
--exclude <pattern> Ignore paths matching a glob
--max-input-bytes <n> Reject files larger than <n> bytes
--max-lines <n> Reject files with more than <n> physical lines
--max-items <n> Reject files with more than <n> parsed items
--max-diagnostics <n> Reject files with more than <n> parse diagnostics
--max-output-bytes <n> Reject fixes producing more than <n> bytes
--max-output-lines <n> Reject fixes producing more than <n> physical lines
--max-references <n> Cap variable references scanned while sorting
--fix Apply verified style fixes and write changed files
--fix-missing With --fix, also insert empty KEY= placeholders for missing keys
--list-rules List all supported lint rules and exit
--explain <rule> Explain one lint rule and its configuration and exit
-- End option parsing
-h, --help Print this usage
--version Print the version
Exit codes: 0 no findings (or all findings fixed), 1 remaining findings,
2 usage/read/parse/write failure.
With no path, searches the current directory recursively (skipping the
--example file itself during directory discovery). The default rule reports
duplicate keys. Fixes are verified through the library before they are
written.";
type Format = OutputFormat;
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Default)]
struct Explicit {
dialect: bool,
format: bool,
recursive: bool,
key_order: bool,
key_case: bool,
quote_style: bool,
equals_spacing: bool,
trim_trailing_whitespace: bool,
exclude: bool,
schema_example: bool,
schema_allow_unknown: bool,
schema_allow_empty: bool,
}
#[derive(Debug)]
struct Options {
dialect: Dialect,
parse_limits: ParseOptions,
edit_limits: EditOptions,
format: Format,
recursive: bool,
fix: bool,
fix_missing: bool,
lint: LintOptions,
schema: Option<SchemaConfig>,
paths: Vec<String>,
config: Option<String>,
exclude: Vec<String>,
explicit: Explicit,
}
fn main() -> ExitCode {
match run() {
Ok(code) => ExitCode::from(code),
Err(message) => {
eprintln!("{message}");
ExitCode::from(FAILURE)
}
}
}
static STDOUT_FAILED: AtomicBool = AtomicBool::new(false);
fn report_stdout_error(error: &io::Error) {
if error.kind() != io::ErrorKind::BrokenPipe && !STDOUT_FAILED.swap(true, Ordering::Relaxed) {
let _ = writeln!(io::stderr().lock(), "adotenv-lint: stdout error: {error}");
}
}
fn write_stdout(text: &str) {
let mut stdout = io::stdout().lock();
if let Err(error) = stdout.write_all(text.as_bytes()) {
report_stdout_error(&error);
}
}
fn write_stdout_line(text: &str) {
let mut stdout = io::stdout().lock();
if let Err(error) = writeln!(stdout, "{text}") {
report_stdout_error(&error);
}
}
fn flush_stdout() {
if let Err(error) = io::stdout().lock().flush() {
report_stdout_error(&error);
}
}
fn finish_output(code: u8) -> u8 {
flush_stdout();
if STDOUT_FAILED.load(Ordering::Relaxed) {
FAILURE
} else {
code
}
}
fn parse_strict_bounded(
source: &str,
dialect: Dialect,
limits: ParseOptions,
) -> Result<Document<'_>, String> {
if limits.max_diagnostics.is_some() {
let (document, diagnostics) = parse_with_options(source, dialect, limits);
if let Some(error) = diagnostics
.iter()
.find(|diagnostic| diagnostic.limit().is_some())
.or_else(|| {
diagnostics
.iter()
.find(|diagnostic| diagnostic.severity() == Severity::Error)
})
{
return Err(error.to_string());
}
return Ok(document);
}
parse_strict_with_options(source, dialect, limits).map_err(|error| error.to_string())
}
fn read_file_bounded(path: &Path, max_input_bytes: Option<usize>) -> Result<String, String> {
if let Ok(metadata) = fs::metadata(path) {
if !metadata.is_file() {
return Err("path is not a regular file".to_owned());
}
}
let mut file = fs::File::open(path).map_err(|error| error.to_string())?;
let metadata = file.metadata().map_err(|error| error.to_string())?;
if !metadata.is_file() {
return Err("path is not a regular file".to_owned());
}
if let Some(limit) = max_input_bytes {
let observed = usize::try_from(metadata.len()).unwrap_or(usize::MAX);
if observed > limit {
return Err(format!(
"input exceeds max_input_bytes limit ({limit} bytes)"
));
}
}
let mut bytes = Vec::new();
let read_result = match max_input_bytes {
Some(limit) => file
.take(limit.saturating_add(1) as u64)
.read_to_end(&mut bytes),
None => file.read_to_end(&mut bytes),
};
read_result.map_err(|error| error.to_string())?;
if let Some(limit) = max_input_bytes {
if bytes.len() > limit {
return Err(format!(
"input exceeds max_input_bytes limit ({limit} bytes)"
));
}
}
String::from_utf8(bytes).map_err(|_| "invalid UTF-8".to_owned())
}
fn run() -> Result<u8, String> {
let args = env::args_os()
.skip(1)
.map(|argument| {
argument
.into_string()
.map_err(|_| "arguments must be valid UTF-8".to_owned())
})
.collect::<Result<Vec<_>, _>>()?;
let mut options = match parse_cli_args(&args)? {
CliAction::Help => {
write_stdout_line(USAGE);
return Ok(finish_output(SUCCESS));
}
CliAction::Version => {
write_stdout_line(&format!("adotenv-lint {}", env!("CARGO_PKG_VERSION")));
return Ok(finish_output(SUCCESS));
}
CliAction::ListRules => {
print_rule_list();
return Ok(finish_output(SUCCESS));
}
CliAction::Explain(rule) => {
print_rule_explanation(rule);
return Ok(finish_output(SUCCESS));
}
CliAction::Run(options) => *options,
};
if options.fix_missing && !options.fix {
return Err("--fix-missing requires --fix".to_owned());
}
apply_config(&mut options)?;
options.edit_limits = options.edit_limits.with_parse_limits(options.parse_limits);
let (schema, example_canonical) = resolve_schema(&options)?;
if options.paths.is_empty() {
options.paths.push(".".to_owned());
options.recursive = true;
}
let paths = collect_paths(
&options.paths,
options.recursive,
&options.exclude,
example_canonical.as_deref(),
)?;
let mut total = 0usize;
let mut had_error = false;
let mut sarif_results = Vec::new();
let mut printed = 0usize;
if options.format == Format::Json {
write_stdout("[");
}
for path in paths {
match process_file(&path, &options, schema.as_ref()) {
Ok((source, findings)) => {
total += findings.len();
emit_file_findings(
&path,
&source,
&options,
&findings,
&mut printed,
&mut sarif_results,
);
}
Err(error) => {
eprintln!("{}: {error}", path.display());
had_error = true;
}
}
}
if options.format == Format::Json {
write_stdout_line("]");
} else if options.format == Format::Sarif {
print_sarif(&sarif_results, !had_error);
}
if had_error {
return Ok(finish_output(FAILURE));
}
Ok(finish_output(if total == 0 { SUCCESS } else { FINDINGS }))
}
fn process_file(
path: &Path,
options: &Options,
schema: Option<&Schema>,
) -> Result<(String, Vec<Finding>), String> {
let source = read_file_bounded(path, options.parse_limits.max_input_bytes)?;
let findings = {
let document = parse_strict_bounded(&source, options.dialect, options.parse_limits)?;
lint_with_options(
&document,
options.lint,
schema,
lint_edit_limits(options.parse_limits, options.edit_limits),
)
};
if options.fix
&& findings.iter().any(|finding| {
finding
.fix()
.is_some_and(|fix| fix_enabled(fix, options.fix_missing))
})
{
fix_file(path, source, options, schema)
} else {
Ok((source, findings))
}
}
fn emit_file_findings(
path: &Path,
source: &str,
options: &Options,
findings: &[Finding],
printed: &mut usize,
sarif_results: &mut Vec<SarifResult>,
) {
match options.format {
Format::Json => {
for finding in findings {
if *printed > 0 {
write_stdout(",");
}
print_json(path, finding);
*printed += 1;
}
}
Format::Github => print_github(path, findings),
Format::Sarif => {
collect_sarif_results(path, source, options.dialect, findings, sarif_results);
}
_ => print_human(path, findings),
}
}
const MAX_FIX_ROUNDS: usize = 64;
const TEMP_NAME_BYTES: usize = 160;
static NEXT_TEMP: AtomicUsize = AtomicUsize::new(0);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FileIdentity {
len: u64,
modified: Option<std::time::SystemTime>,
#[cfg(unix)]
dev: u64,
#[cfg(unix)]
ino: u64,
}
fn file_identity_from_metadata(metadata: &fs::Metadata) -> FileIdentity {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
FileIdentity {
len: metadata.len(),
modified: metadata.modified().ok(),
dev: metadata.dev(),
ino: metadata.ino(),
}
}
#[cfg(not(unix))]
{
FileIdentity {
len: metadata.len(),
modified: metadata.modified().ok(),
}
}
}
fn file_identity(path: &Path) -> io::Result<FileIdentity> {
Ok(file_identity_from_metadata(&fs::metadata(path)?))
}
fn resolve_schema(options: &Options) -> Result<(Option<Schema>, Option<PathBuf>), String> {
let Some(schema_cfg) = &options.schema else {
return Ok((None, None));
};
if schema_cfg.allow_unknown == Some(false)
&& options.lint.unknown_keys
&& schema_cfg.example.is_none()
&& schema_cfg.keys.is_empty()
{
return Err(
"allow_unknown = false (--no-unknown-keys) requires --example or a [schema] configuration with keys"
.to_owned(),
);
}
let (example_source, example_canonical) = if let Some(example_path) = &schema_cfg.example {
let source = read_file_bounded(example_path, options.parse_limits.max_input_bytes)
.map_err(|error| format!("{}: {error}", example_path.display()))?;
let canonical = fs::canonicalize(example_path).ok();
(Some((example_path, source)), canonical)
} else {
(None, None)
};
let example_doc = if let Some((example_path, source)) = &example_source {
let document = parse_strict_bounded(source, options.dialect, options.parse_limits)
.map_err(|error| format!("{}: {error}", example_path.display()))?;
Some(document)
} else {
None
};
Ok((
Some(schema_cfg.resolve(example_doc.as_ref())),
example_canonical,
))
}
fn lint_edit_limits(parse_limits: ParseOptions, edit_limits: EditOptions) -> EditOptions {
let mut limits = EditOptions::new().with_parse_limits(parse_limits);
if let Some(max_references) = edit_limits.max_references {
limits = limits.with_max_references(max_references);
}
limits
}
fn fix_enabled(fix: &Fix, fix_missing: bool) -> bool {
fix_missing || !matches!(fix, Fix::InsertEmpty { .. })
}
fn fix_file(
path: &Path,
mut source: String,
options: &Options,
schema: Option<&Schema>,
) -> Result<(String, Vec<Finding>), String> {
let target = fs::canonicalize(path).map_err(|error| error.to_string())?;
let identity = file_identity(&target).map_err(|error| error.to_string())?;
let current = read_file_bounded(&target, options.parse_limits.max_input_bytes)?;
if current != source {
return Err("file changed after it was read".to_owned());
}
let original = source.clone();
let probe_limits = lint_edit_limits(options.parse_limits, options.edit_limits);
let batch_options = BatchOptions::new()
.with_edit_options(options.edit_limits)
.with_insert_missing(options.fix_missing);
for _ in 0..MAX_FIX_ROUNDS {
let document = parse_strict_bounded(&source, options.dialect, options.parse_limits)
.map_err(|error| format!("cannot parse after fix: {error}"))?;
let findings = lint_with_options(&document, options.lint, schema, probe_limits);
let fixes: Vec<Fix> = findings
.iter()
.filter_map(|finding| {
finding
.fix()
.filter(|fix| fix_enabled(fix, options.fix_missing))
.cloned()
})
.collect();
if fixes.is_empty() {
if source != original {
write_fixed(&target, &source, identity)?;
}
return Ok((source, findings));
}
let batch = apply_batch_with_policy(&document, &fixes, batch_options)
.map_err(|error| error.to_string())?;
if batch.output() == source {
if source != original {
write_fixed(&target, &source, identity)?;
}
return Ok((source, findings));
}
source.clear();
source.push_str(batch.output());
}
Err("fixes did not converge".to_owned())
}
fn write_fixed(path: &Path, source: &str, expected: FileIdentity) -> Result<(), String> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty());
let parent = parent.unwrap_or_else(|| Path::new("."));
let name = path
.file_name()
.ok_or_else(|| "target has no file name".to_owned())?
.to_string_lossy();
let mut stem_end = name.len().min(TEMP_NAME_BYTES);
while !name.is_char_boundary(stem_end) {
stem_end -= 1;
}
let name = &name[..stem_end];
let mut temporary = None;
for _ in 0..16 {
let candidate = parent.join(format!(
".adotenv-lint-{}-{}-{name}",
std::process::id(),
NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
));
let mut open = fs::OpenOptions::new();
open.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
open.mode(0o600);
}
match open.open(&candidate) {
Ok(mut file) => {
if let Err(error) = file
.write_all(source.as_bytes())
.and_then(|()| file.sync_all())
{
let _ = fs::remove_file(&candidate);
return Err(error.to_string());
}
temporary = Some(candidate);
break;
}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error.to_string()),
}
}
let temporary = temporary.ok_or_else(|| "could not create a temporary file".to_owned())?;
let result = (|| {
let symlink_meta = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
if symlink_meta.file_type().is_symlink() || !symlink_meta.is_file() {
return Err("file changed after it was read".to_owned());
}
if file_identity_from_metadata(&symlink_meta) != expected {
return Err("file changed after it was read".to_owned());
}
fs::set_permissions(&temporary, symlink_meta.permissions())
.map_err(|error| error.to_string())?;
replace_file(&temporary, path)
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result
}
#[cfg(unix)]
fn replace_file(temporary: &Path, target: &Path) -> Result<(), String> {
fs::rename(temporary, target).map_err(|error| error.to_string())?;
if let Some(parent) = target.parent() {
if let Ok(directory) = fs::File::open(parent) {
let _ = directory.sync_all();
}
}
Ok(())
}
#[cfg(not(unix))]
fn replace_file(temporary: &Path, target: &Path) -> Result<(), String> {
match fs::rename(temporary, target) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
let backup = target.with_file_name(format!(
".adotenv-backup-{}-{}",
std::process::id(),
NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
));
fs::rename(target, &backup).map_err(|error| error.to_string())?;
match fs::rename(temporary, target) {
Ok(()) => {
let _ = fs::remove_file(&backup);
Ok(())
}
Err(replace_error) => {
let restore = fs::rename(&backup, target);
match restore {
Ok(()) => Err(replace_error.to_string()),
Err(restore_error) => Err(format!(
"replacement failed: {replace_error}; restoring the original failed: {restore_error}; backup left at {}",
backup.display()
)),
}
}
}
}
Err(error) => Err(error.to_string()),
}
}
const MAX_CONFIG_BYTES: usize = 4 * 1024 * 1024;
fn apply_config(options: &mut Options) -> Result<(), String> {
let start = env::current_dir().map_err(|error| error.to_string())?;
let config = if let Some(limit) = options
.parse_limits
.max_input_bytes
.filter(|limit| *limit < MAX_CONFIG_BYTES)
{
let path = match options.config.as_deref() {
Some(path) => Some(PathBuf::from(path)),
None => discover_config(&start),
};
match path {
Some(path) => {
let source = read_file_bounded(&path, Some(limit))
.map_err(|error| format!("{}: {error}", path.display()))?;
Some(LintConfig::from_toml(&source, &path).map_err(|error| error.to_string())?)
}
None => None,
}
} else {
load_effective_config(options.config.as_deref().map(Path::new), &start)
.map_err(|error| error.to_string())?
};
let Some(config) = config else {
return Ok(());
};
let explicit = ConfigExplicit {
dialect: options.explicit.dialect,
format: options.explicit.format,
recursive: options.explicit.recursive,
key_order: options.explicit.key_order,
key_case: options.explicit.key_case,
quote_style: options.explicit.quote_style,
equals_spacing: options.explicit.equals_spacing,
trim_trailing_whitespace: options.explicit.trim_trailing_whitespace,
ignore: options.explicit.exclude,
schema_example: options.explicit.schema_example,
schema_allow_unknown: options.explicit.schema_allow_unknown,
schema_allow_empty: options.explicit.schema_allow_empty,
};
let mut policy = LintPolicy {
dialect: options.dialect,
format: options.format,
recursive: options.recursive,
lint: options.lint,
ignore: options.exclude.clone(),
schema: options.schema.clone(),
};
config.apply(&mut policy, explicit);
options.dialect = policy.dialect;
options.format = policy.format;
options.recursive = policy.recursive;
options.lint = policy.lint;
options.exclude = policy.ignore;
options.schema = policy.schema;
Ok(())
}
fn parse_limit(flag: &str, value: &str) -> Result<usize, String> {
if value.starts_with('+') {
return Err(format!("{flag} expects a non-negative integer: {value}"));
}
value
.parse::<usize>()
.map_err(|_| format!("{flag} expects a non-negative integer: {value}"))
}
#[derive(Debug)]
enum CliAction {
Help,
Version,
ListRules,
Explain(Rule),
Run(Box<Options>),
}
#[cfg(test)]
fn parse_args(args: &mut [String]) -> Result<Options, String> {
match parse_cli_args(args)? {
CliAction::Run(options) => Ok(*options),
CliAction::Help => Err("help requested".to_owned()),
CliAction::Version => Err("version requested".to_owned()),
CliAction::ListRules => Err("list-rules requested".to_owned()),
CliAction::Explain(_) => Err("explain requested".to_owned()),
}
}
#[allow(clippy::too_many_lines)]
fn parse_cli_args(args: &[String]) -> Result<CliAction, String> {
let mut options = Options {
dialect: Dialect::PORTABLE,
parse_limits: ParseOptions::new(),
edit_limits: EditOptions::new(),
format: Format::Human,
recursive: false,
fix: false,
fix_missing: false,
lint: LintOptions::default(),
schema: None,
paths: Vec::new(),
config: None,
exclude: Vec::new(),
explicit: Explicit::default(),
};
let mut index = 0;
let mut options_ended = false;
while index < args.len() {
let argument = &args[index];
if options_ended {
options.paths.push(argument.clone());
index += 1;
continue;
}
match argument.as_str() {
"--" => options_ended = true,
"-h" | "--help" => return Ok(CliAction::Help),
"--version" => return Ok(CliAction::Version),
"--list-rules" => return Ok(CliAction::ListRules),
"--explain" => {
index += 1;
let name = value(args, index, "--explain")?;
let rule = Rule::from_name(name).ok_or_else(|| format!("unknown rule: {name}"))?;
return Ok(CliAction::Explain(rule));
}
"--recursive" | "-r" => {
options.recursive = true;
options.explicit.recursive = true;
}
"--fix" => options.fix = true,
"--fix-missing" => options.fix_missing = true,
"--key-order" => {
options.lint = options.lint.with_key_order(true);
options.explicit.key_order = true;
}
"--trim-trailing-whitespace" => {
options.lint = options.lint.with_trim_trailing_whitespace(true);
options.explicit.trim_trailing_whitespace = true;
}
"--no-unknown-keys" => {
options
.schema
.get_or_insert_with(SchemaConfig::default)
.allow_unknown = Some(false);
options.explicit.schema_allow_unknown = true;
}
"--no-empty-values" => {
options
.schema
.get_or_insert_with(SchemaConfig::default)
.allow_empty = Some(false);
options.explicit.schema_allow_empty = true;
}
"--example" => {
index += 1;
let path = value(args, index, "--example")?;
if path.is_empty() {
return Err("--example requires a non-empty path".to_owned());
}
options
.schema
.get_or_insert_with(SchemaConfig::default)
.example = Some(PathBuf::from(path));
options.explicit.schema_example = true;
}
"--config" => {
index += 1;
options.config = Some(value(args, index, "--config")?.to_owned());
}
"--exclude" => {
index += 1;
options
.exclude
.push(value(args, index, "--exclude")?.to_owned());
options.explicit.exclude = true;
}
"--max-input-bytes" => {
index += 1;
let limit = parse_limit(
"--max-input-bytes",
value(args, index, "--max-input-bytes")?,
)?;
options.parse_limits = options.parse_limits.with_max_input_bytes(limit);
}
"--max-lines" => {
index += 1;
let limit = parse_limit("--max-lines", value(args, index, "--max-lines")?)?;
options.parse_limits = options.parse_limits.with_max_lines(limit);
}
"--max-items" => {
index += 1;
let limit = parse_limit("--max-items", value(args, index, "--max-items")?)?;
options.parse_limits = options.parse_limits.with_max_items(limit);
}
"--max-diagnostics" => {
index += 1;
let limit = parse_limit(
"--max-diagnostics",
value(args, index, "--max-diagnostics")?,
)?;
options.parse_limits = options.parse_limits.with_max_diagnostics(limit);
}
"--max-output-bytes" => {
index += 1;
let limit = parse_limit(
"--max-output-bytes",
value(args, index, "--max-output-bytes")?,
)?;
options.edit_limits = options.edit_limits.with_max_output_bytes(limit);
}
"--max-output-lines" => {
index += 1;
let limit = parse_limit(
"--max-output-lines",
value(args, index, "--max-output-lines")?,
)?;
options.edit_limits = options.edit_limits.with_max_output_lines(limit);
}
"--max-references" => {
index += 1;
let limit =
parse_limit("--max-references", value(args, index, "--max-references")?)?;
options.edit_limits = options.edit_limits.with_max_references(limit);
}
"--dialect" => {
index += 1;
options.dialect = parse_dialect(value(args, index, "--dialect")?)?;
options.explicit.dialect = true;
}
"--format" => {
index += 1;
options.format = parse_format(value(args, index, "--format")?)?;
options.explicit.format = true;
}
"--key-case" => {
index += 1;
options.lint =
options
.lint
.with_key_case(parse_key_case(value(args, index, "--key-case")?)?);
options.explicit.key_case = true;
}
"--quote-style" => {
index += 1;
options.lint = options.lint.with_quote_style(parse_quote_style(value(
args,
index,
"--quote-style",
)?)?);
options.explicit.quote_style = true;
}
"--equals-spacing" => {
index += 1;
options.lint = options.lint.with_equals_spacing(parse_spacing(value(
args,
index,
"--equals-spacing",
)?)?);
options.explicit.equals_spacing = true;
}
argument if argument.starts_with("--explain=") => {
let name = &argument["--explain=".len()..];
if name.is_empty() {
return Err("--explain requires a rule name".to_owned());
}
let rule = Rule::from_name(name).ok_or_else(|| format!("unknown rule: {name}"))?;
return Ok(CliAction::Explain(rule));
}
argument if argument.starts_with("--example=") => {
let path = &argument["--example=".len()..];
if path.is_empty() {
return Err("--example requires a non-empty path".to_owned());
}
options
.schema
.get_or_insert_with(SchemaConfig::default)
.example = Some(PathBuf::from(path));
options.explicit.schema_example = true;
}
argument if argument.starts_with("--dialect=") => {
options.dialect = parse_dialect(&argument["--dialect=".len()..])?;
options.explicit.dialect = true;
}
argument if argument.starts_with("--config=") => {
options.config = Some(argument["--config=".len()..].to_owned());
}
argument if argument.starts_with("--exclude=") => {
options
.exclude
.push(argument["--exclude=".len()..].to_owned());
options.explicit.exclude = true;
}
argument if argument.starts_with("--max-input-bytes=") => {
let limit =
parse_limit("--max-input-bytes", &argument["--max-input-bytes=".len()..])?;
options.parse_limits = options.parse_limits.with_max_input_bytes(limit);
}
argument if argument.starts_with("--max-lines=") => {
let limit = parse_limit("--max-lines", &argument["--max-lines=".len()..])?;
options.parse_limits = options.parse_limits.with_max_lines(limit);
}
argument if argument.starts_with("--max-items=") => {
let limit = parse_limit("--max-items", &argument["--max-items=".len()..])?;
options.parse_limits = options.parse_limits.with_max_items(limit);
}
argument if argument.starts_with("--max-diagnostics=") => {
let limit =
parse_limit("--max-diagnostics", &argument["--max-diagnostics=".len()..])?;
options.parse_limits = options.parse_limits.with_max_diagnostics(limit);
}
argument if argument.starts_with("--max-output-bytes=") => {
let limit = parse_limit(
"--max-output-bytes",
&argument["--max-output-bytes=".len()..],
)?;
options.edit_limits = options.edit_limits.with_max_output_bytes(limit);
}
argument if argument.starts_with("--max-output-lines=") => {
let limit = parse_limit(
"--max-output-lines",
&argument["--max-output-lines=".len()..],
)?;
options.edit_limits = options.edit_limits.with_max_output_lines(limit);
}
argument if argument.starts_with("--max-references=") => {
let limit =
parse_limit("--max-references", &argument["--max-references=".len()..])?;
options.edit_limits = options.edit_limits.with_max_references(limit);
}
argument if argument.starts_with("--format=") => {
options.format = parse_format(&argument["--format=".len()..])?;
options.explicit.format = true;
}
argument if argument.starts_with("--key-case=") => {
options.lint = options
.lint
.with_key_case(parse_key_case(&argument["--key-case=".len()..])?);
options.explicit.key_case = true;
}
argument if argument.starts_with("--quote-style=") => {
options.lint = options
.lint
.with_quote_style(parse_quote_style(&argument["--quote-style=".len()..])?);
options.explicit.quote_style = true;
}
argument if argument.starts_with("--equals-spacing=") => {
options.lint = options
.lint
.with_equals_spacing(parse_spacing(&argument["--equals-spacing=".len()..])?);
options.explicit.equals_spacing = true;
}
argument if argument.starts_with('-') => {
return Err(format!("unknown option: {argument}"));
}
path => options.paths.push(path.to_owned()),
}
index += 1;
}
Ok(CliAction::Run(Box::new(options)))
}
fn value<'a>(args: &'a [String], index: usize, option: &str) -> Result<&'a str, String> {
args.get(index)
.map(String::as_str)
.ok_or_else(|| format!("{option} requires a value"))
}
fn trim_trailing_separators(raw: &str) -> PathBuf {
let trimmed = raw.trim_end_matches(|c| c == '/' || (cfg!(windows) && c == '\\'));
if trimmed.is_empty() || (cfg!(windows) && trimmed.len() == 2 && trimmed.as_bytes()[1] == b':')
{
PathBuf::from(raw)
} else {
PathBuf::from(trimmed)
}
}
fn collect_paths(
paths: &[String],
recursive: bool,
exclude_patterns: &[String],
example_canonical: Option<&Path>,
) -> Result<Vec<PathBuf>, String> {
let excludes = IgnoredPaths::new(exclude_patterns)?;
let mut found = BTreeSet::new();
for raw_path in paths {
let probe = trim_trailing_separators(raw_path);
let path = PathBuf::from(raw_path);
let symlink_meta =
fs::symlink_metadata(&probe).map_err(|error| format!("{}: {error}", path.display()))?;
let metadata =
fs::metadata(&path).map_err(|error| format!("{}: {error}", path.display()))?;
if excludes.is_ignored_with_root(&path, &path) {
continue;
}
if metadata.is_file() {
found.insert(path);
} else if metadata.is_dir() {
if symlink_meta.file_type().is_symlink() {
return Err(format!(
"{}: symbolic link directory is not allowed",
path.display()
));
}
if !recursive {
return Err(format!(
"{}: directory requires --recursive",
path.display()
));
}
walk(&path, &path, &excludes, example_canonical, &mut found)?;
} else {
return Err(format!(
"{}: not a regular file or directory",
path.display()
));
}
}
let mut seen_canonical = BTreeSet::new();
let mut unique = Vec::with_capacity(found.len());
for path in found {
let key = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
if seen_canonical.insert(key) {
unique.push(path);
}
}
Ok(unique)
}
fn walk(
directory: &Path,
root: &Path,
excludes: &IgnoredPaths,
example_canonical: Option<&Path>,
found: &mut BTreeSet<PathBuf>,
) -> Result<(), String> {
let entries =
fs::read_dir(directory).map_err(|error| format!("{}: {error}", directory.display()))?;
let mut entries = entries
.collect::<Result<Vec<_>, _>>()
.map_err(|error| format!("{}: {error}", directory.display()))?;
entries.sort_by_key(std::fs::DirEntry::file_name);
for entry in entries {
let path = entry.path();
if excludes.is_ignored_with_root(&path, root) {
continue;
}
let file_type = entry
.file_type()
.map_err(|error| format!("{}: {error}", path.display()))?;
if file_type.is_symlink() {
continue;
}
if file_type.is_dir() {
let name = entry.file_name();
if !is_ignored_dir(&name.to_string_lossy()) {
walk(&path, root, excludes, example_canonical, found)?;
}
} else if file_type.is_file() && is_env_file(&entry.file_name().to_string_lossy()) {
if example_canonical
.is_some_and(|example| fs::canonicalize(&path).is_ok_and(|canon| canon == example))
{
continue;
}
found.insert(path);
}
}
Ok(())
}
#[cfg(windows)]
fn is_env_file(name: &str) -> bool {
let name = name.to_ascii_lowercase();
name == ".env" || name.starts_with(".env.")
}
#[cfg(not(windows))]
fn is_env_file(name: &str) -> bool {
name == ".env" || name.starts_with(".env.")
}
#[cfg(windows)]
fn is_ignored_dir(name: &str) -> bool {
[".git", "target", "node_modules"]
.iter()
.any(|ignored| name.eq_ignore_ascii_case(ignored))
}
#[cfg(not(windows))]
fn is_ignored_dir(name: &str) -> bool {
matches!(name, ".git" | "target" | "node_modules")
}
fn is_unsafe_key_char(character: char) -> bool {
character.is_control()
|| matches!(
character,
'\u{2028}'
| '\u{2029}'
| '\u{202a}'..='\u{202e}'
| '\u{2066}'..='\u{2069}'
| '\u{200e}'
| '\u{200f}'
| '\u{061c}'
)
}
fn escape_human_key(key: &str) -> Cow<'_, str> {
if !key.chars().any(is_unsafe_key_char) {
return Cow::Borrowed(key);
}
let mut escaped = String::with_capacity(key.len());
for character in key.chars() {
if is_unsafe_key_char(character) {
for part in character.escape_default() {
escaped.push(part);
}
} else {
escaped.push(character);
}
}
Cow::Owned(escaped)
}
fn format_finding_text(finding: &Finding) -> String {
let mut text = finding.message().to_owned();
if let Some(detail) = finding.detail() {
let _ = write!(text, ": {}", escape_human_key(detail));
}
if let Some(key) = finding.key() {
let _ = write!(text, " [{}]", escape_human_key(key));
}
text
}
fn print_rule_list() {
for &rule in Rule::ALL {
let info = rule.explain();
write_stdout_line(&format!("{:<16} {}", info.id, info.summary));
}
}
fn print_rule_explanation(rule: Rule) {
let info = rule.explain();
write_stdout_line(&format!("Rule: {}", info.id));
write_stdout_line(&format!("Summary: {}", info.summary));
write_stdout_line(&format!("Default: {}", info.default_behavior));
write_stdout_line(&format!("Autofix: {}", info.autofix));
write_stdout_line(&format!("Config: {}", info.config));
write_stdout_line(&format!("Rationale: {}", info.rationale));
}
fn print_human(path: &Path, findings: &[Finding]) {
for finding in findings {
write_stdout_line(&format!(
"{}:{}: {}[{}]: {}",
path.display(),
finding.line(),
severity_name(finding.severity()),
finding.rule().as_str(),
format_finding_text(finding)
));
}
}
fn print_github(path: &Path, findings: &[Finding]) {
for finding in findings {
let message = format_finding_text(finding);
write_stdout_line(&format!(
"::{} file={},line={},title={}::{}",
github_level(finding.severity()),
github_property(&path.display().to_string()),
finding.line(),
github_property(finding.rule().as_str()),
github_message(&message)
));
}
}
fn github_level(severity: Severity) -> &'static str {
match severity {
Severity::Error => "error",
Severity::Warning => "warning",
_ => "notice",
}
}
fn print_json(path: &Path, finding: &Finding) {
let detail_field = finding.detail().map_or_else(String::new, |detail| {
format!(",\"detail\":{}", json_string(detail))
});
write_stdout(&format!(
"{{\"path\":{},\"line\":{},\"rule\":{},\"severity\":{},\"message\":{}{detail_field},\"key\":{},\"span\":{{\"start\":{},\"end\":{}}}}}",
json_string(&path.display().to_string()),
finding.line(),
json_string(finding.rule().as_str()),
json_string(severity_name(finding.severity())),
json_string(finding.message()),
finding
.key()
.map_or_else(|| "null".to_owned(), json_string),
finding.span().start,
finding.span().end,
));
}
struct SarifResult {
rule_id: &'static str,
rule_index: usize,
level: &'static str,
message: String,
uri: String,
start_line: usize,
start_column: usize,
end_line: Option<usize>,
end_column: Option<usize>,
byte_offset: usize,
byte_length: usize,
}
fn sarif_level(severity: Severity) -> &'static str {
match severity {
Severity::Error => "error",
Severity::Warning => "warning",
_ => "note",
}
}
fn percent_encode_uri_path(input: &str, preserve_drive_colon: bool) -> String {
let mut encoded = String::with_capacity(input.len());
for (idx, byte) in input.bytes().enumerate() {
let allow_colon = preserve_drive_colon && byte == b':' && idx == 1;
if byte.is_ascii_alphanumeric()
|| matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/')
|| allow_colon
{
encoded.push(char::from(byte));
} else {
let _ = write!(encoded, "%{byte:02X}");
}
}
encoded
}
fn sarif_uri_str(raw: &str, windows_paths: bool) -> String {
if windows_paths {
let normalized = raw.replace('\\', "/");
let device_body = normalized
.strip_prefix("//?/")
.or_else(|| normalized.strip_prefix("//./"));
let unc = device_body
.and_then(|after| {
after
.get(..4)
.filter(|prefix| prefix.eq_ignore_ascii_case("unc/"))
.map(|_| &after[4..])
})
.or_else(|| {
if device_body.is_none() {
normalized.strip_prefix("//")
} else {
None
}
});
if let Some((host, rest)) = unc.and_then(|path| path.split_once('/')) {
if !host.is_empty() {
return format!(
"file://{}/{}",
percent_encode_uri_path(host, false),
percent_encode_uri_path(rest, false)
);
}
}
let body = device_body.unwrap_or(&normalized);
let is_drive = body.len() >= 3
&& body.as_bytes()[0].is_ascii_alphabetic()
&& body.as_bytes()[1] == b':'
&& body.as_bytes()[2] == b'/';
if is_drive {
return format!("file:///{}", percent_encode_uri_path(body, true));
}
if body.starts_with('/') {
let trimmed = body.trim_start_matches('/');
return format!("file:///{}", percent_encode_uri_path(trimmed, false));
}
let mut relative = body;
while let Some(rest) = relative.strip_prefix("./") {
relative = rest.trim_start_matches('/');
}
return percent_encode_uri_path(relative, false);
}
if raw.starts_with('/') {
let trimmed = raw.trim_start_matches('/');
return format!("file:///{}", percent_encode_uri_path(trimmed, false));
}
let mut relative = raw;
while let Some(rest) = relative.strip_prefix("./") {
relative = rest.trim_start_matches('/');
}
percent_encode_uri_path(relative, false)
}
fn sarif_uri(path: &Path) -> String {
sarif_uri_str(&path.to_string_lossy(), cfg!(windows))
}
fn trim_trailing_line_break(source: &str, start: usize, end: usize, dialect: Dialect) -> usize {
if end <= start || end > source.len() {
return end;
}
let slice = &source[start..end];
if slice.ends_with("\r\n") {
end - 2
} else if slice.ends_with('\n')
|| (slice.ends_with('\r') && (dialect.line_breaks != LineBreaks::Lf || end == source.len()))
{
end - 1
} else {
end
}
}
fn collect_sarif_results(
path: &Path,
source: &str,
dialect: Dialect,
findings: &[Finding],
out: &mut Vec<SarifResult>,
) {
if findings.is_empty() {
return;
}
let lines = LineIndex::new(source).with_bom_policy(dialect.bom);
let uri = sarif_uri(path);
for finding in findings {
let span = finding.span();
let start_pos = lines.to_position(span.start, ColumnEncoding::Scalar).ok();
let start_line = start_pos.map_or_else(|| finding.line().max(1), |pos| pos.line + 1);
let start_column = start_pos.map_or(1, |pos| pos.column + 1);
let effective_end = trim_trailing_line_break(source, span.start, span.end, dialect);
let end_pos = if effective_end == span.start {
start_pos
} else {
lines
.to_position(effective_end, ColumnEncoding::Scalar)
.ok()
};
let (end_line, end_column) = end_pos.map_or((None, None), |pos| {
(Some(pos.line + 1), Some(pos.column + 1))
});
let rule_index = Rule::ALL
.iter()
.position(|rule| *rule == finding.rule())
.unwrap_or(0);
out.push(SarifResult {
rule_id: finding.rule().as_str(),
rule_index,
level: sarif_level(finding.severity()),
message: format_finding_text(finding),
uri: uri.clone(),
start_line,
start_column,
end_line,
end_column,
byte_offset: span.start,
byte_length: effective_end.saturating_sub(span.start),
});
}
}
fn render_sarif(results: &[SarifResult], execution_successful: bool) -> String {
let mut out = String::new();
out.push_str(
"{\"$schema\":\"https://json.schemastore.org/sarif-2.1.0.json\",\"version\":\"2.1.0\",\"runs\":[{\"columnKind\":\"unicodeCodePoints\",\"tool\":{\"driver\":{\"name\":\"adotenv-lint\",\"version\":",
);
out.push_str(&json_string(env!("CARGO_PKG_VERSION")));
out.push_str(",\"informationUri\":\"https://zeropier.com/adotenv/\",\"rules\":[");
for (idx, &rule) in Rule::ALL.iter().enumerate() {
if idx > 0 {
out.push(',');
}
let info = rule.explain();
let _ = write!(
out,
"{{\"id\":{},\"shortDescription\":{{\"text\":{}}},\"fullDescription\":{{\"text\":{}}},\"defaultConfiguration\":{{\"level\":\"warning\"}},\"helpUri\":\"https://docs.rs/adotenv-lint\"}}",
json_string(info.id),
json_string(info.summary),
json_string(info.rationale),
);
}
let _ = write!(
out,
"]}}}},\"invocations\":[{{\"executionSuccessful\":{execution_successful}}}],\"results\":[",
);
for (idx, item) in results.iter().enumerate() {
if idx > 0 {
out.push(',');
}
let end_fields = match (item.end_line, item.end_column) {
(Some(end_line), Some(end_col)) => {
format!(",\"endLine\":{end_line},\"endColumn\":{end_col}")
}
_ => String::new(),
};
let _ = write!(
out,
"{{\"ruleId\":{},\"ruleIndex\":{},\"level\":{},\"message\":{{\"text\":{}}},\"locations\":[{{\"physicalLocation\":{{\"artifactLocation\":{{\"uri\":{}}},\"region\":{{\"startLine\":{},\"startColumn\":{}{end_fields},\"byteOffset\":{},\"byteLength\":{}}}}}}}]}}",
json_string(item.rule_id),
item.rule_index,
json_string(item.level),
json_string(&item.message),
json_string(&item.uri),
item.start_line,
item.start_column,
item.byte_offset,
item.byte_length,
);
}
out.push_str("]}]}");
out
}
fn print_sarif(results: &[SarifResult], execution_successful: bool) {
write_stdout_line(&render_sarif(results, execution_successful));
}
fn severity_name(severity: Severity) -> &'static str {
match severity {
Severity::Error => "error",
Severity::Warning => "warning",
_ => "info",
}
}
fn github_property(value: &str) -> String {
value
.replace('%', "%25")
.replace('\r', "%0D")
.replace('\n', "%0A")
.replace(':', "%3A")
.replace(',', "%2C")
}
fn github_message(value: &str) -> String {
value
.replace('%', "%25")
.replace('\r', "%0D")
.replace('\n', "%0A")
}
fn json_string(value: &str) -> String {
let mut output = String::with_capacity(value.len() + 2);
output.push('"');
for character in value.chars() {
match character {
'"' => output.push_str("\\\""),
'\\' => output.push_str("\\\\"),
'\n' => output.push_str("\\n"),
'\r' => output.push_str("\\r"),
'\t' => output.push_str("\\t"),
character if character.is_control() => {
let _ = write!(output, "\\u{:04x}", u32::from(character));
}
character => output.push(character),
}
}
output.push('"');
output
}
#[cfg(test)]
mod tests {
use super::*;
use adotenv::{EqualsSpacing, QuoteStyle};
use adotenv_lint::{KeyCase, Rule};
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).to_owned()).collect()
}
#[test]
fn parses_defaults_and_paths() {
let options = parse_args(&mut args(&["a.env", "b.env"])).unwrap();
assert_eq!(options.dialect, Dialect::PORTABLE);
assert_eq!(options.format, Format::Human);
assert!(!options.recursive);
assert_eq!(options.paths, ["a.env", "b.env"]);
}
#[test]
fn parses_rule_options_and_end_of_options() {
let options = parse_args(&mut args(&[
"--dialect=node",
"--format",
"json",
"--key-order",
"--key-case",
"upper",
"--quote-style=single",
"--equals-spacing=none",
"--trim-trailing-whitespace",
"--recursive",
"--",
"--literal-path",
]))
.unwrap();
assert_eq!(options.dialect, Dialect::NODE_DOTENV);
assert_eq!(options.format, Format::Json);
assert!(options.recursive);
assert!(options.lint.key_order);
assert_eq!(options.lint.key_case, KeyCase::Upper);
assert_eq!(options.lint.quote_style, QuoteStyle::Single);
assert_eq!(options.lint.equals_spacing, EqualsSpacing::None);
assert!(options.lint.trim_trailing_whitespace);
assert_eq!(options.paths, ["--literal-path"]);
}
#[test]
fn rejects_unknown_options() {
assert!(parse_args(&mut args(&["--unknown"])).is_err());
assert!(parse_args(&mut args(&["--format", "nope"])).is_err());
assert!(parse_args(&mut args(&["--dialect"])).is_err());
}
#[test]
fn github_output_escapes_command_data() {
assert_eq!(github_property("a,b:c\n%"), "a%2Cb%3Ac%0A%25");
assert_eq!(github_message("a\r\n%"), "a%0D%0A%25");
}
#[test]
fn json_escaping_is_value_safe() {
assert_eq!(
json_string("a\"b\\c\n\r\t\x01"),
"\"a\\\"b\\\\c\\n\\r\\t\\u0001\""
);
}
#[test]
fn parses_space_and_equals_option_forms() {
let options = parse_args(&mut args(&[
"--recursive",
"--fix",
"--max-lines",
"100",
"--dialect",
"python",
"--config=custom.toml",
"--exclude",
"vendor/**",
"--format=github",
"--key-case=lower",
"--quote-style",
"double",
"--equals-spacing",
"spaces",
"app.env",
]))
.unwrap();
assert!(options.recursive);
assert!(options.fix);
assert_eq!(options.dialect, Dialect::PYTHON_DOTENV);
assert_eq!(options.config.as_deref(), Some("custom.toml"));
assert_eq!(options.exclude, ["vendor/**"]);
assert_eq!(options.format, Format::Github);
assert_eq!(options.lint.key_case, KeyCase::Lower);
assert_eq!(options.lint.quote_style, QuoteStyle::Double);
assert_eq!(options.lint.equals_spacing, EqualsSpacing::Spaces);
assert_eq!(options.paths, ["app.env"]);
assert!(is_ignored_dir(".git"));
assert!(is_ignored_dir("target"));
assert!(is_ignored_dir("node_modules"));
assert!(!is_ignored_dir("nested"));
assert_eq!(github_level(Severity::Warning), "warning");
assert_eq!(github_level(Severity::Info), "notice");
assert_eq!(severity_name(Severity::Warning), "warning");
assert_eq!(severity_name(Severity::Info), "info");
}
#[test]
fn env_name_matching_covers_cascades() {
assert!(is_env_file(".env"));
assert!(is_env_file(".env.production"));
assert!(!is_env_file("env"));
assert!(!is_env_file(".environment"));
}
#[test]
fn rule_and_error_messages_are_stable() {
assert_eq!(Rule::DuplicateKey.as_str(), "duplicate-key");
assert_eq!(Rule::KeyOrder.as_str(), "key-order");
}
#[test]
fn output_helpers_do_not_panic() {
let path = Path::new("app.env");
let doc = adotenv::parse_strict("A=1\nA=2\n").unwrap();
let findings = adotenv_lint::lint(&doc, LintOptions::default());
print_human(path, &findings);
print_github(path, &findings);
print_json(path, &findings[0]);
}
#[test]
fn io_error_is_usage_failure() {
assert!(collect_paths(&["definitely-missing.env".to_owned()], false, &[], None).is_err());
}
#[test]
fn read_file_bounded_and_write_fixed_enforce_boundaries() {
struct TempGuard(PathBuf);
impl Drop for TempGuard {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
let dir = TempGuard(env::temp_dir().join(format!(
"adotenv-lint-unit-{}-{}",
std::process::id(),
NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
)));
fs::create_dir_all(&dir.0).unwrap();
let file = dir.0.join(".env");
fs::write(&file, "A=1\n").unwrap();
assert_eq!(read_file_bounded(&file, Some(4)).unwrap(), "A=1\n");
assert_eq!(read_file_bounded(&file, Some(10)).unwrap(), "A=1\n");
assert!(read_file_bounded(&file, Some(2))
.unwrap_err()
.contains("max_input_bytes"));
let expected = file_identity(&file).unwrap();
let sub = dir.0.join("subdir");
fs::create_dir(&sub).unwrap();
assert!(write_fixed(&sub, "A=2\n", expected)
.unwrap_err()
.contains("changed after it was read"));
}
#[test]
fn trim_trailing_separators_preserves_root() {
assert_eq!(trim_trailing_separators(""), PathBuf::from(""));
assert_eq!(trim_trailing_separators("/"), PathBuf::from("/"));
assert_eq!(
trim_trailing_separators("/tmp/a///"),
PathBuf::from("/tmp/a")
);
#[cfg(windows)]
{
assert_eq!(trim_trailing_separators("C:\\"), PathBuf::from("C:\\"));
assert_eq!(
trim_trailing_separators("C:\\tmp\\a\\\\\\"),
PathBuf::from("C:\\tmp\\a")
);
}
}
#[test]
fn parses_schema_and_bounded_edit_options_in_both_forms() {
let options = parse_args(&mut args(&[
"--example",
".env.example",
"--no-unknown-keys",
"--no-empty-values",
"--max-items",
"50",
"--max-diagnostics",
"10",
"--max-output-bytes",
"1024",
"--max-output-lines",
"20",
"--max-references",
"8",
"app.env",
]))
.unwrap();
let schema = options.schema.as_ref().unwrap();
assert_eq!(schema.example.as_deref(), Some(Path::new(".env.example")));
assert_eq!(schema.allow_unknown, Some(false));
assert_eq!(schema.allow_empty, Some(false));
assert_eq!(options.parse_limits.max_items, Some(50));
assert_eq!(options.parse_limits.max_diagnostics, Some(10));
assert_eq!(options.edit_limits.max_output_bytes, Some(1024));
assert_eq!(options.edit_limits.max_output_lines, Some(20));
assert_eq!(options.edit_limits.max_references, Some(8));
let eq_form = parse_args(&mut args(&[
"--example=other.example",
"--max-items=40",
"--max-diagnostics=5",
"--max-output-bytes=512",
"--max-output-lines=12",
"--max-references=4",
"app.env",
]))
.unwrap();
assert_eq!(
eq_form.schema.as_ref().unwrap().example.as_deref(),
Some(Path::new("other.example"))
);
assert_eq!(eq_form.parse_limits.max_items, Some(40));
assert_eq!(eq_form.parse_limits.max_diagnostics, Some(5));
assert_eq!(eq_form.edit_limits.max_output_bytes, Some(512));
assert_eq!(eq_form.edit_limits.max_output_lines, Some(12));
assert_eq!(eq_form.edit_limits.max_references, Some(4));
assert!(parse_args(&mut args(&["--example="])).is_err());
assert!(parse_args(&mut args(&["--example", ""])).is_err());
assert!(parse_args(&mut args(&["--example"])).is_err());
assert!(parse_args(&mut args(&["--max-items=+5"])).is_err());
assert!(parse_args(&mut args(&["--max-output-bytes=abc"])).is_err());
assert!(parse_args(&mut args(&["--max-references"])).is_err());
assert!(matches!(
escape_human_key("PLAIN_é"),
Cow::Borrowed("PLAIN_é")
));
assert_eq!(
escape_human_key("A\nB\u{2028}C\u{2029}D\u{202e}E\u{2066}F\u{200e}G\u{200f}H\u{061c}"),
"A\\nB\\u{2028}C\\u{2029}D\\u{202e}E\\u{2066}F\\u{200e}G\\u{200f}H\\u{61c}"
);
}
#[test]
fn parses_v04_flags_and_formats_sarif_helpers() {
assert!(matches!(
parse_cli_args(&args(&["--list-rules"])).unwrap(),
CliAction::ListRules
));
assert!(matches!(
parse_cli_args(&args(&["--explain", "missing-key"])).unwrap(),
CliAction::Explain(Rule::MissingKey)
));
assert!(matches!(
parse_cli_args(&args(&["--explain=deprecated-key"])).unwrap(),
CliAction::Explain(Rule::DeprecatedKey)
));
assert!(parse_cli_args(&args(&["--explain"])).is_err());
assert!(parse_cli_args(&args(&["--explain="])).is_err());
assert!(parse_cli_args(&args(&["--explain", "bogus"])).is_err());
assert!(parse_cli_args(&args(&["--explain=bogus"])).is_err());
let opts = parse_args(&mut args(&[
"--format=sarif",
"--fix",
"--fix-missing",
"app.env",
]))
.unwrap();
assert_eq!(opts.format, Format::Sarif);
assert!(opts.fix);
assert!(opts.fix_missing);
assert_eq!(sarif_level(Severity::Error), "error");
assert_eq!(sarif_level(Severity::Warning), "warning");
assert_eq!(sarif_level(Severity::Info), "note");
assert_eq!(sarif_uri_str("./sub/a b.env", false), "sub/a%20b.env");
assert_eq!(sarif_uri_str("././.env", false), ".env");
assert_eq!(sarif_uri_str("env:prod", false), "env%3Aprod");
assert_eq!(sarif_uri_str("./C:/dir/.env", false), "C%3A/dir/.env");
assert_eq!(sarif_uri_str("a\\b.env", false), "a%5Cb.env");
assert_eq!(sarif_uri_str("café.env", false), "caf%C3%A9.env");
assert_eq!(
sarif_uri_str("/home/user/a b/.env", false),
"file:///home/user/a%20b/.env"
);
assert_eq!(sarif_uri_str("//etc/.env", false), "file:///etc/.env");
assert_eq!(sarif_uri_str(".\\sub\\a b.env", true), "sub/a%20b.env");
assert_eq!(sarif_uri_str("foo\\bar.env", true), "foo/bar.env");
assert_eq!(sarif_uri_str("C:rel.env", true), "C%3Arel.env");
assert_eq!(
sarif_uri_str("C:\\dir\\a b.env", true),
"file:///C:/dir/a%20b.env"
);
assert_eq!(
sarif_uri_str("\\\\?\\C:\\dir\\a b.env", true),
"file:///C:/dir/a%20b.env"
);
assert_eq!(
sarif_uri_str("\\\\server\\share\\a b.env", true),
"file://server/share/a%20b.env"
);
assert_eq!(
sarif_uri_str("\\\\?\\UNC\\server\\share\\a b.env", true),
"file://server/share/a%20b.env"
);
assert_eq!(sarif_uri_str("\\rooted\\.env", true), "file:///rooted/.env");
assert_eq!(
trim_trailing_line_break("B=2\nA=1\n", 0, 8, Dialect::PORTABLE),
7
);
assert_eq!(
trim_trailing_line_break("B=2\r\nA=1\r\n", 0, 10, Dialect::PORTABLE),
8
);
assert_eq!(
trim_trailing_line_break("A=1\r", 0, 4, Dialect::PORTABLE),
3
);
assert_eq!(
trim_trailing_line_break("A=1\r\n", 2, 4, Dialect::DOCKER_RAW),
4
);
assert_eq!(
trim_trailing_line_break("A=1\n", 0, 4, Dialect::DOCKER_RAW),
3
);
assert_eq!(
trim_trailing_line_break("A=1\n", 2, 2, Dialect::PORTABLE),
2
);
assert_eq!(
trim_trailing_line_break("A=1\n", 0, 99, Dialect::PORTABLE),
99
);
let insert_fix = Fix::InsertEmpty {
key: "A".to_owned(),
};
assert!(!fix_enabled(&insert_fix, false));
assert!(fix_enabled(&insert_fix, true));
assert!(fix_enabled(&Fix::Sort, false));
}
#[test]
fn sarif_uri_and_line_break_trimming_handle_edge_cases() {
assert_eq!(sarif_uri_str(".//.env", false), ".env");
assert_eq!(sarif_uri_str(".///sub/.env", false), "sub/.env");
assert_eq!(sarif_uri_str(".//./.env", false), ".env");
assert_eq!(sarif_uri_str(".\\\\.env", true), ".env");
assert_eq!(
sarif_uri_str("\\\\.\\C:\\dir\\a b.env", true),
"file:///C:/dir/a%20b.env"
);
assert_eq!(
sarif_uri_str("\\\\?\\Unc\\server\\share\\a b.env", true),
"file://server/share/a%20b.env"
);
assert_eq!(
sarif_uri_str("\\\\.\\uNc\\server\\share\\a b.env", true),
"file://server/share/a%20b.env"
);
assert_eq!(sarif_uri_str("\\\\?\\é\\a.env", true), "%C3%A9/a.env");
assert_eq!(
trim_trailing_line_break("B=2\r\nA=1\r\n", 0, 10, Dialect::COMPOSE),
8
);
assert_eq!(
trim_trailing_line_break("B=2\nA=1\r", 0, 8, Dialect::DOCKER_RAW),
7
);
assert_eq!(
trim_trailing_line_break("A=1\rB=2\n", 0, 4, Dialect::PORTABLE),
3
);
}
}