-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.py
More file actions
executable file
·197 lines (170 loc) · 6.08 KB
/
Copy pathconsole.py
File metadata and controls
executable file
·197 lines (170 loc) · 6.08 KB
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
#!/usr/bin/python3
"""contains the entry point of the command interpreter"""
import cmd
import re
from shlex import split
import models
from models.base_model import BaseModel
from models.user import User
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.state import State
from models.review import Review
# A global constant since both functions within and outside uses it.
CLASSES = [
"BaseModel",
"User",
"City",
"Place",
"State",
"Amenity",
"Review"
]
def parse(arg):
curly_braces = re.search(r"\{(.*?)\}", arg)
brackets = re.search(r"\[(.*?)\]", arg)
if curly_braces is None:
if brackets is None:
return [i.strip(",") for i in split(arg)]
else:
lexer = split(arg[:brackets.span()[0]])
retl = [i.strip(",") for i in lexer]
retl.append(brackets.group())
return retl
else:
lexer = split(arg[:curly_braces.span()[0]])
retl = [i.strip(",") for i in lexer]
retl.append(curly_braces.group())
return retl
def check_args(args):
"""checks if args is valid
Args:
args (str): the string containing the arguments passed to a command
Returns:
Error message if args is None or not a valid class, else the arguments
"""
arg_list = parse(args)
if len(arg_list) == 0:
print("** class name missing **")
elif arg_list[0] not in CLASSES:
print("** class doesn't exist **")
else:
return arg_list
class HBNBCommand(cmd.Cmd):
"""The class that implements the console
for the AirBnB clone web application
"""
prompt = "(hbnb) "
storage = models.storage
def emptyline(self):
"""Command to executed when empty line + <ENTER> key"""
pass
def default(self, arg):
"""Default behaviour for cmd module when input is invalid"""
action_map = {
"all": self.do_all,
"show": self.do_show,
"destroy": self.do_destroy,
"count": self.do_count,
"update": self.do_update,
"create": self.do_create
}
match = re.search(r"\.", arg)
if match:
arg1 = [arg[:match.span()[0]], arg[match.span()[1]:]]
match = re.search(r"\((.*?)\)", arg1[1])
if match:
command = [arg1[1][:match.span()[0]], match.group()[1:-1]]
if command[0] in action_map:
call = "{} {}".format(arg1[0], command[1])
return action_map[command[0]](call)
print("*** Unknown syntax: {}".format(arg))
return False
def do_EOF(self, argv):
"""EOF signal to exit the program"""
print("")
return True
def do_quit(self, argv):
"""When executed, exits the console."""
return True
def do_create(self, argv):
"""Creates a new instance of BaseModel, saves it (to a JSON file)
and prints the id"""
args = check_args(argv)
if args:
print(eval(args[0])().id)
self.storage.save()
def do_show(self, argv):
"""Prints the string representation of an instance based
on the class name and id"""
args = check_args(argv)
if args:
if len(args) != 2:
print("** instance id missing **")
else:
key = "{}.{}".format(args[0], args[1])
if key not in self.storage.all():
print("** no instance found **")
else:
print(self.storage.all()[key])
def do_all(self, argv):
"""Prints all string representation of all instances based or not
based on the class name"""
arg_list = split(argv)
objects = self.storage.all().values()
if not arg_list:
print([str(obj) for obj in objects])
else:
if arg_list[0] not in CLASSES:
print("** class doesn't exist **")
else:
print([str(obj) for obj in objects
if arg_list[0] in str(obj)])
def do_destroy(self, argv):
"""Delete a class instance based on the name and given id."""
arg_list = check_args(argv)
if arg_list:
if len(arg_list) == 1:
print("** instance id missing **")
else:
key = "{}.{}".format(*arg_list)
if key in self.storage.all():
del self.storage.all()[key]
self.storage.save()
else:
print("** no instance found **")
def do_update(self, argv):
"""Updates an instance based on the class name and id by adding or
updating attribute and save it to the JSON file."""
arg_list = check_args(argv)
if arg_list:
if len(arg_list) == 1:
print("** instance id missing **")
else:
instance_id = "{}.{}".format(arg_list[0], arg_list[1])
if instance_id in self.storage.all():
if len(arg_list) == 2:
print("** attribute name missing **")
elif len(arg_list) == 3:
print("** value missing **")
else:
obj = self.storage.all()[instance_id]
if arg_list[2] in type(obj).__dict__:
v_type = type(obj.__class__.__dict__[arg_list[2]])
setattr(obj, arg_list[2], v_type(arg_list[3]))
else:
setattr(obj, arg_list[2], arg_list[3])
else:
print("** no instance found **")
self.storage.save()
def do_count(self, arg):
"""Retrieve the number of instances of a class"""
arg1 = parse(arg)
count = 0
for obj in models.storage.all().values():
if arg1[0] == type(obj).__name__:
count += 1
print(count)
if __name__ == "__main__":
HBNBCommand().cmdloop()