-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.py
executable file
·260 lines (239 loc) · 8.84 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
#!/usr/bin/env python3
"""Console program."""
import cmd
import shlex
import models
import re
import json
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
class HBNBCommand(cmd.Cmd):
"""Base class inherented from cmd module."""
prompt = "(hbnb) "
_classes = [
"BaseModel",
"User",
"State",
"City",
"Amenity",
"Place",
"Review"
]
# ---------------------------- Cmd commands ------------------------------
def emptyline(self):
"""Take care of empty line."""
pass
def default(self, s):
"""Take care of unrecognized commands."""
# line = shlex.split(s)
match = re.search(r"([A-Z]\w*)\.(\w+)\(([^()]*)\)", s)
if match:
class_name = match.group(1)
objects = models.storage.all()
if class_name in HBNBCommand._classes:
command = match.group(2)
if command == "all":
self.do_all(class_name)
elif command == "count":
result = 0
for key, model in objects.items():
if key.startswith(class_name):
result += 1
print(result)
elif command in ["show", "destroy", "update"]:
args = " ".join(match.group(3).split(","))
text = f"{class_name} {args}"
if args[-1] == "}":
# "38f22813-2753-4d42-b37c-57a17f1e4f88", {
# 'first_name': "John",
# "age": 89
# }
match2 = re.search(
r'("[^"]*"), ({[^{}]*})', match.group(3)
)
id = match2.group(1)
attrs = match2.group(2)
for key, value in eval(attrs).items():
self.do_update(f"{class_name} {id} {key} {value}")
else:
eval(f"self.do_{command}('{text}')")
else:
print("** class doesn't exist **")
else:
return cmd.Cmd.default(self, s)
# --------------------------- Main commands ------------------------------
def do_create(self, s):
"""Create a new instance of BaseModel."""
line = shlex.split(s)
n = len(line)
if n:
class_name = line[0]
if class_name not in HBNBCommand._classes:
print("** class doesn't exist **")
else:
new_model = eval(class_name)()
models.storage.new(new_model)
models.storage.save()
print(new_model.id)
else:
print("** class name missing **")
def do_show(self, s):
"""Print string representation of instance based on class name."""
line = shlex.split(s)
n = len(line)
if n:
class_name = line[0]
if class_name not in HBNBCommand._classes:
print("** class doesn't exist **")
else:
if n < 2:
print("** instance id missing **")
else:
objects = models.storage.all()
id = line[1]
if f"{class_name}.{id}" not in objects:
print("** no instance found **")
else:
print(objects[f"{class_name}.{id}"])
else:
print("** class name missing **")
def do_destroy(self, s):
"""Delete an instance based on the class name and id."""
line = shlex.split(s)
n = len(line)
if n:
class_name = line[0]
if class_name not in HBNBCommand._classes:
print("** class doesn't exist **")
else:
if n < 2:
print("** instance id missing **")
else:
objects = models.storage.all()
id = line[1]
if f"{class_name}.{id}" not in objects:
print("** no instance found **")
else:
del objects[f"{class_name}.{id}"]
models.storage.save()
else:
print("** class name missing **")
def do_all(self, s):
"""Print all string representation of all instances."""
line = shlex.split(s)
n = len(line)
objects = models.storage.all()
result = []
if n:
class_name = line[0]
if class_name not in HBNBCommand._classes:
print("** class doesn't exist **")
else:
for key, model in objects.items():
if key.startswith(class_name):
result.append(str(model))
else:
for key, model in objects.items():
result.append(str(model))
if result:
print(result)
def do_update(self, s):
"""Update an instance based on the class name and id."""
line = shlex.split(s)
n = len(line)
if n:
class_name = line[0]
if class_name not in HBNBCommand._classes:
print("** class doesn't exist **")
else:
if n < 2:
print("** instance id missing **")
else:
objects = models.storage.all()
id = line[1]
if f"{class_name}.{id}" not in objects:
print("** no instance found **")
else:
if n < 3:
print("** attribute name missing **")
else:
attr = line[2]
if n < 4:
print("** value missing **")
else:
value = line[3]
dont_touch = ["id", "created_at", "updated_at"]
if attr not in dont_touch:
model = objects[f"{class_name}.{id}"]
if hasattr(model, attr):
t = type(getattr(model, attr))
setattr(model, attr, t(value))
else:
setattr(model, attr, value)
model.save()
else:
print("** class name missing **")
def do_quit(self, line):
"""End of input stream."""
return True
def do_EOF(self, line):
"""End of input stream."""
print()
return True
# --------------------------- Help commands ------------------------------
def help_quit(self):
"""Help quit."""
help_txt = """Used to Exit the interactive console"""
print(help_txt)
def help_create(self):
"""Help on create command."""
help_txt = """create <ModelName>
Creates a new instance of BaseModel, saves it (to the JSON file)
and prints the id. Ex:
(hbnb) create BaseModel
"""
print(help_txt)
def help_show(self):
"""Help on show command."""
help_txt = """show <ModelName> <id>
Prints the string representation of an instance
based on the class name and id.
Ex:
(hbnb) show BaseModel 1234-1234-1234
"""
print(help_txt)
def help_all(self):
"""Help on all command."""
help_txt = """all [<ModelName>]
Prints all string representation of all instances
based or not on the class name. Ex:
(hbnb) all BaseModel
or
(hbnb) all
"""
print(help_txt)
def help_destroy(self):
"""Help on destroy command."""
help_txt = """destroy <BaseModel> <id>
Deletes an instance
based on the class name and id (save the change into the JSON file).
Ex:
(hbnb) destroy BaseModel 1234-1234-1234
"""
print(help_txt)
def help_update(self):
"""Help on update command."""
help_txt = """update <BaseModel> <id> <attr name> <attr value>
Updates an instance
based on the class name and id by adding or updating attribute
(save the change into the JSON file). Ex:
(hbnb) update BaseModel 1234-1234-1234 email "aibnb@mail.com"
"""
print(help_txt)
if __name__ == '__main__':
HBNBCommand().cmdloop()