Skip to content

Commit

Permalink
using custom errors for error handling!
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonak-Adipta-Kalita committed Jul 15, 2024
1 parent 08a551d commit 7a1b008
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 34 deletions.
52 changes: 30 additions & 22 deletions flomo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@

import flomo.tracker as tracker
import flomo.ui as ui

# TODO: "Memory Management" isnt working properly when sessions.db is present without any table
import flomo.errors as errors


@click.group(cls=click_aliases.ClickAliasedGroup)
Expand All @@ -18,24 +17,33 @@ def flomo():
pass


@flomo.command(aliases=["i"])
def init():
"""
Initialize the required files for Flomo.
"""
db = tracker.Tracker(initializing=True)
db.create_table()
db.conn.close()

# Initialize Config


@flomo.command(aliases=["s"])
@click.option("-t", "--tag", default="Default", help="Session tag name.")
@click.option("-n", "--name", default="Work", help="Session Name")
def start(tag: str, name: str):
"""
Start a Flowmodoro session.
"""
# create_db_file = False
# if not os.path.exists(helpers.get_path("sessions.db", True)):
# create_db_file = True

db = tracker.Tracker()
# if create_db_file:
# db.create_table()
db.create_table()
session_id = db.create_session(tag, name, datetime.datetime.now())
db.conn.close()
ui.main(tag.lower(), name, session_id)
try:
db = tracker.Tracker()
db.create_table()
session_id = db.create_session(tag, name, datetime.datetime.now())
db.conn.close()
ui.main(tag.lower(), name, session_id)
except errors.DBFileNotFoundError as e:
print(e)


@flomo.command(aliases=["t"])
Expand All @@ -44,11 +52,13 @@ def tracking():
Show the tracking history.
"""
try:
# if not os.path.exists(helpers.get_path("sessions.db", True)):
# raise sqlite3.OperationalError
tracker.show_sessions()
except sqlite3.OperationalError:
print("No sessions were found.")
except (
errors.DBFileNotFoundError,
errors.NoSessionsError,
errors.NoSessionError,
) as e:
print(e)


@flomo.command(aliases=["d"])
Expand All @@ -58,13 +68,11 @@ def delete(session_id: str):
Delete a session.
"""
try:
# if not os.path.exists(helpers.get_path("sessions.db", True)):
# raise sqlite3.OperationalError
db = tracker.Tracker()
db.delete_session(float(session_id))
db.delete_session(int(session_id))
db.conn.close()
except sqlite3.OperationalError:
print("No sessions were found.")
except (errors.DBFileNotFoundError, errors.NoSessionError) as e:
print(e)


if __name__ == "__main__":
Expand Down
13 changes: 13 additions & 0 deletions flomo/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class DBFileNotFoundError(Exception):
def __init__(self):
super().__init__("Database file does not exist. Please run `flomo init`.")


class NoSessionsError(Exception):
def __init__(self):
super().__init__("No sessions were found.")


class NoSessionError(Exception):
def __init__(self, session_id):
super().__init__(f"No session with ID {session_id} was found.")
2 changes: 1 addition & 1 deletion flomo/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def play_sound():


def message_log(message: str):
path = get_path("message.log", True)
path = get_path("message.log", in_data=True)

with open(path, "a") as f:
f.write(message + "\n")
Expand Down
28 changes: 18 additions & 10 deletions flomo/tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,39 @@
import tabulate

import flomo.helpers as helpers
import flomo.errors as errors


class Tracker:
def __init__(self):
path = helpers.get_path("sessions.db", True)
def __init__(self, initializing: bool = False):
path = helpers.get_path("sessions.db", in_data=True)

self.conn = sqlite3.connect(path)
self.cursor = self.conn.cursor()

if not initializing and not self.db_file_exists():
raise errors.DBFileNotFoundError()

def db_file_exists(self):
self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
return bool(self.cursor.fetchall())

def create_table(self):
self.cursor.execute(
"CREATE TABLE IF NOT EXISTS sessions (id FLOAT PRIMARY KEY, date_time TEXT, tag TEXT, name TEXT, total_time TEXT)"
)
self.conn.commit()

def create_session(
self, tag: str, name: str, start_time: datetime.datetime
) -> float:
session_id = start_time.timestamp() % 1000000
def create_session(self, tag: str, name: str, start_time: datetime.datetime) -> int:
session_id = int(start_time.timestamp() % 1000000)
self.cursor.execute(
"INSERT INTO sessions (id, date_time, tag, name) VALUES (?, ?, ?, ?)",
(session_id, start_time.strftime("%Y-%m-%d %H:%M:%S"), tag, name),
)
self.conn.commit()
return session_id

def update_session(self, session_id: float, end_time: datetime.datetime):
def update_session(self, session_id: int, end_time: datetime.datetime):
date_time = self.get_session(session_id)[1]
total_time = end_time - datetime.datetime.strptime(
date_time, "%Y-%m-%d %H:%M:%S"
Expand All @@ -49,16 +55,18 @@ def get_sessions(self):
self.cursor.execute("SELECT * FROM sessions")
return self.cursor.fetchall()

def get_session(self, session_id: float):
def get_session(self, session_id: int):
self.cursor.execute("SELECT * FROM sessions WHERE id = ?", (session_id,))
return self.cursor.fetchone()

def delete_session(self, session_id: float):
def delete_session(self, session_id: int):
if not self.get_session(session_id):
raise errors.NoSessionError(session_id)
self.cursor.execute("DELETE FROM sessions WHERE id = ?", (session_id,))
self.conn.commit()


def update_session(session_id: float):
def update_session(session_id: int):
db = Tracker()
db.update_session(session_id, datetime.datetime.now())
db.conn.close()
Expand Down
2 changes: 1 addition & 1 deletion flomo/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def get_input(self):
return self.terminal.inkey().lower()


def main(tag: str, name: str, session_id: float):
def main(tag: str, name: str, session_id: int):
# TODO: Do something with the Terminal close issue
try:
while True:
Expand Down

0 comments on commit 7a1b008

Please sign in to comment.