-
Notifications
You must be signed in to change notification settings - Fork 1
/
console.py
executable file
·267 lines (243 loc) · 8.2 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
#!/usr/bin/python3
"""
Module for Command line Interpreter
"""
import cmd
import json
import re
import shlex
import ast
from models.base_model import BaseModel
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.review import Review
from models.user import User
from models import storage
class_dict = {
"BaseModel": BaseModel,
"User": User,
"State": State,
"City": City,
"Amenity": Amenity,
"Place": Place,
"Review": Review
}
function_list = [
"all",
"show",
"create",
"update",
"destroy",
"count"
]
class HBNBCommand(cmd.Cmd):
"""
This class defines console functions
"""
prompt = '(hbnb) '
def do_quit(self, arg):
"""
Quit command to exit the program
"""
return True
def do_EOF(self, arg):
"""
EOF command to exit the program
"""
return True
def emptyline(self):
"""
This function handles empty line
"""
return
def do_create(self, arg):
"""
Create command to create an instance of a class
"""
list_args = parse(arg)
if len(list_args) == 0:
print("** class name missing **")
elif (list_args[0] not in class_dict):
print("** class doesn't exist **")
else:
instance = class_dict[list_args[0]]()
instance.save()
print(instance.id)
def do_show(self, arg):
"""
Show command to print the string representation of an instance \
based on the class name and id
Usage: <class name>.show(<id>)
Usage: show <class name> <id>
"""
list_args = parse(arg)
if len(list_args) == 0:
print("** class name missing **")
elif (list_args[0] not in class_dict):
print("** class doesn't exist **")
elif len(list_args) < 2:
print("** instance id missing **")
elif (f"{list_args[0]}.{list_args[1]}"
) not in storage.FileStorage_objects:
print("** no instance found **")
else:
print(
storage.FileStorage_objects[
f"{list_args[0]}.{list_args[1]}"])
def do_destroy(self, arg):
"""
Destroy command to delete an instance \
based on the class name and id
Usage: <class name>.destroy(<id>)
Usage: destroy <class name> <id>
"""
list_args = parse(arg)
if len(list_args) == 0:
print("** class name missing **")
elif (list_args[0] not in class_dict):
print("** class doesn't exist **")
elif len(list_args) < 2:
print("** instance id missing **")
elif (f"{list_args[0]}.{list_args[1]}"
) not in storage.FileStorage_objects:
print("** no instance found **")
else:
del storage.FileStorage_objects[f"{list_args[0]}.{list_args[1]}"]
storage.save()
def do_all(self, arg):
"""
All command to print all string representation of all instances
Usage: <class name>.all()
Usage: all <class name>
where <class name> is optional
"""
list_args = parse(arg)
if len(list_args) > 0 and list_args[0] not in class_dict:
print("** class doesn't exist **")
else:
list_result = []
for key, value in storage.FileStorage_objects.items():
if len(list_args) == 0:
list_result.append(str(value))
else:
if list_args[0] == value.to_dict()["_class_"]:
list_result.append(str(value))
print(list_result)
def do_count(self, arg):
"""
Count command to retrieve the number of instances of a class
Usage: <class name>.count()
Usage: count <class name>
where <class name> is optional
"""
count = 0
if arg:
list_args = parse(arg)
for key, value in storage.FileStorage_objects.items():
if value._class.__name_ == list_args[0]:
count += 1
else:
for key in storage.FileStorage_objects.keys():
count += 1
print(count)
def do_update(self, arg):
"""
Update command to update an instance based on the class name \
and id by adding or updating attribute
Usage: <class name>.update(<id>, <dictionary representation>)
Usage: <class name>.update(<id>, <attribute name>, <attribute value>)
Usage: update <class name> <id> <attribute name> <attribute value>
"""
list_args = parse(arg)
if len(list_args) == 0:
print("** class name missing **")
elif (list_args[0] not in class_dict):
print("** class doesn't exist **")
elif len(list_args) < 2:
print("** instance id missing **")
elif (f"{list_args[0]}.{list_args[1]}"
) not in storage.FileStorage_objects:
print("** no instance found **")
elif (len(list_args) < 3):
print("** attribute name missing **")
elif (len(list_args) < 4):
print("** value missing **")
else:
setattr(
storage.FileStorage_objects[f"{list_args[0]}.{list_args[1]}"
], list_args[2], tryeval(
(list_args[3])))
instance = storage.FileStorage_objects[
f"{list_args[0]}.{list_args[1]}"]
instance.save()
def default(self, arg):
"""
function that take the user input and process informations \
Usage: <class name>.<function()>
"""
pattern_reg = r"(.*)\.(.*)\((.*?)\)"
if re.search(pattern_reg, str(arg)):
str_arg = re.sub(pattern_reg, r"\2 \1 \3", arg)
list_arg = parse(str_arg)
if list_arg[0] in function_list:
if list_arg[0] == "update":
dict_reg = r"({.: \w})"
if (re.search(dict_reg, str_arg)):
arg_str = re.search(dict_reg, str_arg).group(
0).replace("'", '"')
arg_dict = json.loads(arg_str)
for key, value in arg_dict.items():
if type(value) is str:
value = "\"" + value + "\""
self.do_update("{} {} {} {}".format(
list_arg[1],
list_arg[2].strip(','),
key,
value
))
else:
arg_list = []
for elt in list_arg:
element = elt.strip(',')
if type(element) is str:
element = "\"" + element + "\""
arg_list.append(element)
sentence = ""
for word in arg_list[1:]:
sentence = sentence + " " + str(word)
self.do_update(sentence)
else:
str_arg = str_arg.replace(",", " ")
arg = str_arg.split(" ", 1)
getattr(self, "do_" + list_arg[0])(arg[1])
else:
return syntax_error(arg)
else:
return syntax_error(arg)
@staticmethod
def parse(arg):
"""
Convert a series of zero or more numbers to an argument tuple
"""
return shlex.split(arg)
@staticmethod
def syntax_error(arg):
"""
This function handles Unknow syntax Error
"""
print("*** Unknow syntax: {}".format(arg))
return False
@staticmethod
def tryeval(value):
"""
To find the most appropriate type for value and return the new value
"""
try:
value = ast.literal_eval(value)
except Exception:
pass
return value
if __name__ == '__main__':
HBNBCommand().cmdloop()