-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.py
271 lines (254 loc) · 8.26 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
#!/usr/bin/python3
"""
This is the console base for the unit
"""
import cmd
from models.base_model import BaseModel
from models import storage
import json
import shlex
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):
""" Holberton command prompt to access models data """
prompt = '(hbnb) '
my_dict = {
"BaseModel": BaseModel,
"User": User,
"State": State,
"City": City,
"Amenity": Amenity,
"Place": Place,
"Review": Review
}
def do_nothing(self, arg):
""" Does nothing """
pass
def do_quit(self, arg):
""" Close program and saves safely data """
return True
def do_EOF(self, arg):
""" Close program and saves safely data, when
user input is CTRL + D
"""
print("")
return True
def emptyline(self):
""" Overrides the empty line method """
pass
def do_create(self, arg):
""" Creates a new instance of the basemodel class
Structure: create [class name]
"""
if not arg:
print("** class name missing **")
return
my_data = shlex.split(arg)
if my_data[0] not in HBNBCommand.my_dict.keys():
print("** class doesn't exist **")
return
new_instance = HBNBCommand.my_dict[my_data[0]]()
new_instance.save()
print(new_instance.id)
def do_show(self, arg):
"""
Prints the string representation of an instance
based on the class name and id
Structure: show [class name] [id]
"""
tokens = shlex.split(arg)
if len(tokens) == 0:
print("** class name missing **")
return
if tokens[0] not in HBNBCommand.my_dict.keys():
print("** class doesn't exist **")
return
if len(tokens) <= 1:
print("** instance id missing **")
return
storage.reload()
objs_dict = storage.all()
key = tokens[0] + "." + tokens[1]
if key in objs_dict:
obj_instance = str(objs_dict[key])
print(obj_instance)
else:
print("** no instance found **")
def do_destroy(self, arg):
"""
Deletes an instance based on the class name and id
(saves the changes into the JSON file)
Structure: destroy [class name] [id]
"""
tokens = shlex.split(arg)
if len(tokens) == 0:
print("** class name missing **")
return
if tokens[0] not in HBNBCommand.my_dict.keys():
print("** class doesn't exist **")
return
if len(tokens) <= 1:
print("** instance id missing **")
return
storage.reload()
objs_dict = storage.all()
key = tokens[0] + "." + tokens[1]
if key in objs_dict:
del objs_dict[key]
storage.save()
else:
print("** no instance found **")
def do_all(self, arg):
"""
Prints all string representation of all instances
based or not on the class name
Structure: all [class name] or all
"""
# prints the whole file
storage.reload()
my_json = []
objects_dict = storage.all()
if not arg:
for key in objects_dict:
my_json.append(str(objects_dict[key]))
print(json.dumps(my_json))
return
token = shlex.split(arg)
if token[0] in HBNBCommand.my_dict.keys():
for key in objects_dict:
if token[0] in key:
my_json.append(str(objects_dict[key]))
print(json.dumps(my_json))
else:
print("** class doesn't exist **")
def do_update(self, arg):
"""
Updates an instance based on the class name and
id by adding or updating attribute
(save the change into the JSON file).
Structure: update [class name] [id] [arg_name] [arg_value]
"""
if not arg:
print("** class name missing **")
return
my_data = shlex.split(arg)
storage.reload()
objs_dict = storage.all()
if my_data[0] not in HBNBCommand.my_dict.keys():
print("** class doesn't exist **")
return
if (len(my_data) == 1):
print("** instance id missing **")
return
try:
key = my_data[0] + "." + my_data[1]
objs_dict[key]
except KeyError:
print("** no instance found **")
return
if (len(my_data) == 2):
print("** attribute name missing **")
return
if (len(my_data) == 3):
print("** value missing **")
return
obj = objs_dict[key].__dict__
if my_data[2] in obj.keys():
data_type = type(obj[my_data[2]])
print(data_type)
obj[my_data[2]] = data_type(my_data[3])
else:
obj[my_data[2]] = my_data[3]
storage.save()
def do_update2(self, arg):
"""
Updates an instance based on the class name and
id by adding or updating attribute
(save the change into the JSON file).
Structure: update [class name] [id] [dictionary]
"""
if not arg:
print("** class name missing **")
return
my_dictionary = "{" + arg.split("{")[1]
my_data = shlex.split(arg)
storage.reload()
objs_dict = storage.all()
if my_data[0] not in HBNBCommand.my_dict.keys():
print("** class doesn't exist **")
return
if (len(my_data) == 1):
print("** instance id missing **")
return
try:
key = my_data[0] + "." + my_data[1]
objs_dict[key]
except KeyError:
print("** no instance found **")
return
if (my_dictionary == "{"):
print("** attribute name missing **")
return
my_dictionary = my_dictionary.replace("\'", "\"")
my_dictionary = json.loads(my_dictionary)
my_instance = objs_dict[key]
for my_key in my_dictionary:
if hasattr(my_instance, my_key):
data_type = type(getattr(my_instance, my_key))
setattr(my_instance, my_key, my_dictionary[my_key])
else:
setattr(my_instance, my_key, my_dictionary[my_key])
storage.save()
def do_count(self, arg):
"""
Counts number of instances of a class
"""
counter = 0
objects_dict = storage.all()
for key in objects_dict:
if (arg in key):
counter += 1
print(counter)
def default(self, arg):
""" handle new ways of inputing data """
val_dict = {
"all": self.do_all,
"count": self.do_count,
"show": self.do_show,
"destroy": self.do_destroy,
"update": self.do_update
}
arg = arg.strip()
values = arg.split(".")
if len(values) != 2:
cmd.Cmd.default(self, arg)
return
class_name = values[0]
command = values[1].split("(")[0]
line = ""
if (command == "update" and values[1].split("(")[1][-2] == "}"):
inputs = values[1].split("(")[1].split(",", 1)
inputs[0] = shlex.split(inputs[0])[0]
line = "".join(inputs)[0:-1]
line = class_name + " " + line
self.do_update2(line.strip())
return
try:
inputs = values[1].split("(")[1].split(",")
for num in range(len(inputs)):
if (num != len(inputs) - 1):
line = line + " " + shlex.split(inputs[num])[0]
else:
line = line + " " + shlex.split(inputs[num][0:-1])[0]
except IndexError:
inputs = ""
line = ""
line = class_name + line
if (command in val_dict.keys()):
val_dict[command](line.strip())
if __name__ == '__main__':
HBNBCommand().cmdloop()