Skip to content

Commit

Permalink
use logger instead of prints/warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
purarue committed Oct 12, 2023
1 parent 82f22aa commit 7670e0d
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 28 deletions.
2 changes: 2 additions & 0 deletions calcurse_load/ext/abstract.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import typing
from abc import ABC, abstractmethod
from ..log import logger

if typing.TYPE_CHECKING:
from ..calcurse import Configuration
Expand All @@ -8,6 +9,7 @@
class Extension(ABC):
def __init__(self, config: "Configuration") -> None: # type: ignore[no-untyped-def]
self.config: Configuration = config
self.logger = logger

def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.config})"
Expand Down
63 changes: 38 additions & 25 deletions calcurse_load/ext/gcal.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
from __future__ import annotations
import sys
import json
import glob
import hashlib
import warnings
import logging
import io
from functools import partial
from pathlib import Path
from datetime import datetime
from typing import Any, Dict, List, Iterator, Optional
from typing import List, Iterator, Optional, TYPE_CHECKING

from .abstract import Extension
from .utils import yield_lines

# loads any JSON files in ~/.local/data/calcurse_load/*.json,
if TYPE_CHECKING:
from gcal_index.__main__ import GcalAppointmentData

Json = Dict[str, Any]
# loads any JSON files in ~/.local/data/calcurse_load/*.json,

# one line in the appointment file
CalcurseApt = str
CalcurseLine = str


def pad(i: int) -> str:
Expand All @@ -36,7 +37,7 @@ def create_calcurse_timestamp(epochtime: Optional[int]) -> str:
return f"{pad(dt.month)}/{pad(dt.day)}/{dt.year} @ {pad(dt.hour)}:{pad(dt.minute)}"


def create_calcurse_note(event_data: Json, notes_dir: Path) -> str:
def create_calcurse_note(event_data: GcalAppointmentData, notes_dir: Path) -> str:
"""
Creates the notes file if it doesn't already exist.
Expand All @@ -59,15 +60,17 @@ def create_calcurse_note(event_data: Json, notes_dir: Path) -> str:
return sha


def create_calcurse_event(event_data: Json, notes_dir: Path) -> Optional[CalcurseApt]:
def create_calcurse_event(
event_data: GcalAppointmentData, notes_dir: Path, logger: logging.Logger
) -> Optional[CalcurseLine]:
"""
Takes the exported Google Calendar info, and creates
a corresponding Calcurse 'apts' line, and note
"""
note_hash: str = create_calcurse_note(event_data, notes_dir)
if event_data["start"] is None:
print(f"Event {event_data} has no start time", file=sys.stderr)
logger.warning(f"Event {event_data} has no start time")
return None
note_hash: str = create_calcurse_note(event_data, notes_dir)
start_str = create_calcurse_timestamp(event_data["start"])
end_str = create_calcurse_timestamp(event_data["end"])
if end_str == "":
Expand All @@ -76,25 +79,25 @@ def create_calcurse_event(event_data: Json, notes_dir: Path) -> Optional[Calcurs
return f"{start_str} -> {end_str}>{note_hash} |{event_data['summary']} [gcal]"


def is_google_event(appointment_line: "CalcurseApt") -> bool:
def is_google_event(appointment_line: CalcurseLine) -> bool:
return appointment_line.endswith("[gcal]")


class gcal_ext(Extension):
def load_json_events(self) -> Iterator[Json]:
def load_json_events(self) -> Iterator[GcalAppointmentData]:
json_files: List[str] = glob.glob(
str(self.config.calcurse_load_dir / "gcal" / "*.json")
)
if not json_files:
warnings.warn(
self.logger.warning(
"No json files found in '{}'".format(str(self.config.calcurse_load_dir))
)
else:
for event_json_path in json_files:
with open(event_json_path, "r") as json_f:
yield from json.load(json_f)

def load_calcurse_apts(self) -> Iterator["CalcurseApt"]:
def load_calcurse_apts(self) -> Iterator[CalcurseLine]:
"""
Loads in the calcurse appointments file, removing any google appointments
"""
Expand All @@ -108,21 +111,31 @@ def pre_load(self) -> None:
- create google events from JSON
- write back both event types
"""
filtered_apts: List[CalcurseApt] = list(self.load_calcurse_apts())
self.logger.warn("gcal: running pre-load hook")

filtered_apts: List[CalcurseLine] = list(self.load_calcurse_apts())
self.logger.info(f"Found {len(filtered_apts)} non-gcal events")
calcurse_func = partial(
create_calcurse_event, notes_dir=self.config.calcurse_dir / "notes"
create_calcurse_event,
notes_dir=self.config.calcurse_dir / "notes",
logger=self.logger,
)
google_apts: List[CalcurseApt] = [
google_apts: List[CalcurseLine] = [
ev for ev in map(calcurse_func, self.load_json_events()) if ev is not None
]
print(
f"Writing {len(google_apts)} gcal events to calcurse appointments file",
file=sys.stderr,
self.logger.info(
f"Writing {len(google_apts)} gcal events to calcurse appointments file"
)
with (self.config.calcurse_dir / "apts").open("w") as cal_apts:
for event in filtered_apts + google_apts:
cal_apts.write(event)
cal_apts.write("\n")

buf = io.StringIO()
for event in filtered_apts:
buf.write(event)
buf.write("\n")
for event in google_apts:
buf.write(event)
buf.write("\n")

(self.config.calcurse_dir / "apts").write_text(buf.getvalue())

def post_save(self) -> None:
warnings.warn("gcal doesn't have a post-save hook!")
self.logger.warn("gcal: doesn't have a post-save hook!")
5 changes: 2 additions & 3 deletions calcurse_load/ext/todotxt.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import os
import re
import warnings
from pathlib import Path
from typing import Optional, Iterator, List, Set
from functools import lru_cache
Expand Down Expand Up @@ -111,7 +110,7 @@ def pre_load(self) -> None:
# search common locations
todo_file: Optional[Path] = self._find_todo_file()
if todo_file is None:
warnings.warn("Could not find todo.txt file in expected locations")
self.logger.warning("Could not find todo.txt file in expected locations")
return
# read in todo.txt items
todos: List[TodoTxtTodo] = list(self._read_todotxt_file(todo_file))
Expand All @@ -133,7 +132,7 @@ def post_save(self) -> None:
)
todo_file: Optional[Path] = self._find_todo_file()
if todo_file is None:
warnings.warn("Could not find todo.txt file in expected locations")
self.logger.warning("Could not find todo.txt file in expected locations")
return
# read in todo.txt items, save a set of the text descriptions, so we can compare
# to the newly saved calcurse todos.
Expand Down
24 changes: 24 additions & 0 deletions calcurse_load/log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import os
import logging
from tempfile import gettempdir

from typing import Optional

from logzero import setup_logger # type: ignore[import]

DEFAULT_LEVEL = logging.INFO

logpath = os.path.join(gettempdir(), "calcurse_load.log")


# logzero handles adding handling/modifying levels fine
# can be imported/configured multiple times
def setup(level: Optional[int] = None) -> logging.Logger:
chosen_level = level or int(os.environ.get("CALCURSE_LOAD_LOGS", DEFAULT_LEVEL))
lgr: logging.Logger = setup_logger(
name=__package__, level=chosen_level, disableStderrLogger=True, logfile=logpath
)
return lgr


logger = setup()

0 comments on commit 7670e0d

Please sign in to comment.