Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task 3 and 4 n #1488

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions commit.git
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/bash

if [ $# -eq 0 ]; then
echo "Error: No commit message provided."
echo "Usage: $0 <commit message>"
exit 1
fi

git add .
git commit -m "$*"
git push
175 changes: 108 additions & 67 deletions console.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,84 +2,95 @@
""" Console Module """
import cmd
import sys
from models.base_model import BaseModel

from models.__init__ 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.base_model import BaseModel
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.user import User


class HBNBCommand(cmd.Cmd):
""" Contains the functionality for the HBNB console"""
"""Contains the functionality for the HBNB console"""

# determines prompt for interactive/non-interactive modes
prompt = '(hbnb) ' if sys.__stdin__.isatty() else ''
prompt = "(hbnb) " if sys.__stdin__.isatty() else ""

classes = {
'BaseModel': BaseModel, 'User': User, 'Place': Place,
'State': State, 'City': City, 'Amenity': Amenity,
'Review': Review
}
dot_cmds = ['all', 'count', 'show', 'destroy', 'update']
"BaseModel": BaseModel,
"User": User,
"Place": Place,
"State": State,
"City": City,
"Amenity": Amenity,
"Review": Review,
}
dot_cmds = ["all", "count", "show", "destroy", "update"]
types = {
'number_rooms': int, 'number_bathrooms': int,
'max_guest': int, 'price_by_night': int,
'latitude': float, 'longitude': float
}
"number_rooms": int,
"number_bathrooms": int,
"max_guest": int,
"price_by_night": int,
"latitude": float,
"longitude": float,
}

def preloop(self):
"""Prints if isatty is false"""
if not sys.__stdin__.isatty():
print('(hbnb)')
print("(hbnb)")

def precmd(self, line):
"""Reformat command line for advanced command syntax.

Usage: <class name>.<command>([<id> [<*args> or <**kwargs>]])
(Brackets denote optional fields in usage example.)
"""
_cmd = _cls = _id = _args = '' # initialize line elements
_cmd = _cls = _id = _args = "" # initialize line elements

# scan for general formating - i.e '.', '(', ')'
if not ('.' in line and '(' in line and ')' in line):
if not ("." in line and "(" in line and ")" in line):
return line

try: # parse line left to right
pline = line[:] # parsed line

# isolate <class name>
_cls = pline[:pline.find('.')]
_cls = pline[: pline.find(".")]

# isolate and validate <command>
_cmd = pline[pline.find('.') + 1:pline.find('(')]
_cmd = pline[pline.find(".") + 1 : pline.find("(")]
if _cmd not in HBNBCommand.dot_cmds:
raise Exception

# if parantheses contain arguments, parse them
pline = pline[pline.find('(') + 1:pline.find(')')]
pline = pline[pline.find("(") + 1 : pline.find(")")]
if pline:
# partition args: (<id>, [<delim>], [<*args>])
pline = pline.partition(', ') # pline convert to tuple
pline = pline.partition(", ") # pline convert to tuple

# isolate _id, stripping quotes
_id = pline[0].replace('\"', '')
_id = pline[0].replace('"', "")
# possible bug here:
# empty quotes register as empty _id when replaced

# if arguments exist beyond _id
pline = pline[2].strip() # pline is now str
if pline:
# check for *args or **kwargs
if pline[0] is '{' and pline[-1] is'}'\
and type(eval(pline)) is dict:
if (
pline[0] is "{"
and pline[-1] is "}"
and type(eval(pline)) is dict
):
_args = pline
else:
_args = pline.replace(',', '')
_args = pline.replace(",", "")
# _args = _args.replace('\"', '')
line = ' '.join([_cmd, _cls, _id, _args])
line = " ".join([_cmd, _cls, _id, _args])

except Exception as mess:
pass
Expand All @@ -89,57 +100,86 @@ def precmd(self, line):
def postcmd(self, stop, line):
"""Prints if isatty is false"""
if not sys.__stdin__.isatty():
print('(hbnb) ', end='')
print("(hbnb) ", end="")
return stop

def do_quit(self, command):
""" Method to exit the HBNB console"""
"""Method to exit the HBNB console"""
exit()

def help_quit(self):
""" Prints the help documentation for quit """
"""Prints the help documentation for quit"""
print("Exits the program with formatting\n")

def do_EOF(self, arg):
""" Handles EOF to exit program """
"""Handles EOF to exit program"""
print()
exit()

def help_EOF(self):
""" Prints the help documentation for EOF """
"""Prints the help documentation for EOF"""
print("Exits the program without formatting\n")

def emptyline(self):
""" Overrides the emptyline method of CMD """
"""Overrides the emptyline method of CMD"""
pass

def do_create(self, args):
""" Create an object of any class"""
"""Create an object of any class with optional attributes."""
args = args.split()
if not args:
print("** class name missing **")
return
elif args not in HBNBCommand.classes:

class_name = args[0]
if class_name not in HBNBCommand.classes:
print("** class doesn't exist **")
return
new_instance = HBNBCommand.classes[args]()
storage.save()

# Create instance of the specified class
new_instance = HBNBCommand.classes[class_name]()

# Parse attributes from the remaining arguments
for param in args[1:]:
if "=" not in param:
continue
key, value = param.split("=", 1)

# Handle string values
if value.startswith('"') and value.endswith('"'):
value = value[1:-1].replace("_", " ").replace('\\"', '"')
elif "." in value: # Handle floats
try:
value = float(value)
except ValueError:
continue
else: # Handle integers
try:
value = int(value)
except ValueError:
continue

# Set the attribute to the new instance
setattr(new_instance, key, value)

# Save the new instance
new_instance.save()
print(new_instance.id)
storage.save()

def help_create(self):
""" Help information for the create method """
"""Help information for the create method"""
print("Creates a class of any type")
print("[Usage]: create <className>\n")

def do_show(self, args):
""" Method to show an individual object """
"""Method to show an individual object"""
new = args.partition(" ")
c_name = new[0]
c_id = new[2]

# guard against trailing args
if c_id and ' ' in c_id:
c_id = c_id.partition(' ')[0]
if c_id and " " in c_id:
c_id = c_id.partition(" ")[0]

if not c_name:
print("** class name missing **")
Expand All @@ -160,17 +200,17 @@ def do_show(self, args):
print("** no instance found **")

def help_show(self):
""" Help information for the show command """
"""Help information for the show command"""
print("Shows an individual instance of a class")
print("[Usage]: show <className> <objectId>\n")

def do_destroy(self, args):
""" Destroys a specified object """
"""Destroys a specified object"""
new = args.partition(" ")
c_name = new[0]
c_id = new[2]
if c_id and ' ' in c_id:
c_id = c_id.partition(' ')[0]
if c_id and " " in c_id:
c_id = c_id.partition(" ")[0]

if not c_name:
print("** class name missing **")
Expand All @@ -187,27 +227,27 @@ def do_destroy(self, args):
key = c_name + "." + c_id

try:
del(storage.all()[key])
del storage.all()[key]
storage.save()
except KeyError:
print("** no instance found **")

def help_destroy(self):
""" Help information for the destroy command """
"""Help information for the destroy command"""
print("Destroys an individual instance of a class")
print("[Usage]: destroy <className> <objectId>\n")

def do_all(self, args):
""" Shows all objects, or all objects of a class"""
"""Shows all objects, or all objects of a class"""
print_list = []

if args:
args = args.split(' ')[0] # remove possible trailing args
args = args.split(" ")[0] # remove possible trailing args
if args not in HBNBCommand.classes:
print("** class doesn't exist **")
return
for k, v in storage._FileStorage__objects.items():
if k.split('.')[0] == args:
if k.split(".")[0] == args:
print_list.append(str(v))
else:
for k, v in storage._FileStorage__objects.items():
Expand All @@ -216,15 +256,15 @@ def do_all(self, args):
print(print_list)

def help_all(self):
""" Help information for the all command """
"""Help information for the all command"""
print("Shows all objects, or all of a class")
print("[Usage]: all <className>\n")

def do_count(self, args):
"""Count current number of class instances"""
count = 0
for k, v in storage._FileStorage__objects.items():
if args == k.split('.')[0]:
if args == k.split(".")[0]:
count += 1
print(count)

Expand All @@ -233,8 +273,8 @@ def help_count(self):
print("Usage: count <class_name>")

def do_update(self, args):
""" Updates a certain object with new info """
c_name = c_id = att_name = att_val = kwargs = ''
"""Updates a certain object with new info"""
c_name = c_id = att_name = att_val = kwargs = ""

# isolate cls from id/args, ex: (<cls>, delim, <id/args>)
args = args.partition(" ")
Expand Down Expand Up @@ -264,31 +304,31 @@ def do_update(self, args):
return

# first determine if kwargs or args
if '{' in args[2] and '}' in args[2] and type(eval(args[2])) is dict:
if "{" in args[2] and "}" in args[2] and type(eval(args[2])) is dict:
kwargs = eval(args[2])
args = [] # reformat kwargs into list, ex: [<name>, <value>, ...]
for k, v in kwargs.items():
args.append(k)
args.append(v)
else: # isolate args
args = args[2]
if args and args[0] is '\"': # check for quoted arg
second_quote = args.find('\"', 1)
if args and args[0] is '"': # check for quoted arg
second_quote = args.find('"', 1)
att_name = args[1:second_quote]
args = args[second_quote + 1:]
args = args[second_quote + 1 :]

args = args.partition(' ')
args = args.partition(" ")

# if att_name was not quoted arg
if not att_name and args[0] is not ' ':
if not att_name and args[0] is not " ":
att_name = args[0]
# check for quoted val arg
if args[2] and args[2][0] is '\"':
att_val = args[2][1:args[2].find('\"', 1)]
if args[2] and args[2][0] is '"':
att_val = args[2][1 : args[2].find('"', 1)]

# if att_val was not quoted arg
if not att_val and args[2]:
att_val = args[2].partition(' ')[0]
att_val = args[2].partition(" ")[0]

args = [att_name, att_val]

Expand All @@ -298,7 +338,7 @@ def do_update(self, args):
# iterate through attr names and values
for i, att_name in enumerate(args):
# block only runs on even iterations
if (i % 2 == 0):
if i % 2 == 0:
att_val = args[i + 1] # following item is value
if not att_name: # check for att_name
print("** attribute name missing **")
Expand All @@ -316,9 +356,10 @@ def do_update(self, args):
new_dict.save() # save updates to file

def help_update(self):
""" Help information for the update class """
"""Help information for the update class"""
print("Updates an object with new information")
print("Usage: update <className> <id> <attName> <attVal>\n")


if __name__ == "__main__":
HBNBCommand().cmdloop()
1 change: 1 addition & 0 deletions file.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"Place.3cf584cf-331b-45c8-87a8-ec367dcfd6ed": {"id": "3cf584cf-331b-45c8-87a8-ec367dcfd6ed", "created_at": "2024-12-26T19:26:55.073641", "updated_at": "2024-12-26T19:26:55.073694", "__class__": "Place"}, "State.9d00f28b-d54c-4d2c-af16-20d04bc70966": {"id": "9d00f28b-d54c-4d2c-af16-20d04bc70966", "created_at": "2024-12-26T19:32:46.414784", "updated_at": "2024-12-26T19:32:46.414794", "name": "California", "__class__": "State"}, "State.2d7b0012-1e26-435d-8ea9-f342781d4add": {"id": "2d7b0012-1e26-435d-8ea9-f342781d4add", "created_at": "2024-12-26T19:32:46.414922", "updated_at": "2024-12-26T19:32:46.414928", "name": "Arizona", "__class__": "State"}, "Place.1053f220-4054-4bbd-84cd-7e1ff21fda3d": {"id": "1053f220-4054-4bbd-84cd-7e1ff21fda3d", "created_at": "2024-12-26T19:32:46.415036", "updated_at": "2024-12-26T19:32:46.415047", "city_id": "0001", "user_id": "0001", "name": "My little house", "number_rooms": 4, "number_bathrooms": 2, "max_guest": 10, "price_by_night": 300, "latitude": 37.773972, "longitude": -122.431297, "__class__": "Place"}, "State.0568f8c9-93c6-4457-a22e-89110d4ab8f4": {"id": "0568f8c9-93c6-4457-a22e-89110d4ab8f4", "created_at": "2024-12-26T20:07:43.060579", "updated_at": "2024-12-26T20:07:43.062697", "name": "California", "__class__": "State"}, "State.569f54b9-c959-41f5-8ca3-671c28c1b501": {"id": "569f54b9-c959-41f5-8ca3-671c28c1b501", "created_at": "2024-12-26T20:07:43.072867", "updated_at": "2024-12-26T20:07:43.073088", "name": "Arizona", "__class__": "State"}, "Place.a5bcbc2b-f9f2-4494-84f3-ce8944aeaa77": {"id": "a5bcbc2b-f9f2-4494-84f3-ce8944aeaa77", "created_at": "2024-12-26T20:07:43.143697", "updated_at": "2024-12-26T20:07:43.143930", "city_id": "0001", "user_id": "0001", "name": "My little house", "number_rooms": 4, "number_bathrooms": 2, "max_guest": 10, "price_by_night": 300, "latitude": 37.773972, "longitude": -122.431297, "__class__": "Place"}, "State.747e6936-9c65-48c2-91a1-3878998809ff": {"id": "747e6936-9c65-48c2-91a1-3878998809ff", "created_at": "2024-12-26T20:24:14.794225", "updated_at": "2024-12-26T20:24:14.794326", "name": "California", "__class__": "State"}, "State.e7ba01bf-95d5-4ccb-b1e4-af734d803462": {"id": "e7ba01bf-95d5-4ccb-b1e4-af734d803462", "created_at": "2024-12-26T20:24:14.807588", "updated_at": "2024-12-26T20:24:14.807679", "name": "Arizona", "__class__": "State"}, "Place.864c732a-8c8f-447e-9750-36160c0d794e": {"id": "864c732a-8c8f-447e-9750-36160c0d794e", "created_at": "2024-12-26T20:24:14.870551", "updated_at": "2024-12-26T20:24:14.870735", "city_id": "0001", "user_id": "0001", "name": "My little house", "number_rooms": 4, "number_bathrooms": 2, "max_guest": 10, "price_by_night": 300, "latitude": 37.773972, "longitude": -122.431297, "__class__": "Place"}, "State.5df641c3-4eac-4c2f-8203-63811ff1e25d": {"id": "5df641c3-4eac-4c2f-8203-63811ff1e25d", "created_at": "2024-12-26T21:26:53.440544", "updated_at": "2024-12-26T21:26:53.441147", "name": "California", "__class__": "State"}, "State.abb66181-52e3-45d5-9c15-d3bfdb80ff3a": {"id": "abb66181-52e3-45d5-9c15-d3bfdb80ff3a", "created_at": "2024-12-26T21:26:53.452985", "updated_at": "2024-12-26T21:26:53.453186", "name": "Arizona", "__class__": "State"}, "Place.84f5e215-b6a3-45dd-bcb9-91b03f18c503": {"id": "84f5e215-b6a3-45dd-bcb9-91b03f18c503", "created_at": "2024-12-26T21:26:53.524178", "updated_at": "2024-12-26T21:26:53.524472", "city_id": "0001", "user_id": "0001", "name": "My little house", "number_rooms": 4, "number_bathrooms": 2, "max_guest": 10, "price_by_night": 300, "latitude": 37.773972, "longitude": -122.431297, "__class__": "Place"}, "State.e4ce9678-eb3b-4322-988e-79c867d66c73": {"id": "e4ce9678-eb3b-4322-988e-79c867d66c73", "created_at": "2024-12-26T21:27:13.865525", "updated_at": "2024-12-26T21:27:13.865621", "name": "California", "__class__": "State"}, "State.296cdd4b-7403-4b5b-ad70-e98a65215900": {"id": "296cdd4b-7403-4b5b-ad70-e98a65215900", "created_at": "2024-12-26T21:27:13.879257", "updated_at": "2024-12-26T21:27:13.879362", "name": "Arizona", "__class__": "State"}, "Place.e1bd8b08-a057-439f-afd7-86d0f4b8af55": {"id": "e1bd8b08-a057-439f-afd7-86d0f4b8af55", "created_at": "2024-12-26T21:27:13.935730", "updated_at": "2024-12-26T21:27:13.935954", "city_id": "0001", "user_id": "0001", "name": "My little house", "number_rooms": 4, "number_bathrooms": 2, "max_guest": 10, "price_by_night": 300, "latitude": 37.773972, "longitude": -122.431297, "__class__": "Place"}, "State.0ac174c3-a4f1-45b3-b7df-783c5bba23ba": {"id": "0ac174c3-a4f1-45b3-b7df-783c5bba23ba", "created_at": "2024-12-26T21:29:02.280508", "updated_at": "2024-12-26T21:29:02.280604", "name": "California", "__class__": "State"}, "State.51253fe4-57de-4da2-932f-521cf5831482": {"id": "51253fe4-57de-4da2-932f-521cf5831482", "created_at": "2024-12-26T21:29:02.293688", "updated_at": "2024-12-26T21:29:02.293830", "name": "Arizona", "__class__": "State"}, "Place.97a526a0-a411-43d1-bd99-a8a2297c88e5": {"id": "97a526a0-a411-43d1-bd99-a8a2297c88e5", "created_at": "2024-12-26T21:29:02.352624", "updated_at": "2024-12-26T21:29:02.352806", "city_id": "0001", "user_id": "0001", "name": "My little house", "number_rooms": 4, "number_bathrooms": 2, "max_guest": 10, "price_by_night": 300, "latitude": 37.773972, "longitude": -122.431297, "__class__": "Place"}, "State.0526d118-d842-4a02-9181-3c546a0f85bf": {"id": "0526d118-d842-4a02-9181-3c546a0f85bf", "created_at": "2024-12-26T21:36:15.007339", "updated_at": "2024-12-26T21:36:15.007388", "name": "California", "__class__": "State"}, "State.a7d4b080-1b11-46cf-b84b-9f7fec1baa08": {"id": "a7d4b080-1b11-46cf-b84b-9f7fec1baa08", "created_at": "2024-12-26T21:36:15.012978", "updated_at": "2024-12-26T21:36:15.013048", "name": "Arizona", "__class__": "State"}, "Place.930a14c7-503e-4a49-85cf-bc2996aac7e0": {"id": "930a14c7-503e-4a49-85cf-bc2996aac7e0", "created_at": "2024-12-26T21:36:15.049672", "updated_at": "2024-12-26T21:36:15.049760", "city_id": "0001", "user_id": "0001", "name": "My little house", "number_rooms": 4, "number_bathrooms": 2, "max_guest": 10, "price_by_night": 300, "latitude": 37.773972, "longitude": -122.431297, "__class__": "Place"}}
Binary file added models/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added models/__pycache__/amenity.cpython-310.pyc
Binary file not shown.
Binary file added models/__pycache__/base_model.cpython-310.pyc
Binary file not shown.
Binary file added models/__pycache__/city.cpython-310.pyc
Binary file not shown.
Binary file added models/__pycache__/place.cpython-310.pyc
Binary file not shown.
Binary file added models/__pycache__/review.cpython-310.pyc
Binary file not shown.
Binary file added models/__pycache__/state.cpython-310.pyc
Binary file not shown.
Binary file added models/__pycache__/user.cpython-310.pyc
Binary file not shown.
Binary file added models/engine/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file not shown.
7 changes: 7 additions & 0 deletions setup_mysql_dev.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- preparing MySQL server
CREATE DATABASE IF NOT EXISTS hbnb_dev_db;
CREATE USER IF NOT EXISTS 'hbnb_dev'@'localhost' IDENTIFIED BY 'hbnb_dev_pwd';
GRANT ALL PRIVILEGES ON hbnb_dev_db.* TO 'hbnb_dev'@'localhost';
FLUSH PRIVILEGES;
GRANT SELECT ON performance_schema.* TO 'hbnb_dev'@'localhost';
FLUSH PRIVILEGES;
Loading