Skip to content

Commit 2ba9948

Browse files
authored
Merge pull request sumanth-0#808 from aniruddhaadak9/habit-tracker-cli-773
Add Habit Tracker CLI for issue sumanth-0#773
2 parents f7bcb80 + 370ed2e commit 2ba9948

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#!/usr/bin/env python3
2+
"""Habit Tracker CLI - Track daily habits and view streaks"""
3+
import json
4+
import os
5+
from datetime import datetime, timedelta
6+
from pathlib import Path
7+
8+
HABITS_FILE = Path.home() / ".habit_tracker.json"
9+
10+
def load_habits():
11+
"""Load habits from JSON file"""
12+
if HABITS_FILE.exists():
13+
with open(HABITS_FILE, 'r') as f:
14+
return json.load(f)
15+
return {}
16+
17+
def save_habits(habits):
18+
"""Save habits to JSON file"""
19+
with open(HABITS_FILE, 'w') as f:
20+
json.dump(habits, f, indent=2)
21+
22+
def add_habit(name):
23+
"""Add a new habit"""
24+
habits = load_habits()
25+
if name in habits:
26+
print(f"❌ Habit '{name}' already exists!")
27+
return
28+
habits[name] = {"created": datetime.now().strftime("%Y-%m-%d"), "completed": []}
29+
save_habits(habits)
30+
print(f"✅ Added habit: {name}")
31+
32+
def check_off_habit(name):
33+
"""Mark habit as completed for today"""
34+
habits = load_habits()
35+
if name not in habits:
36+
print(f"❌ Habit '{name}' not found!")
37+
return
38+
today = datetime.now().strftime("%Y-%m-%d")
39+
if today in habits[name]["completed"]:
40+
print(f"ℹ️ Habit '{name}' already completed today!")
41+
return
42+
habits[name]["completed"].append(today)
43+
save_habits(habits)
44+
print(f"🎉 Checked off: {name}")
45+
46+
def calculate_streak(completed_dates):
47+
"""Calculate current streak from completed dates"""
48+
if not completed_dates:
49+
return 0
50+
dates = sorted([datetime.strptime(d, "%Y-%m-%d") for d in completed_dates], reverse=True)
51+
streak = 1
52+
for i in range(len(dates) - 1):
53+
if (dates[i] - dates[i + 1]).days == 1:
54+
streak += 1
55+
else:
56+
break
57+
return streak if (datetime.now().date() - dates[0].date()).days <= 1 else 0
58+
59+
def list_habits():
60+
"""List all habits with streaks"""
61+
habits = load_habits()
62+
if not habits:
63+
print("📝 No habits tracked yet. Add one with: add <habit_name>")
64+
return
65+
print("\n🎯 Your Habits:\n" + "="*50)
66+
for name, data in habits.items():
67+
streak = calculate_streak(data["completed"])
68+
total = len(data["completed"])
69+
print(f" {name:20} | 🔥 {streak:2d} day streak | ✓ {total:3d} total")
70+
print("="*50 + "\n")
71+
72+
def main():
73+
"""Main CLI interface"""
74+
import sys
75+
args = sys.argv[1:]
76+
if not args:
77+
print("Usage: python habit_tracker_cli.py <command> [args]")
78+
print("Commands:")
79+
print(" add <name> - Add a new habit")
80+
print(" check <name> - Check off habit for today")
81+
print(" list - List all habits with streaks")
82+
return
83+
cmd = args[0]
84+
if cmd == "add" and len(args) > 1:
85+
add_habit(" ".join(args[1:]))
86+
elif cmd == "check" and len(args) > 1:
87+
check_off_habit(" ".join(args[1:]))
88+
elif cmd == "list":
89+
list_habits()
90+
else:
91+
print(f"❌ Unknown command: {cmd}")
92+
93+
if __name__ == "__main__":
94+
main()

0 commit comments

Comments
 (0)