๐ A powerful work time tracking tool for the command line
Project description
Drudge CLI Tool - Professional Python Package Edition
A comprehensive, professionally architected command-line tool for tracking work time on tasks with organized daily logs. Built with modern Python package structure, Typer CLI framework, Rich formatting, type hints, dataclasses, and enterprise-level architectural patterns.
๐ฏ Production Ready: Complete package refactor with modular architecture, centralized validation, configuration management, structured logging, and comprehensive unit tests ensuring reliability and maintainability.
๐๏ธ Package Architecture
Modern Python Package Structure
src/worklog/
โโโ __init__.py # Package initialization and public API
โโโ __main__.py # Entry point for python -m worklog
โโโ models.py # Data models (TaskEntry, PausedTask, WorkLogData)
โโโ config.py # Configuration management (WorkLogConfig)
โโโ validators.py # Centralized input validation
โโโ managers/ # Business logic managers
โ โโโ __init__.py
โ โโโ worklog.py # Core WorkLog class
โ โโโ backup.py # Backup management
โ โโโ daily_file.py # Daily file operations
โโโ cli/ # Command-line interface
โ โโโ __init__.py
โ โโโ commands.py # Typer command definitions
โโโ utils/ # Utility functions
โโโ __init__.py
โโโ decorators.py # Common decorators (@auto_save, @requires_data)
๐ Major Refactoring Accomplishments
โ Advanced Architecture Improvements
This version represents a comprehensive architectural refactor with modern software engineering practices:
Separation of Concerns
- WorkLogValidator: Centralized validation logic for dates, times, and task names
- WorkLogConfig: Configuration management with dataclass for customizable settings
- BackupManager: Specialized backup creation and management
- DailyFileManager: Dedicated daily file operations and formatting
- Structured Logging: Professional logging system with configurable levels
- Modular Package: Clean separation into models, managers, CLI, and utilities
Performance & Reliability
- Caching:
@lru_cachedecorators for frequently accessed methods - Enhanced Error Handling: User-friendly error messages with detailed logging
- Atomic Operations: Safe file writes preventing data corruption
- Comprehensive Validation: Input validation at multiple layers
- Memory Efficiency: Optimized file operations and data structures
- Type Safety: Full type hints throughout the codebase
Installation
Prerequisites
- Python 3.8+ (developed with Python 3.13)
- Required packages:
typer[all]andrich
Setup
-
Install required dependencies:
pip install typer[all] rich
-
Install the package in development mode:
cd /path/to/WorkLog pip install -e .
-
Or run directly as a module:
python3 -m src.worklog --help
-
Create a shell alias for convenience:
# Run the setup script ./setup_drudge_alias.sh # Or add manually to your shell config echo 'alias drudge="python3 -m src.worklog"' >> ~/.zshrc source ~/.zshrc
cat setup_alias.sh >> ~/.zshrc source ~/.zshrc
Architecture Components
๐๏ธ Core Classes & Managers
WorkLogValidator
Centralized validation logic eliminating code duplication:
# Validates dates, times, task names with clear error messages
validator = WorkLogValidator()
validator.validate_date_format("2023-12-31", config)
validator.validate_time_format("14:30") # Returns (hours, minutes)
validator.validate_task_name("My Task") # Checks length and characters
WorkLogConfig
Configuration management with sensible defaults:
config = WorkLogConfig(
worklog_dir_name='.worklog', # Customizable directory name
max_recent_tasks=10, # Configurable history length
backup_enabled=True, # Safety features
display_time_format="%Y-%m-%d %H:%M:%S" # Flexible formatting
)
BackupManager
Specialized backup operations for data safety:
- Creates comprehensive backups before destructive operations
- Handles both JSON entries and daily file content
- Consistent backup format with timestamps
DailyFileManager
Dedicated daily file operations:
- Consistent entry formatting across all operations
- Chronological ordering maintenance
- Duplicate entry handling for task completions
Structured Logging
Professional logging system:
import logging
logger = logging.getLogger('worklog')
logger.info("Task started successfully")
logger.error("Data corruption detected")
๐ง Performance Optimizations
- @lru_cache decorators: Caches frequently called formatting methods
- Atomic file operations: Prevents data corruption during saves
- Optimized data structures: Efficient task lookup and management
- Lazy loading: Data loaded only when needed
Modern CLI Interface
The new version uses Typer instead of argparse, providing:
- ๐จ Rich formatting with colors and beautiful tables
- ๐ Automatic help generation with detailed command descriptions
- โ Type safety with comprehensive type hints
- ๐ Command-based interface for better organization
Usage
Modern Command Interface
All commands now use the modern Typer syntax with rich formatting and emojis:
Basic Task Tracking
- Start a task:
drudge start "Task Name" - End a task:
drudge end "Task Name" - Custom start time:
drudge start "Task Name" --time 09:30 - Force start (auto-end active):
drudge start "New Task" --force - Pause a task:
drudge pause "Task Name" - Resume a task:
drudge resume "Task Name"
Viewing Work History
- Show current status:
drudge status - List recent tasks:
drudge recent - List entries:
drudge list - Filter by date:
drudge list --date 2025-10-03 - Filter by task:
drudge list --task "bug" - Daily summary:
drudge daily - Specific date summary:
drudge daily --date 2025-10-03
Configuration and Help
- Show configuration:
drudge config - Show version:
drudge version - Main help:
drudge --help - Command help:
drudge start --help
Command Reference
| Command | Description | Example |
|---|---|---|
drudge start "Name" |
๐ Start a new task | drudge start "Bug fix #123" |
drudge start "Name" --time HH:MM |
๐ Start task at specific time | drudge start "Meeting" --time 09:30 |
drudge start "Name" --force |
๐ Force start (auto-end active tasks) | drudge start "Review" --force |
drudge end "Name" |
๐ End an active task | drudge end "Bug fix #123" |
drudge end "Name" --time HH:MM |
๐ End task at specific time | drudge end "Meeting" --time 17:30 |
drudge pause "Name" |
โธ๏ธ Pause an active task | drudge pause "Task" |
drudge resume "Name" |
โถ๏ธ Resume a paused task | drudge resume "Task" |
drudge status |
๐ Show current work status | drudge status |
drudge recent |
๐ List recent tasks | drudge recent |
drudge recent --limit N |
๐ Show N recent tasks | drudge recent --limit 10 |
drudge list |
๐ List completed entries | drudge list |
drudge list --date YYYY-MM-DD |
๏ฟฝ List entries for specific date | drudge list --date 2025-10-03 |
drudge list --task "keyword" |
๏ฟฝ Filter entries by task name | drudge list --task "bug" |
drudge daily |
๐ Show today's summary | drudge daily |
drudge daily --date YYYY-MM-DD |
๐ Show specific date summary | drudge daily --date 2025-10-03 |
drudge config |
โ๏ธ Show configuration | drudge config |
drudge version |
๐ฆ Show version info | drudge version |
drudge --help |
โ Show help message | drudge --help |
Examples
# Start tracking a task
$ drudge start "Morning emails"
๐ Started 'Morning emails' at 2025-10-03 09:00:00
# End the task
$ drudge end "Morning emails"
๐ Completed 'Morning emails' at 2025-10-03 09:30:00 (Duration: 00:30:00)
# Start a new task with custom time
$ drudge start "Fix bug #123" --time 10:00
๐ Started 'Fix bug #123' at 2025-10-03 10:00:00
# Check current status
$ drudge status
๐ Active Tasks:
โข Fix bug #123 (Running: 00:30:00)
๐ Completed today: 1 tasks
# Pause a task (for lunch, meeting, etc.)
$ drudge pause "Fix bug #123"
โธ๏ธ Paused 'Fix bug #123' at 2025-10-03 12:00:00
# Resume the task
$ drudge resume "Fix bug #123"
โถ๏ธ Resumed 'Fix bug #123' at 2025-10-03 13:00:00
# Complete the task
$ drudge end "Fix bug #123"
๐ Completed 'Fix bug #123' at 2025-10-03 17:00:00 (Duration: 05:00:00)
# View daily summary
$ drudge daily
๐
Daily Summary for 2025-10-03
๐ Total: 2 tasks, 5h 30m
๐ Tasks:
โข Fix bug #123: 5h 0m
โข Morning emails: 0h 30m
# List recent tasks for quick reference
$ drudge recent
๏ฟฝ Recent Tasks:
1. Fix bug #123
2. Morning emails
3. Code review
# View recent work (with rich formatting)
$ worklog recent
### Recent entries (using short options)
```bash
# Show recent entries (default 10)
$ worklog recent
# Show specific number using short option
$ worklog recent -c 5
๐ Recent 5 entries:
2025-10-03 14:00:00 Code review (01:30:15)
2025-10-03 10:30:00 Fix bug #123 (03:00:00)
2025-10-03 09:00:00 Team standup (00:30:00)
# ... and so on
View today's work
$ worklog today ๐ Today's worklog (2025-10-03):
2025-10-03 14:30:15 Fix bug #123 (01:15:07) 2025-10-03 16:00:00 Code review (00:30:45) 2025-10-03 17:15:30 Meeting prep [ACTIVE]
View work from a specific date
$ worklog date 2025-10-02 ๐ Worklog for 2025-10-02:
2025-10-02 09:00:00 Sprint planning (01:30:00) 2025-10-02 11:15:00 Development work (03:45:20)
Custom start times (backdate entries)
$ worklog task "Morning meeting" --start-time 09:00 โ Started tracking: 'Morning meeting' at 2025-10-03 09:00:00
$ worklog start --start-time 08:30 โ Started tracking: '[ANONYMOUS WORK]' at 2025-10-03 08:30:00 ๐ก Use 'worklog task "Task Name"' to assign a name to this session
Clean today's worklog (with backup)
$ worklog clean ๐ Found 15 entries for 2025-10-03 ๐ Daily file: /home/karim/.worklog/2025-10-03.txt Are you sure you want to clean today's worklog? [y/N]: y ๐พ Backup created: /home/karim/.worklog/2025-10-03_backup.txt โ Cleaned 15 JSON entries ๐๏ธ Removed daily file: /home/karim/.worklog/2025-10-03.txt โจ Clean completed for 2025-10-03
Clean specific date worklog (with backup)
$ worklog clean --date 2025-10-01 ๐ Found 8 entries for 2025-10-01 Are you sure you want to clean worklog for 2025-10-01? [y/N]: y ๐พ Backup created: /home/karim/.worklog/2025-10-01_backup.txt โ Cleaned 8 JSON entries โจ Clean completed for 2025-10-01
Clean using short option
$ worklog clean -d 2025-09-30 โน๏ธ No worklog entries found for 2025-09-30
## Data Storage
### Directory Structure
- **`~/.worklog/`** - Main worklog directory
- **`~/.worklog/worklog.json`** - Comprehensive task database (machine-readable)
- **`~/.worklog/YYYY-MM-DD.txt`** - Daily readable logs (human-readable)
### File Formats
- **JSON Database**: Complete task history with precise timestamps and metadata
- **Daily Files**: Clean, readable format per day showing:
- `YYYY-MM-DD HH:MM:SS Task Name (HH:MM:SS)` for completed tasks
- `YYYY-MM-DD HH:MM:SS Task Name [ACTIVE]` for ongoing tasks
### Migration
- Automatically migrates existing `~/.worklog.json` to new directory structure
- Preserves all historical data during upgrade
## Features
- **Single-task mode by default**: Focus on one task at a time (typical workflow)
- **Optional parallel mode**: Use `--parallel` flag for concurrent tasks when needed
- **Smart task switching**: Starting new task automatically stops previous one
- **Enhanced --stop command**: Clears both active AND paused tasks completely
- **Smart --list command**: Shows today's log when no active tasks
- **Automatic duration calculation**: Precisely tracks time spent on tasks
- **Anonymous work sessions**: Start working before knowing the task name
- **Pause/Resume functionality**: Interrupt tasks and continue later
- **Batch operations**: Stop or pause all tasks with single command
- **Custom start times**: Backdate entries with `--start-time HH:MM` format
- **Clean worklog command**: Remove today's entries or specific date entries with backup and confirmation
- **Rich formatting**: Beautiful console output with colors, emojis, and tables
- **Modern CLI**: Typer-based interface with automatic help generation
- **Type safety**: Comprehensive type hints and dataclass structures
- **Organized daily files**: Separate readable file for each day
- **Persistent storage**: Data survives system restarts
- **Clean compact format**: Easy to read timestamps and durations
- **Date-specific viewing**: View work history for any specific date
- **Flexible task naming**: Convert anonymous sessions to named tasks retroactively
- **Session tracking**: Multiple work sessions per task are properly tracked
- **Error handling**: Graceful handling of corrupted data files
- **Data safety**: Backup creation before destructive operations
- **Input validation**: Robust time format validation with clear error messages
- **Extensible design**: JSON + daily files ready for future integrations
## Short Options Reference
For convenience, all major options have short aliases:
| Long Option | Short Options | Description |
|-------------|---------------|-------------|
| `--parallel` | `-p`, `-pl` | Allow multiple concurrent tasks |
| `--start-time` | `-t` | Custom start time (HH:MM) |
| `--count` | `-c` | Number of recent entries to show |
| `--date` | `-d` | Specific date for clean command (YYYY-MM-DD) |
### Command Examples with Short Options
```bash
# Start task in parallel mode with custom time
$ worklog task "Meeting" -p -t 14:30
# Show recent 5 entries
$ worklog recent -c 5
# Start anonymous session with time
$ worklog start -t 09:00
# Clean specific date
$ worklog clean -d 2025-10-01
File Structure Example
~/.worklog/
โโโ worklog.json # Complete database
โโโ 2025-10-01.txt # Daily readable logs
โโโ 2025-10-02.txt
โโโ 2025-10-03.txt
โโโ ...
Daily File Content Example
2025-10-03 09:00:00 Email and Planning (02:15:30)
2025-10-03 11:15:30 Bug fix #456 (01:30:00)
2025-10-03 14:30:00 Bug fix #456 (00:45:45)
2025-10-03 16:00:00 Documentation [ACTIVE]
Note: Tasks with pause/resume show multiple entries, each representing a work session.
Advanced Workflows
Anonymous Work Session
# Start your day without knowing the first task
$ worklog --start
# Later, when you know what you were actually working on
$ worklog "Morning emails and planning"
# The time tracking starts from the --start time, not when you named it
Pause/Resume Workflow
# Working on a task
$ worklog "Important project"
# Need to pause for meeting/lunch
$ worklog --pause
Paused 1 task(s):
- Important project (session: 02:30:15)
# Resume after interruption (two ways to do this)
$ worklog --resume # Resume last paused task
# OR
$ worklog --start # Also resumes if there are paused tasks
# Continue working and finish
$ worklog "Important project"
Finished task: 'Important project' at 2025-10-03 17:00:00
Duration: 01:30:45
Single-Task vs Parallel Mode
# Default: Single-task mode (most common)
$ worklog "Task A"
$ worklog "Task B" # Automatically stops Task A
Stopped previous task(s) (single-task mode):
- Task A (01:15:30)
# Explicit: Parallel mode (when you need multiple tasks)
$ worklog "Task A"
$ worklog "Task B" --parallel # Keeps Task A running
$ worklog "Task C" --parallel # All three tasks now active
Technical Features & Architecture
Modern Python Implementation
- Python 3.8+: Utilizes modern Python features and type system
- Dataclasses: Structured data with
TaskEntry,PausedTask, andWorkLogData - Type hints: Full type annotation for better IDE support and code safety
- Property decorators: Lazy loading and computed properties
- Context managers: Safe file operations with automatic cleanup
- Decorators:
@requires_dataand@auto_savefor clean separation of concerns
CLI Excellence with Typer
- Rich formatting: Beautiful console output with colors and emojis
- Automatic help: Generated help text with command descriptions
- Command-based: Logical organization of functionality
- Type safety: Automatic validation of arguments and options
Testing & Quality Assurance
Comprehensive Test Suite
The refactored WorkLog tool includes a complete unit test suite ensuring reliability:
# Run the updated comprehensive test suite
python3 test_worklog_updated.py
# Test results: 28 tests, 0 failures, 0 errors โ
Test Coverage Areas
- WorkLogValidator: Centralized validation logic testing
- WorkLogConfig: Configuration management validation
- Data Classes: TaskEntry, PausedTask, WorkLogData validation
- Core Operations: Task starting, stopping, ending functionality
- Session Management: Pause, resume, stop-all operations with new API
- Time Handling: Parsing, formatting, duration calculations with ISO timestamps
- CLI Integration: Typer commands and modern interface validation
- Data Persistence: File operations, loading, saving with enhanced error handling
- Integration Scenarios: Complete workflow testing with new architecture
- Error Handling: Enhanced validation and user-friendly error messages
Quality Improvements
- Updated Test Suite: All tests updated to match refactored API
- Architectural Testing: New classes and managers thoroughly tested
- Modern Test Patterns: Uses proper mocking and isolated test environments
- Enhanced Validation Testing: Comprehensive input validation coverage
- Error Recovery Testing: Validates graceful handling of edge cases
Future Integration Notes
The tool is designed with extensibility in mind:
- Dual storage format: JSON for programmatic access, TXT for human reading
- Modular class structure: Clean
WorkLogclass with comprehensive docstrings - Date-organized files: Perfect for daily standup reports and time tracking
- Timestamp format: ISO format compatible with most APIs and databases
- Extensible design: Easy to add fields like project, client, tags, or API integrations
- Error handling: Comprehensive error handling with user-friendly messages
- Directory structure: Organized for easy parsing and backup
- Test-driven development: Full test coverage ensures safe future modifications
Development & Files
Project Structure
WorkLog/
โโโ worklog.py # Main CLI tool with advanced architecture
โโโ worklog_original.py # Original implementation backup
โโโ worklog_argparse_backup.py # Pre-refactor backup
โโโ test_worklog_updated.py # Updated comprehensive test suite (28 tests)
โโโ test_worklog.py # Original test suite (reference)
โโโ test_refactoring.py # Refactoring validation tests
โโโ simple_test.py # Basic functionality verification
โโโ requirements.txt # Python dependencies
โโโ README.md # This comprehensive documentation
โโโ setup_alias.sh # Shell alias setup script
Key Files
worklog.py: Production-ready implementation with advanced architecturetest_worklog_updated.py: Complete test suite for refactored codetest_refactoring.py: Validation tests for new architecture componentssimple_test.py: Quick functionality verificationrequirements.txt: Dependencies (typer[all], rich)- Backup files: Original implementations preserved for reference
Running Tests
# Updated comprehensive test suite (recommended)
python3 test_worklog_updated.py
# Quick functionality verification
python3 simple_test.py
# Architecture validation tests
python3 test_refactoring.py
# Original test suite (for reference)
python3 -m unittest test_worklog.py -v
๐ฏ Refactoring Summary
This refactoring demonstrates modern Python development practices:
- Separation of Concerns: Specialized classes for validation, configuration, backup management, and daily file operations
- Centralized Logic: Eliminated code duplication through centralized validation and configuration
- Enhanced Error Handling: User-friendly error messages with comprehensive logging
- Performance Optimization: Caching and optimized file operations
- Maintainable Architecture: Clean class structure with clear responsibilities
- Comprehensive Testing: Updated test suite covering all new functionality
- Professional Standards: Structured logging, atomic operations, and robust data validation
The result is a more maintainable, reliable, and extensible codebase while preserving all original functionality.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file drudge_cli-2.0.1.tar.gz.
File metadata
- Download URL: drudge_cli-2.0.1.tar.gz
- Upload date:
- Size: 42.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2c8321cff3fa8b7a2aa9c69b22b4b429b8b5d798a38c077a7e7aabf35b789715
|
|
| MD5 |
f63f61dee6d9c09e1bb91de30ccf2e5f
|
|
| BLAKE2b-256 |
6de81b2414db310a000f1a7acc7c8b9c8eee8673a05453c6f2247f88fce91f7b
|
File details
Details for the file drudge_cli-2.0.1-py3-none-any.whl.
File metadata
- Download URL: drudge_cli-2.0.1-py3-none-any.whl
- Upload date:
- Size: 29.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
56c0b20702c60f2994556618410cfbc1bd2bd40cb5d442867c30f3f952550304
|
|
| MD5 |
2e1c7eca5cd79a917070dbeb6bbad4e1
|
|
| BLAKE2b-256 |
cb00d255cb3c19ca55656473eab4a914e23b345654b25f838ad8ed781d3292f3
|