#!/usr/bin/env python3 import os import sys import subprocess import argparse from pathlib import Path # Import helper functions sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)))) from helpers.functions import printfe, ensure_dependencies, command_exists DOTFILES_ROOT = os.path.expanduser("~/.dotfiles") def lint_ansible(fix=False): """Run ansible-lint on Ansible files""" ansible_dir = os.path.join(DOTFILES_ROOT, "config/ansible") if not os.path.isdir(ansible_dir): printfe("yellow", "No ansible directory found at config/ansible") return 0 # Find all YAML files in the ansible directory yaml_files = [] for ext in [".yml", ".yaml"]: yaml_files.extend(list(Path(ansible_dir).glob(f"**/*{ext}"))) if not yaml_files: printfe("yellow", "No Ansible files found in config/ansible to lint") return 0 if not command_exists("ansible-lint"): printfe("red", "ansible-lint is not installed. Please install it with pip or your package manager.") return 1 printfe("blue", f"Running ansible-lint{' with auto-fix' if fix else ''}...") files_to_lint = [str(f) for f in yaml_files] command = ["ansible-lint"] if fix: command.append("--fix") command.extend(files_to_lint) result = subprocess.run(command) return result.returncode def lint_nix(): """Run nixfmt on Nix files""" nix_files = list(Path(DOTFILES_ROOT).glob("**/*.nix")) if not nix_files: printfe("yellow", "No Nix files found to lint") return 0 if not command_exists("nixfmt"): printfe("red", "nixfmt is not installed. Please install it with nix-env or your package manager.") return 1 printfe("blue", "Running nixfmt...") exit_code = 0 for nix_file in nix_files: printfe("cyan", f"Formatting {nix_file}") result = subprocess.run(["nixfmt", str(nix_file)]) if result.returncode != 0: exit_code = 1 return exit_code def main(): parser = argparse.ArgumentParser(description="Run linters on dotfiles") parser.add_argument("--ansible", action="store_true", help="Run only ansible-lint") parser.add_argument("--nix", action="store_true", help="Run only nixfmt") parser.add_argument("--fix", action="store_true", help="Auto-fix issues where possible (for ansible-lint)") args = parser.parse_args() # If no specific linter is specified, run both run_ansible = args.ansible or not (args.ansible or args.nix) run_nix = args.nix or not (args.ansible or args.nix) exit_code = 0 if run_ansible: ansible_result = lint_ansible(fix=args.fix) if ansible_result != 0: exit_code = ansible_result if run_nix: nix_result = lint_nix() if nix_result != 0: exit_code = nix_result return exit_code if __name__ == "__main__": sys.exit(main())