Skip to content

Commit

Permalink
Fix linting errors (ruff)
Browse files Browse the repository at this point in the history
  • Loading branch information
cochaviz committed Aug 13, 2024
1 parent 53f3665 commit 0ead9f8
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 54 deletions.
51 changes: 25 additions & 26 deletions src/dear_diary/core/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import os

import frontmatter
from git import InvalidGitRepositoryError, NoSuchPathError, Repo

# local imports
from dear_diary.core.models.entry import Entry
from git import InvalidGitRepositoryError, NoSuchPathError, Repo


class Backend():
class Backend:
def read_entries(self) -> list[Entry]:
"""
Reads the entries from the backend and returns them as a list.
Expand All @@ -17,43 +18,46 @@ def read_entries(self) -> list[Entry]:

def write_entries(self, entries: list[Entry]):
"""
Writes the entries to the backend.
Writes the entries to the backend.
The backend should be able to handle the case when the entries are
empty.
"""
raise NotImplementedError()

def synced(self, entries: list[Entry]) -> bool:
"""
Returns True if the backend is in sync with the local entries.
The backend is considered to be in sync if the entries in the
backend are the same as the entries in the list. The order of
the entries is not important.
"""
raise NotImplementedError()


class GitBackend(Backend):
"""
Manages entries using a git repository as the backend. The repository
is assumed to be a local repository.
is assumed to be a local repository.
The entries are saved as markdown files in the repository in the
top-level directory. Each file is named after the date of the entry and
the 'metadata' is saved as the 'frontmatter' of the markdown file.
"""

repo: Repo = None # type: ignore
repo: Repo = None # type: ignore

def __init__(self, repo_path, init_if_not_exists=True):
try:
self.repo = Repo(repo_path)
except NoSuchPathError or InvalidGitRepositoryError:
if init_if_not_exists:
self._init_repo(repo_path)

assert self.repo and not self.repo.bare, f"Repository at {repo_path} is faulty or does not exist. Make sure `init_if_not_exists` is set to True."

assert (
self.repo and not self.repo.bare
), f"Repository at {repo_path} is faulty or does not exist. Make sure `init_if_not_exists` is set to True."

def _init_repo(self, repo_path):
if os.path.exists(repo_path):
Expand All @@ -64,9 +68,9 @@ def _init_repo(self, repo_path):
# otherwise, it's safe to remove the directory
# FIXME: this is a bit dangerous, perhaps just rename the directory
os.rmdir(repo_path)

self.repo = Repo.init(repo_path)

def _markdown_files_in(self, folder_path: str):
return glob.glob(os.path.join(folder_path, "*.md"))

Expand All @@ -80,8 +84,8 @@ def _read_entries_from_path(self, folder_path: str):
Entry(
# I might regret this formatting later
date=datetime.date.fromisoformat(date),
content=file.content,
metadata=file.metadata
content=file.content,
metadata=file.metadata,
)
)
return entries
Expand All @@ -99,22 +103,18 @@ def _write_entries_to_path(self, folder_path: str, entries: list[Entry]):
file.write(file_content)

def read_entries(self) -> list[Entry]:
return self._read_entries_from_path(
str(self.repo.working_dir)
)
return self._read_entries_from_path(str(self.repo.working_dir))

def write_entries(self, entries: list[Entry]):
self._write_entries_to_path(
str(self.repo.working_dir),
entries
)
self._write_entries_to_path(str(self.repo.working_dir), entries)
self.repo.index.add(self._markdown_files_in(str(self.repo.working_dir)))
self.repo.index.commit("Update entries")

def synced(self, entries: list[Entry]) -> bool:
return self.repo.is_dirty()
return self.repo.is_dirty()


class EntryManager():
class EntryManager:
def __init__(self, backend: Backend):
self.entries: list[Entry] = []
self.backend: Backend = backend
Expand All @@ -130,9 +130,8 @@ def get_entry(self, date: datetime.date):
return None

def __enter__(self):
self.entries = self.backend.read_entries()
self.entries = self.backend.read_entries()
return self

def __exit__(self, *_):
self.backend.write_entries(self.entries)

2 changes: 1 addition & 1 deletion src/dear_diary/core/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
__all__ = [
"Entry",
"Message",
]
]
13 changes: 7 additions & 6 deletions src/dear_diary/core/models/entry.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime

from pydantic import BaseModel, field_validator


Expand All @@ -7,11 +8,11 @@ class Entry(BaseModel):
content: str
metadata: dict = {}

@field_validator('content')
@field_validator("content")
@classmethod
def content_must_not_be_empty(cls, v):
if v == '':
raise ValueError('Content is not allowed to be empty.')
if v == "":
raise ValueError("Content is not allowed to be empty.")
return v

def __repr__(self):
Expand Down Expand Up @@ -39,7 +40,7 @@ def __gt__(self, other):
if not isinstance(other, Entry):
return NotImplemented
return self.date > other.date

def __ge__(self, other):
if not isinstance(other, Entry):
return NotImplemented
Expand All @@ -49,6 +50,6 @@ def __ne__(self, other):
if not isinstance(other, Entry):
return NotImplemented
return self.date != other.date

def __str__(self):
return f"{self.date}: {self.content}"
return f"{self.date}: {self.content}"
2 changes: 1 addition & 1 deletion src/dear_diary/core/models/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


class Message(BaseModel):
message: str
message: str
43 changes: 23 additions & 20 deletions src/dear_diary/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,30 @@
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

from dear_diary.core.database import EntryManager, GitBackend

# local imports
from dear_diary.core.models import Entry, Message
from dear_diary.core.database import EntryManager, GitBackend

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates("templates")
entry_manager_backend = GitBackend("entries")


@app.get("/")
def show_diary_today(request: Request):
"""
Redirect to entry of the current day.
"""
return show_diary(str(datetime.date.today()), request)


@app.get("/{entry_date}", response_class=HTMLResponse)
def show_diary(entry_date: str, request: Request):
try:
date = datetime.date.fromisoformat(entry_date)
date = datetime.date.fromisoformat(entry_date)
if date > datetime.date.today():
raise ValueError("Date cannot be in the future")
except ValueError:
Expand All @@ -35,22 +38,22 @@ def show_diary(entry_date: str, request: Request):

with EntryManager(entry_manager_backend) as entry_manager:
# get the index of the current entry in the sorted entries
if (entry := entry_manager.get_entry(date)):
if entry := entry_manager.get_entry(date):
entry_number = sorted(entry_manager.entries).index(entry) + 1
else:
entry_number = len(entry_manager.entries) + 1

context = {
"relevant_entries" : list(map(
lambda single_entry: single_entry.date,
entry_manager.entries[:5]
)),
"diary_entry_placeholder" : f"Entry for {date}...",
"date" : date,
"entry_number" : entry_number,
"relevant_entries": list(
map(lambda single_entry: single_entry.date, entry_manager.entries[:5])
),
"diary_entry_placeholder": f"Entry for {date}...",
"date": date,
"entry_number": entry_number,
}
return templates.TemplateResponse(request, "index.html", context)


@app.post(
"/entry/",
response_model=Message,
Expand All @@ -60,26 +63,26 @@ def post_entry(entry: Entry):
entry_manager.add_entry(entry)
print(entry_manager.entries)

return JSONResponse(content={
"message": f"Entry for added for {entry.date} was successfully added!",
})
return JSONResponse(
content={
"message": f"Entry for added for {entry.date} was successfully added!",
}
)


@app.get(
"/entry/{entry_date}",
response_model=Entry,
responses= {
404: { "model": Message, "description": "Entry not found." },
}
responses={
404: {"model": Message, "description": "Entry not found."},
},
)
def get_entry(entry_date: str):
with EntryManager(entry_manager_backend) as entry_manager:
entry = entry_manager.get_entry(datetime.date.fromisoformat(entry_date))
if entry is None:
return JSONResponse(
status_code=404,
content={ "message": f"Entry for {entry_date} not found." }
status_code=404,
content={"message": f"Entry for {entry_date} not found."},
)
return entry


0 comments on commit 0ead9f8

Please sign in to comment.