Last active
December 4, 2019 14:26
-
-
Save DoremyR3d/59c2d8dfb04db2ff66b6bc3c5d64ac6a to your computer and use it in GitHub Desktop.
jdiff sorter
This file contains 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
import json | |
import os | |
import collections | |
import argparse | |
def init_argparser(): | |
parser = argparse.ArgumentParser(description="A tool that sorts keys in jdiffs") | |
parser.add_argument("sourcepath", help="The path where the jdiff(s) to sort is/are") | |
parser.add_argument("targetpath", help="The path to the file/dir where the script will write") | |
parser.add_argument("-d", help="Marks the path as 'folders' and not 'files'", action='store_true', | |
default=False) | |
parser.add_argument("-r", help="If used with -d, it asks to look for jdiffs in child folders, too", | |
action='store_true', default=False) | |
return vars(parser.parse_args()) | |
def load_sort_and_dump(sourcepath, targetpath): | |
with open(sourcepath) as jdiff: | |
x = json.load(jdiff) | |
ox = collections.OrderedDict(sorted(x.items())) | |
targetdict = collections.OrderedDict() | |
for _key, _value in ox.items(): | |
_ovalue = collections.OrderedDict(sorted(_value.items(), key=lambda tupple: int(tupple[0].split("_")[0]))) | |
targetdict[_key] = _ovalue | |
with open(targetpath, mode="w", encoding='utf-8', newline='\n') as out: | |
json.dump(targetdict, out, indent=4) | |
def walk_in_sourcepath(rootpath, targetpath, recursive): | |
if not os.path.exists(rootpath): | |
print(f"I'm in {rootpath}") | |
print(f"{rootpath} doesn't exist!") | |
exit(22) | |
if not os.path.exists(targetpath): | |
os.makedirs(targetpath) | |
for root, subdirs, files in os.walk(rootpath): | |
for jdiff_file in [f for f in files if f.endswith("jdiff")]: | |
load_sort_and_dump(os.path.join(root, jdiff_file), os.path.join(targetpath, jdiff_file)) | |
if not recursive: | |
break | |
pass | |
if __name__ == '__main__': | |
argv = init_argparser() | |
if not argv["d"]: | |
load_sort_and_dump(argv["sourcepath"], argv["targetpath"]) | |
else: | |
walk_in_sourcepath(argv["sourcepath"], argv["targetpath"], argv["r"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment