- Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsort-redir.py
59 lines (48 loc) · 2 KB
/
sort-redir.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Python 3 script to sort .openpublishing.redirection.json by any of the fields
# Requires a Python 3 installation on your computer, see https://www.python.org/downloads
#
# Usage:
# python sort-redir.py <options>
#
# Options:
# -i <inputfile> specifies the input file; default is .openpublishing.redirection.json
# -o <outputfile> specifies the output file: default is .openpublishing.redirection.sorted.json
# -s <sortfield> specifies the name of the field to sort by; default is source_path. Can also use redirect_url
importsys
importgetopt
importjson
defmain(argv):
# Arg defaults
in_file='.openpublishing.redirection.json'
out_file='.openpublishing.redirection.sorted.json'
sort_field='source_path'
usage_string='python sort-redir.py [-i <inputfile>] [-o <outputfile>] [-s <sortfield>] [-h] [-?]'
# Process arguments if provided
try:
opts, args=getopt.getopt(argv, "i:o:s:h?") #, ["inputfile=", "outputfile=", "sortfield="]
exceptgetopt.GetoptError:
print(usage_string)
sys.exit(2)
foropt, arginopts:
ifopt=='-h'oropt=='-?':
print(usage_string)
sys.exit()
elifoptin ("-i", "--inputfile"):
in_file=arg
elifoptin ("-o", "--outputfile"):
out_file=arg
elifoptin ("-s", "--sortfield"):
sort_field=arg
print('Sorting', in_file, 'by', sort_field, 'into', out_file)
withopen(in_file) asfile:
data=json.load(file)
# The redirections object within the json
redirects=data['redirections']
# Do the sorting and stuff the array back into the original json object
data_sorted=sorted(redirects, key=lambdaredirect: redirect[sort_field])
data['redirections'] =data_sorted
withopen(out_file, 'w') asoutfile:
json.dump(data, outfile, indent=4)
if__name__=="__main__":
# Give main all args except the .py filename
main(sys.argv[1:])