-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort_keys.py
executable file
·168 lines (154 loc) · 6.53 KB
/
sort_keys.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env python3.6
import sys
from collections import Counter
def remove_duplicates(val):
output = []
seen = set()
for j in val:
if j not in seen:
output.append(j)
seen.add(j)
return output
def sort_keys(fname):
lst = []
full = fname.split('.')
fname = full[0]
ext = '.' + full[-1] if len(full) > 1 else ''
try:
with open(fname + ext) as f:
seen = set()
for idx, line in enumerate(f):
if line and line != '\n' and line not in seen:
try:
if line.split('| ')[1][:3] == 'DLC':
lst.append((f'z{line.split("| ")[1]}', line))
else:
lst.append((line.split('| ')[1], line))
if not all(len(i) == 5 for i in line.split(' |')[0].split('-'))\
or len(line.split(' |')[0]) != 17:
if line.split('|')[1]:
print(f'Malformed key-name pair on line {idx + 1}: {line[:-1]}')
else:
print(f'Malformed key on line {idx + 1}: {line.split("| ")[1]}')
except IndexError:
print(f'Missing name on line {idx + 1}: {line[:-3]}')
seen.add(line)
sorted_lst = sorted(lst, key=lambda k: k[0])
with open(f'{fname}_sorted{ext}', 'w') as f_s:
for i in sorted_lst:
f_s.write(f'{i[1]}')
# Pulls together multiple keys for the same game
rem = iter(remove_duplicates(sorted_lst))
counter = Counter(i[0][1:] if i[0][:4] == 'zDLC'
else i[0] for i in remove_duplicates(sorted_lst))
with open(f'{fname}_list{ext}', 'w') as f_l:
for i in rem:
name = i[0][1:] if i[0][:4] == 'zDLC' else i[0]
if counter.get(name) == 1:
f_l.write(f'{name}')
else:
f_l.write(f'{name[:-1]} * {counter.get(name)}\n')
for j in range(1, counter.get(name)):
next(rem)
f_l.write(f'\nTotal keys: {len(sorted_lst)}\n')
except FileNotFoundError:
print(f'{fname} does not exist.')
except IsADirectoryError:
print(f'{fname} is a directory.')
except PermissionError:
print(f'You do not have rights to {fname}.')
def add_keys(fname, lst):
# Joins args by spaces, then splits by commas. This allows for something similar to a CSV from a list.
lst = [f"{i.split(' ')[0]} | {' '.join(i.split(' ')[1:])}\n" for i in ' '.join(lst).split(', ')]
try:
with open(fname, 'a+') as f:
f.writelines(lst)
except FileNotFoundError:
print(f'{fname} does not exist.')
except IsADirectoryError:
print(f'{fname} is a directory.')
except PermissionError:
print(f'You do not have rights to {fname}.')
def pop_keys(fname, lst):
lst = ' '.join(lst).split(', ')
try:
with open(fname, 'r') as f_l:
lines = f_l.read().splitlines()
with open(fname, 'w') as f:
print('Analysis complete:')
skip = [None] * len(lines)
for key in lst:
for idx, line in enumerate(lines):
if skip[idx]:
continue
tem = line.split(' | ')
try:
if tem[0] == key:
print(line)
lines.remove(line)
break # Only deletes the first instance
elif tem[1] == key:
print(line)
lines.remove(line)
break # Only deletes the first instance
except IndexError:
skip[idx] = True
lines = [line + '\n' for line in lines]
f.writelines(lines)
except FileNotFoundError:
print(f'{fname} does not exist.')
except IsADirectoryError:
print(f'{fname} is a directory.')
except PermissionError:
print(f'You do not have rights to {fname}.')
if __name__ == '__main__':
try:
cmd = sys.argv[1]
except IndexError:
cmd = None
if cmd == 'add':
try:
add_keys(sys.argv[2], sys.argv[3:])
except IndexError:
print(f'Usage: {sys.argv[0]} add [file] [keys]\n'
'\nwhere keys is a comma separated list of Steam keys'
'\nin the format `XXXXX-XXXXX-XXXXX name`.'
'\nPrepend `name` with \'DLC: \' if it is addon content.')
else:
sort_keys(sys.argv[2])
elif cmd == 'sort':
try:
x = sys.argv[2]
except IndexError:
print(f'Usage: {sys.argv[0]} sort [file]')
else:
sort_keys(x)
elif cmd == 'pop':
try:
x = (sys.argv[2], sys.argv[3:])
except IndexError:
print(f'Usage: {sys.argv[0]} pop [file] [keys]\n\n`keys` can be names or keys.')
else:
pop_keys(*x)
print('List has been sorted.')
sort_keys(x[0])
elif cmd == 'help':
print('\n'.join(
[f'sort: {sys.argv[0]} sort <file>',
'Exactly as it says on the tin: Sorts the keys alphabetically by game name.',
'Creates and writes to the files [filename]_list[.ext]',
'and [filename]_sorted[.ext] (yes, it preserves your file extension!)',
f'add: {sys.argv[0]} add <file> <keys>',
'`keys` must be in the format `key name, key name, key name`,',
'i.e. `XXXXX-YYYYY-ZZZZZ xyz, 12345-67891-01112 123`.',
'This will append the keys and name to the end of',
'your source file and then resort your keys - don\'t worry about duplicates,',
'the sorting algorithm handles them for you.',
f'pop: {sys.argv[0]} pop <file> <keys>',
'`keys` can be any comma-delimited list of keys and names (although not both!),',
'i.e. `XXXXX-YYYYY-ZZZZZ, 123` would \'pop\' (remove and print) the key-name pairs',
'added in `add`s example. Note that this is a destructive command,',
'and that it should be used with care in order to avoid losing your keys!']))
else:
print(f'Usage: {sys.argv[0]} sort|add|pop {{key(s)}}'
f'\n{sys.argv[0]} help for more information')