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