-
Notifications
You must be signed in to change notification settings - Fork 0
/
dot-pyson.py
executable file
·325 lines (277 loc) · 8.49 KB
/
dot-pyson.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/python3
import sys
import os
import readline
import glob
import shlex
from config import trace
import config
__command_actions = {}
__file_actions = []
__key_actions = []
__prompt = ">>>"
__sort = True
__last_viewed = ""
__time_to_go = False
def command(name):
def command_decorator(function):
__command_actions[name] = function
return function
return command_decorator
def file_command(name):
def command_decorator(function):
__command_actions[name] = function
__file_actions.append(name)
return function
return command_decorator
def key_command(name):
def command_decorator(function):
__command_actions[name] = function
__key_actions.append(name)
return function
return command_decorator
def main():
global __prompt
global __time_to_go
print("JSON configuration utility version (1.0.0)")
handle_arguments()
readline.set_completer_delims("\t\n")
readline.parse_and_bind("tab: complete")
readline.set_completer(auto_complete)
command = ""
while True:
try:
user_input = input(__prompt + " ").strip()
except KeyboardInterrupt:
print()
if __time_to_go:
exit_command()
else:
__time_to_go = True
print("Press ^C again to close. Running another command resets this.")
continue
if not user_input:
continue
run_command(user_input)
__time_to_go = False
@trace
def auto_complete(text, state):
for command in __file_actions:
command += " "
if text.startswith(command):
return ([command + path for path in glob.glob(text.replace(command, "")+"*")]+[None])[state]
for command in __key_actions:
command += " "
if text.startswith(command):
key_info = text.partition(" ")[2].rpartition(".")
return ([command + key_info[0] + key_info[1] + key
for key
in config.keys_at(key_info[0])
if key.startswith(key_info[2])]+[None])[state]
return ([command for command in __command_actions.keys() if command.startswith(text)]+[None])[state]
@trace
def run_command(command_line):
command_line = command_line.split(" ")
command = command_line[0]
arguments = shlex.split(" ".join(command_line[1:]))
if command in __command_actions:
try:
__command_actions[command](*arguments)
except TypeError as error:
print("An incorrect number of arguments were supplied.")
help_command(command)
else:
print("Unrecognized command")
@trace
def handle_arguments():
global __prompt
global __sort
# No arguments.
if len(sys.argv) < 2:
return
index = 1
# Go while there are two values left
while index < len(sys.argv):
flag = sys.argv[index]
index += 1
# Check flags that require no arguments
if flag[0] != "-":
try:
run_command("load " + flag)
except:
print("Error loading file, exiting.")
exit_command()
continue
if flag == "--unsorted":
__sort = False
continue
if flag == "--debug":
config.debug = True
continue
if index == len(sys.argv):
break
argument = sys.argv[index]
index += 1
if flag == "-p" or flag == "--prompt":
__prompt = argument
elif flag == "-c" or flag == "--command":
run_command(argument)
@command("quit")
@command("exit")
@trace
def exit_command():
"""
exit
quit Exits the program."""
print("Goodbye")
quit()
@command("help")
@trace
def help_command(command=None):
"""
help Displays help for a command if it is given or for all commands otherwise.
Usage: help [COMMAND]"""
if not command:
for command_doc in sorted_documentation():
print(command_doc)
return
if command in __command_actions:
print(__command_actions[command].__doc__)
else:
print("Unrecognized command. Please type 'help' to see the help for all commands.")
@trace
def sorted_documentation():
return [sorted_function.__doc__ for sorted_function in sorted({command_function for command_function in __command_actions.values()}, key=lambda f: f.__name__)]
@key_command("print")
@key_command("cat")
@key_command("view")
@trace
def view_command(property_path=None):
"""
print
cat
view Displays the loaded JSON document, if there is one. Otherwise does
nothing. You can give it a property path to view a smaller part of
the document.
Usage: print [PROPERTY]"""
global __last_viewed
__last_viewed = property_path
print(config.to_string(property_path))
@file_command("open")
@file_command("load")
@trace
def load_command(file_path):
"""
open
load Opens a new file and loads it's contents into memory, where it can
be worked with.
Usage: load FILE"""
config.load(file_path, __sort)
@command("pwd")
@command("cwd")
@trace
def cwd_command():
"""
pwd
cwd Shows the present working directory. Paths to files are relative
to this path.
Usage: pwd"""
print(os.getcwd())
@file_command("cd")
@trace
def cd_command(path):
"""
cd Changes the present working directory.
Usage: cd PATH"""
os.chdir(path)
@key_command("keys")
@key_command("ls")
@trace
def keys_command(property_path=None):
"""
ls
keys Displays all the keys at a given path. If no property path is
given then all the keys at the top level of the document will
be displayed.
Usage: keys [PROPERTY]"""
keys = config.keys_at(property_path)
for key in sorted(keys):
print("{0:.<70}{1:.>10}".format(key, keys[key]))
@key_command("edit")
@key_command("set")
@trace
def set_command(property_path, value):
"""
edit
set Requires a key path and a value. Will set the value at the
key path to the supplied value. This operation will create the
property path if it doesn't already exist.
To set a value to be an object, you must surround the keys
with quotes. Embed quotes in your value with \".
Usage: set PROPERTY VALUE"""
config.set_property(property_path, value)
@key_command("del")
@key_command("rm")
@trace
def delete_command(property_path):
"""
del
rm Remove a property from the JSON path. Use "write" to save the
change.
Usage: rm PROPERTY"""
config.remove_property(property_path)
@command("last")
@command("view-last")
@command("print-last")
@trace
def view_last_command():
"""
last
view-last
print-last View the last property printed.
Usage: last"""
global __last_viewed
print((__last_viewed + ": " if __last_viewed else "") + config.to_string(__last_viewed))
@command("edit-last")
@command("set-last")
@trace
def set_last_command(property_path, value=None):
"""
edit-last
set-last Set the value at the last property that was printed. If a
property is given too, it will be added as a property of the
last printed item.
Usage: set-last [PROPERTY] VALUE"""
# For now, if you only send one value, it is the value.
# I can't keyword call this since I'm calling it dynamically.
if not value:
value = property_path
property_path = ""
else:
property_path = "." + property_path
config.set_property(__last_viewed + property_path, value)
@command("del-last")
@command("rm-last")
@trace
def delete_last_command():
"""
del-last
rm-last Delete the last property that was printed.
Usage: rm-last"""
global __last_viewed
if not __last_viewed:
print("Last viewed is the top level, cannot delete.")
return
config.remove_property(__last_viewed)
__last_viewed = None
@file_command("write")
@file_command("save")
@trace
def save_command(file_path):
"""
write
save Writes the changes to the document back to disk.
Usage: save"""
config.save(file_path)
if __name__ == "__main__":
main()