Skip to content

Instantly share code, notes, and snippets.

@dnlbauer
Created October 30, 2024 09:33
Show Gist options
  • Save dnlbauer/cf6530f3df29da3fe47994f60ddc654a to your computer and use it in GitHub Desktop.
Save dnlbauer/cf6530f3df29da3fe47994f60ddc654a to your computer and use it in GitHub Desktop.
simple script to edit gtimelog log file from cli
#!env python3
import os
from datetime import datetime
import subprocess
# Define the path to the timelog file
TIMELINE_PATH = os.path.expanduser("~/.local/share/gtimelog/timelog.txt")
def ensure_timelog_file():
# Ensure the directory exists
os.makedirs(os.path.dirname(TIMELINE_PATH), exist_ok=True)
def add_task_to_timelog(task_name, billable=True, ignored=False):
ensure_timelog_file()
# Get the current time for the new entry
now = datetime.now()
# Insert blank line if the last entry was on a different day
with open(TIMELINE_PATH, "r") as file:
lines = file.readlines()
try:
last_line = lines[-1] if lines else ""
last_line_date = datetime.strptime(last_line[:10], "%Y-%m-%d")
except (ValueError, IndexError) as e:
print(e)
last_line_date = None
with open(TIMELINE_PATH, "a") as file:
# Insert a blank line if the last entry was on a different day
if last_line_date and last_line_date.date() != now.date():
file.write("\n")
# Append the new entry
if ignored:
postfix = " ***"
elif not billable:
postfix = " **"
else:
postfix = ""
timestamp = now.strftime("%Y-%m-%d %H:%M")
file.write(f"{timestamp}: {task_name}{postfix}\n")
print(f"Task '{task_name}{postfix}' added at {timestamp}")
def open_timelog_in_editor():
editor = os.getenv("EDITOR", "vim")
subprocess.run([editor, TIMELINE_PATH])
if __name__ == "__main__":
import argparse
# Setup CLI arguments
parser = argparse.ArgumentParser(description="Add a new task to the gtimelog timelog.txt")
parser.add_argument("task_name", nargs="?", type=str, help="Name of the task to add")
parser.add_argument("--edit", action="store_true", help="Open timelog file for editing")
args = parser.parse_args()
if args.edit:
open_timelog_in_editor()
else:
task_name = args.task_name.strip().rstrip("*").strip()
ignored = False
billable = True
if args.task_name.strip().endswith("***"):
ignored = True
billable = False
elif args.task_name.strip().endswith("**"):
ignored = False
billable = False
add_task_to_timelog(task_name, billable, ignored)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment