Skip to content
Merged
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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Simple time/task logging on the command line. Plain-text log, no dependencies.
```bash
tl add [-t|--time <value>] <description> # start a task now, or at <value> (14:30, 1h5m, 1h, 15m)
tl note [-t|--time <value>] <note> # add a note to the current task, now or at <value>
tl todo <text> # remember something for the next day
tl todos # show the previous day's todos
tl help # overview of all commands
tl version # show the version

Expand Down Expand Up @@ -87,6 +89,7 @@ They use a temporary home folder, so your real `~/.timelog` is never touched.
- A task lasts from its own `add` line to the next `add` or `stop` line.
- `stop` ends the current task. The time after it is not counted, and it has an optional reason, e.g. `tl stop lunch`.
- `note` adds a line to the current task. It does not end the task and does not change the totals.
- `todo` is a reminder for the next day. The first entry of a new day (`add`, `note` or `todo`) prints the todos of the most recent earlier day that has a log file, so a weekend does not hide them. Only that one day is looked at, and todos have no done status yet.
- Each day has its own file, and a new day starts with nothing running.
- Totals group by exact task name.
- Entries are sorted by time before durations are calculated. A task added later with `-t` lands in the right place, even though the file is append-only.
Expand All @@ -95,7 +98,7 @@ They use a temporary home folder, so your real `~/.timelog` is never touched.

Data lives in one plain-text file per day: `~/.timelog/<yyyy-mm-dd>.tsv`

One line per entry, with three tab-separated fields: date and time, type (`add`, `note` or `stop`), and text. The text of a `stop` is optional.
One line per entry, with three tab-separated fields: date and time, type (`add`, `note`, `todo` or `stop`), and text. The text of a `stop` is optional.

```text
2026-09-23 08:30 add Ticket-67: Investigate
Expand Down
85 changes: 85 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,88 @@ def test_missing_text(self):
code, _, err = self.run_cmd(commands.note, [])
self.assertEqual(code, 1)
self.assertIn("description is missing", err)


class TodoTest(CommandTestCase):
def test_todo(self):
code, out, _ = self.run_cmd(commands.todo, ["Call", "the client"])
self.assertEqual(code, 0)
self.assertEqual(out, "Todo added: Call the client\n")
self.assertEqual(self.lines(), ["2026-09-23 12:00\ttodo\tCall the client"])

def test_time_flag_is_rejected(self):
for flag in ("-t", "--time"):
with self.subTest(flag=flag):
code, out, err = self.run_cmd(commands.todo, [flag, "5m", "x"])
self.assertEqual(code, 1)
self.assertEqual(out, "")
self.assertIn("not allowed", err)
self.assertFalse(self.day_file().exists())

def test_missing_text(self):
code, _, err = self.run_cmd(commands.todo, [])
self.assertEqual(code, 1)
self.assertIn("description is missing", err)
self.assertFalse(self.day_file().exists())


class CarryOverTest(CommandTestCase):
def write_day(self, day, *lines):
path = self.day_file(day)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("".join(line + "\n" for line in lines), encoding="utf-8")

def test_first_entry_shows_previous_todos(self):
self.write_day("2026-09-22", "2026-09-22 17:00\tadd\tWork", "2026-09-22 17:30\ttodo\tCall the client")
code, out, _ = self.run_cmd(commands.add, ["Team daily"])
self.assertEqual(code, 0)
self.assertEqual(
out, "Todos from Tue 2026-09-22:\n - Call the client\n\nStarted: Team daily (12:00)\n"
)

def test_second_entry_does_not_repeat(self):
self.write_day("2026-09-22", "2026-09-22 17:30\ttodo\tCall the client")
self.run_cmd(commands.add, ["One"])
_, out, _ = self.run_cmd(commands.note, ["Two"])
self.assertEqual(out, "Note added: Two (12:00)\n")

def test_note_and_todo_also_trigger(self):
self.write_day("2026-09-22", "2026-09-22 17:30\ttodo\tCall the client")
_, out, _ = self.run_cmd(commands.note, ["Hi"])
self.assertTrue(out.startswith("Todos from Tue 2026-09-22:"))

def test_gap_day_uses_latest_earlier_file(self):
self.write_day("2026-09-18", "2026-09-18 17:30\ttodo\tFriday thing")
_, out, _ = self.run_cmd(commands.add, ["x"])
self.assertIn("Todos from Fri 2026-09-18:\n - Friday thing", out)

def test_only_the_previous_day_is_used(self):
self.write_day("2026-09-20", "2026-09-20 17:30\ttodo\tOld")
self.write_day("2026-09-22", "2026-09-22 17:30\tadd\tNo todo here")
_, out, _ = self.run_cmd(commands.add, ["x"])
self.assertEqual(out, "Started: x (12:00)\n")

def test_no_previous_files(self):
_, out, _ = self.run_cmd(commands.add, ["x"])
self.assertEqual(out, "Started: x (12:00)\n")

def test_todos_command(self):
self.write_day("2026-09-22", "2026-09-22 17:30\ttodo\tA", "2026-09-22 17:40\ttodo\tB")
code, out, _ = self.run_cmd(commands.todos, [])
self.assertEqual(code, 0)
self.assertEqual(out, "Todos from Tue 2026-09-22:\n - A\n - B\n")
self.assertFalse(self.day_file().exists())

def test_todos_command_when_none(self):
_, out, _ = self.run_cmd(commands.todos, [])
self.assertEqual(out, "No todos from the previous day.\n")

def test_todos_rejects_arguments(self):
code, _, err = self.run_cmd(commands.todos, ["--all"])
self.assertEqual(code, 1)
self.assertIn("takes no arguments", err)

def test_bad_lines_are_skipped(self):
self.write_day("2026-09-22", "garbage", "2026-09-22 17:30\ttodo\tOK")
_, out, _ = self.run_cmd(commands.todos, [])
self.assertIn(" - OK", out)
56 changes: 54 additions & 2 deletions timelog/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ def _resolve_time(time_str, prefix: str):
return when


def _save(entry: Entry) -> None:
"""Append the entry. If it is the first of the day, print the previous day's todos first."""
today = _now().date()
first_of_day = not storage.day_exists(today)
day, found = storage.previous_todos(today) if first_of_day else (None, [])
storage.append_entry(entry)
if found:
print(render.todo_list(day, found))
print()


def add(args: List[str]) -> int:
"""tl add [-t|--time <value>] <description>: start a task.

Expand Down Expand Up @@ -90,7 +101,7 @@ def add(args: List[str]) -> int:
)
return 1

storage.append_entry(entry)
_save(entry)
if time_str:
print(render.time_added(entry))
else:
Expand Down Expand Up @@ -126,7 +137,48 @@ def note(args: List[str]) -> int:
)
return 1

storage.append_entry(entry)
_save(entry)
print(render.note_added(entry))

return 0


def todo(args: List[str]) -> int:
"""tl todo <text>: remember something for the next day.

The next day's first entry shows it, and `tl todos` shows it again.

Example:
tl todo Call the client
"""
if args and args[0] in TIME_FLAGS:
print(render.flag_not_allowed("tl todo", args[0]), file=sys.stderr)
return 1

entry = Entry(time=_now(), type="todo", text=" ".join(args))
if not entry.text:
print(
render.missing_argument_error("tl todo", "description", "tl todo <description>"),
file=sys.stderr
)
return 1

_save(entry)
print(render.todo_added(entry))

return 0


def todos(args: List[str]) -> int:
"""tl todos: show the todos from the previous day."""
if args:
print("tl todos: takes no arguments. Usage: tl todos", file=sys.stderr)
return 1

day, found = storage.previous_todos(_now().date())
if found:
print(render.todo_list(day, found))
else:
print(render.no_todos())

return 0
2 changes: 1 addition & 1 deletion timelog/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


TIME_FORMAT = "%Y-%m-%d %H:%M"
TYPES = ("add", "note") # planned more types later (e.g. list, stop)
TYPES = ("add", "note", "todo") # planned more types later (e.g. stop)


def clean_text(text: str) -> str:
Expand Down
20 changes: 19 additions & 1 deletion timelog/render.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Turns results into text for the terminal. No files and no printing."""
from datetime import datetime
from datetime import date, datetime
from typing import List

from .model import Entry

Expand Down Expand Up @@ -37,6 +38,23 @@ def note_added(entry: Entry) -> str:
return _format_action("Note added", entry)


def todo_added(entry: Entry) -> str:
"""The message after `tl todo`, e.g. 'Todo added: Call the client'."""
return f"Todo added: {entry.text}"


def todo_list(day: date, entries: List[Entry]) -> str:
"""Todos of one day as a heading and a bullet list."""
lines = [f"Todos from {day.strftime('%a %Y-%m-%d')}:"]
lines += [f" - {e.text}" for e in entries]
return "\n".join(lines)


def no_todos() -> str:
"""The message when the previous day has no todos."""
return "No todos from the previous day."


def missing_argument_error(prefix: str, argument: str, example: str) -> str:
"""Returns an error message when a required argument is missing."""
return f"{prefix}: {argument} is missing. Usage: {example}"
Expand Down
43 changes: 43 additions & 0 deletions timelog/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""
from datetime import date
from pathlib import Path
from typing import List, Optional, Tuple

from .model import Entry

Expand All @@ -16,6 +17,48 @@ def _day_file(day: date) -> Path:
return _data_dir() / (day.isoformat() + ".tsv")


def day_exists(day: date) -> bool:
"""True if anything has been logged on that day."""
return _day_file(day).exists()


def _read_entries(day: date) -> List[Entry]:
"""All entries of one day in file order. Lines that can't be parsed (hand edits) are skipped."""
entries = []
with _day_file(day).open(encoding="utf-8") as f:
for line in f:
try:
entries.append(Entry.from_line(line))
except ValueError:
continue
return entries


def _previous_day(before: date) -> Optional[date]:
"""The latest day earlier than `before` that has a log file, or None."""
days = []
if _data_dir().is_dir():
for path in _data_dir().glob("*.tsv"):
try:
day = date.fromisoformat(path.stem)
except ValueError:
continue
if day < before:
days.append(day)
return max(days, default=None)


def previous_todos(before: date) -> Tuple[Optional[date], List[Entry]]:
"""The todos of the most recent day earlier than `before`, as (that day, todos).

Only that one day is looked at, so a day off between does not hide its todos,
but todos from older days are not carried further."""
day = _previous_day(before)
if day is None:
return None, []
return day, [e for e in _read_entries(day) if e.type == "todo"]


def append_entry(entry: Entry) -> None:
"""Add one add-type line to the file of the entry's date. Creates the folder and file if needed."""
path = _day_file(entry.time.date())
Expand Down
4 changes: 4 additions & 0 deletions tl.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
Commands:
add [-t | --time <value>] <description> start a task now, or at <value>
note [-t | --time <value>] <text> add a note now, or at <value>
todo <text> remember something for the next day
todos show the previous day's todos
version show the version
help show this help

Expand All @@ -28,6 +30,8 @@
COMMANDS = {
"add": commands.add,
"note": commands.note,
"todo": commands.todo,
"todos": commands.todos,
}

# Planned commands from README
Expand Down