Created
April 29, 2019 05:36
-
-
Save xeptore/4877351ae8972b1859d5ca35e6db8bbc to your computer and use it in GitHub Desktop.
ASP .NET Core using statements sort git precommit hook
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/python3.7 | |
import subprocess | |
import re | |
from collections import defaultdict | |
stagedFiles = subprocess.run(["git", "diff", "--cached", "--name-only", "--diff-filter=ACM"], capture_output=True, text=True).stdout.strip().split("\n") | |
def sortLines(lines): | |
d = defaultdict(list) | |
zipped = [(x[6:x.index(".")], x) for x in lines] | |
[d[k].append(v) for (k, v) in zipped] | |
for (k, v) in d.items(): | |
v.sort(key=lambda x: len(x), reverse=True) | |
return [item for (k, v) in sorted(d.items(), key=lambda i: i[0]) for item in v] | |
prog = re.compile(r"^using .*;$", re.MULTILINE) | |
exitCode = 0 | |
changedFiles = list() | |
for stagedFile in stagedFiles: | |
rf = "" | |
with open(stagedFile, "r") as file: | |
readfile = file.read() | |
usingLines = prog.findall(readfile) | |
usingLinesCopy = usingLines.copy() | |
sortedUsingLines = sortLines(usingLines) | |
if usingLinesCopy == sortedUsingLines: | |
continue | |
exitCode = 1 | |
newUsings = "\n".join(sortedUsingLines) | |
rf = newUsings + "\n" + "\n".join(readfile.split("\n")[len(sortedUsingLines):]) | |
file.close() | |
with open(stagedFile, "w") as wfile: | |
wfile.write(rf) | |
changedFiles.append(stagedFile) | |
wfile.close() | |
for cf in changedFiles: | |
print(" => File Changed:", cf) | |
exit(exitCode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment