-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconsole.py
executable file
·252 lines (211 loc) · 7.94 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
#!/usr/bin/python3
"""
This module serves as the entry point for the command interpreter.
It introduces the `HBNBCommand` class, a subclass of `cmd.Cmd`.
The primary purpose of this module is to provide abstractions for interacting with
a versatile storage system (FileStorage / DB).
These abstractions facilitate seamless transitions between different storage types
without requiring extensive codebase modifications.
The functionality of this module enables interactive and non-interactive operations, allowing users to:
- Create data models
- Manage objects (create, update, destroy, etc.) through a console / interpreter
- Persist objects to a file (JSON file)
Usage Example:
$ ./console
(hbnb)
(hbnb) help
Documented commands (type help <topic>):
========================================
EOF create help quit
(hbnb)
(hbnb) quit
$
"""
import cmd
import re
import os
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.place import Place
from models.amenity import Amenity
from models.review import Review
# Our classess
current_classes = {
'BaseModel': BaseModel,
'User': User,
'Amenity': Amenity,
'City': City,
'State': State,
'Place': Place,
'Review': Review
}
def check_class_name(args, check_id=False):
"""
Check if the class name is valid:
- if the class name is missing, print ** class name missing **
- if the class name does not exist, print ** class does not exist **
- if the id is missing, print ** id missing **
"""
if len(args) == 0:
print("** class name missing **")
return False
if args[0] not in current_classes.keys():
print("** class doesn't exist **")
return False
if check_id and len(args) == 1:
print("** instance id missing **")
return False
return True
class HBNBCommand(cmd.Cmd):
"""
class HBNBCommand that inherits from cmd.Cmd
Defines command interepreter that implement the basic functionalities for creating,
showing, destroying, listing, and updating instances in your command interpreter.
Rules:
- You can assume arguments are always in the right order
- Each arguments are separated by a space
- A string argument with a space must be between double quote
- The error management starts from the first argument to the last one
"""
prompt = "(hbnb) "
def default(self, arg):
"""Default behavior for cmd module when input is invalid"""
argdict = {
"all": self.do_all,
"show": self.do_show,
"destroy": self.do_destroy,
"count": self.do_count,
"update": self.do_update
}
match = re.search(r"\.", arg)
if match is not None:
argl = [arg[:match.span()[0]], arg[match.span()[1]:]]
match = re.search(r"\((.*?)\)", argl[1])
if match is not None:
command = [argl[1][:match.span()[0]], match.group()[1:-1]]
if command[0] in argdict.keys():
call = "{} {}".format(argl[0], command[1])
return argdict[command[0]](call)
print("*** Unknown syntax: {}".format(arg))
return False
def do_count(self, arg):
"""
Retrieve the number of instances of a class.
ex: $ User.count()
"""
args = arg.split()
if not check_class_name(args):
return
class_name = args[0]
instances_count = sum(1 for instance in storage.all()
.values() if instance.__class__.__name__ == class_name)
print(instances_count)
def do_quit(self, arg):
"""Quit command to exit the program."""
return True
def do_EOF(self, arg):
"""EOF signal to exit the program."""
print("")
return True
def emptyline(self):
"""Do nothing upon receiving an empty line."""
pass
def do_create(self , arg):
"""
ex: $ create BaseModel
if the class exists then create it:
Creates a new instance of the class.
save it to JSON file and return id of the new instance
"""
args = arg.split()
if not check_class_name(args):
return
class_name = args[0]
new_instance = current_classes[class_name]()
new_instance.save()
print(new_instance.id)
def do_show(self, arg):
"""
ex: $ show BaseModel 1234-1234-1234
Prints the string representation of an instance based on the class name and id
if the isntance of the class name doesn't exist for the id, print ** no instance found **
"""
args = arg.split()
if not check_class_name(args, check_id=True):
return
all_instances = storage.all()
key = "{}.{}".format(args[0], args[1])
req_instance = all_instances.get(key, None)
if req_instance is None:
print("** no instance found **")
return
print(req_instance)
def do_destroy(self , arg):
"""
ex: $ destroy BaseModel 1234-1234-1234
Deletes an instance based on the class name and id (save the change into the JSON file)
"""
args = arg.split()
if not check_class_name(args, check_id=True):
return
all_instances = storage.all()
key = "{}.{}".format(args[0], args[1])
req_instance = all_instances.get(key, None)
if req_instance is None:
print("** no instance found **")
return
del all_instances[key]
storage.save()
def do_all(self, arg):
"""
List all instances of the class name
The printed result must be a list of strings
If the class name doesn’t exist, print ** class doesn't exist **
ex: $ all BaseModel
"""
args = arg.split()
all_instances = storage.all() #all return a dictionary with all instances
if len(args) == 0:
for _, instance in all_instances.items():
print(str(instance))
return
if args[0] not in current_classes.keys():
print("** class doesn't exist **")
return
else:
for _, instance in all_instances.items():
if instance.__class__.__name__ == args[0]:
print(str(instance))
return
def do_update(self, arg):
"""
Updates an instance based on the class name and id
ex: $ update <class name> <id> <attribute name> "<attribute value>"
Update BaseModel 1234-1234-1234 email "[email protected]"
Updates an instance based on the class name and id (save the change into the JSON file)
"""
args = arg.split(maxsplit=3)
if not check_class_name(args, check_id=True):
return
all_instances = storage.all()
key = "{}.{}".format(args[0], args[1])
req_instance = all_instances.get(key, None)
if req_instance is None:
print("** no instance found **")
return
if len(args) < 3:
print("** attribute name missing **")
return
if len(args) < 4:
print("** value missing **")
return
if args[2] in ["id", "created_at", "updated_at"]:
print("** cannot update id, created_at, or updated_at **")
return
setattr(req_instance, args[2], args[3])
storage.save()
if __name__ == '__main__':
HBNBCommand().cmdloop()