Skip to content

Commit

Permalink
Use functions & cached properties (i.e. @functools.cached_property) f…
Browse files Browse the repository at this point in the history
…or lastModifiedDate and ideaDate
  • Loading branch information
arjun-menon committed Jul 25, 2024
1 parent 46f8584 commit d1db07e
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 29 deletions.
19 changes: 4 additions & 15 deletions alteza/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,21 +111,10 @@ def linkObj(dstFile: FileNode) -> str:
env |= {"link": link}
env |= {"linkObj": linkObj}

env |= {"lastUpdatedObj": pyPageNode.lastUpdated}
# The formatting below might only work on Linux. https://stackoverflow.com/a/29980406/908430
env |= {
"lastUpdated": pyPageNode.lastUpdated.strftime("%Y %b %-d at %-H:%M %p")
}

if isinstance(pyPageNode, Md):
env |= {"ideaDateObj": pyPageNode.ideaDate}
env |= {
"ideaDate": (
pyPageNode.ideaDate.strftime("%Y %b %-d at %-H:%M %p")
if pyPageNode.ideaDate is not None
else ""
)
}
env |= {"getLastModifiedObj": lambda: pyPageNode.lastModifiedObj}
env |= {"getLastModified": pyPageNode.getLastModified}
env |= {"getIdeaDateObj": pyPageNode.getIdeaDateObj}
env |= {"getIdeaDate": pyPageNode.getIdeaDate}

# Invoke pypage
pyPageOutput = pypage(toProcessFurther, env)
Expand Down
36 changes: 26 additions & 10 deletions alteza/fs.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import functools
import os
import re
from collections import defaultdict
Expand Down Expand Up @@ -195,15 +196,27 @@ class AltezaException(Exception):


class PageNode(FileNode):
def __init__(self, parent: Optional[FsNode], dirPath: str, fileName: str) -> None:
super().__init__(parent, dirPath, fileName)
# TODO/FIXME: Convert these to function calls:
self.lastUpdated: datetime = self.getLastUpdated(self.fullPath)
self.ideaDate: Optional[date] = self.getGitFileFirstAuthDate(self.fullPath)
default_date_format: str = "%Y %b %-d"
default_datetime_format: str = default_date_format + " at %-H:%M %p"

@staticmethod
def getLastUpdated(path: str) -> datetime:
def getLastModified(self, f: str = default_datetime_format) -> str:
# The formatting below might only work on Linux. https://stackoverflow.com/a/29980406/908430
return self.lastModifiedObj.strftime(f)

def getIdeaDate(self, f: str = default_date_format) -> str:
ideaDate = self.getIdeaDateObj()
return ideaDate.strftime(f) if ideaDate else ""

def getIdeaDateObj(self) -> Optional[date]:
if isinstance(self, Md):
if self.ideaDate is not None:
return self.ideaDate
return self.gitFirstAuthDate

@functools.cached_property
def lastModifiedObj(self) -> datetime:
"""Get last modified date from: (a) git history, or (b) system modified time."""
path = self.fileName
if PageNode.isGitRepo():
lastUpdated = PageNode.getGitFileLastAuthDate(path)
if lastUpdated is not None:
Expand All @@ -212,6 +225,7 @@ def getLastUpdated(path: str) -> datetime:

@staticmethod
def isGitRepo() -> bool:
# TODO refactor: Move this method to parent DirNode?
try:
check_output(["git", "status"], stderr=STDOUT).decode()
return True
Expand All @@ -228,8 +242,9 @@ def getGitFileLastAuthDate(path: str) -> Optional[datetime]:
except Exception:
return None

@staticmethod
def getGitFileFirstAuthDate(path: str) -> Optional[date]:
@functools.cached_property
def gitFirstAuthDate(self) -> Optional[date]:
path = self.fileName
if PageNode.isGitRepo():
try:
git_output = check_output(
Expand Down Expand Up @@ -261,14 +276,15 @@ class Md(PyPageNode):
def __init__(self, parent: Optional[FsNode], dirPath: str, fileName: str) -> None:
super().__init__(parent, dirPath, fileName)

self.ideaDate: Optional[date] = None
# Handle file names that start with a date:
dateFragmentLength = len("YYYY-MM-DD-")
if len(self.baseName) > dateFragmentLength:
dateFragment_ = self.baseName[:dateFragmentLength]
remainingBasename = self.baseName[dateFragmentLength:]
if re.match("[0-9]{4}-[0-9]{2}-[0-9]{2}-$", dateFragment_):
dateFragment = dateFragment_[:-1]
self.ideaDate: Optional[date] = date.fromisoformat(dateFragment)
self.ideaDate = date.fromisoformat(dateFragment)
self.realName: str = remainingBasename

class Result(NamedTuple):
Expand Down
2 changes: 1 addition & 1 deletion test_content/sectionK/sectionL/2023-09-21-lizard.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

Scaly and happy.

I first began writing this on {{ideaDate}}.
I first began writing this on {{getIdeaDate()}}.

2 changes: 1 addition & 1 deletion test_content/sectionK/sectionL/magic-turtle.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ And had a happy {{mood + 'ful'}} day.

Want to visit a [joyful squirrel]({{link("joyful-squirrel")}})?

This page was last updated on {{lastUpdated}}.
This page was last updated on {{getLastModified()}}.

Check out his friend, the [lizard]({{link('lizard')}}).
4 changes: 2 additions & 2 deletions test_content/sectionK/sectionM/joyful-squirrel.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ Want to learn about a [magic turtle]({{link("magic-turtle")}})?

This is [what a "megabyte" is]({{link("just_a_test")}}).

This page was started on {{ideaDate}}.
This page was started on {{getIdeaDate()}}.

This page was started on {{lastUpdated}}.
This page was started on {{getLastModified()}}.

Back [home](..).
Empty file removed test_content/sectionZ/oranges.md
Empty file.

0 comments on commit d1db07e

Please sign in to comment.