forked from AkinsolaTemidayo/AirBnB_clone_v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.py
executable file
·342 lines (281 loc) · 10.9 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
#!/usr/bin/python3
""" Console Module """
import cmd
import sys
from models.base_model import BaseModel
from models.__init__ import storage
from models.user import User
from models.place import Place
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.review import Review
import re
class HBNBCommand(cmd.Cmd):
""" Contains the functionality for the HBNB console"""
# determines prompt for interactive/non-interactive modes
prompt = '(hbnb) ' if sys.__stdin__.isatty() else ''
classes = {
'BaseModel': BaseModel, 'User': User, 'Place': Place,
'State': State, 'City': City, 'Amenity': Amenity,
'Review': Review
}
dot_cmds = ['all', 'count', 'show', 'destroy', 'update']
types = {
'number_rooms': int, 'number_bathrooms': int,
'max_guest': int, 'price_by_night': int,
'latitude': float, 'longitude': float
}
def preloop(self):
"""Prints if isatty is false"""
if not sys.__stdin__.isatty():
print('(hbnb)')
def precmd(self, line):
"""Reformat command line for advanced command syntax.
Usage: <class name>.<command>([<id> [<*args> or <**kwargs>]])
(Brackets denote optional fields in usage example.)
"""
_cmd = _cls = _id = _args = '' # initialize line elements
# scan for general formating - i.e '.', '(', ')'
if not ('.' in line and '(' in line and ')' in line):
return line
try: # parse line left to right
pline = line[:] # parsed line
# isolate <class name>
_cls = pline[:pline.find('.')]
# isolate and validate <command>
_cmd = pline[pline.find('.') + 1:pline.find('(')]
if _cmd not in HBNBCommand.dot_cmds:
raise Exception
# if parantheses contain arguments, parse them
pline = pline[pline.find('(') + 1:pline.find(')')]
if pline:
# partition args: (<id>, [<delim>], [<*args>])
pline = pline.partition(', ') # pline convert to tuple
# isolate _id, stripping quotes
_id = pline[0].replace('\"', '')
# possible bug here:
# empty quotes register as empty _id when replaced
# if arguments exist beyond _id
pline = pline[2].strip() # pline is now str
if pline:
# check for *args or **kwargs
if pline[0] == '{' and pline[-1] == '}'\
and type(eval(pline)) is dict:
_args = pline
else:
_args = pline.replace(',', '')
# _args = _args.replace('\"', '')
line = ' '.join([_cmd, _cls, _id, _args])
except Exception as mess:
pass
finally:
return line
def postcmd(self, stop, line):
"""Prints if isatty is false"""
if not sys.__stdin__.isatty():
print('(hbnb) '),
return stop
def do_quit(self, command):
""" Method to exit the HBNB console"""
exit()
def help_quit(self):
""" Prints the help documentation for quit """
print("Exits the program with formatting\n")
def do_EOF(self, arg):
""" Handles EOF to exit program """
print()
exit()
def help_EOF(self):
""" Prints the help documentation for EOF """
print("Exits the program without formatting\n")
def emptyline(self):
""" Overrides the emptyline method of CMD """
pass
def do_create(self, args):
""" Create an object of any class"""
try:
class_name = args.split(" ")[0]
except IndexError:
pass
if not class_name:
print("** class name missing **")
return
elif class_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
all_list = args.split(" ")
new_instance = eval(class_name)()
for i in range(1, len(all_list)):
key, value = tuple(all_list[i].split("="))
if value.startswith('"'):
value = value.strip('"').replace("_", " ")
else:
try:
value = eval(value)
except Exception:
print(f"** couldnt evaluate {value}")
pass
if hasattr(new_instance, key):
setattr(new_instance, key, value)
storage.new(new_instance)
print(new_instance.id)
new_instance.save()
def help_create(self):
""" Help information for the create method """
print("Creates a class of any type")
print("[Usage]: create <className>\n")
def do_show(self, args):
""" Method to show an individual object """
new = args.partition(" ")
c_name = new[0]
c_id = new[2]
# guard against trailing args
if c_id and ' ' in c_id:
c_id = c_id.partition(' ')[0]
if not c_name:
print("** class name missing **")
return
if c_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
if not c_id:
print("** instance id missing **")
return
key = c_name + "." + c_id
try:
print(storage._FileStorage__objects[key])
except KeyError:
print("** no instance found **")
def help_show(self):
""" Help information for the show command """
print("Shows an individual instance of a class")
print("[Usage]: show <className> <objectId>\n")
def do_destroy(self, args):
""" Destroys a specified object """
new = args.partition(" ")
c_name = new[0]
c_id = new[2]
if c_id and ' ' in c_id:
c_id = c_id.partition(' ')[0]
if not c_name:
print("** class name missing **")
return
if c_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
if not c_id:
print("** instance id missing **")
return
key = c_name + "." + c_id
try:
del(storage.all()[key])
storage.save()
except KeyError:
print("** no instance found **")
def help_destroy(self):
""" Help information for the destroy command """
print("Destroys an individual instance of a class")
print("[Usage]: destroy <className> <objectId>\n")
def do_all(self, args):
""" Shows all objects, or all objects of a class"""
print_list = []
if args:
args = args.split(' ')[0] # remove possible trailing args
if args not in HBNBCommand.classes:
print("** class doesn't exist **")
return
for k, v in storage._FileStorage__objects.items():
if k.split('.')[0] == args:
print_list.append(str(v))
else:
for k, v in storage._FileStorage__objects.items():
print_list.append(str(v))
print(print_list)
def help_all(self):
""" Help information for the all command """
print("Shows all objects, or all of a class")
print("[Usage]: all <className>\n")
def do_count(self, args):
"""Count current number of class instances"""
count = 0
for k, v in storage._FileStorage__objects.items():
if args == k.split('.')[0]:
count += 1
print(count)
def help_count(self):
""" """
print("Usage: count <class_name>")
def do_update(self, args):
""" Updates a certain object with new info """
c_name = c_id = att_name = att_val = kwargs = ''
# isolate cls from id/args, ex: (<cls>, delim, <id/args>)
args = args.partition(" ")
if args[0]:
c_name = args[0]
else: # class name not present
print("** class name missing **")
return
if c_name not in HBNBCommand.classes: # class name invalid
print("** class doesn't exist **")
return
# isolate id from args
args = args[2].partition(" ")
if args[0]:
c_id = args[0]
else: # id not present
print("** instance id missing **")
return
# generate key from class and id
key = c_name + "." + c_id
# determine if key is present
if key not in storage.all():
print("** no instance found **")
return
# first determine if kwargs or args
if '{' in args[2] and '}' in args[2] and type(eval(args[2])) is dict:
kwargs = eval(args[2])
args = [] # reformat kwargs into list, ex: [<name>, <value>, ...]
for k, v in kwargs.items():
args.append(k)
args.append(v)
else: # isolate args
args = args[2]
if args and args[0] == '\"': # check for quoted arg
second_quote = args.find('\"', 1)
att_name = args[1:second_quote]
args = args[second_quote + 1:]
args = args.partition(' ')
# if att_name was not quoted arg
if not att_name and args[0] != ' ':
att_name = args[0]
# check for quoted val arg
if args[2] and args[2][0] == '\"':
att_val = args[2][1:args[2].find('\"', 1)]
# if att_val was not quoted arg
if not att_val and args[2]:
att_val = args[2].partition(' ')[0]
args = [att_name, att_val]
# retrieve dictionary of current objects
new_dict = storage.all()[key]
# iterate through attr names and values
for i, att_name in enumerate(args):
# block only runs on even iterations
if (i % 2 == 0):
att_val = args[i + 1] # following item is value
if not att_name: # check for att_name
print("** attribute name missing **")
return
if not att_val: # check for att_value
print("** value missing **")
return
# type cast as necessary
if att_name in HBNBCommand.types:
att_val = HBNBCommand.types[att_name](att_val)
# update dictionary with name, value pair
new_dict.__dict__.update({att_name: att_val})
new_dict.save() # save updates to file
def help_update(self):
""" Help information for the update class """
print("Updates an object with new information")
print("Usage: update <className> <id> <attName> <attVal>\n")