-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconsole.py
executable file
·245 lines (206 loc) · 7.16 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
#!/usr/bin/python3
"""a module that implements the console app (cmd)"""
import cmd
import shlex
import re
from models.base_model import BaseModel
from models.user import User
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 import storage
class HBNBCommand(cmd.Cmd):
"""the class that handles the cmd console interface"""
prompt = "(hbnb) "
# stores available classes in key, value pair (dict)
available_cls = {
"BaseModel": BaseModel,
"User": User,
"State": State,
"City": City,
"Amenity": Amenity,
"Place": Place,
"Review": Review,
}
def do_quit(self, line):
"""method to exit the program if quit is used"""
return True
def do_EOF(self, line):
"""method to exit the program with EOF"""
return True
def emptyline(self):
"""an emptyline should do nothing"""
pass
def do_create(self, lines):
"""creates a new instance.
Usage: create <class_name>
"""
if not lines:
print("** class name missing **")
return
tokens = shlex.split(lines)
# print(len(tokens))
if len(tokens) == 1:
if tokens[0] not in HBNBCommand.available_cls.keys():
print("** class doesn't exist **")
return
# print("available")
obj = HBNBCommand.available_cls[tokens[0]]()
obj.save()
print(obj.id)
def do_show(self, lines):
"""prints the string representation of an instance based on the
class name and id
Usage: show <class_name> <object_id>
"""
if not lines:
print("** class name missing **")
return
tokens = shlex.split(lines)
if tokens[0] not in HBNBCommand.available_cls.keys():
print("** class doesn't exist **")
return
if len(tokens) == 1:
print("** instance id missing **")
return
if len(tokens) == 2:
# load the dict format of objects from file storage
storage.reload()
# return all ojects
objs = storage.all()
key = f"{tokens[0]}.{tokens[1]}"
if key not in objs.keys():
print("** no instance found **")
return
else:
print(objs[key])
def do_destroy(self, lines):
"""Deletes an instance based on the class name and id
Usage: destroy <class_name> <object_id>
"""
if not lines:
print("** class name missing **")
return
tokens = shlex.split(lines)
if tokens[0] not in HBNBCommand.available_cls.keys():
print("** class doesn't exist **")
return
if len(tokens) == 1:
print("** instance id missing **")
return
if len(tokens) == 2:
# load the dict format of objects from file storage
storage.reload()
# return all ojects
objs = storage.all()
key = f"{tokens[0]}.{tokens[1]}"
if key not in objs.keys():
print("** no instance found **")
return
else:
del objs[key]
# save change into the JSON file
storage.save()
def do_all(self, lines):
"""Prints all string representation of all instances
Usage: all or all <class_name>
"""
objs = storage.all()
# no class name passed to all $ all
if not lines:
obj_list = []
for key in objs:
obj_list.append(str(objs[key]))
print(obj_list)
return
# if a class name passed to $ all <class_name>
tokens = shlex.split(lines)
if tokens[0] not in HBNBCommand.available_cls.keys():
print("** class doesn't exist **")
else:
p = [str(objs[k]) for k in objs if k.split(".")[0] == tokens[0]]
print(p)
return
def do_update(self, lines):
"""updates an instance based on the class name and id
Usage: update <class name> <id> <attribute name> "<attribute value>"
"""
if not lines:
print("** class name missing **")
return
tokens = shlex.split(lines)
# print(len(tokens))
if tokens[0] not in HBNBCommand.available_cls.keys():
print("** class doesn't exist **")
return
if len(lines) == 1:
print("** instance id missing **")
return
storage.reload()
objs = storage.all()
key = f"{tokens[0]}.{tokens[1]}"
if key not in objs.keys() and len(tokens) >= 2:
print("** no instance found **")
return
if key in objs.keys() and len(tokens) == 2:
print("** attribute name missing **")
return
if len(tokens) == 3:
print("** value missing **")
if len(tokens) == 4:
if hasattr(objs[key], tokens[2]):
attribute_type = type(getattr(objs[key], tokens[2]))
try:
setattr(objs[key], tokens[2], attribute_type(tokens[3]))
except ValueError:
return
else:
v = tokens[3]
# check the type of the value
if v.isdigit() or v.startswith("-") and v[1:].isdigit:
v = int(v)
elif isinstance(v, str):
v = str(v)
elif "." in v and all(p.isdigit() for p in v.split(".", 1)):
v = float(v)
else:
print("Not type float, int nor str")
setattr(objs[key], tokens[2], v)
storage.save()
def default(self, lines):
"""this handl default commands to console"""
cmds = {
"show": self.do_show,
"all": self.do_all,
"update": self.do_update,
"destroy": self.do_destroy,
"count": self.do_count,
}
match = re.search(r"\.", lines)
if match:
slines = [lines[:match.span()[0]], lines[match.span()[1]:]]
match = re.search(r"\((.*?)\)", slines[1])
if match:
cmd = [slines[1][: match.span()[0]], match.group()[1:-1]]
if cmd[0] in cmds.keys():
call = f"{slines[0]} {cmd[1]}"
return cmds[cmd[0]](call)
print("*** Unknown command ***")
return
def do_count(self, lines):
"""method that retrieve the number of instances of a class
Usage: <class name>.class()
"""
count = 0
objs = storage.all()
tokens = shlex.split(lines)
if len(tokens) == 1:
if tokens[0] in HBNBCommand.available_cls.keys():
for key in objs:
if key.split(".")[0] == tokens[0]:
count += 1
print(count)
if __name__ == "__main__":
HBNBCommand().cmdloop()