Skip to content

Commit

Permalink
preserve ansible # jinja2 header
Browse files Browse the repository at this point in the history
  • Loading branch information
nbari committed Oct 12, 2023
1 parent 6feecd3 commit 58be8eb
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Expand Up @@ -69,7 +69,7 @@ source-includes = ["tests/"]
[tool.pdm.build]
editable-backend = "path"

[tool.pdm.overrides]
[tool.pdm.resolution.overrides]

# To be removed once https://github.com/flakeheaven/flakeheaven/issues/132 is solved
"importlib-metadata" = ">=3.10"
Expand Down
9 changes: 8 additions & 1 deletion src/yamlfix/services.py
Expand Up @@ -149,9 +149,16 @@ def fix_code(source_code: str, config: Optional[YamlfixConfig] = None) -> str:
else:
shebang = ""

if source_code.startswith("#jinja2:") or source_code.startswith("# jinja2:"):
eolpos = source_code.find("\n") + 1
jinja2 = source_code[:eolpos]
source_code = source_code[eolpos:]
else:
jinja2 = ""

yaml = Yaml(config=config)
fixer = SourceCodeFixer(yaml=yaml, config=config)

source_code = fixer.fix(source_code=source_code)

return shebang + source_code
return jinja2 + shebang + source_code
14 changes: 14 additions & 0 deletions tests/unit/test_services.py
Expand Up @@ -74,6 +74,20 @@ def test_fix_files_issues_warning(self, tmp_path: Path) -> None:
class TestFixCode:
"""Test the fix_code function."""

def test_fix_code_ignore_jinja2(self) -> None:
"""Ignores jinja2 line if present at the beginning of the source."""
source = dedent(
"""\
# jinja2:lstrip_blocks: true
---
program: yamlfix
"""
)

result = fix_code(source)

assert result == source

def test_fix_code_ignore_shebang(self) -> None:
"""Ignores shebang lines if present at the beginning of the source."""
source = dedent(
Expand Down

0 comments on commit 58be8eb

Please sign in to comment.