-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.py
executable file
·453 lines (390 loc) · 15.8 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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#!/usr/bin/python3
""" Module for the console """
import cmd
import sys
import models
import signal
from os import getenv
from models.amenity import Amenity
from models.base_model import BaseModel
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.user import User
import shlex # for splitting the line along spaces except in double quotes
classes = {
"Amenity": Amenity,
"BaseModel": BaseModel,
"City": City,
"Place": Place,
"Review": Review,
"State": State,
"User": User,
}
if getenv("HBNB_TYPE_STORAGE") == "db":
del classes["BaseModel"]
class HBNBCommand(cmd.Cmd):
"""HBNH console"""
prompt = "(hbnb) "
def preloop(self):
"""Handles intro to command interpreter."""
print(".----------------------------.")
print("| Welcome to hbnb CLI! |")
print("| for help, input 'help' |")
print("| for quit, input 'quit' |")
print(".----------------------------.")
def postloop(self):
"""Handles exit to command interpreter."""
print(".----------------------------.")
print("| Well, that sure was fun! |")
print(".----------------------------.")
def do_EOF(self, arg):
"""Exits console"""
return True
def emptyline(self):
"""overwriting the emptyline method"""
return False
def do_quit(self, arg):
"""Quit command to exit the program"""
return True
def default(self, arg):
"""Default behavior for cmd module."""
cmds = {
"all": self.do_all,
"count": self.do_count,
"create": self.do_create,
"show": self.do_show,
"destroy": self.do_destroy,
"update": self.do_update,
}
if "." in arg and "(" in arg and ")" in arg:
cls = arg[:arg.index(".")]
method = arg[arg.index(".") + 1:arg.index("(")]
arguments = arg[arg.index("(") + 1:arg.index(")")]
arguments = arguments.replace("=", " ")
arguments = "{} {}".format(cls, arguments.replace(",", ""))
if method in cmds.keys():
return cmds[method](arguments)
self.stdout.write("*** Unknown syntax: %s\n" % arg)
return
def _key_value_parser(self, args):
"""creates a dictionary from a list of strings"""
new_dict = {}
for arg in args:
if "=" in arg:
kvp = arg.split("=", 1)
key = kvp[0]
value = kvp[1]
if value[0] == value[-1] == '"':
value = shlex.split(value)[0].replace("_", " ")
else:
try:
value = int(value)
except:
try:
value = float(value)
except:
continue
new_dict[key] = value
return new_dict
def do_create(self, arg):
"""Creates a new instance of a class.
Usage: create <class> <param 1> <param 2> ..., or
<class>.create(<param 1> <param 2> ...)
Ex: (hbnb) create City name="Tokyo"
(hbnb) City.create(name="Tokyo")
"""
args = arg.split()
if len(args) == 0:
print("** class name missing **")
return False
if args[0] in classes:
new_dict = self._key_value_parser(args[1:])
instance = classes[args[0]](**new_dict)
else:
print("** class doesn't exist **")
return False
print(instance.id)
instance.save()
def do_show(self, arg):
"""Prints the string representation of an instance based on its class
and ID.
Usage: show <class> <id> or <class>.show(<id>)
Ex: (hbnb) show City 1234-abcd-5678-efgh
(hbnb) City.show(1234-abcd-5678-efgh)
"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
return False
if args[0] in classes:
if len(args) > 1:
key = args[0] + "." + args[1]
if key in models.storage.all():
print(models.storage.all()[key])
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")
def do_destroy(self, arg):
"""Deletes an instance based on its class and ID.
Usage: destroy <class> <id> or <class>.destroy(<id>)
Ex: (hbnb) destroy City 1234-abcd-5678-efgh
(hbnb) City.destroy(1234-abcd-5678-efgh)
"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
elif args[0] in classes:
if len(args) > 1:
key = args[0] + "." + args[1]
if key in models.storage.all():
if getenv("HBNB_TYPE_STORAGE") == "db":
instance = models.storage.all()[key]
instance.delete()
else:
models.storage.all().pop(key)
models.storage.save()
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")
def do_all(self, arg):
"""Displays string representation of all instances of a given class.
If no class is specified, displays all instantiated objects.
Usage: all or all <class> or <class>.all()
Ex: (hbnb) all
(hbnb) all BaseModel
(hbnb) BaseModel.all()
"""
args = shlex.split(arg)
obj_list = []
if len(args) == 0:
obj_dict = models.storage.all()
elif args[0] in classes:
obj_dict = models.storage.all(classes[args[0]])
else:
print("** class doesn't exist **")
return False
for key in obj_dict:
obj_list.append(str(obj_dict[key]))
print("[", end="")
print(", ".join(obj_list), end="")
print("]")
def do_count(self, arg):
"""Retrieves the number of instances of a class.
Usage: count <class> or <class>.count()
Ex: (hbnb) count City
(hbnb) City.count()
"""
args = shlex.split(arg)
if len(args) == 0:
print("** class name missing **")
return False
if args[0] not in classes:
print("** class doesn't exist **")
return False
count = 0
for key in models.storage.all().keys():
if args[0] in key:
count += 1
print(count)
def do_update(self, arg):
"""Updates an instance based on the class name and id by adding
or updating an attribute.
Usage: update <class name> <id> <attribute name> <attribute value> or
<class name>.update(<id>, <attribute name>, <attribute value>)
Ex: (hbnb) update City 1234-abcd-5678-efgh name Chicago
(hbnb) City.update(1234-abcd-5678-efgh, name, Chicago)
(hbnb) City.update(1234-abcd, {'name': 'Chicago', 'address': 'None'})
"""
args = shlex.split(arg)
integers = ["number_rooms", "number_bathrooms", "max_guest", "price_by_night"]
floats = ["latitude", "longitude"]
if len(args) == 0:
print("** class name missing **")
elif args[0] in classes:
if len(args) > 1:
k = args[0] + "." + args[1]
if k in models.storage.all():
if len(args) > 2:
if len(args) > 3:
if args[0] == "Place":
if args[2] in integers:
try:
args[3] = int(args[3])
except:
args[3] = 0
elif args[2] in floats:
try:
args[3] = float(args[3])
except:
args[3] = 0.0
setattr(models.storage.all()[k], args[2], args[3])
models.storage.all()[k].save()
else:
print("** value missing **")
else:
print("** attribute name missing **")
else:
print("** no instance found **")
else:
print("** instance id missing **")
else:
print("** class doesn't exist **")
# Define methods to display help for each class:
def help_BaseModel(self):
"""Help for the BaseModel class."""
message = """A class which other classes inherit from.
Usage: <command> BaseModel or BaseModel.<command>()
"""
print(message)
def help_Amenity(self):
"""Help for Amenity class."""
message = """A class which represents an amenity.
Usage: <command> Amenity or Amenity.<command>()
Required attributes (columns) to create an Amenity:
attr_name | data-type | mandatory
-----------------------------------
name | string | yes
Ex: (hbnb) create Amenity name="Wifi" or
(hbnb) Amenity.create(name="Wifi")
"""
print(message)
def help_City(self):
"""Help for City class."""
message = """A class which represents a city.
Usage: <command> City or City.<command>()
Required attributes (columns) to create a City:
attr_name | data-type | mandatory
-----------------------------------
name | string | yes
state_id | string | yes
Ex: (hbnb) create City name="Tokyo" state_id="1234-abcd-efgh-54678" or
(hbnb) City.create(name="Tokyo" state_id="1234-abcd-efgh-54678")
"""
print(message)
def help_Place(self):
"""Help for Place class."""
message = """A class which represents a place.
Usage: <command> Place or Place.<command>()
Required attributes (columns) to create a Place:
attr_name | data-type | mandatory
-----------------------------------------
name | string | yes
city_id | string | yes
state_id | string | yes
number_rooms | integer | yes
number_bathrooms| integer | yes
max_guest | integer | yes
price_by_night | integer | yes
description | string | no
latitude | float | no
longitude | float | no
amenity_ids | list | no
Ex: (hbnb) create Place city_id="0001" user_id="0001" name="My_little_house" number_rooms=4 number_bathrooms=2 max_guest=10 price_by_night=300 latitude=37.773972 longitude=-122.431297
or (hbnb) Place.create(create Place city_id="0001" user_id="0001" name="My_little_house" number_rooms=4 number_bathrooms=2 max_guest=10 price_by_night=300 latitude=37.773972 longitude=-122.431297)
"""
print(message)
def help_Review(self):
"""Help for Review class."""
message = """A class which represents a review.
Usage: <command> Review or Review.<command>()
Required attributes (columns) to create a Review:
attr_name | data-type | mandatory
-----------------------------------
place_id | string | yes
user_id | string | yes
text | string | yes
Ex: (hbnb) create Review place_id="123-abc-456-def" user_id="123-abc-456-def" text="Amazing_place,_huge_kitchen"
or (hbnb) Review.create(place_id="123-abc-456-def" user_id="123-abc-456-def" text="Amazing_place,_huge_kitchen")
"""
print(message)
def help_State(self):
"""Help for State class."""
message = """A class which represents a state.
Usage: <command> State or State.<command>()
Required attributes (columns) to create a State:
attr_name | data-type | mandatory
-----------------------------------
name | string | yes
Ex: (hbnb) Create State name="California" or
(hbnb) State.create(name="California")
"""
print(message)
def help_User(self):
"""Help for User class."""
message = """A class which represents a user.
Usage: <command> User or User.<command>()
Required attributes (columns) to create a User:
attr_name | data-type | mandatory
------------------------------------
first_name | string | yes
last_name | string | yes
email | string | yes
password | string | yes
Ex: (hbnb) create User email="[email protected]" password="guipwd" first_name="Guillaume" last_name="Snow"
or (hbnb) User.create(email="[email protected]" password="guipwd" first_name="Guillaume" last_name="Snow")
"""
print(message)
# Implement autocomplete for commands:
def complete_all(self, text, line, begidx, endidx):
"""Auto complete for create command"""
if not text:
completions = [cls for cls in classes.keys()]
else:
text = text.capitalize()
completions = [cls for cls in classes.keys() if cls.startswith(text)]
return completions
def complete_count(self, text, line, begidx, endidx):
"""Auto complete for create command"""
if not text:
completions = [cls for cls in classes.keys()]
else:
text = text.capitalize()
completions = [cls for cls in classes.keys() if cls.startswith(text)]
return completions
def complete_create(self, text, line, begidx, endidx):
"""Auto complete for create command"""
if not text:
completions = [cls for cls in classes.keys()]
else:
text = text.capitalize()
completions = [cls for cls in classes.keys() if cls.startswith(text)]
return completions
def complete_destroy(self, text, line, begidx, endidx):
"""Auto complete for create command"""
if not text:
completions = [cls for cls in classes.keys()]
else:
text = text.capitalize()
completions = [cls for cls in classes.keys() if cls.startswith(text)]
return completions
def complete_show(self, text, line, begidx, endidx):
"""Auto complete for create command"""
if not text:
completions = [cls for cls in classes.keys()]
else:
text = text.capitalize()
completions = [cls for cls in classes.keys() if cls.startswith(text)]
return completions
def complete_update(self, text, line, begidx, endidx):
"""Auto complete for create command"""
if not text:
completions = [cls for cls in classes.keys()]
else:
text = text.capitalize()
completions = [cls for cls in classes.keys() if cls.startswith(text)]
return completions
def signal_handler(sig, frame):
"""Handle SIGNINT"""
print("exiting...")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
if __name__ == "__main__":
HBNBCommand().cmdloop()