-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconsole.py
executable file
·188 lines (165 loc) · 4.9 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
#!/usr/bin/python3
import cmd
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):
"""Console"""
prompt = "(hbnb) "
__classes = ["BaseModel",
"User",
"Place",
"State",
"City",
"Amenity",
"Review"
]
def do_quit(self, line):
"""to Exit Console
"""
return True
def do_EOF(self, line):
"""to Exit Console
"""
return True
def emptyline(self):
"""Passes an emply line instead of repeating previous command
"""
pass
def do_create(self, arg):
"""Creates a new instance of BaseModel, saves it (to the JSON file) and prints the id
"""
args = arg.split()
if len(args) == 0:
print("** class name missing **")
elif args[0] not in self.__classes:
print("** class doesn't exist **")
else:
new_object = eval(f"{args[0]}")()
print(new_object.id)
storage.save()
def do_show(self, arg):
"""Prints the string representation of an instance based on the class name and id
"""
args = arg.split()
#no_cls_name = eval(f"{args[0]")())
if len(args) == 0:
print("** class name missing **")
elif args[0] not in self.__classes:
print("** class doesn't exist **")
elif len(args) == 1:
print("** instance id missing **")
elif f"{args[0]}.{args[1]}" not in storage.all():
print("** no instance found **")
else:
print(storage.all()[f"{args[0]}.{args[1]}"])
def do_destroy(self, arg):
""" Deletes an instance based on the class name and id (save the change into the JSON file)
"""
args = arg.split()
if len(args) == 0:
print("** class name missing **")
elif args[0] not in self.__classes:
print("** class doesn't exist **")
elif len(args) == 1:
print("** instance id missing **")
elif f"{args[0]}.{args[1]}" not in storage.all():
print("** no instance found **")
else:
del storage.all()[f"{args[0]}.{args[1]}"]
storage.save()
def do_all(self, arg):
"""Prints all string representation of all instances based or not on the class name.
"""
args = arg.split()
if len(args) == 0:
print([str(v) for v in storage.all().values()])
elif args[0] not in self.__classes:
print("** class doesn't exist **")
else:
print([str(v) for k, v in storage.all().items() if k.startswith(args[0])])
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)
"""
args = arg.split()
if len(args) == 0:
print("** class name missing **")
elif args[0] not in self.__classes:
print("** class doesn't exist **")
elif len(args) == 1:
print("** instance id missing **")
elif f"{args[0]}.{args[1]}" not in storage.all():
print("** no instance found **")
elif len(args) == 2:
print("** attribute name missing **")
elif len(args) == 3:
print("** value missing **")
else:
obj_name = args[0]
obj_id = args[1]
obj_key = f"{obj_name}.{obj_id}"
obj = storage.all()[obj_key]
attr_name = args[2]
attr_value = args[3].replace('"', "").replace("'", "")
#print("-----------")
#print()
#print(obj)
# if attr_value == "'" or attr_value == '"':
# attr_value = attr_value[1:-1]
# attr_value = attr_value.strip('"').strip("'")
# print(attr_value)
if hasattr(obj, attr_name):
type_ = type(getattr(obj, attr_name))
if type_ in [str, int, float]:
attr_value = type_(attr_value)
setattr(obj, attr_name, attr_value)
else:
setattr(obj, attr_name, attr_value)
storage.save()
def default(self, arg):
"""default
"""
args = arg.split(".")
if args[0] in self.__classes:
if args[1] == "all()":
self.do_all(args[0])
elif args[1] == "count()":
list_ = [v for k, v in storage.all().items() if k.startswith(args[0])]
print(len(list_))
elif args[1].startswith("show"):
split_ = args[1].split('"')
id_ = split_[1]
self.do_show(f"{args[0]} {id_}")
elif args[1].startswith("destroy"):
split_ = args[1].split('"')
id_ = split_[1]
self.do_destroy(f"{args[0]} {id_}")
elif args[1].startswith("update"):
if '{' or '}' in args[1]:
split_ = args[1].split("(")
split_ = split_[1].split(", {")
id_ = split_[0].strip('"')
dict_ = "{" + split_[1].strip(')')
dict_ = eval(dict_)
for k, v in dict_.items():
#print(f"{k} = {v}")
self.do_update(f"{args[0]} {id_} {k} {v}")
else:
print("I don't have a dictionary")
id_ = split_[0]
replace_ = args[1].replace('"', "")
split_ = replace_.split("(")
split_ = split_[1].strip(")").split(", ")
attr_name = split_[1]
attr_value = split_[2]
#print(id_)
#print(attr_name)
#print(attr_value)
self.do_update(f"{args[0]} {id_} {attr_name} {attr_value}")
if __name__ == "__main__":
HBNBCommand().cmdloop()