-
Notifications
You must be signed in to change notification settings - Fork 31
/
console.py
executable file
·280 lines (237 loc) · 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
#!/usr/bin/python3
"""
The console v: 0.0.1
Contains the entry point of the command interpreter
"""
import cmd
import json
import re
import models
# from models import storage
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):
"""
Custom console class
"""
prompt = '(hbnb) '
def my_errors(self, line, num_of_args):
"""Displays error messages to user
Args:
line(any): gets user input using command line
num_of_args(int): number of input arguments
Description:
Displays output to the use based on
the input commands.
"""
classes = ["BaseModel", "User", "State", "City",
"Amenity", "Place", "Review"]
msg = ["** class name missing **",
"** class doesn't exist **",
"** instance id missing **",
"** no instance found **",
"** attribute name missing **",
"** value missing **"]
if not line:
print(msg[0])
return 1
args = line.split()
if num_of_args >= 1 and args[0] not in classes:
print(msg[1])
return 1
elif num_of_args == 1:
return 0
if num_of_args >= 2 and len(args) < 2:
print(msg[2])
return 1
d = storage.all()
for i in range(len(args)):
if args[i][0] == '"':
args[i] = args[i].replace('"', "")
key = args[0] + '.' + args[1]
if num_of_args >= 2 and key not in d:
print(msg[3])
return 1
elif num_of_args == 2:
return 0
if num_of_args >= 4 and len(args) < 3:
print(msg[4])
return 1
if num_of_args >= 4 and len(args) < 4:
print(msg[5])
return 1
return 0
def handle_empty_line(self, line):
"""
Eliminates empty lines
"""
return False
def do_quit(self, line):
"""Handles the 'quit' command
Args:
line(args): input argument for quiting
the terminal
"""
return True
def do_EOF(self, line):
"""Quits command interpreter with ctrl+d
Args:
line(args): input argument for quiting
the terminal
"""
return True
def do_create(self, line):
"""Creates a new instance of @cls_name class,
and prints the new instance's ID.
Args:
line(args): Arguments to enter with command: <class name>
Example: 'create User'
"""
if (self.my_errors(line, 1) == 1):
return
args = line.split(" ")
"""
args[0] contains class name, create new instance
of that class updates 'updated_at' attribute,
and saves into JSON file
"""
obj = eval(args[0])()
obj.save()
print(obj.id)
def do_show(self, line):
"""Prints a string representation of an instance.
Args:
line(line): to enter with command <class name> <id>
Example: 'show User 1234-1234-1234'
"""
if (self.my_errors(line, 2) == 1):
return
args = line.split()
d = storage.all()
if args[1][0] == '"':
args[1] = args[1].replace('"', "")
key = args[0] + '.' + args[1]
print(d[key])
def do_destroy(self, line):
"""Deletes an instance of a certain class.
Args:
line(args): to enter with command: <class name> <id>
Example: 'destroy User 1234-1234-1234'
"""
if (self.my_errors(line, 2) == 1):
return
args = line.split()
d = storage.all()
if args[1][0] == '"':
args[1] = args[1].replace('"', "")
key = args[0] + '.' + args[1]
del d[key]
storage.save()
def do_all(self, line):
"""Shows all instances, or instances of a certain class
Args:
line(args): enter with command (optional): <class name>
Example: 'all' OR 'all User'
"""
d = storage.all()
if not line:
print([str(x) for x in d.values()])
return
args = line.split()
if (self.my_errors(line, 1) == 1):
return
print([str(v) for v in d.values()
if v.__class__.__name__ == args[0]])
def do_update(self, line):
"""Updates an instance based on the class name
and id by adding or updating an attribute
Args:
line(args): receives the commands:
<class name> <id> <attribute name> "<attribute value>"
Example: 'update User 1234-1234-1234 my_name "Bob"'
"""
if (self.my_errors(line, 4) == 1):
return
args = line.split()
d = storage.all()
for i in range(len(args[1:]) + 1):
if args[i][0] == '"':
args[i] = args[i].replace('"', "")
key = args[0] + '.' + args[1]
attr_k = args[2]
attr_v = args[3]
try:
if attr_v.isdigit():
attr_v = int(attr_v)
elif float(attr_v):
attr_v = float(attr_v)
except ValueError:
pass
class_attr = type(d[key]).__dict__
if attr_k in class_attr.keys():
try:
attr_v = type(class_attr[attr_k])(attr_v)
except Exception:
print("Entered wrong value type")
return
setattr(d[key], attr_k, attr_v)
storage.save()
def my_count(self, class_n):
"""
Method counts instances of a certain class
"""
count_instance = 0
for instance_object in storage.all().values():
if instance_object.__class__.__name__ == class_n:
count_instance += 1
print(count_instance)
def default(self, line):
"""Method to take care of following commands:
<class name>.all()
<class name>.count()
<class name>.show(<id>)
<class name>.destroy(<id>)
<class name>.update(<id>, <attribute name>, <attribute value>)
<class name>.update(<id>, <dictionary representation)
Description:
Creates a list representations of functional models
Then use the functional methods to implement user
commands, by validating all the input commands
"""
names = ["BaseModel", "User", "State", "City", "Amenity",
"Place", "Review"]
commands = {"all": self.do_all,
"count": self.my_count,
"show": self.do_show,
"destroy": self.do_destroy,
"update": self.do_update}
args = re.match(r"^(\w+)\.(\w+)\((.*)\)", line)
if args:
args = args.groups()
if not args or len(args) < 2 or args[0] not in names \
or args[1] not in commands.keys():
super().default(line)
return
if args[1] in ["all", "count"]:
commands[args[1]](args[0])
elif args[1] in ["show", "destroy"]:
commands[args[1]](args[0] + ' ' + args[2])
elif args[1] == "update":
params = re.match(r"\"(.+?)\", (.+)", args[2])
if params.groups()[1][0] == '{':
dic_p = eval(params.groups()[1])
for k, v in dic_p.items():
commands[args[1]](args[0] + " " + params.groups()[0] +
" " + k + " " + str(v))
else:
rest = params.groups()[1].split(", ")
commands[args[1]](args[0] + " " + params.groups()[0] + " " +
rest[0] + " " + rest[1])
if __name__ == '__main__':
cli = HBNBCommand()
cli.cmdloop()