From 247692c2203388b96b1d1d89568485e452a59d3b Mon Sep 17 00:00:00 2001 From: dmillzilla <37204972+dmillzilla@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:40:00 -0600 Subject: [PATCH 1/2] Fix role-relative task includes and linting edge cases --- CHANGELOG.md | 8 ++ src/dependencies.rs | 126 ++++++++++++++++++- src/extra_rules.rs | 66 ++++++++-- src/loading.rs | 6 +- src/rules.rs | 1 + src/static_rules.rs | 2 +- tests/fixtures/task_arguments.json | 190 +++++++++++++++++++++++++++++ tests/project_loading.rs | 46 +++++++ tests/shell_pipelines.rs | 10 ++ tests/task_arguments.rs | 32 +++++ 10 files changed, 477 insertions(+), 10 deletions(-) create mode 100644 tests/fixtures/task_arguments.json create mode 100644 tests/task_arguments.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b82aaa..db08e86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## Unreleased + +- Resolve role-relative task includes with Ansible role and playbook fallbacks, + including targets already prefixed with `tasks/`. +- Keep quoted text and shell comments from faking an enabled `pipefail`. +- Exempt Jinja blocks and comments from `no-tabs` while preserving Jinja checks. +- Check commands supplied through `_raw_params` for module recommendations. + ## 0.1.2 — 2026-11-06 - Check templated `ignore_errors` settings while preserving the check-mode and diff --git a/src/dependencies.rs b/src/dependencies.rs index c5cabaf..4f523ca 100644 --- a/src/dependencies.rs +++ b/src/dependencies.rs @@ -165,7 +165,11 @@ fn literal( .filter(|file| !file.is_empty() && file != "/dev/null") { result.push(Dependency { - path: path.parent().unwrap_or(Path::new(".")).join(file), + path: if kind == FileKind::Tasks { + task_path(path, &file, variables) + } else { + path.parent().unwrap_or(Path::new(".")).join(file) + }, kind, position, plugin_base: None, @@ -173,6 +177,48 @@ fn literal( } } +/// Resolve static task targets without executing Ansible. Keep the current +/// include directory first for nested includes, then use the role/task and +/// loader-basedir fallbacks from DataLoader.path_dwim_relative. +pub(crate) fn task_path(path: &Path, file: &str, variables: &serde_json::Value) -> PathBuf { + let direct = path.parent().unwrap_or(Path::new(".")).join(file); + if Path::new(file).is_absolute() { + return direct; + } + let role = variables + .get("role_path") + .and_then(serde_json::Value::as_str) + .map(Path::new); + let cwd = std::env::current_dir().ok(); + let base = variables + .get("playbook_dir") + .and_then(serde_json::Value::as_str) + .map(Path::new) + .or(cwd.as_deref()); + let mut candidates = vec![direct.clone()]; + if let Some(role) = role { + candidates.push(role.join("tasks").join(file)); + } + // DataLoader's unfrackpath("tasks/") uses the process working + // directory, whereas its later path_dwim fallback uses the loader basedir. + if role.is_some() + && let Some(cwd) = &cwd + { + candidates.push(cwd.join("tasks").join(file)); + } + if let Some(role) = role { + candidates.push(role.join(file)); + } + if let Some(base) = base { + candidates.push(base.join("tasks").join(file)); + candidates.push(base.join(file)); + } + candidates + .into_iter() + .find(|p| p.exists()) + .unwrap_or(direct) +} + fn local_role( path: &Path, role: Option<&str>, @@ -237,3 +283,81 @@ fn local_role( } } } + +#[cfg(test)] +mod tests { + use super::task_path; + use serde_json::json; + use std::{fs, path::Path}; + + #[test] + fn role_task_search_order_matches_dataloader_without_execution() { + // Expected selections verified with ansible-core 2.21.5 + // DataLoader.path_dwim_relative(role, "tasks", target, is_role=True). + for (target, files, selected) in [ + ( + "tasks/configure.yml", + vec!["roles/example/tasks/configure.yml"], + "roles/example/tasks/configure.yml", + ), + ( + "tasks/configure.yml", + vec![ + "roles/example/tasks/tasks/configure.yml", + "roles/example/tasks/configure.yml", + ], + "roles/example/tasks/tasks/configure.yml", + ), + ( + "tasks/configure.yml", + vec![ + "tasks/tasks/configure.yml", + "roles/example/tasks/configure.yml", + ], + "roles/example/tasks/configure.yml", + ), + ( + "configure.yml", + vec![ + "roles/example/tasks/configure.yml", + "roles/example/configure.yml", + "configure.yml", + ], + "roles/example/tasks/configure.yml", + ), + ( + "configure.yml", + vec!["tasks/configure.yml", "roles/example/configure.yml"], + "roles/example/configure.yml", + ), + ( + "configure.yml", + vec!["roles/example/configure.yml", "configure.yml"], + "roles/example/configure.yml", + ), + ("configure.yml", vec!["configure.yml"], "configure.yml"), + ] { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + for file in files { + let path = root.join(file); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, "---\n[]\n").unwrap(); + } + let vars = json!({"role_path": root.join("roles/example"), "playbook_dir": root}); + assert_eq!( + task_path(&root.join("roles/example/tasks/main.yml"), target, &vars), + root.join(selected) + ); + let absolute = root.join(selected); + assert_eq!( + task_path( + Path::new("unrelated/main.yml"), + absolute.to_str().unwrap(), + &vars + ), + absolute + ); + } + } +} diff --git a/src/extra_rules.rs b/src/extra_rules.rs index 28b65ec..3cf683a 100644 --- a/src/extra_rules.rs +++ b/src/extra_rules.rs @@ -204,13 +204,7 @@ pub fn task<'a>(task: &'a Node, action: &Action<'a>, emit: &mut impl FnMut(&str, && let Some(command) = action.command() { let command = crate::template::mask_expressions(command); - let has_pipefail = command.split([';', '\n']).any(|statement| { - let words: Vec<_> = statement.split_whitespace().collect(); - words.first() == Some(&"set") - && words.windows(2).any(|pair| { - pair[0].starts_with('-') && pair[0].ends_with('o') && pair[1] == "pipefail" - }) - }); + let has_pipefail = has_pipefail(&command); let powershell = action .argument("executable") .is_some_and(|value| value.contains("pwsh") || value.contains("powershell")); @@ -421,3 +415,61 @@ fn has_pipeline(text: &str) -> bool { } false } + +// Shell separators and comments only delimit statements outside quoted words. +// Preserve word boundaries so data containing `set -o pipefail` cannot disable +// the pipeline check. This parser never invokes a shell. +fn has_pipefail(text: &str) -> bool { + let mut quote = None; + let mut escape = false; + let mut comment = false; + let mut statement = String::new(); + let enabled = |statement: &str| { + let Ok(words) = shell_words::split(statement) else { + return false; + }; + words.first().is_some_and(|word| word == "set") + && words.windows(2).any(|pair| { + pair[0].starts_with('-') && pair[0].ends_with('o') && pair[1] == "pipefail" + }) + }; + let chars: Vec<_> = text.chars().collect(); + for (index, &ch) in chars.iter().enumerate() { + if comment { + if ch != '\n' { + continue; + } + comment = false; + } + if escape { + statement.push(ch); + escape = false; + continue; + } + if ch == '\\' && quote != Some('\'') { + statement.push(ch); + escape = true; + continue; + } + if quote.is_none() + && ch == '#' + && (index == 0 || chars[index - 1].is_whitespace() || chars[index - 1] == ';') + { + comment = true; + } else if quote == Some(ch) { + quote = None; + statement.push(ch); + } else if quote.is_none() && matches!(ch, '\'' | '"') { + quote = Some(ch); + statement.push(ch); + } else if quote.is_none() && matches!(ch, ';' | '\n' | '&' | '|') { + if enabled(&statement) { + return true; + } + statement.clear(); + } else { + statement.push(ch); + } + } + enabled(&statement) +} diff --git a/src/loading.rs b/src/loading.rs index 283fb7a..78ed712 100644 --- a/src/loading.rs +++ b/src/loading.rs @@ -401,7 +401,11 @@ impl Loader<'_> { if let Some(file) = crate::template::render_path(value, vars, &self.options.settings.collection_index) { - let target = path.parent().unwrap_or(Path::new(".")).join(file); + let target = if kind == FileKind::Tasks { + crate::dependencies::task_path(path, &file, vars) + } else { + path.parent().unwrap_or(Path::new(".")).join(file) + }; if loaded && !target.is_file() { self.graph.diagnostics.push(Diagnostic::error( path, diff --git a/src/rules.rs b/src/rules.rs index c978eb5..7fbb501 100644 --- a/src/rules.rs +++ b/src/rules.rs @@ -844,6 +844,7 @@ impl<'a> Action<'a> { } }) .or_else(|| self.argument("cmd")) + .or_else(|| self.argument("_raw_params")) } } diff --git a/src/static_rules.rs b/src/static_rules.rs index 9ee49fa..aa6ad89 100644 --- a/src/static_rules.rs +++ b/src/static_rules.rs @@ -872,7 +872,7 @@ fn tabs<'a>( ) { match &node.kind { crate::yaml::Kind::Scalar { value, .. } - if value.contains('\t') && !value.contains("{{") => + if value.contains('\t') && !regex!(r"(?s)\{[\{%#].*[%#\}]\}").is_match(value) => { emit("no-tabs", "Use spaces instead of tabs", node, container) } diff --git a/tests/fixtures/task_arguments.json b/tests/fixtures/task_arguments.json new file mode 100644 index 0000000..8375361 --- /dev/null +++ b/tests/fixtures/task_arguments.json @@ -0,0 +1,190 @@ +[ + { + "case": "tabs-plain-tab", + "source": "---\n- name: Inspect parity\n ansible.builtin.debug:\n msg: \"ready\\tvalue\"\n", + "reference": { + "exit": 2, + "issues": [ + { + "type": "issue", + "check_name": "no-tabs", + "categories": [ + "formatting" + ], + "url": "https://docs.ansible.com/projects/lint/rules/no-tabs/", + "severity": "major", + "description": "Most files should not contain tabs.", + "fingerprint": "4a99438cfbb065d318c9d8b9552b04445413510dca29acf9c05801bcea83974a", + "location": { + "path": "tasks/main.yml", + "positions": { + "begin": { + "line": 4, + "column": 10 + } + } + }, + "content": { + "body": "Task/Handler: Inspect parity" + } + } + ] + } + }, + { + "case": "tabs-plain-clean", + "source": "---\n- name: Inspect parity\n ansible.builtin.debug:\n msg: \"ready value\"\n", + "reference": { + "exit": 0, + "issues": [] + } + }, + { + "case": "tabs-expression-tab", + "source": "---\n- name: Inspect parity\n ansible.builtin.debug:\n msg: \"{{ value\\t| default(42) }}\"\n", + "reference": { + "exit": 0, + "issues": [ + { + "type": "issue", + "check_name": "jinja[spacing]", + "categories": [ + "formatting" + ], + "url": "https://docs.ansible.com/projects/lint/rules/jinja/", + "severity": "minor", + "description": "Jinja2 spacing could be improved: {{ value\t| default(42) }} -> {{ value | default(42) }}", + "fingerprint": "d3a89c8e552926f8156267020d842a558442d7bd68d4690915dcba96a77aea4c", + "location": { + "path": "tasks/main.yml", + "positions": { + "begin": { + "line": 4, + "column": 10 + } + } + }, + "content": { + "body": "Jinja2 template rewrite recommendation: `{{ value | default(42) }}`." + } + } + ] + } + }, + { + "case": "tabs-block-tab", + "source": "---\n- name: Inspect parity\n ansible.builtin.debug:\n msg: \"{% if\\tready %}Ready{% endif %}\"\n", + "reference": { + "exit": 0, + "issues": [ + { + "type": "issue", + "check_name": "jinja[spacing]", + "categories": [ + "formatting" + ], + "url": "https://docs.ansible.com/projects/lint/rules/jinja/", + "severity": "minor", + "description": "Jinja2 spacing could be improved: {% if\tready %}Ready{% endif %} -> {% if ready %}Ready{% endif %}", + "fingerprint": "41be5643ad58787390e72a2528f1dc6a3e13fb225ed71ab324635976a251e74b", + "location": { + "path": "tasks/main.yml", + "positions": { + "begin": { + "line": 4, + "column": 10 + } + } + }, + "content": { + "body": "Jinja2 template rewrite recommendation: `{% if ready %}Ready{% endif %}`." + } + } + ] + } + }, + { + "case": "tabs-comment-tab", + "source": "---\n- name: Inspect parity\n ansible.builtin.debug:\n msg: \"Ready {# a\\tcomment #}\"\n", + "reference": { + "exit": 0, + "issues": [] + } + }, + { + "case": "command-cmd-positive", + "source": "---\n- name: Inspect parity\n ansible.builtin.command:\n cmd: git clone https://example.invalid/repo\n changed_when: false\n", + "reference": { + "exit": 2, + "issues": [ + { + "type": "issue", + "check_name": "command-instead-of-module", + "categories": [ + "command-shell", + "idiom" + ], + "url": "https://docs.ansible.com/projects/lint/rules/command-instead-of-module/", + "severity": "major", + "description": "git used in place of git module", + "fingerprint": "3de8dbfd883f1b9a6d10380f30619e66d5f9013d6d3a2ad1ffb22f4d85b1189d", + "location": { + "path": "tasks/main.yml", + "lines": { + "begin": 2 + } + }, + "content": { + "body": "Task/Handler: Inspect parity" + } + } + ] + } + }, + { + "case": "command-raw-positive", + "source": "---\n- name: Inspect parity\n ansible.builtin.command:\n _raw_params: git clone https://example.invalid/repo\n changed_when: false\n", + "reference": { + "exit": 2, + "issues": [ + { + "type": "issue", + "check_name": "command-instead-of-module", + "categories": [ + "command-shell", + "idiom" + ], + "url": "https://docs.ansible.com/projects/lint/rules/command-instead-of-module/", + "severity": "major", + "description": "git used in place of git module", + "fingerprint": "3de8dbfd883f1b9a6d10380f30619e66d5f9013d6d3a2ad1ffb22f4d85b1189d", + "location": { + "path": "tasks/main.yml", + "lines": { + "begin": 2 + } + }, + "content": { + "body": "Task/Handler: Inspect parity" + } + } + ] + } + }, + { + "case": "command-raw-exempt", + "source": "---\n- name: Inspect parity\n ansible.builtin.command:\n _raw_params: git log\n changed_when: false\n", + "reference": { + "exit": 0, + "issues": [] + } + }, + { + "case": "command-cmd-exempt", + "source": "---\n- name: Inspect parity\n ansible.builtin.command:\n cmd: git log\n changed_when: false\n", + "reference": { + "exit": 0, + "issues": [] + } + } +] diff --git a/tests/project_loading.rs b/tests/project_loading.rs index 5950731..379ba99 100644 --- a/tests/project_loading.rs +++ b/tests/project_loading.rs @@ -1523,3 +1523,49 @@ fn role_prefixes_use_standalone_metadata_and_the_short_installed_role_identity() ); } } + +#[test] +fn role_prefixed_includes_resolve_and_lint_the_selected_file() { + for (target, selected) in [ + ("tasks/configure.yml", "roles/example/tasks/configure.yml"), + ("configure.yml", "configure.yml"), + ] { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(root, ".ansible-lint", "offline: true\n"); + write( + root, + "site.yml", + "---\n- name: Test role includes\n hosts: localhost\n gather_facts: false\n roles:\n - example\n", + ); + write( + root, + "roles/example/tasks/main.yml", + &format!( + "---\n- name: Load configuration tasks\n ansible.builtin.include_tasks: {target}\n" + ), + ); + write( + root, + selected, + "---\n- name: Show a message\n ansible.builtin.debug:\n msg: hello\n", + ); + let output = std::process::Command::new(env!("CARGO_BIN_EXE_oxible")) + .current_dir(root) + .env("PATH", "") + .args(["site.yml", "--offline", "--no-cache", "-f", "json"]) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(0), + "{} {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + serde_json::from_slice::(&output.stdout).unwrap(), + serde_json::json!([]) + ); + } +} diff --git a/tests/shell_pipelines.rs b/tests/shell_pipelines.rs index d6b7b47..beb630d 100644 --- a/tests/shell_pipelines.rs +++ b/tests/shell_pipelines.rs @@ -8,6 +8,16 @@ fn templated_shell_pipelines_match_reference_issues_and_exits() { fs::create_dir(directory.path().join("tasks")).unwrap(); fs::write(directory.path().join(".ansible-lint"), "offline: true\n").unwrap(); let cases = &[ + ( + "quoted-fake-pipefail", + "echo 'x; set -o pipefail; y'; false | true", + true, + ), + ( + "comment-fake-pipefail", + "echo ready # ; set -o pipefail\nfalse | true", + true, + ), ("plain-pipeline", "printf ready | cat", true), ("templated-argument", "echo {{ value }} | cat", true), ("templated-filter", "echo {{ value | quote }} | cat", true), diff --git a/tests/task_arguments.rs b/tests/task_arguments.rs new file mode 100644 index 0000000..9a16548 --- /dev/null +++ b/tests/task_arguments.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use serde_json::Value; +use std::{fs, process::Command}; + +#[test] +fn jinja_tabs_and_raw_commands_match_pinned_issue_fields_and_exit_status() { + let cases: Value = serde_json::from_str(include_str!("fixtures/task_arguments.json")).unwrap(); + let directory = tempfile::tempdir().unwrap(); + fs::create_dir(directory.path().join("tasks")).unwrap(); + fs::write(directory.path().join(".ansible-lint"), "offline: true\n").unwrap(); + for case in cases.as_array().unwrap() { + fs::write( + directory.path().join("tasks/main.yml"), + case["source"].as_str().unwrap(), + ) + .unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_oxible")) + .current_dir(directory.path()) + .env("PATH", "") + .args(["tasks/main.yml", "--offline", "--no-cache", "-f", "json"]) + .output() + .unwrap(); + let issues: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(issues, case["reference"]["issues"], "{}", case["case"]); + assert_eq!( + output.status.code().map(i64::from), + case["reference"]["exit"].as_i64(), + "{}", + case["case"] + ); + } +} From ce64d82f400f4291b8315f732881ee64779ce89c Mon Sep 17 00:00:00 2001 From: dmillzilla <37204972+dmillzilla@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:41:44 -0600 Subject: [PATCH 2/2] Keep conditional pipefail text from suppressing pipeline checks --- src/extra_rules.rs | 2 +- tests/shell_pipelines.rs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/extra_rules.rs b/src/extra_rules.rs index 3cf683a..6e512de 100644 --- a/src/extra_rules.rs +++ b/src/extra_rules.rs @@ -462,7 +462,7 @@ fn has_pipefail(text: &str) -> bool { } else if quote.is_none() && matches!(ch, '\'' | '"') { quote = Some(ch); statement.push(ch); - } else if quote.is_none() && matches!(ch, ';' | '\n' | '&' | '|') { + } else if quote.is_none() && matches!(ch, ';' | '\n') { if enabled(&statement) { return true; } diff --git a/tests/shell_pipelines.rs b/tests/shell_pipelines.rs index beb630d..fe7143c 100644 --- a/tests/shell_pipelines.rs +++ b/tests/shell_pipelines.rs @@ -18,6 +18,11 @@ fn templated_shell_pipelines_match_reference_issues_and_exits() { "echo ready # ; set -o pipefail\nfalse | true", true, ), + ( + "conditional-pipefail", + "true || set -o pipefail; false | true", + true, + ), ("plain-pipeline", "printf ready | cat", true), ("templated-argument", "echo {{ value }} | cat", true), ("templated-filter", "echo {{ value | quote }} | cat", true),