-
Notifications
You must be signed in to change notification settings - Fork 1
/
console.py
executable file
·230 lines (206 loc) · 7.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
#!/usr/bin/python3
"""
This module provides a command line interface for the program
"""
import cmd
from models import storage
from models.base_model import BaseModel
from models.amenity import Amenity
from models.state import State
from models.user import User
from models.place import Place
from models.city import City
from models.review import Review
from models.engine.file_storage import FileStorage
class HBNBCommand(cmd.Cmd):
"""
Provides methods for handling commands in the program CLI
"""
prompt = "(hbnb) "
CLASSES = [
"BaseModel", "User", "State",
"Amenity", "Place", "City", "Review"
]
def do_create(self, line):
"""
Creates a new instance of an object
Usage create <object>
"""
args = line.split(" ")
if line == "":
print("** class name missing **")
elif line not in HBNBCommand.CLASSES:
print("** class doesn't exist **")
else:
if args[0] == "BaseModel":
base = BaseModel()
elif args[0] == "User":
base = User()
elif args[0] == "State":
base = State()
elif args[0] == "Amenity":
base = Amenity()
elif args[0] == "Place":
base = Place()
elif args[0] == "City":
base = City()
elif args[0] == "Review":
base = Review()
print(base.id)
storage.save()
def do_show(self, line):
"""
Prints the string representation of an instance
Usage: show <object> <id>
"""
objs = storage.all()
args = line.split(" ")
if line == "":
print("** class name missing **")
elif args[0] not in HBNBCommand.CLASSES:
print("** class doesn't exist **")
elif len(args) < 2:
print("** instance id missing **")
else:
args[1] = args[1].replace('"', '') \
if args[1][0] == '"' else args[1]
classname_id = args[0] + "." + args[1]
if classname_id not in objs.keys():
print("** no instance found **")
else:
print(objs[classname_id])
def do_destroy(self, line):
"""
Deletes an instance
Usage: destroy <object> <id>
"""
objs = storage.all()
args = line.split(" ")
if line == "":
print("** class name missing **")
elif args[0] not in HBNBCommand.CLASSES:
print("** class doesn't exist **")
elif len(args) < 2:
print("** instance id missing **")
else:
args[1] = args[1].replace('"', '') \
if args[1][0] == '"' else args[1]
classname_id = args[0] + "." + args[1]
if classname_id not in objs.keys():
print("** no instance found **")
else:
del objs[classname_id]
storage.save()
def do_all(self, line):
"""
Prints all string representation of all instances
Usage: all <object> | all
"""
objs = storage.all()
args = line.split(" ")
if args[0] != "":
if args[0] not in HBNBCommand.CLASSES:
print("** class doesn't exist **")
else:
all_list = []
for obj in objs:
if obj.startswith(args[0]):
all_list.append(str(objs[obj]))
print(all_list)
else:
all_list = []
for obj in objs:
all_list.append(str(objs[obj]))
print(all_list)
def do_update(self, line):
"""
Updates an instance by adding or updating attribute
Usage: update <class name> <id> <attribute name> "<attribute value>"
"""
objs = storage.all()
args = line.split(" ")
if line == "":
print("** class name missing **")
elif args[0] not in HBNBCommand.CLASSES:
print("** class doesn't exist **")
elif len(args) < 2:
print("** instance id missing **")
else:
args[1] = args[1].replace('"', '') \
if args[1][0] == '"' else args[1]
classname_id = args[0] + "." + args[1]
if classname_id not in objs.keys():
print("** no instance found **")
elif len(args) < 3:
print("** attribute name missing **")
elif len(args) < 4:
print("** value missing **")
else:
args[2] = args[2].replace('"', '').replace("'", "")
obj = objs[classname_id]
if args[3].startswith('"') and args[3].endswith('"') or \
args[3].startswith("'") and args[3].endswith("'"):
setattr(obj, args[2], str(args[3][1:-1]))
elif args[3].startswith('"') and not args[3].endswith('"') or \
args[3].startswith("'") and not args[3].endswith("'"):
str_value = ""
for arg in args[3:]:
str_value += " " + arg
if arg.endswith('"') or arg.endswith("'"):
break
setattr(obj, args[2], str(str_value[2:-1]))
elif "." in args[3]:
setattr(obj, args[2], float(args[3]))
else:
setattr(obj, args[2], int(args[3]))
storage.save()
def do_count(self, line):
"""
Count the number of objects
"""
objs = storage.all()
args = line.split(" ")
obj_names = list(map(lambda obj: type(obj).__name__, objs.values()))
print("{}".format(obj_names.count(line)))
def update_dict(self, command, line):
attr = line.split("{")[1][0:-2].replace(":", "").split(", ")
for item in attr:
comm = command + " " + item
self.onecmd(comm)
def default(self, line):
"""
Handle other commands like:
<class name>.all()
<class name>.count()
"""
METHODS = ["all", "count", "show", "destroy", "update"]
if "." in line:
command = line[:-1].replace(",", "")\
.replace("(", " ").replace(".", " ").split(" ")
command[0], command[1] = command[1], command[0]
if command[1] in HBNBCommand.CLASSES and command[0] in METHODS:
if command[0] == "update" and "{" in line:
self.update_dict(" ".join(command[:3]), line)
return None
self.onecmd(" ".join(command))
return None
return cmd.Cmd.default(self, line)
def do_EOF(self, line):
"""
Ends the command line interpreter
Usage: CTRL+D
"""
return True
def do_quit(self, line):
"""
Ends the command line interpreter
Usage: quit
"""
return True
def emptyline(self):
"""
Ignore empty lines (ENTER)
"""
pass
if __name__ == "__main__":
HBNBCommand().cmdloop()