-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsole.py
executable file
·285 lines (244 loc) · 9.54 KB
/
console.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
#!/usr/bin/python3
"""Module defines custom command line interpreter HBNB"""
import cmd
from models.engine.file_storage import FileStorage
import models
import re
import json
class HBNBCommand(cmd.Cmd):
"""define internals of a HBNBCommand instance"""
prompt = "(hbnb) "
# model_classes = MODEL_CLASSES
def do_quit(self, cmd_arg):
return True
def help_quit(self):
print("Quit command to exit the program\n")
def do_EOF(self, cmd_arg):
print()
return True
def help_EOF(self):
print("Exit the interpreter")
print("You can also use the ctrl-D shortcut.")
def emptyline(self):
pass
def parse_cmd(self, cmd_arg):
print("before arg_list: {}".format(cmd_arg))
arg_list = cmd_arg.split()
print("from arg_list: {}".format(arg_list))
arg_count = len(arg_list)
return arg_list, arg_count
def precmd(self, line):
"""Hook method executed just before the command line is interpreted,
but after the input prompt is generated and issued."""
# regex to check if line matches string.string() and then split
m = re.match(r'([A-Za-z]+\.[a-z]+?)[(](.*)[)]', line)
if m and m.group(2):
# before processing the line, check if it contains a curly bracket
# with a bunch of things inside it
# if yes then use a different method to parse the arguments
# if input is of form
# <model>.<cmd>([<"id">[,[att_name, att_value | {key: value}]]])
line_str = m.group(1)
arg = m.group(2)
# print("from precmd: {}".format(line_str))
model_cls, cmd = line_str.split(".")
line_start = cmd + " " + model_cls
# check for curly brackets in arg
# if there is curly brackets split on the curly bracket
# update object using dict representation
d_match = re.search(r'{(.*)}', arg)
if d_match:
# if dictionary was passed as parameter
# extract the id
# if input of form
# <"id">, <{key: value}>
id_ = arg[:arg.find(',')].strip('"')
# extract the dictionary representation
r = d_match.group(0)
r = r.replace("'", '"') # use only double quotes
# concat to form: <cmd> <model> <id> <dictionary rep>
line = line_start + " " + id_ + " " + r
else:
# if no dictionary match
# that means input is of form
# <"id">[, [attr_name, attr_value]]
arg_list = arg.split()
if len(arg_list) == 1:
# only <"id"> passed
arg = arg_list[0].strip('"')
else:
new_list = []
for item in arg_list:
new_ = item.strip('"\',')
new_list.append(new_)
arg = ' '.join(new_list)
# ex: <cmd> <model> <id> [attr_name attr_value]
line = line_start + " " + arg
elif m:
# if input is in form
# <model>.<cmd>()
line_comp = m.group(1).split('.')
cls, cmd = line_comp
# print("line_comp: {}".format(line_comp))
line = cmd + " " + cls
return line
def do_create(self, cmd_arg):
"""
creates a new instance of BaseModel, saves it to JSON file and
prints the id
"""
arg_list, arg_count = self.parse_cmd(cmd_arg)
if arg_count == 0:
print("** class name missing **")
elif arg_count > 0:
try:
model_cls = FileStorage.model_classes[arg_list[0]]
new_model = model_cls()
print(new_model.id)
models.storage.save()
except KeyError:
print("** class doesn't exist **")
def do_show(self, cmd_arg):
"""
Prints the string representation of an instance based on the class name
and id.
example: $ show BaseModel 121212
"""
arg_list, arg_count = self.parse_cmd(cmd_arg)
if arg_count == 0:
print("** class name missing **")
elif arg_list[0] not in FileStorage.model_classes.keys():
print("** class doesn't exist **")
elif arg_count == 1:
print("** instance id missing **")
else:
try:
objs_dict = models.storage.all()
storage_key = f"{arg_list[0]}.{arg_list[1]}"
model_instance = objs_dict[storage_key]
print(model_instance)
except KeyError:
print("** no instance found **")
def do_destroy(self, cmd_arg):
"""
Deletes an instance based on the class name and id (saves the change
into the JSON file)
example: $ destroy BaseModel 1234-1234-1234
"""
arg_list, arg_count = self.parse_cmd(cmd_arg)
if arg_count == 0:
print("** class name missing **")
elif arg_list[0] not in FileStorage.model_classes.keys():
print("** class doesn't exist **")
elif arg_count == 1:
print("** instance id missing **")
else:
try:
objs_dict = models.storage.all()
storage_key = f"{arg_list[0]}.{arg_list[1]}"
del objs_dict[storage_key]
models.storage.save()
except KeyError:
print("** no instance found **")
def do_all(self, cmd_arg):
"""
prints all string representation of all instances based on or not on
the class name
"""
arg_list, arg_count = self.parse_cmd(cmd_arg)
output_list = []
objs_dict = models.storage.all()
if arg_count == 0:
for key, value in objs_dict.items():
output_list.append(str(value))
else:
if arg_list[0] not in FileStorage.model_classes.keys():
print("** class doesn't exist **")
else:
for key, value in objs_dict.items():
cls_name, id_ = key.split('.')
if cls_name == arg_list[0]:
output_list.append(str(value))
if len(output_list) > 0:
print(output_list)
def do_count(self, cmd_arg):
"""
retrieve the number of instances of a class
"""
arg_list, arg_count = self.parse_cmd(cmd_arg)
objs_dict = models.storage.all()
count = 0
if arg_list[0] not in FileStorage.model_classes.keys():
print("** class doesn't exist **")
else:
for key, value in objs_dict.items():
cls_name, id_ = key.split('.')
if cls_name == arg_list[0]:
count += 1
print(count)
def do_update(self, cmd_arg):
"""
updates an instance based on the class name and id by adding or
updating attribute and saves the change into storage
"""
# initialize variables for cls and id
cls = id_ = ''
# cmd_arg example for dict parameter
# User 1bccf9d7-af3d-40d0-940e-66d546f0622e {"first_name": "John"}
m_dict = re.search(r'{(.*)}', cmd_arg)
if m_dict:
# convert dict representation passed as argument to python
# dictionary
p_dict = json.loads(m_dict.group(0))
cls, id_ = cmd_arg[:cmd_arg.find('{')-1].split()
else:
arg_list, arg_count = self.parse_cmd(cmd_arg)
cls, id_, *rest = arg_list
if cls == '':
print("** class name missing **")
return
elif cls not in FileStorage.model_classes.keys():
print("** class doesn't exist **")
return
elif id_ == '':
print("** instance id missing **")
return
else:
objs_dict = models.storage.all()
storage_key = f"{cls}.{id_}"
# update model instance
if m_dict:
try:
model_inst = objs_dict[storage_key]
for key, value in p_dict.items():
attr_name = key
attr_value = value
cur_attr_val = getattr(model_inst, attr_name, None)
if cur_attr_val:
# cast update value to attribute type
attr_type = type(cur_attr_val)
attr_value = attr_type(attr_value)
setattr(model_inst, attr_name, attr_value)
model_inst.save()
except KeyError:
print("** no instance found **")
elif arg_count == 2:
print("** attribute name missing **")
elif arg_count == 3:
print("** value missing **")
else:
try:
model_inst = objs_dict[storage_key]
attr_name = arg_list[2]
attr_value = arg_list[3].strip("\"'")
cur_attr_val = getattr(model_inst, attr_name, None)
if cur_attr_val:
# cast update value to attribute type
attr_type = type(cur_attr_val)
attr_value = attr_type(attr_value)
setattr(model_inst, attr_name, attr_value)
model_inst.save()
except KeyError:
print("** no instance found **")
if __name__ == '__main__':
HBNBCommand().cmdloop()