Skip to content

Commit 50f7d5d

Browse files
committed
Add pre-commit to sort yml files
1 parent 2b089bc commit 50f7d5d

File tree

2 files changed

+119
-0
lines changed

2 files changed

+119
-0
lines changed

.pre-commit-config.yaml

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
---
18+
default_stages: [pre-commit]
19+
default_language_version:
20+
python: python3
21+
minimum_pre_commit_version: '3.2.0'
22+
repos:
23+
- repo: local
24+
hooks:
25+
- id: sort-actions-yml
26+
name: Sort actions.yml
27+
entry: ./scripts/sort_yml.py
28+
language: python
29+
additional_dependencies: ['rich>=12.4.4', 'ruamel.yaml']
30+
require_serial: true
31+
files: ^actions\.yml$

scripts/sort_yml.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#!/usr/bin/env python3
2+
# Licensed to the Apache Software Foundation (ASF) under one
3+
# or more contributor license agreements. See the NOTICE file
4+
# distributed with this work for additional information
5+
# regarding copyright ownership. The ASF licenses this file
6+
# to you under the Apache License, Version 2.0 (the
7+
# "License"); you may not use this file except in compliance
8+
# with the License. You may obtain a copy of the License at
9+
#
10+
# http://www.apache.org/licenses/LICENSE-2.0
11+
#
12+
# Unless required by applicable law or agreed to in writing,
13+
# software distributed under the License is distributed on an
14+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
# KIND, either express or implied. See the License for the
16+
# specific language governing permissions and limitations
17+
# under the License.
18+
#
19+
# /// script
20+
# requires-python = ">=3.11"
21+
# dependencies = [
22+
# "rich",
23+
# "ruamel.yaml",
24+
# ]
25+
# ///
26+
27+
from ruamel.yaml import YAML
28+
from ruamel.yaml.comments import CommentedMap
29+
import sys
30+
from pathlib import Path
31+
from rich.console import Console
32+
33+
console = Console(width=400, color_system="standard")
34+
35+
36+
def sort_yaml_file(input_file: str):
37+
"""Sorts the keys of a YAML file in alphabetical order"""
38+
39+
yaml = YAML()
40+
yaml.preserve_quotes = True
41+
42+
input_path = Path(input_file)
43+
44+
if not input_path.exists():
45+
raise FileNotFoundError(f"File '{input_file}' not found.")
46+
47+
with open(input_path, 'r', encoding='utf-8') as f:
48+
data = yaml.load(f)
49+
50+
sorted_data = CommentedMap()
51+
52+
sorted_keys: list[str] = sorted(data.keys(), key=str.lower)
53+
54+
# Copy data in sorted order
55+
for key in sorted_keys:
56+
sorted_data[key] = data[key]
57+
58+
# Preserve any comment at the beginning of the file
59+
if hasattr(data, 'ca') and hasattr(data.ca, 'comment'):
60+
if not hasattr(sorted_data, 'ca'):
61+
sorted_data.ca = data.ca.__class__()
62+
sorted_data.ca.comment = data.ca.comment
63+
64+
with open(input_path, 'w', encoding='utf-8') as f:
65+
yaml.dump(sorted_data, f)
66+
67+
68+
errors = []
69+
def main():
70+
files = sys.argv[1:]
71+
for file in files:
72+
console.print(f"[blue]Sorting YAML file {file}")
73+
try:
74+
sort_yaml_file(file)
75+
console.print(f"[blue]✅ YAML file sorted successfully {file}!")
76+
except FileNotFoundError as e:
77+
errors.append((file, str(e)))
78+
except Exception as e:
79+
errors.append((file, str(e)))
80+
81+
if errors:
82+
console.print("[red]Errors occurred while sorting YAML files:")
83+
for file, error in errors:
84+
console.print(f"[red]File: {file} - Error: {error}")
85+
sys.exit(1)
86+
87+
if __name__ == "__main__":
88+
main()

0 commit comments

Comments
 (0)