Skip to content

Commit

Permalink
GHA: add salty linter
Browse files Browse the repository at this point in the history
  • Loading branch information
saltydk committed Feb 3, 2024
1 parent 36e9b42 commit c234934
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/saltbox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ jobs:
- name: Run ansible linter
run: ansible-lint

- name: Run salty linter
run: python3 ./scripts/salty-linter.py ./roles

add-contributors:
runs-on: ubuntu-22.04
if: github.ref == 'refs/heads/master'
Expand Down
61 changes: 61 additions & 0 deletions scripts/salty-linter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import os
import sys

def lint_ansible_defaults(content, file_path):
errors = []
lines = content.split('\n')

multi_line_jinja_start = None
within_multi_line_jinja = False

for line_no, line in enumerate(lines, start=1):
stripped_line = line.strip()

if stripped_line == '---':
continue

if '{{' in stripped_line and not within_multi_line_jinja:
multi_line_jinja_start = line.find('{{')
within_multi_line_jinja = '}}' not in stripped_line

elif within_multi_line_jinja:
if 'if' in stripped_line or 'else' in stripped_line:
if line.find('if') < multi_line_jinja_start and line.find('else') < multi_line_jinja_start:
message = f"'if/else' within Jinja expression should align with the start."
errors.append((line_no, message))

if '}}' in stripped_line:
within_multi_line_jinja = False

if '}}' in stripped_line and within_multi_line_jinja:
within_multi_line_jinja = False

for error in errors:
line_no, message = error
print(f"::warning file={file_path},line={line_no},endLine={line_no},title=Salty Lint Error::{message}")

return len(errors) > 0

def crawl_and_lint_ansible_roles(roles_dir):
errors_found = False

if not os.path.exists(roles_dir):
print("Roles directory does not exist.")
return

for role_name in os.listdir(roles_dir):
defaults_main_path = os.path.join(roles_dir, role_name, "defaults", "main.yml")
if os.path.isfile(defaults_main_path):
with open(defaults_main_path, 'r') as file:
content = file.read()
if lint_ansible_defaults(content, defaults_main_path):
errors_found = True

sys.exit(1 if errors_found else 0)

if len(sys.argv) < 2:
print("Usage: python script.py /path/to/your/ansible/roles")
sys.exit(1)

roles_directory_path = sys.argv[1]
crawl_and_lint_ansible_roles(roles_directory_path)

0 comments on commit c234934

Please sign in to comment.