Skip to content

Instantly share code, notes, and snippets.

@DaniPopes
Created April 10, 2024 14:55
Show Gist options
  • Save DaniPopes/080ea7e2c3bb34820fed66cba640671d to your computer and use it in GitHub Desktop.
Save DaniPopes/080ea7e2c3bb34820fed66cba640671d to your computer and use it in GitHub Desktop.
Sort Rust `#[derive(...)]` macros
#!/usr/bin/env python3
import re
import sys
ORDER = [
"Clone",
"Copy",
"Debug",
"Default",
"PartialEq",
"Eq",
"PartialOrd",
"Ord",
"Hash",
"Serialize",
"Deserialize",
]
def main():
derive_regex = re.compile(
r"#[\s\n]*\[[\s\n]*derive[\s\n]*\((.*?)\)[\s\n]*\]", re.DOTALL
)
files = sys.argv[1:]
for file in files:
with open(file, "r") as f:
s = f.read()
s = derive_regex.sub(derive_replacer, s)
with open(file, "w") as f:
f.write(s)
pass
def derive_replacer(match: re.Match[str]):
args = match.group(1)
derives = args.split(",")
derives = map(lambda s: s.strip(), derives)
derives = filter(lambda s: s != "", derives)
derives = sorted(derives, key=derive_key)
derives = ", ".join(derives)
return f"#[derive({derives})]"
def derive_key(derive: str):
try:
return ORDER.index(derive)
except ValueError:
return float("inf")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment