Last active
December 11, 2024 14:05
-
-
Save patrickallaert/4ec249bd0ad5bfad7a01f0f1983566ca to your computer and use it in GitHub Desktop.
Sort translation yaml file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import yaml | |
import sys | |
class PreserveLoader(yaml.SafeLoader): | |
pass | |
# Remove all boolean resolvers to prevent conversion of "Yes", "No", etc. | |
PreserveLoader.yaml_implicit_resolvers = { | |
key: [(tag, regexp) for tag, regexp in resolvers if tag != 'tag:yaml.org,2002:bool'] | |
for key, resolvers in PreserveLoader.yaml_implicit_resolvers.items() | |
} | |
class QuotingDumper(yaml.SafeDumper): | |
def represent_scalar(self, tag, value, style=None): | |
if isinstance(value, str) and (':' in value or '\n' in value or value.strip() != value): | |
style = '"' | |
return super().represent_scalar(tag, value, style) | |
def increase_indent(self, flow=False, indentless=False): | |
return super(QuotingDumper, self).increase_indent(flow, False) | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print("Usage: sort-yaml <file_name.yaml>") | |
sys.exit(1) | |
try: | |
file_path = sys.argv[1] | |
with open(file_path, 'r') as file: | |
data = yaml.load(file, Loader=PreserveLoader) | |
if not isinstance(data, dict): | |
raise ValueError("The YAML file must contain a dictionary at the root level.") | |
with open(file_path, 'w') as file: | |
yaml.dump( | |
{k: data[k] for k in sorted(data.keys(), key=lambda x: str(x).lower())}, | |
file, | |
Dumper=QuotingDumper, | |
allow_unicode=True, | |
sort_keys=False, | |
width=float("inf"), | |
default_style=None, | |
) | |
except Exception as e: | |
print(f"Error: {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment