-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconsole.py
executable file
·308 lines (260 loc) · 10.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
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
#!/usr/bin/python3
"""defines a command interpreter 'console' for the AirBnB web app"""
import cmd
import sys
from models.base_model import BaseModel
from models 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
class HBNBCommand(cmd.Cmd):
"""represents HBNB command interpreter"""
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 precmd(self, line):
"""Reformat command line for advanced command syntax.
Usage: <class name>.<command>([<id> [<*args> or <**kwargs>]])
(Brackets for optional fields.)
"""
_cmd = _cls = _id = _args = ''
# 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[:]
# 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
# parsing arguments if present
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:
pass
finally:
return line
def postcmd(self, stop, line):
"""Prints 'hbnb' if not isatty"""
if not sys.__stdin__.isatty():
print('(hbnb) ', end='')
return stop
def emptyline(self):
"""Called when an empty line is entered and do nothing"""
pass
def do_quit(self, arg):
"""Quit command to exit the program"""
exit()
def help_quit(self):
""" Prints the help documentation for quit """
print("Exits the program with formatting\n")
def do_EOF(self, arg):
"""exits the cmd"""
print()
exit()
def help_EOF(self):
""" Prints the help documentation for EOF """
print("Exits the program without formatting\n")
def do_create(self, arg):
"""create an instance of the specified class"""
if not arg:
print("** class name missing **")
return
elif arg not in HBNBCommand.classes:
print("** class doesn't exist **")
return
new = HBNBCommand.classes[arg]()
print(new.id)
storage.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, arg):
"""show an object"""
args = arg.partition(" ")
class_name = args[0]
class_id = args[2]
# manipulate trailling args
if class_id and ' ' in class_id:
class_id = class_id.partition(" ")[0]
if not class_name:
print("** class name missing **")
return
if class_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
if not class_id:
print("** instance id missing **")
return
key = class_name + "." + class_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, arg):
"""delete an object"""
args = arg.partition(" ")
class_name = args[0]
class_id = args[2]
# manipulate trailling args
if class_id and ' ' in class_id:
class_id = class_id.partition(' ')[0]
if not class_name:
print("** class name missing **")
return
if class_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
if not class_id:
print("** class doesn't exist **")
return
key = class_name + "." + class_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, arg):
"""display the string representation
of all instances or an instance of a specifiec class
"""
print_list = []
if arg:
class_name = arg.partition(' ')[0]
if class_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
for key, value in storage._FileStorage__objects.items():
if key.split('.')[0] == arg:
print_list.append(str(value))
else:
for key, value in storage._FileStorage__objects.items():
print_list.append(str(value))
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):
""" count num of class instances """
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")
if __name__ == '__main__':
HBNBCommand().cmdloop()