Fix secret word check and format code

This commit is contained in:
2025-08-01 14:04:20 +03:00
parent b9f41bbda8
commit 6caeb998c4

View File

@@ -2,7 +2,7 @@
"""
Pre-commit hook to prevent committing secret files that are not encrypted with Ansible Vault.
This hook checks if any staged files contain 'secret' or 'secrets' in their filename.
This hook checks if any staged files contain 'secret' or 'secrets' word in their filename.
If such files are found and they don't start with '$ANSIBLE_VAULT', the commit is blocked.
"""
@@ -11,19 +11,19 @@ import subprocess
import os
ANSIBLE_VAULT_MARKER = '$ANSIBLE_VAULT'
ANSIBLE_VAULT_MARKER = "$ANSIBLE_VAULT"
def get_staged_files():
"""Get list of staged files for commit."""
try:
result = subprocess.run(
['git', 'diff', '--cached', '--name-only'],
["git", "diff", "--cached", "--name-only"],
capture_output=True,
text=True,
check=True
check=True,
)
return result.stdout.strip().split('\n') if result.stdout.strip() else []
return result.stdout.strip().split("\n") if result.stdout.strip() else []
except subprocess.CalledProcessError as e:
print(f"Error getting staged files: {e}")
return []
@@ -32,7 +32,8 @@ def get_staged_files():
def has_secret_in_name(filename):
"""Check if filename contains 'secret' or 'secrets'."""
basename = os.path.basename(filename).lower()
return 'secret' in basename or 'secrets' in basename
words = basename.split(".")
return "secret" in words or "secrets" in words
def is_ansible_vault_file(filepath):
@@ -41,7 +42,7 @@ def is_ansible_vault_file(filepath):
if not os.path.exists(filepath):
return False
with open(filepath, 'r', encoding='utf-8') as f:
with open(filepath, "r", encoding="utf-8") as f:
first_line = f.readline().strip()
return first_line.startswith(ANSIBLE_VAULT_MARKER)
except (IOError, UnicodeDecodeError):
@@ -65,7 +66,7 @@ def main():
if violations:
print("❌ COMMIT BLOCKED: Secret files must be encrypted with Ansible Vault!")
print("\nThe following files contain 'secret' or 'secrets' in their name")
print("\nThe following files contain 'secret' or 'secrets' word in their name")
print("but are not encrypted with Ansible Vault:")
print()
@@ -84,5 +85,5 @@ def main():
return 0
if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main())