From c8f47f0fa824fcfce6c107d151cbdafce9edab7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fl=C3=A1vio=20Faria?= Date: Mon, 2 Jun 2025 16:26:13 -0400 Subject: [PATCH] feat: sort top-level nodes of YAML files --- .pre-commit-hooks.yaml | 6 ++++++ hooks/yaml/yaml-sort.sh | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100755 hooks/yaml/yaml-sort.sh diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 7efb3f6..5d2c6ee 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -87,6 +87,12 @@ entry: hooks/yaml/yaml-extension.sh language: script files: \.yml$ +- id: yaml-sort + name: "yaml-sort: Style formatting" + description: "Ensure top-level nodes are sorted in YAML files" + entry: hooks/yaml/yaml-sort.sh + language: script + files: \.yaml$ ###################### # Yalc related hook - id: yalc-check diff --git a/hooks/yaml/yaml-sort.sh b/hooks/yaml/yaml-sort.sh new file mode 100755 index 0000000..0c68ed1 --- /dev/null +++ b/hooks/yaml/yaml-sort.sh @@ -0,0 +1,36 @@ +#!/bin/bash + +set -e + +yaml_file="$1" + +main() { + if [[ ! -f "$yaml_file" ]]; then + echo "Error: $yaml_file not found" + exit 1 + fi + if ! command -v yq &> /dev/null; then + echo "Error: yq is required but not installed" + echo "Install with: brew install yq" + exit 1 + fi + + temp_file=$(mktemp) + + yq eval 'sort_keys(.)' "$yaml_file" > "$temp_file" + + if [[ $? -eq 0 ]]; then + mv "$temp_file" "$yaml_file" + echo "Sorted top-level keys in $yaml_file." + git add "$yaml_file" + exit 0 + else + echo "Error: Failed to sort YAML file" + rm -f "$temp_file" + exit 1 + fi +} + +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + main "$@" +fi