use std::{
fs,
path::{Path, PathBuf},
process::{Command, Output},
sync::atomic::{AtomicU64, Ordering},
};
static NEXT: AtomicU64 = AtomicU64::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"adotenv-lint-cli-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&path).unwrap();
Self(path)
}
fn file(&self, name: &str, source: &str) -> PathBuf {
let path = self.0.join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(&path, source).unwrap();
path
}
fn file_at(&self, relative: &str, source: &str) -> PathBuf {
let path = self.0.join(relative);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(&path, source).unwrap();
path
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn run(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
.args(args)
.output()
.unwrap()
}
fn run_in(directory: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
.current_dir(directory)
.args(args)
.output()
.unwrap()
}
#[test]
fn reports_findings_and_exit_code_one() {
let dir = TempDir::new();
let file = dir.file("app.env", "A=1\nA=2\n");
let output = run(&[file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.contains("duplicate-key"), "{text}");
assert!(text.contains('A'), "{text}");
}
#[test]
fn clean_file_exits_zero() {
let dir = TempDir::new();
let file = dir.file("app.env", "A=1\nB=2\n");
let output = run(&[file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(0));
assert_eq!(output.stdout.len(), 0);
}
#[test]
fn key_order_and_json_output_work() {
let dir = TempDir::new();
let file = dir.file("app.env", "B=2\nA=1\n");
let output = run(&["--format=json", "--key-order", file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.starts_with('['), "{text}");
assert!(text.contains("\"rule\":\"key-order\""), "{text}");
assert!(text.contains("\"path\":"), "{text}");
}
#[test]
fn recursive_discovery_finds_env_cascades() {
let dir = TempDir::new();
dir.file("nested/.env", "A=1\n");
dir.file("nested/.env.production", "B=2\n");
dir.file("nested/ignored.txt", "A=1\nA=2\n");
let output = run(&["--recursive", dir.path().to_str().unwrap()]);
assert_eq!(output.status.code(), Some(0));
}
#[test]
fn parse_and_usage_failures_exit_two() {
let dir = TempDir::new();
let bad = dir.file("bad.env", "BAD KEY=value\n");
let output = run(&[bad.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(2));
let output = run(&["--unknown"]);
assert_eq!(output.status.code(), Some(2));
}
#[test]
fn double_dash_allows_a_dash_prefixed_path() {
let dir = TempDir::new();
let file = dir.file("--dash.env", "A=1\nA=2\n");
let output = run(&["--", file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1));
}
#[test]
fn fix_applies_verified_key_order_and_exits_zero() {
let dir = TempDir::new();
let file = dir.file("app.env", "B=2\nA=1\n");
let output = run(&["--fix", "--key-order", file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(0));
assert_eq!(fs::read_to_string(&file).unwrap(), "A=1\nB=2\n");
}
#[test]
fn fix_reports_unfixable_findings_without_rewriting() {
let dir = TempDir::new();
let file = dir.file("app.env", "A=1\nA=2\n");
let output = run(&["--fix", file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1));
assert_eq!(fs::read_to_string(&file).unwrap(), "A=1\nA=2\n");
}
#[test]
fn fix_applies_quote_style() {
let dir = TempDir::new();
let file = dir.file("app.env", "A='one'\nC='two'\n");
let output = run(&["--fix", "--quote-style=double", file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(0));
assert_eq!(fs::read_to_string(&file).unwrap(), "A=\"one\"\nC=\"two\"\n");
}
#[test]
fn config_controls_rules_and_cli_overrides_format() {
let dir = TempDir::new();
let config = dir.file(
".adotenv-lint.toml",
"key_order = true\nformat = \"json\"\n",
);
let file = dir.file("app.env", "B=2\nA=1\n");
let output = run(&["--config", config.to_str().unwrap(), file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.trim_start().starts_with('['), "{text}");
assert!(text.contains("key-order"), "{text}");
let output = run(&[
"--config",
config.to_str().unwrap(),
"--format=human",
file.to_str().unwrap(),
]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(!text.trim_start().starts_with('['), "{text}");
assert!(text.contains("key-order"), "{text}");
}
#[test]
fn default_config_is_read_from_the_working_directory() {
let dir = TempDir::new();
dir.file(".adotenv-lint.toml", "key_order = true\n");
dir.file("app.env", "B=2\nA=1\n");
let output = run_in(dir.path(), &["app.env"]);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8(output.stdout)
.unwrap()
.contains("key-order"));
}
#[test]
fn invalid_config_is_a_usage_failure() {
let dir = TempDir::new();
let config = dir.file(".adotenv-lint.toml", "unknown = true\n");
let file = dir.file("app.env", "A=1\n");
let output = run(&["--config", config.to_str().unwrap(), file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(2));
assert!(String::from_utf8(output.stderr)
.unwrap()
.contains("unknown field"));
}
#[cfg(windows)]
#[test]
fn recursive_discovery_is_case_insensitive_on_windows() {
let dir = TempDir::new();
dir.file(".ENV", "A=1\nA=2\n");
dir.file(".ENV.production", "B=2\nB=3\n");
dir.file_at(".GIT/ignored.env", "C=1\nC=2\n");
let output = run(&["--recursive", dir.path().to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.contains(".ENV"), "{text}");
assert!(text.contains(".ENV.production"), "{text}");
assert!(!text.contains("ignored.env"), "{text}");
}
#[test]
fn fix_batches_multiple_key_case_renames() {
let dir = TempDir::new();
let file = dir.file("app.env", "a=1\nb=2\n");
let output = run(&["--fix", "--key-case=upper", file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(0));
assert_eq!(fs::read_to_string(&file).unwrap(), "A=1\nB=2\n");
}
#[test]
fn rule_severity_and_ignore_patterns_are_honored() {
let dir = TempDir::new();
dir.file(
".adotenv-lint.toml",
"ignore = [\".env.skip\"]\n[rules]\nduplicate-key = \"error\"\n",
);
dir.file(".env.skip", "A=1\nA=2\n");
dir.file(".env", "B=1\nB=2\n");
let output = run_in(dir.path(), &["--format=json", ".env"]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.contains("\"severity\":\"error\""), "{text}");
let output = run_in(dir.path(), &["--format=github", ".env"]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.starts_with("::error "), "{text}");
let output = run_in(dir.path(), &[".env"]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.contains("error[duplicate-key]"), "{text}");
let output = run_in(dir.path(), &["--recursive", "."]);
assert_eq!(output.status.code(), Some(1));
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.contains(".env"), "{text}");
assert!(!text.contains(".env.skip"), "{text}");
let output = run_in(
dir.path(),
&["--recursive", "--exclude=.env", "--exclude=.env.skip", "."],
);
assert_eq!(output.status.code(), Some(0));
}
#[test]
fn config_is_discovered_from_an_ancestor_directory() {
let dir = TempDir::new();
dir.file(".adotenv-lint.toml", "key_order = true\n");
dir.file_at("nested/app.env", "B=2\nA=1\n");
let nested = dir.path().join("nested");
let output = run_in(&nested, &["app.env"]);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8(output.stdout)
.unwrap()
.contains("key-order"));
}
#[test]
fn fix_batches_renames_sorting_and_quote_style() {
let dir = TempDir::new();
let file = dir.file("app.env", "b='two'\na='one'\n");
let output = run(&[
"--fix",
"--key-case=upper",
"--key-order",
"--quote-style=double",
file.to_str().unwrap(),
]);
assert_eq!(output.status.code(), Some(0));
assert_eq!(fs::read_to_string(&file).unwrap(), "A=\"one\"\nB=\"two\"\n");
}
#[test]
fn exclude_matches_an_explicit_file_by_basename() {
let dir = TempDir::new();
let file = dir.file("app.env", "A=1\nA=2\n");
let output = run(&["--exclude=app.env", file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(0));
assert_eq!(output.stdout.len(), 0);
}
#[test]
fn fix_handles_a_long_target_file_name() {
let dir = TempDir::new();
let name = format!("{}.env", "x".repeat(180));
let file = dir.file(&name, "B=2\nA=1\n");
let output = run(&["--fix", "--key-order", file.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(0));
assert_eq!(fs::read_to_string(&file).unwrap(), "A=1\nB=2\n");
}
#[test]
fn rules_table_can_enable_and_disable_rules() {
let dir = TempDir::new();
dir.file(".adotenv-lint.toml", "[rules]\nkey-order = \"error\"\n");
dir.file(".env", "B=2\nA=1\n");
let output = run_in(dir.path(), &[".env"]);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8(output.stdout)
.unwrap()
.contains("key-order"));
dir.file(".adotenv-lint.toml", "[rules]\nduplicate-key = \"off\"\n");
dir.file(".env", "A=1\nA=2\n");
let output = run_in(dir.path(), &[".env"]);
assert_eq!(output.status.code(), Some(0));
}
#[test]
fn parse_limit_flags_bound_input_bytes_and_lines() {
let dir = TempDir::new();
let file = dir.file("app.env", "A=1\nB=2\nC=3\n");
let too_many_lines = run(&["--max-lines", "2", file.to_str().unwrap()]);
assert_eq!(too_many_lines.status.code(), Some(2));
assert!(String::from_utf8(too_many_lines.stderr)
.unwrap()
.contains("line"));
let too_many_bytes = run(&["--max-input-bytes=6", file.to_str().unwrap()]);
assert_eq!(too_many_bytes.status.code(), Some(2));
assert!(String::from_utf8(too_many_bytes.stderr)
.unwrap()
.contains("limit"));
let within_limits = run(&[
"--max-input-bytes",
"64",
"--max-lines=3",
file.to_str().unwrap(),
]);
assert_eq!(within_limits.status.code(), Some(0));
let bad_val = run(&["--max-lines=abc", file.to_str().unwrap()]);
assert_eq!(bad_val.status.code(), Some(2));
let missing_val = run(&["--max-input-bytes"]);
assert_eq!(missing_val.status.code(), Some(2));
}
#[test]
fn help_version_default_scan_multi_json_and_dir_without_recursive() {
let help = run(&["--help"]);
assert_eq!(help.status.code(), Some(0));
assert!(String::from_utf8(help.stdout)
.unwrap()
.contains("--max-lines"));
let version = run(&["--version"]);
assert_eq!(version.status.code(), Some(0));
assert!(String::from_utf8(version.stdout)
.unwrap()
.starts_with("adotenv-lint "));
let dir = TempDir::new();
let file = dir.file(".env", "A=1\nA=2\nB=3\nB=4\n");
let dir_err = run(&[dir.path().to_str().unwrap()]);
assert_eq!(dir_err.status.code(), Some(2));
assert!(String::from_utf8(dir_err.stderr)
.unwrap()
.contains("--recursive"));
let default_scan = run_in(dir.path(), &["--format=json"]);
assert_eq!(default_scan.status.code(), Some(1));
let json = String::from_utf8(default_scan.stdout).unwrap();
assert!(json.starts_with("[{") && json.trim_end().ends_with("}]"));
assert!(json.contains("},{"));
let walk_dir = TempDir::new();
walk_dir.file_at("nested/.env", "A=1\nA=2\n");
walk_dir.file_at(".git/.env", "X=1\nX=2\n");
walk_dir.file_at("target/.env", "Y=1\nY=2\n");
let walk_out = run(&["--recursive", walk_dir.path().to_str().unwrap()]);
assert_eq!(walk_out.status.code(), Some(1));
let walk_text = String::from_utf8(walk_out.stdout).unwrap();
assert!(walk_text.contains("nested"));
assert!(!walk_text.contains(".git"));
assert!(!walk_text.contains("target"));
let utf8_name = format!("{}é.env", "a".repeat(159));
let utf8_file = dir.file(&utf8_name, "B=2\nA=1\n");
let utf8_fix = run(&["--fix", "--key-order", utf8_file.to_str().unwrap()]);
assert_eq!(utf8_fix.status.code(), Some(0));
assert_eq!(fs::read_to_string(&utf8_file).unwrap(), "A=1\nB=2\n");
let fix_limited = run(&["--fix", "--max-lines=2", file.to_str().unwrap()]);
assert_eq!(fix_limited.status.code(), Some(2));
let bad1 = dir.file("bad1.env", "BAD KEY=1\n");
let bad2 = dir.file("bad2.env", "ALSO BAD=2\n");
let multi = run(&[bad1.to_str().unwrap(), bad2.to_str().unwrap()]);
assert_eq!(multi.status.code(), Some(2));
let multi_err = String::from_utf8(multi.stderr).unwrap();
assert!(multi_err.contains("bad1.env"), "{multi_err}");
assert!(multi_err.contains("bad2.env"), "{multi_err}");
let opt_help = run(&["--config", "--help", file.to_str().unwrap()]);
assert_eq!(opt_help.status.code(), Some(2));
let opt_err = String::from_utf8(opt_help.stderr).unwrap();
assert!(opt_err.contains("--help"), "{opt_err}");
let dedup_dir = TempDir::new();
let target = dedup_dir.file(".env", "A=1\nA=2\n");
let alt = dedup_dir.path().join(".").join(".env");
let dedup = run(&[target.to_str().unwrap(), alt.to_str().unwrap()]);
assert_eq!(dedup.status.code(), Some(1));
let dedup_out = String::from_utf8(dedup.stdout).unwrap();
assert_eq!(dedup_out.lines().count(), 1, "{dedup_out}");
let bytes_lint = run(&["--max-input-bytes=4", file.to_str().unwrap()]);
assert_eq!(bytes_lint.status.code(), Some(2));
assert!(String::from_utf8(bytes_lint.stderr)
.unwrap()
.contains("limit"));
let bytes_fix = run(&["--fix", "--max-input-bytes=4", file.to_str().unwrap()]);
assert_eq!(bytes_fix.status.code(), Some(2));
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let sym_root = TempDir::new();
let outside = TempDir::new();
outside.file(".env", "A=1\nA=2\n");
let link = sym_root.path().join("linked");
symlink(outside.path(), &link).unwrap();
let no_slash = run(&["--recursive", link.to_str().unwrap()]);
assert_eq!(no_slash.status.code(), Some(2));
assert!(String::from_utf8(no_slash.stderr)
.unwrap()
.contains("symbolic link directory"));
let with_slash = run(&["--recursive", &format!("{}/", link.display())]);
assert_eq!(with_slash.status.code(), Some(2));
assert!(String::from_utf8(with_slash.stderr)
.unwrap()
.contains("symbolic link directory"));
}
}
#[cfg(unix)]
#[test]
fn closed_stdout_pipe_and_stdout_write_errors_report_cleanly() {
use std::process::Stdio;
let dir = TempDir::new();
let many = "K=v\n".repeat(10_000);
let big = dir.file("big.env", &many);
let mut child = Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
.arg(&big)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
drop(child.stdout.take());
let pipe_out = child.wait_with_output().unwrap();
assert_eq!(
pipe_out.status.code(),
Some(1),
"{}",
String::from_utf8_lossy(&pipe_out.stderr)
);
assert_eq!(String::from_utf8_lossy(&pipe_out.stderr), "");
#[cfg(target_os = "linux")]
if let Ok(full) = fs::OpenOptions::new().write(true).open("/dev/full") {
let help_out = Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
.arg("--help")
.stdout(full)
.output()
.unwrap();
assert_eq!(help_out.status.code(), Some(2));
let err = String::from_utf8(help_out.stderr).unwrap();
assert!(err.contains("stdout error"), "{err}");
assert_eq!(err.matches("stdout error").count(), 1, "{err}");
let full2 = fs::OpenOptions::new()
.write(true)
.open("/dev/full")
.unwrap();
let small = dir.file("small.env", "A=1\nA=2\n");
let lint_out = Command::new(env!("CARGO_BIN_EXE_adotenv-lint"))
.arg(&small)
.stdout(full2)
.output()
.unwrap();
assert_eq!(lint_out.status.code(), Some(2));
let err2 = String::from_utf8(lint_out.stderr).unwrap();
assert!(err2.contains("stdout error"), "{err2}");
assert_eq!(err2.matches("stdout error").count(), 1, "{err2}");
}
}
#[test]
fn schema_example_and_config_flags_validate_end_to_end() {
let dir = TempDir::new();
let example = dir.file(".env.example", "HOST=localhost\nPORT=8080\nSECRET=\n");
let env_file = dir.file(".env", "HOST=localhost\nSECRET=\nEXTRA=top-secret-val\n");
let basic = run(&[
"--example",
example.to_str().unwrap(),
env_file.to_str().unwrap(),
]);
assert_eq!(basic.status.code(), Some(1));
let basic_out = String::from_utf8(basic.stdout).unwrap();
assert!(basic_out.contains("missing-key"), "{basic_out}");
assert!(basic_out.contains("[PORT]"), "{basic_out}");
assert!(!basic_out.contains("unknown-key"), "{basic_out}");
assert!(!basic_out.contains("empty-value"), "{basic_out}");
let strict = run(&[
"--format=json",
"--example",
example.to_str().unwrap(),
"--no-unknown-keys",
"--no-empty-values",
env_file.to_str().unwrap(),
]);
assert_eq!(strict.status.code(), Some(1));
let strict_out = String::from_utf8(strict.stdout).unwrap();
assert!(
strict_out.contains("\"rule\":\"missing-key\""),
"{strict_out}"
);
assert!(
strict_out.contains("\"rule\":\"unknown-key\""),
"{strict_out}"
);
assert!(
strict_out.contains("\"rule\":\"empty-value\""),
"{strict_out}"
);
assert!(!strict_out.contains("top-secret-val"), "{strict_out}");
let rec_dir = TempDir::new();
rec_dir.file(".env.example", "HOST=\nPORT=\n");
rec_dir.file(".env", "HOST=localhost\nPORT=8080\n");
let rec_ok = run_in(
rec_dir.path(),
&[
"--example",
".env.example",
"--no-unknown-keys",
"--no-empty-values",
],
);
assert_eq!(
rec_ok.status.code(),
Some(0),
"stdout={} stderr={}",
String::from_utf8_lossy(&rec_ok.stdout),
String::from_utf8_lossy(&rec_ok.stderr)
);
let explicit_example = run_in(
rec_dir.path(),
&[
"--example=.env.example",
"--no-empty-values",
".env.example",
],
);
assert_eq!(explicit_example.status.code(), Some(1));
assert!(String::from_utf8(explicit_example.stdout)
.unwrap()
.contains("empty-value"));
let empty_only = dir.file("empty.env", "EMPTY=\nBARE\nOK=1\n");
let standalone_empty = run(&["--no-empty-values", empty_only.to_str().unwrap()]);
assert_eq!(standalone_empty.status.code(), Some(1));
let standalone_out = String::from_utf8(standalone_empty.stdout).unwrap();
assert_eq!(
standalone_out.matches("empty-value").count(),
2,
"{standalone_out}"
);
let bad_unknown = run(&["--no-unknown-keys", empty_only.to_str().unwrap()]);
assert_eq!(bad_unknown.status.code(), Some(2));
assert!(String::from_utf8(bad_unknown.stderr)
.unwrap()
.contains("--no-unknown-keys"));
}
#[test]
fn discovered_schema_config_resolves_relative_example_and_shapes() {
let cfg_dir = TempDir::new();
cfg_dir.file(".env.example", "HOST=localhost\nPORT=8080\nAPP_ENV=prod\n");
cfg_dir.file(
".adotenv-lint.toml",
r#"[rules]
invalid-value = "error"
missing-key = "error"
[schema]
example = ".env.example"
allow_unknown = false
[schema.keys.PORT]
shape = "port"
[schema.keys.APP_ENV]
one_of = ["dev", "staging", "prod"]
"#,
);
cfg_dir.file_at(
"nested/.env",
"HOST=localhost\nPORT=secret-bad\nAPP_ENV=prod\n",
);
let nested = cfg_dir.path().join("nested");
let cfg_out = run_in(&nested, &["--format=github", ".env"]);
assert_eq!(cfg_out.status.code(), Some(1));
let cfg_text = String::from_utf8(cfg_out.stdout).unwrap();
assert!(cfg_text.contains("::error "), "{cfg_text}");
assert!(cfg_text.contains("invalid-value"), "{cfg_text}");
assert!(!cfg_text.contains("secret-bad"), "{cfg_text}");
}
#[test]
fn bounded_fix_and_two_pass_unquoted_cli_options_work_end_to_end() {
let dir = TempDir::new();
let unquote = dir.file("unquote.env", "b = \"two\" \na = \"one\"\n");
let fixed = run(&[
"--fix",
"--key-case=upper",
"--key-order",
"--quote-style=unquoted",
"--equals-spacing=none",
"--trim-trailing-whitespace",
unquote.to_str().unwrap(),
]);
assert_eq!(
fixed.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&fixed.stderr)
);
assert_eq!(fs::read_to_string(&unquote).unwrap(), "A=one\nB=two\n");
let expand = dir.file("expand.env", "A=1\n");
let byte_capped = run(&[
"--fix",
"--equals-spacing=spaces",
"--max-output-bytes=4",
expand.to_str().unwrap(),
]);
assert_eq!(byte_capped.status.code(), Some(2));
assert!(String::from_utf8(byte_capped.stderr)
.unwrap()
.contains("output"));
assert_eq!(fs::read_to_string(&expand).unwrap(), "A=1\n");
let lines = dir.file("lines.env", "B=2\nA=1\n");
let line_capped = run(&[
"--fix",
"--equals-spacing=spaces",
"--max-output-lines=1",
lines.to_str().unwrap(),
]);
assert_eq!(line_capped.status.code(), Some(2));
assert_eq!(fs::read_to_string(&lines).unwrap(), "B=2\nA=1\n");
let refs = dir.file("refs.env", "C=3\nB=$A\nA=1\n");
let ref_capped = run(&[
"--fix",
"--key-order",
"--max-references=0",
refs.to_str().unwrap(),
]);
assert_eq!(ref_capped.status.code(), Some(1));
assert!(String::from_utf8(ref_capped.stdout)
.unwrap()
.contains("key-order"));
assert_eq!(fs::read_to_string(&refs).unwrap(), "C=3\nB=$A\nA=1\n");
let ref_allowed = run(&[
"--fix",
"--key-order",
"--max-references=2",
refs.to_str().unwrap(),
]);
assert_eq!(ref_allowed.status.code(), Some(1));
assert_eq!(fs::read_to_string(&refs).unwrap(), "B=$A\nA=1\nC=3\n");
let items_capped = run(&["--max-items=1", lines.to_str().unwrap()]);
assert_eq!(items_capped.status.code(), Some(2));
let dup = dir.file("dup.env", "A=1\nA=2\n");
let diag_capped = run(&["--max-diagnostics=0", dup.to_str().unwrap()]);
assert_eq!(diag_capped.status.code(), Some(2));
let example = dir.file("mix.example", "A=1\nB=2\nC=3\n");
let mixed = dir.file("mixed.env", "B=2\nA=1\n");
let mix_out = run(&[
"--fix",
"--key-order",
"--example",
example.to_str().unwrap(),
mixed.to_str().unwrap(),
]);
assert_eq!(mix_out.status.code(), Some(1));
assert_eq!(fs::read_to_string(&mixed).unwrap(), "A=1\nB=2\n");
assert!(String::from_utf8(mix_out.stdout)
.unwrap()
.contains("missing-key"));
}
#[test]
fn sort_output_limits_diagnostics_budget_github_keys_and_compose_example() {
let dir = TempDir::new();
let dup = dir.file("dup.env", "A=1\nA=2\n");
let example = dir.file("mix.example", "A=1\nB=2\nC=3\n");
let mixed = dir.file("mixed.env", "A=1\nB=2\n");
let sort_bytes = dir.file("sort_bytes.env", "B=2\nA=1\n");
let sort_bytes_out = run(&[
"--fix",
"--key-order",
"--max-output-bytes=4",
sort_bytes.to_str().unwrap(),
]);
assert_eq!(sort_bytes_out.status.code(), Some(2));
assert_eq!(fs::read_to_string(&sort_bytes).unwrap(), "B=2\nA=1\n");
let sort_lines_out = run(&[
"--fix",
"--key-order",
"--max-output-lines=1",
sort_bytes.to_str().unwrap(),
]);
assert_eq!(sort_lines_out.status.code(), Some(2));
assert_eq!(fs::read_to_string(&sort_bytes).unwrap(), "B=2\nA=1\n");
let warn_ok = run(&["--max-diagnostics=10", dup.to_str().unwrap()]);
assert_eq!(warn_ok.status.code(), Some(1));
let parse_err = dir.file("bad_diag.env", "BAD KEY=1\n");
let err_with_budget = run(&["--max-diagnostics=10", parse_err.to_str().unwrap()]);
assert_eq!(err_with_budget.status.code(), Some(2));
let gh_missing = run(&[
"--format=github",
"--example",
example.to_str().unwrap(),
mixed.to_str().unwrap(),
]);
assert_eq!(gh_missing.status.code(), Some(1));
let gh_text = String::from_utf8(gh_missing.stdout).unwrap();
assert!(
gh_text.contains("missing-key::required key is missing [C]"),
"{gh_text}"
);
let compose_dir = TempDir::new();
compose_dir.file(".adotenv-lint.toml", "[rules]\nmissing-key = \"off\"\n");
compose_dir.file(".env.example", "AWS_PROFILE\nHOST=localhost\n");
compose_dir.file(".env", "HOST=localhost\n");
let compose_out = run_in(
compose_dir.path(),
&[
"--dialect=compose",
"--example=.env.example",
"--no-unknown-keys",
".env",
],
);
assert_eq!(compose_out.status.code(), Some(1));
let compose_text = String::from_utf8(compose_out.stdout).unwrap();
assert!(compose_text.contains("missing-key"), "{compose_text}");
assert!(compose_text.contains("[AWS_PROFILE]"), "{compose_text}");
let closed_cfg_dir = TempDir::new();
closed_cfg_dir.file(".adotenv-lint.toml", "[schema]\nallow_unknown = false\n");
closed_cfg_dir.file(".env", "A=1\n");
let closed_err = run_in(closed_cfg_dir.path(), &[".env"]);
assert_eq!(closed_err.status.code(), Some(2));
assert!(String::from_utf8(closed_err.stderr)
.unwrap()
.contains("allow_unknown = false"));
let cfg_cap = run_in(closed_cfg_dir.path(), &["--max-input-bytes=4", ".env"]);
assert_eq!(cfg_cap.status.code(), Some(2));
assert!(String::from_utf8(cfg_cap.stderr)
.unwrap()
.contains("max_input_bytes"));
let ctrl_file = dir.file("ctrl.env", "'A\nB'=1\n'A\nB'=2\n");
let ctrl_out = run(&["--dialect=python", ctrl_file.to_str().unwrap()]);
assert_eq!(ctrl_out.status.code(), Some(1));
let ctrl_text = String::from_utf8(ctrl_out.stdout).unwrap();
assert_eq!(ctrl_text.lines().count(), 1, "{ctrl_text:?}");
assert!(ctrl_text.contains("[A\\nB]"), "{ctrl_text:?}");
}
#[test]
fn github_key_escaping_and_config_four_mib_cap() {
let bidi_dir = TempDir::new();
bidi_dir.file(
".env",
"'A\x1b[31m\u{202e}\u{2028}B'=1\n'A\x1b[31m\u{202e}\u{2028}B'=2\n",
);
let gh_bidi = run_in(
bidi_dir.path(),
&["--dialect=python", "--format=github", ".env"],
);
assert_eq!(gh_bidi.status.code(), Some(1));
let gh_bidi_text = String::from_utf8(gh_bidi.stdout).unwrap();
assert!(
gh_bidi_text.contains("\\u{1b}")
&& gh_bidi_text.contains("\\u{202e}")
&& gh_bidi_text.contains("\\u{2028}")
&& !gh_bidi_text.contains('\x1b')
&& !gh_bidi_text.contains('\u{202e}')
&& !gh_bidi_text.contains('\u{2028}'),
"{gh_bidi_text}"
);
let exact_cfg_dir = TempDir::new();
let exact_cfg = format!("# {}\n", "x".repeat(4 * 1024 * 1024 - 3));
assert_eq!(exact_cfg.len(), 4 * 1024 * 1024);
exact_cfg_dir.file(".adotenv-lint.toml", &exact_cfg);
exact_cfg_dir.file(".env", "A=1\n");
let exact_ok = run_in(exact_cfg_dir.path(), &["--max-input-bytes=8388608", ".env"]);
assert_eq!(exact_ok.status.code(), Some(0));
let big_cfg_dir = TempDir::new();
let oversized_cfg = format!("# {}\n", "x".repeat(4 * 1024 * 1024 - 2));
assert_eq!(oversized_cfg.len(), 4 * 1024 * 1024 + 1);
big_cfg_dir.file(".adotenv-lint.toml", &oversized_cfg);
big_cfg_dir.file(".env", "A=1\n");
let big_cfg_err = run_in(big_cfg_dir.path(), &["--max-input-bytes=8388608", ".env"]);
assert_eq!(big_cfg_err.status.code(), Some(2));
let big_cfg_stderr = String::from_utf8(big_cfg_err.stderr).unwrap();
assert!(
big_cfg_stderr.contains("4194304"),
"expected 4 MiB cap error: {big_cfg_stderr}"
);
}
#[derive(Debug, PartialEq)]
enum JsonVal {
Null,
Bool(bool),
Number(i64),
String(String),
Array(Vec<JsonVal>),
Object(Vec<(String, JsonVal)>),
}
impl JsonVal {
fn field(&self, name: &str) -> &JsonVal {
let Self::Object(entries) = self else {
panic!("expected JSON object, got {self:?}");
};
entries
.iter()
.find_map(|(k, v)| (k == name).then_some(v))
.unwrap_or_else(|| panic!("missing JSON field {name:?} in {self:?}"))
}
fn get_field(&self, name: &str) -> Option<&JsonVal> {
let Self::Object(entries) = self else {
return None;
};
entries.iter().find_map(|(k, v)| (k == name).then_some(v))
}
fn as_str(&self) -> &str {
let Self::String(s) = self else {
panic!("expected JSON string, got {self:?}");
};
s
}
fn as_i64(&self) -> i64 {
let Self::Number(n) = self else {
panic!("expected JSON number, got {self:?}");
};
*n
}
fn as_array(&self) -> &[JsonVal] {
let Self::Array(items) = self else {
panic!("expected JSON array, got {self:?}");
};
items
}
}
struct JsonParser<'a> {
bytes: &'a [u8],
pos: usize,
}
impl JsonParser<'_> {
fn skip_ws(&mut self) {
while self.pos < self.bytes.len()
&& matches!(self.bytes[self.pos], b' ' | b'\n' | b'\r' | b'\t')
{
self.pos += 1;
}
}
fn peek(&mut self) -> Option<u8> {
self.skip_ws();
self.bytes.get(self.pos).copied()
}
fn expect(&mut self, ch: u8) {
self.skip_ws();
assert_eq!(self.bytes.get(self.pos).copied(), Some(ch));
self.pos += 1;
}
fn parse_value(&mut self) -> JsonVal {
match self.peek().expect("unexpected EOF") {
b'{' => self.parse_object(),
b'[' => self.parse_array(),
b'"' => JsonVal::String(self.parse_string()),
b't' => {
assert!(self.bytes[self.pos..].starts_with(b"true"));
self.pos += 4;
JsonVal::Bool(true)
}
b'f' => {
assert!(self.bytes[self.pos..].starts_with(b"false"));
self.pos += 5;
JsonVal::Bool(false)
}
b'n' => {
assert!(self.bytes[self.pos..].starts_with(b"null"));
self.pos += 4;
JsonVal::Null
}
b'-' | b'0'..=b'9' => self.parse_number(),
other => panic!("unexpected JSON byte {other:?} at {}", self.pos),
}
}
fn parse_object(&mut self) -> JsonVal {
self.expect(b'{');
let mut entries = Vec::new();
if self.peek() == Some(b'}') {
self.pos += 1;
return JsonVal::Object(entries);
}
loop {
let key = self.parse_string();
self.expect(b':');
let val = self.parse_value();
entries.push((key, val));
match self.peek() {
Some(b',') => self.pos += 1,
Some(b'}') => {
self.pos += 1;
return JsonVal::Object(entries);
}
other => panic!("expected ',' or '}}', got {other:?}"),
}
}
}
fn parse_array(&mut self) -> JsonVal {
self.expect(b'[');
let mut items = Vec::new();
if self.peek() == Some(b']') {
self.pos += 1;
return JsonVal::Array(items);
}
loop {
items.push(self.parse_value());
match self.peek() {
Some(b',') => self.pos += 1,
Some(b']') => {
self.pos += 1;
return JsonVal::Array(items);
}
other => panic!("expected ',' or ']', got {other:?}"),
}
}
}
fn parse_string(&mut self) -> String {
self.expect(b'"');
let mut out = String::new();
while self.pos < self.bytes.len() {
let b = self.bytes[self.pos];
self.pos += 1;
match b {
b'"' => return out,
b'\\' => {
let esc = self.bytes[self.pos];
self.pos += 1;
match esc {
b'"' => out.push('"'),
b'\\' => out.push('\\'),
b'/' => out.push('/'),
b'b' => out.push('\u{0008}'),
b'f' => out.push('\u{000c}'),
b'n' => out.push('\n'),
b'r' => out.push('\r'),
b't' => out.push('\t'),
b'u' => {
let hex =
std::str::from_utf8(&self.bytes[self.pos..self.pos + 4]).unwrap();
let code = u32::from_str_radix(hex, 16).unwrap();
self.pos += 4;
out.push(char::from_u32(code).unwrap());
}
other => panic!("invalid JSON escape \\{other:?}"),
}
}
_ => {
let start = self.pos - 1;
let s = std::str::from_utf8(&self.bytes[start..]).unwrap();
let ch = s.chars().next().unwrap();
self.pos = start + ch.len_utf8();
out.push(ch);
}
}
}
panic!("unterminated JSON string");
}
fn parse_number(&mut self) -> JsonVal {
self.skip_ws();
let start = self.pos;
if self.bytes[self.pos] == b'-' {
self.pos += 1;
}
while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
self.pos += 1;
}
let text = std::str::from_utf8(&self.bytes[start..self.pos]).unwrap();
JsonVal::Number(text.parse::<i64>().unwrap())
}
}
fn parse_json(input: &str) -> JsonVal {
let mut parser = JsonParser {
bytes: input.as_bytes(),
pos: 0,
};
let val = parser.parse_value();
parser.skip_ws();
assert_eq!(parser.pos, parser.bytes.len(), "trailing JSON data");
val
}
#[test]
fn list_rules_and_explain_flags_cover_all_rules_and_reject_invalid() {
let list_out = run(&["--list-rules"]);
assert_eq!(list_out.status.code(), Some(0));
let list_text = String::from_utf8(list_out.stdout).unwrap();
let expected_rules = [
"duplicate-key",
"key-order",
"key-case",
"quote-style",
"whitespace",
"missing-key",
"unknown-key",
"empty-value",
"invalid-value",
"deprecated-key",
];
assert_eq!(list_text.lines().count(), expected_rules.len());
for rule in expected_rules {
assert!(list_text.contains(rule), "missing {rule} in:\n{list_text}");
let exp = run(&["--explain", rule]);
assert_eq!(exp.status.code(), Some(0), "rule={rule}");
let exp_text = String::from_utf8(exp.stdout).unwrap();
assert!(
exp_text.contains(&format!("Rule: {rule}")),
"{exp_text}"
);
assert!(exp_text.contains("Summary: "), "{exp_text}");
assert!(exp_text.contains("Default: "), "{exp_text}");
assert!(exp_text.contains("Autofix: "), "{exp_text}");
assert!(exp_text.contains("Config: "), "{exp_text}");
assert!(exp_text.contains("Rationale: "), "{exp_text}");
}
let eq_exp = run(&["--explain=deprecated-key"]);
assert_eq!(eq_exp.status.code(), Some(0));
assert!(String::from_utf8(eq_exp.stdout)
.unwrap()
.contains("Rule: deprecated-key"));
let kc_exp = run(&["--explain=key-case"]);
assert_eq!(kc_exp.status.code(), Some(0));
let kc_text = String::from_utf8(kc_exp.stdout).unwrap();
assert!(
!kc_text.contains("key_case = \"upper\" | \"lower\" | \"off\""),
"{kc_text}"
);
for bad_args in [
&["--explain"][..],
&["--explain="][..],
&["--explain", "no-such-rule"][..],
&["--explain=no-such-rule"][..],
] {
let bad = run(bad_args);
assert_eq!(bad.status.code(), Some(2), "{bad_args:?}");
}
}
#[test]
fn fix_missing_is_opt_in_and_never_copies_example_values() {
let dir = TempDir::new();
dir.file(
".env.example",
"API_KEY=example-secret-never-copy\nHOST=localhost\nPORT=8080\n",
);
let env_file = dir.file(".env", "port=8080\n");
let usage_err = run_in(
dir.path(),
&["--example=.env.example", "--fix-missing", ".env"],
);
assert_eq!(usage_err.status.code(), Some(2));
assert!(String::from_utf8(usage_err.stderr)
.unwrap()
.contains("--fix-missing requires --fix"));
let style_only = run_in(
dir.path(),
&[
"--example=.env.example",
"--key-case=upper",
"--fix",
".env",
],
);
assert_eq!(style_only.status.code(), Some(1));
assert_eq!(fs::read_to_string(&env_file).unwrap(), "PORT=8080\n");
let style_stdout = String::from_utf8(style_only.stdout).unwrap();
assert!(style_stdout.contains("missing-key"), "{style_stdout}");
assert!(style_stdout.contains("[API_KEY]"), "{style_stdout}");
assert!(style_stdout.contains("[HOST]"), "{style_stdout}");
let scaffold = run_in(
dir.path(),
&[
"--example=.env.example",
"--key-case=upper",
"--key-order",
"--fix",
"--fix-missing",
".env",
],
);
assert_eq!(scaffold.status.code(), Some(0));
let fixed_content = fs::read_to_string(&env_file).unwrap();
assert_eq!(fixed_content, "API_KEY=\nHOST=\nPORT=8080\n");
assert!(!fixed_content.contains("example-secret-never-copy"));
assert!(!fixed_content.contains("localhost"));
let strict_dir = TempDir::new();
strict_dir.file(
".adotenv-lint.toml",
"[schema]\nallow_empty = false\n[schema.keys.HOST]\nshape = \"host\"\n[schema.keys.PORT]\nshape = \"port\"\n",
);
let strict_env = strict_dir.file(".env", "PORT=8080\n");
let strict_out = run_in(strict_dir.path(), &["--fix", "--fix-missing", ".env"]);
assert_eq!(strict_out.status.code(), Some(1));
assert_eq!(
fs::read_to_string(&strict_env).unwrap(),
"PORT=8080\nHOST=\n"
);
let strict_text = String::from_utf8(strict_out.stdout).unwrap();
assert!(strict_text.contains("empty-value"), "{strict_text}");
assert!(strict_text.contains("[HOST]"), "{strict_text}");
}
#[test]
fn sarif_clean_file_emits_valid_empty_results() {
let clean_dir = TempDir::new();
clean_dir.file(".env", "A=1\n");
let clean_out = run_in(clean_dir.path(), &["--format=sarif", ".env"]);
assert_eq!(clean_out.status.code(), Some(0));
let clean_sarif = parse_json(&String::from_utf8(clean_out.stdout).unwrap());
assert_eq!(clean_sarif.field("version").as_str(), "2.1.0");
assert_eq!(
clean_sarif.field("$schema").as_str(),
"https://json.schemastore.org/sarif-2.1.0.json"
);
let clean_run = &clean_sarif.field("runs").as_array()[0];
assert_eq!(clean_run.field("columnKind").as_str(), "unicodeCodePoints");
assert_eq!(
clean_run.field("invocations").as_array()[0].field("executionSuccessful"),
&JsonVal::Bool(true)
);
let driver = clean_run.field("tool").field("driver");
assert_eq!(driver.field("name").as_str(), "adotenv-lint");
assert_eq!(driver.field("version").as_str(), env!("CARGO_PKG_VERSION"));
assert_eq!(
driver.field("informationUri").as_str(),
"https://zeropier.com/adotenv/"
);
assert_eq!(driver.field("rules").as_array().len(), 10);
assert_eq!(clean_run.field("results").as_array().len(), 0);
let err_dir = TempDir::new();
let bad_path = err_dir.file("bad.env", "NOT VALID\n");
let unsorted_path = err_dir.file("order.env", "B=2\nA=1\n");
let partial_out = run(&[
"--format=sarif",
"--key-order",
bad_path.to_str().unwrap(),
unsorted_path.to_str().unwrap(),
]);
assert_eq!(partial_out.status.code(), Some(2));
let partial_sarif = parse_json(&String::from_utf8(partial_out.stdout).unwrap());
let partial_run = &partial_sarif.field("runs").as_array()[0];
assert_eq!(
partial_run.field("invocations").as_array()[0].field("executionSuccessful"),
&JsonVal::Bool(false)
);
let order_res = &partial_run.field("results").as_array()[0];
let order_loc = &order_res.field("locations").as_array()[0].field("physicalLocation");
assert!(
order_loc
.field("artifactLocation")
.field("uri")
.as_str()
.starts_with("file:///"),
"{order_loc:?}"
);
let region = order_loc.field("region");
assert_eq!(region.field("startLine").as_i64(), 1);
assert_eq!(region.field("startColumn").as_i64(), 1);
assert_eq!(region.field("endLine").as_i64(), 2);
assert_eq!(region.field("endColumn").as_i64(), 4);
assert_eq!(region.field("byteOffset").as_i64(), 0);
assert_eq!(region.field("byteLength").as_i64(), 7);
}
#[test]
fn sarif_handles_compose_crlf_eof_cr_and_double_slash_relative_paths() {
let dir = TempDir::new();
dir.file("crlf.env", "B=2\r\nA=1\r\n");
dir.file("eofcr.env", "B=2\nA=1\r");
let crlf_out = run_in(
dir.path(),
&[
"--dialect=compose",
"--key-order",
"--format=sarif",
".//crlf.env",
],
);
assert_eq!(crlf_out.status.code(), Some(1));
let crlf_sarif = parse_json(&String::from_utf8(crlf_out.stdout).unwrap());
let crlf_loc = &crlf_sarif.field("runs").as_array()[0]
.field("results")
.as_array()[0]
.field("locations")
.as_array()[0]
.field("physicalLocation");
assert_eq!(
crlf_loc.field("artifactLocation").field("uri").as_str(),
"crlf.env"
);
let crlf_reg = crlf_loc.field("region");
assert_eq!(crlf_reg.field("startLine").as_i64(), 1);
assert_eq!(crlf_reg.field("startColumn").as_i64(), 1);
assert_eq!(crlf_reg.field("endLine").as_i64(), 2);
assert_eq!(crlf_reg.field("endColumn").as_i64(), 4);
assert_eq!(crlf_reg.field("byteOffset").as_i64(), 0);
assert_eq!(crlf_reg.field("byteLength").as_i64(), 8);
let eofcr_out = run_in(
dir.path(),
&[
"--dialect=docker",
"--key-order",
"--format=sarif",
".///eofcr.env",
],
);
assert_eq!(eofcr_out.status.code(), Some(1));
let eofcr_sarif = parse_json(&String::from_utf8(eofcr_out.stdout).unwrap());
let eofcr_loc = &eofcr_sarif.field("runs").as_array()[0]
.field("results")
.as_array()[0]
.field("locations")
.as_array()[0]
.field("physicalLocation");
assert_eq!(
eofcr_loc.field("artifactLocation").field("uri").as_str(),
"eofcr.env"
);
let eofcr_reg = eofcr_loc.field("region");
assert_eq!(eofcr_reg.field("startLine").as_i64(), 1);
assert_eq!(eofcr_reg.field("startColumn").as_i64(), 1);
assert_eq!(eofcr_reg.field("endLine").as_i64(), 2);
assert_eq!(eofcr_reg.field("endColumn").as_i64(), 4);
assert_eq!(eofcr_reg.field("byteOffset").as_i64(), 0);
assert_eq!(eofcr_reg.field("byteLength").as_i64(), 7);
}
#[test]
fn sarif_and_detail_outputs_are_spec_compliant_value_free_and_post_fix_accurate() {
let dir = TempDir::new();
dir.file(
".adotenv-lint.toml",
r#"
[rules]
deprecated-key = "error"
invalid-value = "warning"
missing-key = "error"
[schema.keys.REQ_HOST]
shape = "host"
[schema.keys.OLD_VAR]
required = false
deprecated = "use NEW_VAR\u001b[31m\u202e"
[schema.keys.TOKEN]
prefix = "sk_"
min_len = 8
[schema.keys.BIND]
shape = "socket-addr"
[schema.keys.ADMIN]
shape = "email"
"#,
);
dir.file(
"app env.env",
"\u{feff}TOKEN=super-secret-bad\nOLD_VAR=secret-legacy\nBIND=127.0.0.1:8080\nADMIN=ops@example.com\n",
);
let sarif_out = run_in(
dir.path(),
&["--format=sarif", "--key-order", "--fix", "./app env.env"],
);
assert_eq!(sarif_out.status.code(), Some(1));
let sarif_raw = String::from_utf8(sarif_out.stdout).unwrap();
assert!(!sarif_raw.contains("super-secret-bad"), "{sarif_raw}");
assert!(!sarif_raw.contains("secret-legacy"), "{sarif_raw}");
assert!(!sarif_raw.contains('\u{202e}'), "{sarif_raw}");
assert!(!sarif_raw.contains('\x1b'), "{sarif_raw}");
let sarif = parse_json(&sarif_raw);
let run_obj = &sarif.field("runs").as_array()[0];
let rules = run_obj
.field("tool")
.field("driver")
.field("rules")
.as_array();
let results = run_obj.field("results").as_array();
assert_eq!(results.len(), 3, "{sarif_raw}");
let r0 = &results[0];
assert_eq!(r0.field("ruleId").as_str(), "missing-key");
let idx0 = usize::try_from(r0.field("ruleIndex").as_i64()).unwrap();
assert_eq!(rules[idx0].field("id").as_str(), "missing-key");
assert_eq!(r0.field("level").as_str(), "error");
let loc0 = &r0.field("locations").as_array()[0].field("physicalLocation");
assert_eq!(
loc0.field("artifactLocation").field("uri").as_str(),
"app%20env.env"
);
let reg0 = loc0.field("region");
assert_eq!(reg0.field("startLine").as_i64(), 1);
assert_eq!(reg0.field("startColumn").as_i64(), 1);
assert_eq!(reg0.field("endLine").as_i64(), 1);
assert_eq!(reg0.field("endColumn").as_i64(), 1);
assert_eq!(reg0.field("byteOffset").as_i64(), 3);
assert_eq!(reg0.field("byteLength").as_i64(), 0);
let r1 = &results[1];
assert_eq!(r1.field("ruleId").as_str(), "deprecated-key");
let idx1 = usize::try_from(r1.field("ruleIndex").as_i64()).unwrap();
assert_eq!(rules[idx1].field("id").as_str(), "deprecated-key");
assert_eq!(r1.field("level").as_str(), "error");
let msg1 = r1.field("message").field("text").as_str();
assert!(msg1.contains("use NEW_VAR"), "{msg1}");
assert!(
msg1.contains("\\u{1b}") && msg1.contains("\\u{202e}"),
"{msg1}"
);
let reg1 = r1.field("locations").as_array()[0]
.field("physicalLocation")
.field("region");
assert_eq!(reg1.field("startLine").as_i64(), 3);
assert_eq!(reg1.field("startColumn").as_i64(), 1);
assert_eq!(reg1.field("endLine").as_i64(), 3);
assert_eq!(reg1.field("endColumn").as_i64(), 8);
let r2 = &results[2];
assert_eq!(r2.field("ruleId").as_str(), "invalid-value");
assert_eq!(r2.field("level").as_str(), "warning");
assert!(
r2.field("message")
.field("text")
.as_str()
.contains("expected prefix \"sk_\""),
"{r2:?}"
);
let reg2 = r2.field("locations").as_array()[0]
.field("physicalLocation")
.field("region");
assert_eq!(reg2.field("startLine").as_i64(), 4);
assert_eq!(reg2.field("startColumn").as_i64(), 7);
}
#[test]
fn json_human_and_github_outputs_emit_escaped_details_value_free() {
let dir = TempDir::new();
dir.file(
".adotenv-lint.toml",
r#"
[rules]
deprecated-key = "error"
missing-key = "error"
[schema.keys.REQ_HOST]
shape = "host"
[schema.keys.OLD_VAR]
required = false
deprecated = "use NEW_VAR\u001b[31m\u202e"
[schema.keys.TOKEN]
prefix = "sk_"
"#,
);
dir.file(
"app env.env",
"OLD_VAR=secret-legacy\nTOKEN=super-secret-bad\n",
);
let json_out = run_in(dir.path(), &["--format=json", "./app env.env"]);
assert_eq!(json_out.status.code(), Some(1));
let json_raw = String::from_utf8(json_out.stdout).unwrap();
assert!(!json_raw.contains("super-secret-bad"));
assert!(!json_raw.contains("secret-legacy"));
let json_arr = parse_json(&json_raw);
let items = json_arr.as_array();
assert_eq!(items.len(), 3);
assert_eq!(items[0].field("rule").as_str(), "deprecated-key");
assert!(items[0].field("detail").as_str().starts_with("use NEW_VAR"));
assert_eq!(items[1].field("rule").as_str(), "missing-key");
assert!(items[1].get_field("detail").is_none());
assert_eq!(items[2].field("rule").as_str(), "invalid-value");
assert_eq!(items[2].field("detail").as_str(), "expected prefix \"sk_\"");
let human_out = run_in(dir.path(), &["./app env.env"]);
assert_eq!(human_out.status.code(), Some(1));
let human_raw = String::from_utf8(human_out.stdout).unwrap();
assert!(human_raw.contains("error[deprecated-key]: key is deprecated: use NEW_VAR"));
assert!(human_raw.contains("expected prefix \"sk_\" [TOKEN]"));
assert!(!human_raw.contains('\u{202e}'));
let gh_out = run_in(dir.path(), &["--format=github", "./app env.env"]);
assert_eq!(gh_out.status.code(), Some(1));
let gh_raw = String::from_utf8(gh_out.stdout).unwrap();
assert!(gh_raw.contains("title=deprecated-key::key is deprecated: use NEW_VAR"));
assert!(gh_raw.contains("expected prefix \"sk_\" [TOKEN]"));
assert!(!gh_raw.contains('\u{202e}'));
}