634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ```
4 | ######## ### ###### ## ## ###### ## ## ######## ###### ## ##
5 | ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
6 | ## ## ## ## ## ## ## ## ## ## ## ## ##
7 | ## ## ## ###### ##### ## ######### ###### ## #####
8 | ## ######### ## ## ## ## ## ## ## ## ## ##
9 | ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
10 | ## ## ## ###### ## ## ###### ## ## ######## ###### ## ##
11 | ```
12 |
13 | > _A non-AI automatic scheduler for taskwarrior (i.e. alternative to skedpal / timehero / flowsavvy / reclaim / trevor / motion)_
14 |
15 | 
16 |
17 |
18 |
19 | This is a taskwarrior extension that automatically schedules your tasks based on your working hours,
20 | estimated time, and calendar events, finding an optimal time to work on each task and match all your
21 | deadlines.
22 |
23 | ## Features
24 |
25 | - [x] **Use arbitrarily complex time maps for working hours**
26 | - [x] Block scheduling time using iCal calendars (meetings, vacations, holidays, etc.)
27 | - [x] **Parallel scheduling algorithm for multiple tasks, considering urgency and dependencies**
28 | - [x] Dry-run mode: preview scheduling without modifying your Taskwarrior database
29 | - [x] Custom urgency weighting for scheduling (via CLI or config)
30 | - [x] **Auto-fix scheduling to match due dates**
31 | - [x] Force update of iCal calendars, bypassing cache
32 | - [x] Simple, customizable reports for planned and unplanned tasks
33 | - [x] Emoji and attribute customization in reports
34 | - [ ] Use Google API to access calendars
35 | - [ ] Export tasks to iCal calendar and API calendars
36 |
37 | ## Install
38 |
39 | 1. `pipx install taskcheck`
40 | 2. `taskcheck --install`
41 |
42 | ## How does it work
43 |
44 | This extension parses your pending and waiting tasks sorted decreasingly by urgency and tries to schedule them in the future.
45 | It considers their estimated time to schedule all tasks starting from the most urgent one.
46 |
47 | #### UDAs
48 |
49 | Taskcheck leverages two UDAs, `estimated` and `time_map`. The `estimated` attribute is
50 | the expected time to complete the task in hours. The `time_map` is a comma-separated list of strings
51 | that indicates the hours per day in which you will work on a task (e.g. `work`, `weekend`, etc.).
52 | The exact correspondence between the `time_map` and the hours of the day is defined in the configuration
53 | file of taskcheck. For instance:
54 |
55 | ```toml
56 | [time_maps]
57 | # get an error)
58 | [time_maps.work]
59 | monday = [[9, 12.30], [14, 17]]
60 | tuesday = [[9, 12.30], [14, 17]]
61 | # ...
62 | ```
63 |
64 | #### They say it's an "AI"
65 |
66 | Taskcheck will also parse online iCal calendars (Google, Apple, etc.) and will match them with your time maps.
67 | It will then modify the Taskwarrior tasks by adding the `completion_date` attribute with the expected
68 | date of completion and the `scheduled` attribute with the date in which the task is expected to
69 | start.
70 |
71 | It will also print a red line for every task whose `completion_date` is after its `due_date`.
72 |
73 | In general, it is recommended to run taskcheck rather frequently and at least once at the beginning
74 | of your working day.
75 |
76 | #### Reports
77 |
78 | You can also print simple reports that exploit the `scheduling` UDA filled by Taskcheck to grasp
79 | how much time you have to work on which task in which day. For
80 | instance:
81 |
82 | - `taskcheck -r today` will show the tasks planned for today
83 | - `taskcheck -r 1w` will show the tasks planned for the next week
84 |
85 | ## Configuration
86 |
87 | `taskcheck --install` allows you to create required and recommended configurations for
88 | Taskwarrior. It will also generate a default configuration file for taskcheck.
89 |
90 | Below is an example of a taskcheck configuration file, with all relevant options:
91 |
92 | ```toml
93 | [time_maps]
94 | # Define your working hours for each named time map (in 24h format, e.g. 9.5 = 9:30)
95 | [time_maps.work]
96 | monday = [[9, 12.30], [14, 17]]
97 | tuesday = [[9, 12.30], [14, 17]]
98 | wednesday = [[9, 12.30], [14, 17]]
99 | thursday = [[9, 12.30], [14, 17]]
100 | friday = [[9, 12.30], [14, 17]]
101 |
102 | [time_maps.weekend]
103 | saturday = [[9, 12.30]]
104 | sunday = [[9, 12.30]]
105 |
106 | [scheduler]
107 | days_ahead = 1000 # How far to go with the schedule (lower values = faster computation)
108 | weight_urgency = 1.0 # Default weight for urgency in scheduling (overridable via CLI)
109 | # if weight_urgency is set to 0, only due urgency is considered
110 | # by default, this factor is automatically reduced if some task cannot be scheduled in time,
111 | # leading to tasks with due dates being prioritized (see --no-auto-adjust-urgency)
112 |
113 | [calendars]
114 | # iCal calendars can be used to block your time and make the scheduling more precise
115 | [calendars.1]
116 | url = "https://your/url/to/calendar.ics"
117 | expiration = 0.08 # In hours (0.08 hours ≈ 5 minutes)
118 | timezone = "Europe/Rome" # If set, force timezone for this calendar (see TZ database)
119 |
120 | [calendars.holidays]
121 | url = "https://www.officeholidays.com/ics-clean/italy/milan"
122 | event_all_day_is_blocking = true
123 | expiration = 720 # In hours (720 hours = 30 days)
124 |
125 | [report]
126 | include_unplanned = true
127 | additional_attributes = ["estimated", "due", "urgency"] # Extra attributes to show in the report
128 | additional_attributes_unplanned = ["due", "urgency"] # Extra attributes for unplanned tasks
129 | emoji_keywords = {"meet"=":busts_in_silhouette:", "review"=":mag_right:"} # Map keywords to emoji
130 | ```
131 |
132 | ### Configuration Options
133 |
134 | - **[scheduler]**
135 | - `days_ahead`: How many days ahead to schedule tasks.
136 | - `weight_urgency`: Default weight for urgency in scheduling (0.0 to 1.0). Can be overridden with `--urgency-weight`.
137 | - **[calendars]**
138 | - `url`: iCal URL to block time.
139 | - `expiration`: Cache expiration in hours.
140 | - `timezone`: (Optional) Force a timezone for this calendar.
141 | - `event_all_day_is_blocking`: (Optional, bool) Treat all-day events as blocking.
142 | - **[report]**
143 | - `include_unplanned`: Show unplanned tasks in a separate section.
144 | - `additional_attributes`: Extra columns to show in the report.
145 | - `additional_attributes_unplanned`: Extra columns for unplanned tasks.
146 | - `emoji_keywords`: Map keywords in task descriptions to emoji.
147 |
148 | ## Algorithm
149 |
150 | The algorithm simulates what happens if you work on a task for a certain time on a given day.
151 |
152 | For each day X starting from today, it sorts the tasks by decreasing urgency.
153 | It start from the most urgent tasks that can be allocated on day X depending on the task's
154 | `time_map` and on your calendars. It allocates a few number of hours to the task,
155 | then recomputes the urgencies exactly as Taskwarrior would do
156 | if it was running on day X. Having recomputed the urgencies, it restarts.
157 |
158 | If after 2 hours a long task has decreased its urgency, it will be noticed and the newer most urgent
159 | task will get scheduled in its place.
160 |
161 | For `today`, taskcheck will skip the hours in the past -- i.e. if you're running at 12 pm, it will
162 | skip all the available slots until 12 pm.
163 |
164 | The maximum time that is allocated at each attempt is by default 2 hours
165 | (or less if the task is shorter), but you can change it by tuning the Taskwarrior UDA `min_block`.
166 |
167 | After the scheduling is done, if any task has a `completion_date` after its `due_date`, the
168 | `weight_urgency` factor is reduced by 0.1 and the scheduling is repeated, until all tasks
169 | are scheduled before their due dates or the `weight_urgency` factor reaches 0.
170 |
171 | ## Tips and Tricks
172 |
173 | - You can exclude a task from being scheduled by removing the `time_map` or `estimated` attributes.
174 | - You can see tasks that you can execute now with the `task ready` report.
175 |
176 | ## CLI Options
177 |
178 | ```
179 | usage: __main__.py [-h] [-v] [-i] [-r REPORT] [-s] [-f] [--taskrc TASKRC] [--urgency-weight URGENCY_WEIGHT] [--dry-run] [--no-auto-adjust-urgency]
180 |
181 | options:
182 | -h, --help show this help message and exit
183 | -v, --verbose Increase output verbosity.
184 | -i, --install Install the UDAs, required settings, and default config file.
185 | -r REPORT, --report REPORT
186 | Generate a report of the tasks based on the scheduling; can be any Taskwarrior datetime specification (e.g. today, tomorrow, eom, som, 1st, 2nd, etc.). It is considered as `by`, meaning that the report will be
187 | generated for all the days until the specified date and including it.
188 | -s, --schedule Perform the scheduling algorithm, giving a schedule and a scheduling UDA and alerting for not completable tasks
189 | -f, --force-update Force update of all ical calendars by ignoring cache expiration
190 | --taskrc TASKRC Set custom TASKRC directory for debugging purposes
191 | --urgency-weight URGENCY_WEIGHT
192 | Weight for urgency in scheduling (0.0 to 1.0), overrides config value. When 1.0, the whole Taskwarrior urgency is used for scheduling. When 0.0, the Taskwarrior urgency is reduced to only due urgency.
193 | --dry-run Perform scheduling without modifying the Taskwarrior database, useful for testing
194 | --no-auto-adjust-urgency
195 | Disable automatic reduction of urgency weight … (default: enabled)
196 | ```
197 |
198 | ### Examples
199 |
200 | - `taskcheck --schedule`
201 | Run the scheduler and update your Taskwarrior tasks.
202 | - `taskcheck --schedule --dry-run`
203 | Preview the schedule without modifying your database.
204 | - `taskcheck --schedule --urgency-weight 0.5`
205 | Use a custom urgency weighting for this run.
206 | - `taskcheck --schedule --no-auto-adjust-urgency`
207 | Avoid the automatically reduction of urgency weight if tasks can't be scheduled before their due dates.
208 | - `taskcheck --report today`
209 | Show the schedule for today.
210 | - `taskcheck --report 1w`
211 | Show the schedule for the next week.
212 | - `taskcheck --force-update`
213 | Force refresh of all iCal calendars, ignoring cache.
214 |
--------------------------------------------------------------------------------
/nvim-dap.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "name": "uv (default)",
6 | "type": "python",
7 | "request": "launch",
8 | "module": "taskcheck",
9 | "env": {},
10 | "args": [],
11 | "cwd": "${workspaceFolder}"
12 | },
13 | {
14 | "name": "uv (report)",
15 | "type": "python",
16 | "request": "launch",
17 | "module": "taskcheck",
18 | "env": {},
19 | "args": [
20 | "-r",
21 | "mon"
22 | ],
23 | "cwd": "${workspaceFolder}"
24 | }
25 | ]
26 | }
27 |
--------------------------------------------------------------------------------
/publish.fish:
--------------------------------------------------------------------------------
1 | set newversion (sed -n 's/^version = "\(.*\)"$/\1/p' pyproject.toml)
2 | git commit -am "new v$newversion"
3 | git tag -a v$newversion -m "v$newversion"
4 | git push --tags
5 | uv build
6 | uv publish --username __token__ --password (rbw get "pypi" "00sapo" -f "token")
7 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "taskcheck"
3 | version = "1.0.0-3"
4 | description = "Automatic scheduler for taskwarrior"
5 | readme = "README.md"
6 | requires-python = ">=3.11"
7 | dependencies = [
8 | "appdirs>=1.4.4",
9 | "icalendar>=6.0.1",
10 | "random-unicode-emoji>=2.8",
11 | "requests>=2.32.3",
12 | "rich>=13.9.4",
13 | ]
14 |
15 | [project.scripts]
16 | taskcheck = "taskcheck.__main__:main"
17 |
18 | [build-system]
19 | requires = ["setuptools>=45", "wheel"]
20 | build-backend = "setuptools.build_meta"
21 |
22 | [tool.setuptools]
23 | license-files = []
24 |
25 | [tool.setuptools.packages.find]
26 | where = ["."]
27 | include = ["taskcheck*"]
28 |
29 | [tool.uv]
30 | package = true
31 |
32 | [dependency-groups]
33 | dev = [
34 | "freezegun>=1.5.2",
35 | "pytest>=8.3.5",
36 | "pytest-cov>=6.1.1",
37 | "pytest-mock>=3.14.1",
38 | "responses>=0.25.7",
39 | ]
40 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [tool:pytest]
2 | testpaths = tests
3 | python_files = test_*.py
4 | python_classes = Test*
5 | python_functions = test_*
6 | addopts =
7 | -v
8 | --tb=short
9 | --strict-markers
10 | --disable-warnings
11 | markers =
12 | slow: marks tests as slow (deselect with '-m "not slow"')
13 | integration: marks tests as integration tests
14 | unit: marks tests as unit tests
15 |
--------------------------------------------------------------------------------
/run_tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Comprehensive test runner script for taskcheck
4 | # Usage: ./run_tests.sh [options]
5 |
6 | set -e # Exit on any error
7 |
8 | # Colors for output
9 | RED='\033[0;31m'
10 | GREEN='\033[0;32m'
11 | YELLOW='\033[1;33m'
12 | BLUE='\033[0;34m'
13 | NC='\033[0m' # No Color
14 |
15 | # Default options
16 | VERBOSE=false
17 | COVERAGE=true
18 | HTML_REPORT=false
19 | SPECIFIC_TEST=""
20 | FAIL_FAST=true
21 | PARALLEL=false
22 |
23 | # Parse command line arguments
24 | while [[ $# -gt 0 ]]; do
25 | case $1 in
26 | -v | --verbose)
27 | VERBOSE=true
28 | shift
29 | ;;
30 | --no-coverage)
31 | COVERAGE=false
32 | shift
33 | ;;
34 | --html)
35 | HTML_REPORT=true
36 | shift
37 | ;;
38 | -t | --test)
39 | SPECIFIC_TEST="$2"
40 | shift 2
41 | ;;
42 | -x | --fail-fast)
43 | FAIL_FAST=true
44 | shift
45 | ;;
46 | -j | --parallel)
47 | PARALLEL=true
48 | shift
49 | ;;
50 | -h | --help)
51 | echo "Usage: $0 [options]"
52 | echo "Options:"
53 | echo " -v, --verbose Run tests with verbose output"
54 | echo " --no-coverage Skip coverage reporting"
55 | echo " --html Generate HTML coverage report"
56 | echo " -t, --test FILE Run specific test file or test"
57 | echo " -x, --fail-fast Stop on first failure"
58 | echo " -j, --parallel Run tests in parallel"
59 | echo " -h, --help Show this help message"
60 | exit 0
61 | ;;
62 | *)
63 | echo "Unknown option: $1"
64 | exit 1
65 | ;;
66 | esac
67 | done
68 |
69 | echo -e "${BLUE}🧪 Running taskcheck tests${NC}"
70 | echo "=================================="
71 |
72 | # Check if uv is available
73 | if ! command -v uv &>/dev/null; then
74 | echo -e "${RED}❌ uv is not installed or not in PATH${NC}"
75 | echo "Please install uv: https://docs.astral.sh/uv/getting-started/installation/"
76 | exit 1
77 | fi
78 |
79 | # Install dependencies if needed
80 | echo -e "${YELLOW}📦 Installing test dependencies...${NC}"
81 | uv sync --group dev
82 |
83 | # Build pytest command
84 | PYTEST_CMD="uv run pytest"
85 |
86 | # Add verbose flag
87 | if [ "$VERBOSE" = true ]; then
88 | PYTEST_CMD="$PYTEST_CMD -v"
89 | fi
90 |
91 | # Add coverage flags
92 | if [ "$COVERAGE" = true ]; then
93 | PYTEST_CMD="$PYTEST_CMD --cov=taskcheck --cov-report=term-missing"
94 |
95 | if [ "$HTML_REPORT" = true ]; then
96 | PYTEST_CMD="$PYTEST_CMD --cov-report=html"
97 | fi
98 | fi
99 |
100 | # Add fail fast flag
101 | if [ "$FAIL_FAST" = true ]; then
102 | PYTEST_CMD="$PYTEST_CMD -x"
103 | fi
104 |
105 | # Add parallel execution
106 | if [ "$PARALLEL" = true ]; then
107 | PYTEST_CMD="$PYTEST_CMD -n auto"
108 | fi
109 |
110 | # Add specific test if provided
111 | if [ -n "$SPECIFIC_TEST" ]; then
112 | PYTEST_CMD="$PYTEST_CMD $SPECIFIC_TEST"
113 | fi
114 |
115 | echo -e "${BLUE}🚀 Running command: $PYTEST_CMD${NC}"
116 | echo ""
117 |
118 | # Run the tests
119 | if eval $PYTEST_CMD; then
120 | echo ""
121 | echo -e "${GREEN}✅ All tests passed!${NC}"
122 |
123 | if [ "$COVERAGE" = true ] && [ "$HTML_REPORT" = true ]; then
124 | echo -e "${BLUE}📊 HTML coverage report generated: htmlcov/index.html${NC}"
125 | fi
126 |
127 | exit 0
128 | else
129 | echo ""
130 | echo -e "${RED}❌ Tests failed!${NC}"
131 | exit 1
132 | fi
133 |
--------------------------------------------------------------------------------
/taskcheck/__main__.py:
--------------------------------------------------------------------------------
1 | import tomllib
2 | import argparse
3 |
4 | from taskcheck.parallel import check_tasks_parallel
5 | from taskcheck.common import config_dir
6 |
7 | arg_parser = argparse.ArgumentParser()
8 | arg_parser.add_argument(
9 | "-v", "--verbose", action="store_true", help="Increase output verbosity."
10 | )
11 | arg_parser.add_argument(
12 | "-i",
13 | "--install",
14 | action="store_true",
15 | help="Install the UDAs, required settings, and default config file.",
16 | )
17 | arg_parser.add_argument(
18 | "-r",
19 | "--report",
20 | action="store",
21 | help="Generate a report of the tasks based on the scheduling; can be any Taskwarrior datetime specification (e.g. today, tomorrow, eom, som, 1st, 2nd, etc.). It is considered as `by`, meaning that the report will be generated for all the days until the specified date and including it.",
22 | )
23 | arg_parser.add_argument(
24 | "-s",
25 | "--schedule",
26 | action="store_true",
27 | help="Perform the scheduling algorithm, giving a schedule and a scheduling UDA and alerting for not completable tasks.",
28 | )
29 | arg_parser.add_argument(
30 | "-f",
31 | "--force-update",
32 | action="store_true",
33 | help="Force update of all ical calendars by ignoring cache expiration.",
34 | )
35 | arg_parser.add_argument(
36 | "--taskrc",
37 | action="store",
38 | help="Set custom TASKRC directory for debugging purposes.",
39 | )
40 | arg_parser.add_argument(
41 | "--urgency-weight",
42 | type=float,
43 | help="Weight for urgency in scheduling (0.0 to 1.0), overrides config value. When 1.0, the whole Taskwarrior urgency is used for scheduling. When 0.0, the Taskwarrior urgency is reduced to only due urgency.",
44 | )
45 | arg_parser.add_argument(
46 | "--dry-run",
47 | action="store_true",
48 | help="Perform scheduling without modifying the Taskwarrior database, useful for testing.",
49 | )
50 | arg_parser.add_argument(
51 | "--no-auto-adjust-urgency",
52 | dest="auto_adjust_urgency",
53 | action="store_false",
54 | default=True,
55 | help="Disable automatic reduction of urgency weight when tasks cannot be completed on time. (Enabled by default, meaning automatic reduction will occur.)",
56 | )
57 |
58 |
59 | # Load working hours and exceptions from TOML file
60 | def load_config():
61 | """
62 | Loads the configuration from the TOML file located at config_dir / "taskcheck.toml".
63 | Returns a dictionary with the config structure, e.g.:
64 | {
65 | "time_maps": {
66 | "work": {
67 | "monday": [[9, 12.30], [14, 17]],
68 | "tuesday": [[9, 12.30], [14, 17]],
69 | ...
70 | }
71 | },
72 | "scheduler": {
73 | "days_ahead": 365,
74 | "weight_urgency": 1.0,
75 | ...
76 | },
77 | "report": {
78 | "include_unplanned": true,
79 | "additional_attributes": [],
80 | "additional_attributes_unplanned": [],
81 | "emoji_keywords": {},
82 | ...
83 | }
84 | }
85 | """
86 | with open(config_dir / "taskcheck.toml", "rb") as f:
87 | config = tomllib.load(f)
88 | return config
89 |
90 |
91 | def main():
92 | args = arg_parser.parse_args()
93 |
94 | # Load data and check tasks
95 | print_help = True
96 | result = None
97 | if args.install:
98 | from taskcheck.install import install
99 |
100 | install()
101 | return
102 |
103 | if args.schedule:
104 | config = load_config()
105 | check_tasks_kwargs = dict(
106 | verbose=args.verbose,
107 | force_update=args.force_update,
108 | taskrc=args.taskrc,
109 | urgency_weight_override=args.urgency_weight,
110 | dry_run=args.dry_run,
111 | auto_adjust_urgency=args.auto_adjust_urgency,
112 | )
113 | # Only add auto_adjust_urgency if it is present and a real bool (not a mock)
114 | result = check_tasks_parallel(
115 | config,
116 | **check_tasks_kwargs,
117 | )
118 | print_help = False
119 |
120 | if args.report:
121 | from taskcheck.report import generate_report
122 |
123 | config = load_config()
124 | scheduling_results = None
125 | if args.schedule and args.dry_run:
126 | # If we just did a dry-run schedule, use those results
127 | scheduling_results = result
128 | generate_report(
129 | config,
130 | args.report,
131 | args.verbose,
132 | force_update=args.force_update,
133 | taskrc=args.taskrc,
134 | scheduling_results=scheduling_results,
135 | )
136 | print_help = False
137 |
138 | if print_help:
139 | arg_parser.print_help()
140 |
141 |
142 | if __name__ == "__main__":
143 | main()
144 |
--------------------------------------------------------------------------------
/taskcheck/common.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import json
3 | from datetime import datetime, timedelta
4 | from pathlib import Path
5 | import appdirs
6 | from rich.console import Console
7 |
8 | from taskcheck.ical import ical_to_dict
9 |
10 | console = Console()
11 |
12 | config_dir = Path(appdirs.user_config_dir("task"))
13 |
14 | # Taskwarrior status to avoid
15 | AVOID_STATUS = ["completed", "deleted", "recurring"]
16 |
17 | long_range_time_map = {}
18 |
19 |
20 | def get_task_env(taskrc=None):
21 | import os
22 | env = os.environ.copy()
23 | if taskrc:
24 | env['TASKRC'] = taskrc
25 | env['TASKDATA'] = taskrc
26 | return env
27 |
28 |
29 | # Get tasks from Taskwarrior and sort by urgency
30 | def get_tasks(taskrc=None):
31 | env = get_task_env(taskrc)
32 | result = subprocess.run(["task", "export"], capture_output=True, text=True, env=env)
33 | tasks = json.loads(result.stdout)
34 | return sorted(
35 | (task for task in tasks if "estimated" in task),
36 | key=lambda t: -t.get("urgency", 0),
37 | )
38 |
39 |
40 | def hours_to_decimal(hour):
41 | return int(hour) + (hour - int(hour)) * 100 / 60
42 |
43 |
44 | def hours_to_time(hour):
45 | hours = int(hour)
46 | minutes = int((hour - hours) * 100)
47 | return datetime.strptime(f"{hours}:{minutes}", "%H:%M").time()
48 |
49 |
50 | def time_to_decimal(time):
51 | # round to 2 digits after the point
52 | return time.hour + time.minute / 60
53 |
54 |
55 | def get_available_hours(time_map, date, calendars, verbose=False):
56 | day_of_week = date.strftime("%A").lower()
57 | schedule = time_map.get(day_of_week, [])
58 | available_hours = sum(
59 | hours_to_decimal(end) - hours_to_decimal(start) for start, end in schedule
60 | )
61 |
62 | blocked_hours = 0
63 | for schedule_start, schedule_end in schedule:
64 | # schedule_start and schedule_end are numbers, actually
65 | # so let's convert them to datetime.time objects
66 | schedule_start = hours_to_time(schedule_start)
67 | schedule_end = hours_to_time(schedule_end)
68 | schedule_blocked_hours = 0
69 | for calendar in calendars:
70 | for event in calendar:
71 | # we use str to make object serializable as jsons
72 | if isinstance(event["start"], str):
73 | event["start"] = datetime.fromisoformat(event["start"])
74 | if isinstance(event["end"], str):
75 | event["end"] = datetime.fromisoformat(event["end"])
76 |
77 | if event["start"].date() > date:
78 | break
79 | elif event["end"].date() < date:
80 | continue
81 |
82 | # check if the event overlaps with one of the working hours
83 | event_start = event["start"].time()
84 | event_end = event["end"].time()
85 | if event["start"].date() < date:
86 | event_start = datetime(date.year, date.month, date.day, 0, 0).time()
87 | if event["end"].date() > date:
88 | event_end = datetime(date.year, date.month, date.day, 23, 59).time()
89 |
90 | if event_start < schedule_end and event_end > schedule_start:
91 | schedule_blocked_hours += time_to_decimal(
92 | min(schedule_end, event_end)
93 | ) - time_to_decimal(max(schedule_start, event_start))
94 | if verbose and schedule_blocked_hours > 0:
95 | print(
96 | f"Blocked hours on {date} between {schedule_start} and {schedule_end}: {schedule_blocked_hours}"
97 | )
98 | blocked_hours += schedule_blocked_hours
99 | available_hours -= blocked_hours
100 | return available_hours
101 |
102 |
103 | def pdth_to_hours(duration_str):
104 | # string format is P#DT#H
105 | # with D and H optional
106 | duration_str = duration_str[1:] # Remove leading "P"
107 | days, hours, minutes = 0, 0, 0
108 | if "D" in duration_str:
109 | days, duration_str = duration_str.split("D")
110 | days = int(days)
111 | if "H" in duration_str:
112 | if "T" in duration_str:
113 | hours = int(duration_str.split("T")[1].split("H")[0])
114 | else:
115 | hours = int(duration_str.split("H")[0])
116 | if "M" in duration_str:
117 | if "H" in duration_str:
118 | minutes = int(duration_str.split("H")[1].split("M")[0])
119 | else:
120 | if "T" in duration_str:
121 | minutes = int(duration_str.split("T")[1].split("M")[0])
122 | else:
123 | minutes = int(duration_str.split("M")[0])
124 | return days * 24 + hours + minutes / 60
125 |
126 |
127 | def hours_to_pdth(hours):
128 | days_ = hours / 24
129 | hours_ = hours % 24
130 | minutes_ = int(round((hours_ - int(hours_)) * 60))
131 | days_ = int(days_)
132 | hours_ = int(hours_)
133 | minutes_ = int(minutes_)
134 | ret = "P"
135 | if days_ == 0:
136 | ret += "T"
137 | else:
138 | ret += f"{days_}DT"
139 | if hours_ > 0:
140 | ret += f"{hours_}H"
141 | if minutes_ > 0:
142 | ret += f"{minutes_}M"
143 | if ret == "PT":
144 | print("Warning: hours_to_pdth() returned 'PT' for hours = ", hours)
145 | return ret
146 |
147 |
148 | def get_long_range_time_map(
149 | time_maps, time_map_names, days_ahead, calendars, verbose=False
150 | ):
151 | key = ",".join(time_map_names)
152 | if key in long_range_time_map:
153 | task_time_map = long_range_time_map[key]
154 | else:
155 | if verbose:
156 | print(f"Calculating long range time map for {key}")
157 | task_time_map = []
158 | for d in range(days_ahead):
159 | date = datetime.today().date() + timedelta(days=d)
160 | daily_hours = 0
161 | for time_map_name in time_map_names:
162 | if time_map_name not in time_maps:
163 | raise ValueError(f"Time map '{time_map_name}' does not exist.")
164 | time_map = time_maps[time_map_name]
165 | daily_hours += get_available_hours(time_map, date, calendars)
166 | task_time_map.append(daily_hours)
167 | long_range_time_map[key] = task_time_map
168 |
169 | today_time = time_to_decimal(datetime.now().time())
170 | today_weekday = datetime.today().strftime("%A").lower()
171 | today_used_hours = 0
172 | # compare with the time_maps of today
173 | for time_map_name in time_map_names:
174 | time_map = time_maps[time_map_name].get(today_weekday)
175 | if time_map:
176 | for schedule_start, schedule_end in time_map:
177 | schedule_start = hours_to_decimal(schedule_start)
178 | schedule_end = hours_to_decimal(schedule_end)
179 | if schedule_start <= today_time <= schedule_end:
180 | today_used_hours += today_time - schedule_start
181 | break
182 | elif today_time > schedule_end:
183 | today_used_hours += schedule_end - schedule_start
184 | return task_time_map, today_used_hours
185 |
186 |
187 | def mark_end_date(
188 | due_date, end_date, start_date, scheduling_note, id, description=None, taskrc=None
189 | ):
190 | start_end_fields = [f"scheduled:{start_date}", f"completion_date:{end_date}"]
191 | env = get_task_env(taskrc)
192 |
193 | subprocess.run(
194 | [
195 | "task",
196 | str(id),
197 | "modify",
198 | *start_end_fields,
199 | f'scheduling:"{scheduling_note}"',
200 | ],
201 | stdout=subprocess.DEVNULL,
202 | stderr=subprocess.DEVNULL,
203 | env=env,
204 | )
205 | if due_date is not None and end_date > due_date:
206 | # print in bold red using ANSI escape codes
207 | description = "('" + description + "')" if description is not None else ""
208 | print(f"\033[1;31mTask {id} {description} may not be completed on time\033[0m")
209 |
210 |
211 | def get_calendars(config, verbose=False, force_update=False):
212 | calendars = []
213 | for calname in config["calendars"]:
214 | calendar = config["calendars"][calname]
215 | calendar = ical_to_dict(
216 | calendar["url"],
217 | config["scheduler"]["days_ahead"],
218 | all_day=calendar["event_all_day_is_blocking"],
219 | expiration=calendar["expiration"],
220 | verbose=verbose,
221 | tz_name=calendar.get("timezone"),
222 | force_update=force_update,
223 | )
224 | calendar.sort(key=lambda e: e["start"])
225 | calendars.append(calendar)
226 | if verbose:
227 | print(f"Loaded {len(calendars)} calendars")
228 | return calendars
229 |
--------------------------------------------------------------------------------
/taskcheck/ical.py:
--------------------------------------------------------------------------------
1 | import hashlib
2 | import json
3 | from icalendar import Calendar
4 | from datetime import datetime, timedelta
5 | from dateutil.rrule import rruleset, rrulestr
6 | import requests
7 | from pathlib import Path
8 | import appdirs
9 | import zoneinfo
10 |
11 | import time
12 |
13 | CACHE = Path(appdirs.user_cache_dir("taskcheck"))
14 |
15 |
16 | def fetch_ical_data(url):
17 | response = requests.get(url)
18 | response.raise_for_status()
19 | return response.text
20 |
21 |
22 | def parse_ical_events(ical_text, days_ahead, all_day, tz_name=None, verbose=False):
23 | cal = Calendar.from_ical(ical_text)
24 | today = datetime.now().date()
25 | end_date = today + timedelta(days=days_ahead)
26 |
27 | events = []
28 | exceptions = set()
29 |
30 | for component in cal.walk():
31 | if component.name == "VEVENT":
32 | event_start = component.get("dtstart").dt
33 | event_end = component.get("dtend").dt
34 | recurrence_rule = component.get("rrule")
35 | recurrence_id = component.get("recurrence-id")
36 |
37 | # skip all-day events if not requested
38 | is_all_day = not hasattr(event_start, "hour") or event_start == event_end
39 | if is_all_day:
40 | if not all_day:
41 | continue
42 | else:
43 | # all-day events should block since 00:00 and end at 23:59:59
44 | event_start = datetime(
45 | event_start.year,
46 | event_start.month,
47 | event_start.day,
48 | 0,
49 | 0,
50 | 0,
51 | 0,
52 | )
53 | event_end = event_start + timedelta(days=1) - timedelta(seconds=1)
54 | if recurrence_id:
55 | if end_date >= recurrence_id.dt.date() >= today:
56 | # this was an occurrence of a recurring event
57 | # but has been moved, let's record the exception that must be removed
58 | exceptions.add(recurrence_id.dt.isoformat())
59 |
60 | occurrences = rruleset()
61 | if recurrence_rule:
62 | # avoid handling rules that are already ended
63 | # and don't create events beyond end_date
64 | until = recurrence_rule.get("UNTIL")
65 | if until is not None:
66 | until = until[0].date()
67 | if until < today:
68 | continue
69 | rrule = rrulestr(
70 | str(recurrence_rule.to_ical(), "utf-8"),
71 | dtstart=event_start,
72 | )
73 | occurrences.rrule(rrule) # type: ignore
74 | # exceptions to recurring events
75 | excdates = component.get("exdate")
76 | if excdates is not None:
77 | if isinstance(excdates, list):
78 | # concatenate all the .dts into one list
79 | excdates = [e for exdate in excdates for e in exdate.dts]
80 | else:
81 | excdates = excdates.dts
82 | for excdate in excdates:
83 | if end_date >= excdate.dt.date() >= today:
84 | exceptions.add(excdate.dt.isoformat())
85 | else:
86 | # if event is not recurring, add it as a single event
87 | if event_start.date() >= today and event_end.date() <= end_date:
88 | occurrences.rdate(event_start)
89 |
90 | for occurrence in occurrences:
91 | if tz_name is not None:
92 | occurrence = occurrence.astimezone(zoneinfo.ZoneInfo(tz_name))
93 | end = occurrence + (event_end - event_start)
94 | if occurrence.date() >= today and end.date() <= end_date:
95 | events.append(
96 | {
97 | # "summary": component.get("summary"),
98 | "start": occurrence.isoformat(),
99 | "end": end.isoformat(),
100 | }
101 | )
102 | elif end.date() > end_date:
103 | break
104 |
105 | with_exc_len = len(events)
106 | events = [event for event in events if event["start"] not in exceptions]
107 | if verbose:
108 | print(
109 | f"Removed {with_exc_len - len(events)} events that are exceptions to recurring events"
110 | )
111 | events.sort(key=lambda x: x["start"])
112 | return events
113 |
114 |
115 | def get_cache_filename(url):
116 | hash_object = hashlib.sha256(url.encode())
117 | return CACHE / f"{hash_object.hexdigest()}.json"
118 |
119 |
120 | def ical_to_dict(
121 | url, days_ahead=7, all_day=False, expiration=0.25, verbose=False, tz_name=None, force_update=False
122 | ):
123 | CACHE.mkdir(exist_ok=True, parents=True)
124 | cache_file = CACHE / get_cache_filename(url)
125 | current_time = time.time()
126 |
127 | # Check if cache file exists and is not expired
128 | if cache_file.exists() and not force_update:
129 | cache_mtime = cache_file.stat().st_mtime
130 | if current_time - cache_mtime < expiration * 3600:
131 | with open(cache_file, "r") as f:
132 | events = json.load(f)
133 | if verbose:
134 | print("Loaded events from cache")
135 | return events
136 |
137 | # Fetch and parse iCal data
138 | ttt = time.time()
139 | ical_text = fetch_ical_data(url)
140 | if verbose:
141 | print("Time taken to fetch ical data: ", time.time() - ttt)
142 | ttt = time.time()
143 | events = parse_ical_events(
144 | ical_text, days_ahead, all_day, tz_name=tz_name, verbose=verbose
145 | )
146 | if verbose:
147 | print("Time taken to parse ical data: ", time.time() - ttt)
148 |
149 | # Save events to cache
150 | with open(cache_file, "w") as f:
151 | json.dump(events, f)
152 |
153 | return events
154 |
--------------------------------------------------------------------------------
/taskcheck/install.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | from taskcheck.common import config_dir
3 |
4 |
5 | default_config = """
6 | [time_maps]
7 | [time_maps.work]
8 | monday = [[9, 12.30], [14, 17]]
9 | tuesday = [[9, 12.30], [14, 17]]
10 | wednesday = [[9, 12.30], [14, 17]]
11 | thursday = [[9, 12.30], [14, 17]]
12 | friday = [[9, 12.30], [14, 17]]
13 |
14 | [scheduler]
15 | days_ahead = 365
16 | weight_urgency = 1.0
17 |
18 | [report]
19 | include_unplanned = true
20 | additional_attributes = []
21 | additional_attributes_unplanned = []
22 | emoji_keywords = {}
23 | """
24 |
25 |
26 | def apply_config(key, value):
27 | subprocess.run(
28 | [
29 | "task",
30 | "rc.confirmation=0",
31 | "config",
32 | key,
33 | value,
34 | ],
35 | stdout=subprocess.DEVNULL,
36 | )
37 |
38 |
39 | def install():
40 | """
41 | Adds the required and optional settings explaining them to the user.
42 | Also initialize the config file with some sane default.
43 | """
44 |
45 | # Define the required configurations
46 | required_configs = [
47 | ("uda.time_map.type", "string"),
48 | ("uda.time_map.label", "Time Map"),
49 | ("uda.time_map.default", "work"),
50 | ("uda.estimated.type", "duration"),
51 | ("uda.estimated.label", "Estimated Time"),
52 | ("uda.completion_date.type", "date"),
53 | ("uda.completion_date.label", "Expected Completion Date"),
54 | ("uda.scheduling.type", "string"),
55 | ("uda.scheduling.label", "Scheduling"),
56 | ("uda.min_block.type", "numeric"),
57 | ("uda.min_block.label", "Minimum Time Block"),
58 | ("uda.min_block.default", "2"),
59 | ("recurrence.confirmation", "no"),
60 | ]
61 |
62 | # Optional configurations
63 | optional_configs = [
64 | ("urgency.uda.estimated.PT1H.coefficient", "1"),
65 | ("urgency.uda.estimated.PT2H.coefficient", "2.32"),
66 | ("urgency.uda.estimated.PT3H.coefficient", "3.67"),
67 | ("urgency.uda.estimated.PT4H.coefficient", "4.64"),
68 | ("urgency.uda.estimated.PT5H.coefficient", "5.39"),
69 | ("urgency.uda.estimated.PT6H.coefficient", "6.02"),
70 | ("urgency.uda.estimated.PT7H.coefficient", "6.56"),
71 | ("urgency.uda.estimated.PT8H.coefficient", "7.03"),
72 | ("urgency.uda.estimated.PT9H.coefficient", "7.45"),
73 | ("urgency.uda.estimated.PT10H.coefficient", "7.82"),
74 | ("urgency.uda.estimated.PT11H.coefficient", "8.16"),
75 | ("urgency.uda.estimated.PT12H.coefficient", "8.47"),
76 | ("urgency.uda.estimated.PT13H.coefficient", "8.75"),
77 | ("urgency.uda.estimated.PT14H.coefficient", "9.01"),
78 | ("urgency.uda.estimated.PT15H.coefficient", "9.25"),
79 | ("urgency.uda.estimated.PT16H.coefficient", "9.47"),
80 | ("urgency.uda.estimated.PT17H.coefficient", "9.68"),
81 | ("urgency.uda.estimated.PT18H.coefficient", "9.87"),
82 | ("urgency.uda.estimated.PT19H.coefficient", "10.05"),
83 | ("urgency.uda.estimated.PT20H.coefficient", "10.22"),
84 | ("urgency.uda.estimated.PT21H.coefficient", "10.38"),
85 | ("urgency.uda.estimated.PT22H.coefficient", "10.53"),
86 | ("urgency.uda.estimated.PT23H.coefficient", "10.67"),
87 | ("urgency.uda.estimated.P1D.coefficient", "10.80"),
88 | ("urgency.uda.estimated.P1DT1H.coefficient", "10.93"),
89 | ("urgency.uda.estimated.P1DT2H.coefficient", "11.05"),
90 | ("urgency.uda.estimated.P1DT3H.coefficient", "11.16"),
91 | ("urgency.uda.estimated.P1DT4H.coefficient", "11.27"),
92 | ("urgency.uda.estimated.P1DT5H.coefficient", "11.37"),
93 | ("urgency.uda.estimated.P1DT6H.coefficient", "11.47"),
94 | ("urgency.uda.estimated.P1DT7H.coefficient", "11.56"),
95 | ("urgency.uda.estimated.P1DT8H.coefficient", "11.65"),
96 | ("urgency.uda.estimated.P1DT9H.coefficient", "11.73"),
97 | ("urgency.uda.estimated.P1DT10H.coefficient", "11.81"),
98 | ("urgency.uda.estimated.P1DT11H.coefficient", "11.89"),
99 | ("urgency.uda.estimated.P1DT12H.coefficient", "11.96"),
100 | (
101 | "report.ready.columns",
102 | "id,start.age,entry.age,depends.indicator,priority,project,tags,recur.indicator,scheduled.relative,due.relative,until.remaining,description,urgency",
103 | ),
104 | ("journal.info", "0"),
105 | ("urgency.inherit", "1"),
106 | ("urgency.blocked.coefficient", "0"),
107 | ("urgency.blocking.coefficient", "0"),
108 | ("urgency.waiting.coefficient", "0"),
109 | ("urgency.scheduled.coefficient", "0"),
110 | ]
111 |
112 | answer = input(
113 | """
114 | _________________________________________________________________________________________
115 | Required configuration for taskcheck includes:
116 | - 3 UDA fields
117 | - turning off confirmation for recurring tasks
118 |
119 | Do you want to continue? [y/N] """
120 | )
121 | if answer.lower() not in ["y", "yes"]:
122 | return
123 |
124 | answer = input(
125 | """
126 | _________________________________________________________________________________________
127 | Optional configuration for taskcheck includes:
128 | - urgency coefficients for estimated time (up to 36 hour duration)
129 | - better `ready` report columns
130 | - turning off printing journal logs in the task details
131 | - turning on urgency inheritance from dependant tasks and disabling blocked and blocking urgency coefficients (as recommended by Taskwarrior documentation)
132 | - turning off urgency for waiting and scheduled tasks (taskcheck already take them into account)
133 |
134 | Do you want to apply optional configurations? [y/N] """
135 | )
136 | if answer.lower() not in ["y", "yes"]:
137 | configs = required_configs
138 | else:
139 | configs = required_configs + optional_configs
140 |
141 | # Apply configurations using apply_config
142 | try:
143 | for key, value in configs:
144 | apply_config(key, value)
145 | print("Taskwarrior configurations have been applied successfully.")
146 | except Exception as e:
147 | print(f"Failed to apply configurations: {e}")
148 |
149 | answer = input(
150 | """
151 | _________________________________________________________________________________________
152 | Do you want to create a default config file for taskcheck? [y/N] """
153 | )
154 | if answer.lower() not in ["y", "yes"]:
155 | return
156 |
157 | config_dir.mkdir(parents=True, exist_ok=True)
158 | config_file = config_dir / "taskcheck.toml"
159 | if config_file.exists():
160 | print(f"Config file already exists at {config_file}")
161 | return
162 | with open(config_file, "w") as f:
163 | f.write(default_config)
164 |
165 | print(f"Default config file created at {config_file}")
166 |
167 |
168 | if __name__ == "__main__":
169 | install()
170 |
--------------------------------------------------------------------------------
/taskcheck/parallel.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import re
3 | import subprocess
4 | from dataclasses import dataclass
5 | from datetime import datetime, timedelta
6 |
7 | from taskcheck.common import (
8 | AVOID_STATUS,
9 | console,
10 | get_calendars,
11 | get_long_range_time_map,
12 | get_task_env,
13 | get_tasks,
14 | hours_to_decimal,
15 | hours_to_pdth,
16 | pdth_to_hours,
17 | )
18 |
19 |
20 | @dataclass
21 | class UrgencyCoefficients:
22 | estimated: dict
23 | inherit: bool
24 | active: float
25 | age_max: int
26 | urgency_due: float
27 | urgency_age: float
28 |
29 |
30 | def get_urgency_coefficients(taskrc=None):
31 | """
32 | Retrieves urgency coefficients from Taskwarrior configurations.
33 | Returns a dictionary mapping 'estimated..coefficient' to its float value and a
34 | boolean indicating if the urgency should be inherited by its dependants (`urgency.inherit`).
35 | """
36 | env = get_task_env(taskrc)
37 | result = subprocess.run(["task", "_show"], capture_output=True, text=True, env=env)
38 | inherit_urgency = False
39 | active_task_coefficient = 0
40 | est_coeffs = {}
41 | urgency_age_max = 0
42 | urgency_age = 0
43 | urgency_due = 0
44 | pattern1 = re.compile(r"^urgency\.uda\.estimated\.(.+)\.coefficient=(.+)$")
45 | pattern2 = re.compile(r"^urgency\.inherit=(.+)$")
46 | pattern3 = re.compile(r"^urgency\.active\.coefficient=(.+)$")
47 | pattern4 = re.compile(r"^urgency\.age\.max=(.+)$")
48 | pattern5 = re.compile(r"^urgency\.due\.coefficient=(.+)$")
49 | pattern6 = re.compile(r"^urgency\.age\.coefficient=(.+)$")
50 | for line in result.stdout.splitlines():
51 | match = pattern1.match(line)
52 | if match:
53 | estimated_value = match.group(1)
54 | coefficient = float(match.group(2))
55 | est_coeffs[estimated_value] = coefficient
56 |
57 | match = pattern2.match(line)
58 | if match:
59 | inherit_urgency = match.group(1) == "1"
60 |
61 | match = pattern3.match(line)
62 | if match:
63 | active_coefficient = float(match.group(1))
64 | active_task_coefficient = active_coefficient
65 |
66 | match = pattern4.match(line)
67 | if match:
68 | urgency_age_max = int(match.group(1))
69 |
70 | match = pattern5.match(line)
71 | if match:
72 | urgency_due = float(match.group(1))
73 |
74 | match = pattern6.match(line)
75 | if match:
76 | urgency_age = float(match.group(1))
77 |
78 | return UrgencyCoefficients(
79 | est_coeffs,
80 | inherit_urgency,
81 | active_task_coefficient,
82 | urgency_age_max,
83 | urgency_due,
84 | urgency_age,
85 | )
86 |
87 |
88 | def check_tasks_parallel(
89 | config,
90 | verbose=False,
91 | force_update=False,
92 | taskrc=None,
93 | urgency_weight_override=None,
94 | dry_run=False,
95 | auto_adjust_urgency=False,
96 | ):
97 | """
98 | config: dict loaded from load_config(), see its docstring for structure.
99 | """
100 | tasks = get_tasks(taskrc=taskrc)
101 | time_maps = config["time_maps"]
102 | days_ahead = config["scheduler"]["days_ahead"]
103 |
104 | # Handle weight configuration
105 | if urgency_weight_override is not None:
106 | initial_weight_urgency = urgency_weight_override
107 | else:
108 | initial_weight_urgency = config["scheduler"].get("weight_urgency", 1.0)
109 |
110 | calendars = get_calendars(config, verbose=verbose, force_update=force_update)
111 | urgency_coefficients = get_urgency_coefficients(taskrc=taskrc)
112 |
113 | current_weight = initial_weight_urgency
114 |
115 | # Always re-initialize task_info inside the loop to avoid mutated state
116 | task_info_original = initialize_task_info(
117 | tasks, time_maps, days_ahead, urgency_coefficients, calendars
118 | )
119 | task_info = copy.deepcopy(task_info_original)
120 | tasks_overdue = []
121 | while current_weight >= 0.0:
122 | if verbose and auto_adjust_urgency and current_weight < initial_weight_urgency:
123 | console.print(
124 | f"[yellow]Retrying with urgency weight: {current_weight:.1f}[/yellow]"
125 | )
126 |
127 | task_info = copy.deepcopy(task_info_original)
128 | for day_offset in range(days_ahead):
129 | allocate_time_for_day(
130 | task_info,
131 | day_offset,
132 | urgency_coefficients,
133 | verbose,
134 | current_weight,
135 | )
136 |
137 | # Check if any tasks cannot be completed on time
138 | tasks_overdue = []
139 | for info in task_info.values():
140 | task = info["task"]
141 | due = task.get("due")
142 |
143 | if due is not None:
144 | due_dt = datetime.strptime(due, "%Y%m%dT%H%M%SZ")
145 |
146 | # Case 1: Task has no scheduling at all and has remaining hours
147 | if not info["scheduling"] and info["remaining_hours"] > 0:
148 | tasks_overdue.append(task)
149 | # Case 2: Task is scheduled but completion date is after due date
150 | elif info["scheduling"]:
151 | scheduled_dates = sorted(info["scheduling"].keys())
152 | if scheduled_dates:
153 | end_date = scheduled_dates[-1]
154 | end_date_dt = datetime.strptime(end_date, "%Y-%m-%d")
155 | if end_date_dt > due_dt:
156 | tasks_overdue.append(task)
157 |
158 | # If no tasks are overdue or auto-adjust is disabled, break the loop
159 | if not tasks_overdue or not auto_adjust_urgency:
160 | break
161 |
162 | # If we have overdue tasks and auto-adjust is enabled, reduce weight and try again
163 | if verbose:
164 | console.print(
165 | f"[red]{len(tasks_overdue)} task(s) cannot be completed on time[/red]"
166 | )
167 |
168 | current_weight = round(current_weight - 0.1, 1)
169 |
170 | if current_weight < 0.0:
171 | break
172 |
173 | # After loop completes, check if we still have overdue tasks
174 | if auto_adjust_urgency and current_weight < initial_weight_urgency:
175 | if tasks_overdue:
176 | # We tried to adjust but still have overdue tasks
177 | console.print(
178 | "[red]Warning: cannot find a solution even with urgency weight 0.0[/red]"
179 | )
180 | else:
181 | # We successfully resolved overdue tasks by adjusting weight
182 | console.print(
183 | f"[green]Final urgency weight: {max(current_weight, 0.0):.1f}[/green]"
184 | )
185 |
186 | if dry_run:
187 | # Generate JSON output instead of updating tasks
188 | scheduling_results = []
189 | for info in task_info.values():
190 | task = info["task"]
191 | if not info["scheduling"]:
192 | continue
193 |
194 | scheduled_dates = sorted(info["scheduling"].keys())
195 | start_date = scheduled_dates[0]
196 | end_date = scheduled_dates[-1]
197 |
198 | scheduling_note = ""
199 | for date_str in scheduled_dates:
200 | hours = info["scheduling"][date_str]
201 | scheduling_note += f"{date_str} - {hours_to_pdth(hours)}\n"
202 |
203 | task_result = {
204 | "id": task["id"],
205 | "uuid": task["uuid"],
206 | "description": task["description"],
207 | "project": task.get("project", ""),
208 | "urgency": task.get("urgency", 0),
209 | "estimated": task["estimated"],
210 | "due": task.get("due", ""),
211 | "scheduled": start_date,
212 | "completion_date": end_date,
213 | "scheduling": scheduling_note.strip(),
214 | }
215 |
216 | # Check if task will be completed on time
217 | due = task.get("due")
218 | end_date_dt = datetime.strptime(end_date, "%Y-%m-%d")
219 | if due is not None and end_date_dt > datetime.strptime(
220 | due, "%Y%m%dT%H%M%SZ"
221 | ):
222 | task_result["warning"] = "Task may not be completed on time"
223 | console.print(
224 | f"[red]Warning: Task {task['id']} ('{task['description']}') is not going to be completed on time.[/red]"
225 | )
226 |
227 | scheduling_results.append(task_result)
228 |
229 | return scheduling_results
230 | else:
231 | # Normal operation - update tasks in Taskwarrior
232 | update_tasks_with_scheduling_info(task_info, verbose, taskrc)
233 |
234 | return None
235 |
236 |
237 | def initialize_task_info(tasks, time_maps, days_ahead, urgency_coefficients, calendars):
238 | task_info = {}
239 | today = datetime.today().date()
240 | for task in tasks:
241 | if task.get("status") in AVOID_STATUS:
242 | continue
243 | if "estimated" not in task or "time_map" not in task:
244 | continue
245 | estimated_hours = pdth_to_hours(task["estimated"])
246 | time_map_names = task["time_map"].split(",")
247 | task_time_map, today_used_hours = get_long_range_time_map(
248 | time_maps, time_map_names, days_ahead, calendars
249 | )
250 | task_uuid = task["uuid"]
251 | initial_urgency = float(task.get("urgency", 0))
252 | estimated_urgency = urgency_estimated(
253 | {"remaining_hours": estimated_hours}, None, urgency_coefficients
254 | )
255 | due_urgency = urgency_due({"task": task}, today, urgency_coefficients)
256 | age_urgency = urgency_age({"task": task}, today, urgency_coefficients)
257 | task_info[task_uuid] = {
258 | "task": task,
259 | "remaining_hours": estimated_hours,
260 | "task_time_map": task_time_map,
261 | "today_used_hours": today_used_hours,
262 | "scheduling": {},
263 | "urgency": initial_urgency,
264 | "estimated_urgency": estimated_urgency,
265 | "due_urgency": due_urgency,
266 | "age_urgency": age_urgency,
267 | "started": False,
268 | }
269 | return task_info
270 |
271 |
272 | def allocate_time_for_day(
273 | task_info,
274 | day_offset,
275 | urgency_coefficients,
276 | verbose,
277 | weight_urgency,
278 | ):
279 | date = datetime.today().date() + timedelta(days=day_offset)
280 | total_available_hours = compute_total_available_hours(task_info, day_offset)
281 | # if verbose:
282 | # print(f"Day {date}, total available hours: {total_available_hours:.2f}")
283 | if total_available_hours <= 0:
284 | return
285 |
286 | day_remaining_hours = total_available_hours
287 | tasks_remaining = prepare_tasks_remaining(task_info, day_offset)
288 |
289 | while day_remaining_hours > 0 and tasks_remaining:
290 | recompute_urgencies(tasks_remaining, urgency_coefficients, date, weight_urgency)
291 | sorted_task_ids = sorted(
292 | tasks_remaining.keys(),
293 | key=lambda x: tasks_remaining[x]["urgency"],
294 | reverse=True,
295 | )
296 |
297 | allocated = False
298 | for uuid in sorted_task_ids:
299 | if uuid not in tasks_remaining:
300 | # already completed
301 | continue
302 | info = tasks_remaining[uuid]
303 | if any(d in tasks_remaining for d in info["task"].get("depends", [])):
304 | # cannot execute this task until all its dependencies are completed
305 | if verbose:
306 | print(
307 | "Skipping task",
308 | info["task"]["id"],
309 | "due to dependency on:",
310 | [
311 | tasks_remaining[_d]["task"]["id"]
312 | for _d in info["task"].get("depends", [])
313 | if _d in tasks_remaining
314 | ],
315 | )
316 | continue
317 |
318 | wait = info["task"].get("wait")
319 | if wait and date <= datetime.strptime(wait, "%Y%m%dT%H%M%SZ").date():
320 | if verbose:
321 | print(f"Skipping task {info['task']['id']} due to wait date {wait}")
322 | continue
323 | allocation = allocate_time_to_task(info, day_offset, day_remaining_hours)
324 | if allocation > 0:
325 | day_remaining_hours -= allocation
326 | allocated = True
327 | date_str = date.isoformat()
328 | update_task_scheduling(info, allocation, date_str)
329 | if verbose:
330 | print(
331 | f"Allocated {allocation:.2f} hours to task {info['task']['id']} on {date} with urgency {info['urgency']:.2f} and estimated-related urgency {info['estimated_urgency']:.2f}"
332 | )
333 | if (
334 | info["remaining_hours"] <= 0
335 | or info["task_time_map"][day_offset] <= 0
336 | ):
337 | del tasks_remaining[uuid]
338 | # if day_remaining_hours <= 0:
339 | break
340 | if not allocated:
341 | break
342 | # if verbose and day_remaining_hours > 0:
343 | # print(f"Unused time on {date}: {day_remaining_hours:.2f} hours")
344 |
345 |
346 | def compute_total_available_hours(task_info, day_offset):
347 | if day_offset == 0:
348 | total_hours_list = [
349 | info["task_time_map"][day_offset] - info["today_used_hours"]
350 | for info in task_info.values()
351 | if day_offset < len(info["task_time_map"])
352 | ]
353 | else:
354 | total_hours_list = [
355 | info["task_time_map"][day_offset]
356 | for info in task_info.values()
357 | if day_offset < len(info["task_time_map"])
358 | ]
359 | total_available_hours = max(total_hours_list) if total_hours_list else 0
360 | return total_available_hours
361 |
362 |
363 | def prepare_tasks_remaining(task_info, day_offset):
364 | return {
365 | info["task"]["uuid"]: info
366 | for info in task_info.values()
367 | if info["remaining_hours"] > 0
368 | and day_offset < len(info["task_time_map"])
369 | and info["task_time_map"][day_offset] > 0
370 | }
371 |
372 |
373 | def urgency_due(info, date, urgency_coefficients):
374 | lfs = 0
375 | task = info["task"]
376 | if "due" in task:
377 | due = datetime.strptime(task["due"], "%Y%m%dT%H%M%SZ").date()
378 | # Map a range of 21 days to the value 0.2 - 1.0
379 | days_overdue = (date - due).days
380 | if days_overdue >= 7.0:
381 | lfs = 1.0 # < 1 wk ago
382 | elif days_overdue >= -14.0:
383 | lfs = ((days_overdue + 14.0) * 0.8 / 21.0) + 0.2
384 | else:
385 | lfs = 0.2 # 2 wks
386 | return lfs * urgency_coefficients.urgency_due
387 |
388 |
389 | def urgency_age(info, date, urgency_coefficients):
390 | urgency_age_max = urgency_coefficients.age_max
391 | lfs = 1.0
392 | task = info["task"]
393 | if "entry" not in task:
394 | return 1.0
395 | entry = datetime.strptime(task["entry"], "%Y%m%dT%H%M%SZ").date()
396 | age = (date - entry).days # in days
397 | if urgency_age_max == 0 or age >= urgency_age_max:
398 | lfs = 1.0
399 | return lfs * age / urgency_age_max * urgency_coefficients.urgency_age
400 |
401 |
402 | def urgency_estimated(info, date, urgency_coefficients):
403 | """
404 | Computes the estimated urgency for the given remaining hours using the coefficients.
405 | """
406 | # Find the closest match (e.g., if '2h' is not available, use '1h' or '3h')
407 | closest_match = min(
408 | urgency_coefficients.estimated.keys(),
409 | key=lambda x: abs(pdth_to_hours(x) - info["remaining_hours"]),
410 | )
411 | coefficient = urgency_coefficients.estimated[closest_match]
412 | return coefficient
413 |
414 |
415 | def update_urgency(info, urgency_key, urgency_compute_fn, urgency_coefficients, date):
416 | urgency_value = urgency_compute_fn(info, date, urgency_coefficients)
417 | old_urgency = info[urgency_key]
418 | # if old_urgency != urgency_value:
419 | # print(
420 | # f"new urgency value for task {info['task']['id']}: {urgency_key}: {urgency_value}"
421 | # )
422 | info[urgency_key] = urgency_value
423 | info["urgency"] = info["urgency"] - old_urgency + urgency_value
424 |
425 |
426 | def recompute_urgencies(tasks_remaining, urgency_coefficients, date, weight_urgency):
427 | """Recompute urgency simulating that today is `date`"""
428 | # Recompute estimated urgencies as before
429 | for info in tasks_remaining.values():
430 | # Update estimated urgency
431 | update_urgency(
432 | info, "estimated_urgency", urgency_estimated, urgency_coefficients, date
433 | )
434 | # Update due partial urgency
435 | update_urgency(info, "due_urgency", urgency_due, urgency_coefficients, date)
436 | # Update age partial urgency
437 | update_urgency(info, "age_urgency", urgency_age, urgency_coefficients, date)
438 |
439 | # Apply weights to create a combined score
440 | base_urgency = info["urgency"] - info["due_urgency"]
441 | base_urgency *= weight_urgency
442 | # Always add due_urgency, only weight estimated and age
443 | weighted_urgency = base_urgency + info["due_urgency"]
444 | info["urgency"] = weighted_urgency
445 |
446 | started_by_user = info["task"].get("start", "") != ""
447 | started_by_scheduler = info["started"]
448 | if started_by_scheduler and not started_by_user:
449 | # If the task was started by the scheduler, apply the active task coefficient
450 | info["urgency"] += urgency_coefficients.active
451 | info["started"] = False
452 |
453 | if urgency_coefficients.inherit:
454 | # Build reverse dependencies mapping
455 | reverse_deps = {} # Map from task_uuid to list of tasks that depend on it
456 | for task_uuid, info in tasks_remaining.items():
457 | for dep_uuid in info["task"].get("depends", []):
458 | if dep_uuid not in reverse_deps:
459 | reverse_deps[dep_uuid] = []
460 | reverse_deps[dep_uuid].append(task_uuid)
461 |
462 | # Define a recursive function to compute the maximum urgency
463 | def get_max_urgency(info, visited):
464 | task_uuid = info["task"]["uuid"]
465 | if task_uuid in visited:
466 | return visited[task_uuid] # Return cached value to avoid cycles
467 | # Start with the current task's urgency
468 | urgency = info["urgency"]
469 | visited[task_uuid] = urgency # Mark as visited
470 | # Recursively compute urgencies of tasks that depend on this task
471 | for dep_uuid in reverse_deps.get(task_uuid, []):
472 | if dep_uuid in tasks_remaining:
473 | dep_info = tasks_remaining[dep_uuid]
474 | dep_urgency = get_max_urgency(dep_info, visited)
475 | urgency = max(urgency, dep_urgency)
476 | visited[task_uuid] = urgency # Update with the maximum urgency found
477 | return urgency
478 |
479 | # Update urgencies based on tasks that depend on them
480 | for info in tasks_remaining.values():
481 | visited = {} # Reset visited dictionary for each task
482 | max_urgency = get_max_urgency(info, visited)
483 | info["urgency"] = max_urgency # Update the task's urgency
484 |
485 |
486 | def allocate_time_to_task(info, day_offset, day_remaining_hours):
487 | if day_offset >= len(info["task_time_map"]):
488 | return 0
489 |
490 | task_daily_available = info["task_time_map"][day_offset]
491 | if task_daily_available <= 0:
492 | return 0
493 |
494 | allocation = min(
495 | info["remaining_hours"],
496 | task_daily_available,
497 | day_remaining_hours,
498 | hours_to_decimal(info["task"].get("min_block", 2)),
499 | )
500 |
501 | if allocation <= 0.05:
502 | return 0
503 |
504 | if info["remaining_hours"] == info["task"]["estimated"]:
505 | info["started"] = True
506 | info["remaining_hours"] -= allocation
507 | info["task_time_map"][day_offset] -= allocation
508 |
509 | return allocation
510 |
511 |
512 | def update_task_scheduling(info, allocation, date_str):
513 | if date_str not in info["scheduling"]:
514 | info["scheduling"][date_str] = 0
515 | info["scheduling"][date_str] += allocation
516 |
517 |
518 | def update_tasks_with_scheduling_info(task_info, verbose, taskrc):
519 | for info in task_info.values():
520 | task = info["task"]
521 | scheduling_note = ""
522 | scheduled_dates = sorted(info["scheduling"].keys())
523 | if not scheduled_dates:
524 | continue
525 | start_date = scheduled_dates[0]
526 | end_date = scheduled_dates[-1]
527 | for date_str in scheduled_dates:
528 | hours = info["scheduling"][date_str]
529 | scheduling_note += f"{date_str} - {hours_to_pdth(hours)}\n"
530 |
531 | subprocess.run(
532 | [
533 | "task",
534 | str(task["id"]),
535 | "modify",
536 | f"scheduled:{start_date}",
537 | f"completion_date:{end_date}",
538 | f'scheduling:"{scheduling_note.strip()}"',
539 | ],
540 | stdout=subprocess.DEVNULL,
541 | stderr=subprocess.DEVNULL,
542 | env=get_task_env(taskrc),
543 | )
544 | due = task.get("due")
545 | end_date = datetime.strptime(end_date, "%Y-%m-%d")
546 | if due is not None and end_date > datetime.strptime(due, "%Y%m%dT%H%M%SZ"):
547 | console.print(
548 | f"[red]Warning: Task {task['id']} ('{task['description']}') is not going to be completed on time.[/red]"
549 | )
550 |
551 | if verbose:
552 | print(
553 | f"Updated task {task['id']} with scheduled dates {start_date} to {end_date}"
554 | )
555 |
--------------------------------------------------------------------------------
/taskcheck/report.py:
--------------------------------------------------------------------------------
1 | import random
2 | import sys
3 | from datetime import timedelta
4 | from datetime import datetime
5 | import json
6 | import re
7 | import subprocess
8 |
9 |
10 | from rich import print
11 | from rich.console import Console
12 | from rich.table import Table
13 | from rich.text import Text
14 | from rich.panel import Panel
15 |
16 | from random_unicode_emoji import random_emoji
17 |
18 |
19 | DEFAULT_EMOJI_KEYWORDS = {
20 | "meet": ":busts_in_silhouette:",
21 | "incontr": ":busts_in_silhouette:",
22 | "rencontr": ":busts_in_silhouette:",
23 | "reun": ":busts_in_silhouette:",
24 | "treff": ":busts_in_silhouette:",
25 | "review": ":mag_right:",
26 | "revis": ":mag_right:",
27 | "révis": ":mag_right:",
28 | "überprüf": ":mag_right:",
29 | "write": ":pencil2:",
30 | "scriv": ":pencil2:",
31 | "écri": ":pencil2:",
32 | "escrib": ":pencil2:",
33 | "schreib": ":pencil2:",
34 | "read": ":books:",
35 | "legg": ":books:",
36 | "lis": ":books:",
37 | "le": ":books:",
38 | "les": ":books:",
39 | "posta": ":email:",
40 | "courri": ":email:",
41 | "corre": ":email:",
42 | "mail": ":email:",
43 | "call": ":telephone_receiver:",
44 | "chiam": ":telephone_receiver:",
45 | "appel": ":telephone_receiver:",
46 | "llam": ":telephone_receiver:",
47 | "ruf": ":telephone_receiver:",
48 | "présent": ":chart_with_upwards_trend:",
49 | "present": ":chart_with_upwards_trend:",
50 | "präsent": ":chart_with_upwards_trend:",
51 | "learn": ":mortar_board:",
52 | "impar": ":mortar_board:",
53 | "appren": ":mortar_board:",
54 | "aprend": ":mortar_board:",
55 | "lern": ":mortar_board:",
56 | "search": ":mag:",
57 | "cerc": ":mag:",
58 | "cherch": ":mag:",
59 | "busc": ":mag:",
60 | "such": ":mag:",
61 | "idea": ":bulb:",
62 | "idé": ":bulb:",
63 | "ide": ":bulb:",
64 | "break": ":coffee:",
65 | "paus": ":coffee:",
66 | "descans": ":coffee:",
67 | "lunch": ":fork_and_knife:",
68 | "pranz": ":fork_and_knife:",
69 | "déjeun": ":fork_and_knife:",
70 | "almorz": ":fork_and_knife:",
71 | "mittag": ":fork_and_knife:",
72 | "test": ":test_tube:",
73 | "develop": ":hammer_and_wrench:",
74 | "svilupp": ":hammer_and_wrench:",
75 | "développ": ":hammer_and_wrench:",
76 | "desarroll": ":hammer_and_wrench:",
77 | "entwickl": ":hammer_and_wrench:",
78 | "disegn": ":art:",
79 | "diseñ": ":art:",
80 | "design": ":art:",
81 | "dafar": ":memo:",
82 | "tarea": ":memo:",
83 | "todo": ":memo:",
84 | "bug": ":beetle:",
85 | "käfer": ":beetle:",
86 | "fix": ":wrench:",
87 | "corregg": ":wrench:",
88 | "répar": ":wrench:",
89 | "beheb": ":wrench:",
90 | "urgent": ":exclamation:",
91 | "dringend": ":exclamation:",
92 | "deadlin": ":hourglass_flowing_sand:",
93 | "scadenz": ":hourglass_flowing_sand:",
94 | "délais": ":hourglass_flowing_sand:",
95 | "fechalim": ":hourglass_flowing_sand:",
96 | "frist": ":hourglass_flowing_sand:",
97 | "updat": ":arrows_counterclockwise:",
98 | "aggiorn": ":arrows_counterclockwise:",
99 | "mett": ":arrows_counterclockwise:",
100 | "actualiz": ":arrows_counterclockwise:",
101 | "aktualisier": ":arrows_counterclockwise:",
102 | "clean": ":broom:",
103 | "pul": ":broom:",
104 | "nettoy": ":broom:",
105 | "limpi": ":broom:",
106 | "reinig": ":broom:",
107 | "deploy": ":rocket:",
108 | "rilasc": ":rocket:",
109 | "déploy": ":rocket:",
110 | "despleg": ":rocket:",
111 | "bereitstell": ":rocket:",
112 | "festegg": ":tada:",
113 | "célébr": ":tada:",
114 | "celebr": ":tada:",
115 | "feier": ":tada:",
116 | "research": ":microscope:",
117 | "ricerc": ":microscope:",
118 | "recherch": ":microscope:",
119 | "investig": ":microscope:",
120 | "forsch": ":microscope:",
121 | "shop": ":shopping_cart:",
122 | "achet": ":shopping_cart:",
123 | "compr": ":shopping_cart:",
124 | "einkauf": ":shopping_cart:",
125 | "social": ":handshake:",
126 | "sozial": ":handshake:",
127 | "exercis": ":running_shoe:",
128 | "eserciz": ":running_shoe:",
129 | "exercic": ":running_shoe:",
130 | "ejerc": ":running_shoe:",
131 | "übun": ":running_shoe:",
132 | "évènement": ":calendar:",
133 | "event": ":calendar:",
134 | "movie": ":clapper:",
135 | "pelicul": ":clapper:",
136 | "film": ":clapper:",
137 | "music": ":musical_note:",
138 | "musik": ":musical_note:",
139 | "travel": ":airplane:",
140 | "viagg": ":airplane:",
141 | "voyag": ":airplane:",
142 | "viaj": ":airplane:",
143 | "reis": ":airplane:",
144 | "home": ":house:",
145 | "mais": ":house:",
146 | "cas": ":house:",
147 | "haus": ":house:",
148 | "docu": ":notebook:",
149 | "dokum": ":notebook:",
150 | "backup": ":floppy_disk:",
151 | "salvat": ":floppy_disk:",
152 | "sauveg": ":floppy_disk:",
153 | "copiaseg": ":floppy_disk:",
154 | "sicher": ":floppy_disk:",
155 | "debug": ":bug:",
156 | "débug": ":bug:",
157 | "note": ":spiral_notepad:",
158 | "not": ":spiral_notepad:",
159 | "focus": ":dart:",
160 | "concentr": ":dart:",
161 | "konzentrier": ":dart:",
162 | "codic": ":computer:",
163 | "cod": ":computer:",
164 | "code": ":computer:",
165 | "serveur": ":cloud:",
166 | "servidor": ":cloud:",
167 | "server": ":cloud:",
168 | "client": ":briefcase:",
169 | "priorid": ":bangbang:",
170 | "priorit": ":bangbang:",
171 | "star": ":star:",
172 | "stell": ":star:",
173 | "étoil": ":star:",
174 | "estrell": ":star:",
175 | "stern": ":star:",
176 | "critic": ":fire:",
177 | "kritisch": ":fire:",
178 | }
179 |
180 |
181 | def get_tasks(config, tasks, year, month, day):
182 | regex = re.compile(rf"{year:04d}-{month:02d}-{day:02d} - ([PDTHM0-9]+)")
183 | valid_tasks = []
184 | for task in tasks:
185 | for line in task["scheduling"].split("\n"):
186 | m = regex.match(line)
187 | if m:
188 | due = task.get("due", "")
189 | if due:
190 | due = datetime.strptime(due, "%Y%m%dT%H%M%SZ")
191 | due = due - datetime.today()
192 | valid_tasks.append(
193 | {
194 | "id": task["id"],
195 | "project": task.get("project", ""),
196 | "description": task["description"],
197 | "urgency": task["urgency"],
198 | "scheduling_day": f"{year}-{month}-{day}",
199 | "scheduling_hours": m.group(1),
200 | **{
201 | attr: task.get(attr, "")
202 | for attr in config.get("additional_attributes", [])
203 | },
204 | }
205 | )
206 | valid_tasks = sorted(valid_tasks, key=lambda x: x["urgency"], reverse=True)
207 | return valid_tasks
208 |
209 |
210 | def get_taskwarrior_date(date, _retry=True, taskrc=None):
211 | from taskcheck.common import get_task_env
212 |
213 | env = get_task_env(taskrc)
214 | date = subprocess.run(
215 | ["task", "calc", date],
216 | capture_output=True,
217 | text=True,
218 | env=env,
219 | )
220 | date = date.stdout.strip()
221 | try:
222 | date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
223 | except Exception as _:
224 | if _retry:
225 | return get_taskwarrior_date("today+" + date, False, taskrc)
226 | else:
227 | print(
228 | "Please provide a valid date. Check with `task calc` that your date is in the format YYYY-MM-DDTHH:MM:SS",
229 | file=sys.stderr,
230 | )
231 | exit(2)
232 | return date
233 |
234 |
235 | def get_days_in_constraint(constraint, taskrc=None):
236 | current_date = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
237 | constraint = get_taskwarrior_date(constraint, taskrc=taskrc)
238 | while current_date <= constraint:
239 | yield current_date.year, current_date.month, current_date.day
240 | current_date += timedelta(days=1)
241 |
242 |
243 | def tostring(value):
244 | if isinstance(value, bool):
245 | return "Yes" if value else "No"
246 | elif isinstance(value, datetime):
247 | return value.strftime("%Y-%m-%d %H:%M")
248 | elif isinstance(value, str):
249 | try:
250 | date = datetime.strptime(value, "%Y%m%dT%H%M%SZ")
251 | return date.strftime("%Y-%m-%d %H:%M")
252 | except ValueError:
253 | return value
254 | else:
255 | return str(value)
256 |
257 |
258 | def get_unplanned_tasks(config, tasks, taskrc=None):
259 | from taskcheck.common import get_task_env
260 |
261 | env = get_task_env(taskrc)
262 | tasks = subprocess.run(
263 | ["task", "scheduling:", "status:pending", "export"],
264 | capture_output=True,
265 | text=True,
266 | env=env,
267 | )
268 | tasks = json.loads(tasks.stdout)
269 | return tasks
270 |
271 |
272 | def generate_report(config, constraint, verbose=False, force_update=False, taskrc=None, scheduling_results=None):
273 | config = config["report"]
274 | console = Console()
275 |
276 | if scheduling_results is not None:
277 | # Use provided scheduling results (from dry-run mode)
278 | tasks = scheduling_results
279 | else:
280 | # Fetch tasks from Taskwarrior normally
281 | tasks = fetch_tasks(taskrc)
282 |
283 | if config.get("include_unplanned"):
284 | unplanned_tasks = get_unplanned_tasks(config, tasks, taskrc=taskrc)
285 | display_unplanned_tasks(console, config, unplanned_tasks)
286 |
287 | for year, month, day in get_days_in_constraint(constraint, taskrc=taskrc):
288 | this_day_tasks = get_tasks(config, tasks, year, month, day)
289 |
290 | display_date_header(console, year, month, day)
291 |
292 | display_tasks_table(console, config, this_day_tasks)
293 |
294 |
295 | def fetch_tasks(taskrc=None):
296 | """Fetch tasks from the task manager and return them as a JSON object."""
297 | from taskcheck.common import get_task_env
298 |
299 | env = get_task_env(taskrc)
300 | tasks = subprocess.run(
301 | ["task", "scheduling~.", "(", "+PENDING", "or", "+WAITING", ")", "export"],
302 | capture_output=True,
303 | text=True,
304 | env=env,
305 | )
306 | return json.loads(tasks.stdout)
307 |
308 |
309 | def display_date_header(console, year, month, day):
310 | """Display a date header with a calendar emoji."""
311 | date_str = f":calendar: [bold cyan]{year}-{month}-{day}[/bold cyan]"
312 | console.print(Panel(date_str, style="bold blue", expand=False))
313 |
314 |
315 | def display_tasks_table(console, config, tasks):
316 | """Display a table of tasks for a specific day."""
317 | if tasks:
318 | table = build_tasks_table(config, tasks)
319 | console.print(table)
320 | else:
321 | console.print("[italic dim]No tasks scheduled for this day.[/italic dim]")
322 |
323 |
324 | def build_tasks_table(config, tasks):
325 | """Build a Rich table for displaying tasks."""
326 | table = Table(show_header=True, header_style="bold blue")
327 | table.add_column("Task", style="dim", width=12)
328 | table.add_column("Project", style="dim", width=12)
329 | table.add_column("Description")
330 | table.add_column("Time", justify="right")
331 | for attr in config.get("additional_attributes", []):
332 | table.add_column(attr.capitalize(), justify="right")
333 |
334 | for task in tasks:
335 | task_id = f"[bold green]#{task['id']}[/bold green]"
336 | project = task.get("project", "")
337 | description = Text(task["description"], style="italic")
338 | hours = f"[yellow]{task['scheduling_hours']}[/yellow]"
339 | emoji = get_task_emoji(config, task)
340 |
341 | table.add_row(
342 | f"{emoji} {task_id}",
343 | project,
344 | description,
345 | hours,
346 | *[
347 | tostring(task.get(attr, ""))
348 | for attr in config.get("additional_attributes", [])
349 | ],
350 | )
351 | return table
352 |
353 |
354 | def get_task_emoji(config, task):
355 | """Get an emoji based on keywords in the task description."""
356 | for keyword in config.get("emoji_keywords", []):
357 | if keyword in task["description"].lower():
358 | return config["emoji_keywords"][keyword]
359 | for keyword, emoji in DEFAULT_EMOJI_KEYWORDS.items():
360 | if keyword in task["description"].lower():
361 | return emoji
362 | # sum the unicode numbers of each letter in the description and use it as seed to get a random unicode
363 | # emoji
364 | seed = sum(ord(char) for char in task["description"])
365 | emoji = ""
366 | # seed the next call to random.choice
367 | random.seed(seed)
368 | emoji = random_emoji()[0]
369 | # some emoji coutn for more than one character and misbehave the tables of rich
370 | if len(emoji) > 1:
371 | while len(emoji) != 1:
372 | emoji = random_emoji()[0]
373 | return emoji
374 |
375 |
376 | def display_unplanned_tasks(console, config, tasks):
377 | """Display unplanned tasks if any are found."""
378 | if tasks:
379 | table = build_unplanned_tasks_table(config, tasks)
380 | console.print(Panel("Unplanned Tasks", style="bold blue", expand=False))
381 | console.print(table)
382 | else:
383 | console.print(
384 | Panel(
385 | "[italic dim]No unplanned tasks found.[/italic dim]",
386 | style="bold blue",
387 | expand=False,
388 | )
389 | )
390 |
391 |
392 | def build_unplanned_tasks_table(config, tasks):
393 | """Build a Rich table for displaying unplanned tasks."""
394 | table = Table(show_header=True, header_style="bold blue")
395 | table.add_column("Task", style="dim", width=12)
396 | table.add_column("Project", style="dim", width=12)
397 | table.add_column("Description")
398 | for attr in config.get("additional_attributes_unplanned", []):
399 | table.add_column(attr.capitalize(), justify="right")
400 |
401 | for task in tasks:
402 | task_id = f"[bold green]#{task['id']}[/bold green]"
403 | project = task.get("project", "")
404 | description = Text(task["description"], style="italic")
405 | emoji = get_task_emoji(config, task)
406 |
407 | table.add_row(
408 | f"{emoji} {task_id}",
409 | project,
410 | description,
411 | *[
412 | tostring(task.get(attr, ""))
413 | for attr in config.get("additional_attributes_unplanned", [])
414 | ],
415 | )
416 | return table
417 |
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import json
3 | import tempfile
4 | from datetime import datetime, timedelta
5 | from pathlib import Path
6 | from unittest.mock import Mock, patch
7 |
8 |
9 | @pytest.fixture
10 | def sample_config():
11 | """Sample configuration for testing."""
12 | return {
13 | "time_maps": {
14 | "work": {
15 | "monday": [[9.0, 17.0]],
16 | "tuesday": [[9.0, 17.0]],
17 | "wednesday": [[9.0, 17.0]],
18 | "thursday": [[9.0, 17.0]],
19 | "friday": [[9.0, 17.0]],
20 | "saturday": [],
21 | "sunday": []
22 | },
23 | "personal": {
24 | "monday": [[18.0, 22.0]],
25 | "tuesday": [[18.0, 22.0]],
26 | "wednesday": [[18.0, 22.0]],
27 | "thursday": [[18.0, 22.0]],
28 | "friday": [[18.0, 22.0]],
29 | "saturday": [[10.0, 18.0]],
30 | "sunday": [[10.0, 18.0]]
31 | }
32 | },
33 | "scheduler": {
34 | "days_ahead": 7,
35 | "weight_urgency": 1.0,
36 | "weight_due_date": 0.0
37 | },
38 | "calendars": {
39 | "work_calendar": {
40 | "url": "https://example.com/calendar.ics",
41 | "event_all_day_is_blocking": True,
42 | "expiration": 0.25,
43 | "timezone": "UTC"
44 | }
45 | },
46 | "report": {
47 | "include_unplanned": True,
48 | "additional_attributes": ["urgency", "priority"],
49 | "additional_attributes_unplanned": ["urgency", "due"],
50 | "emoji_keywords": {
51 | "meeting": ":busts_in_silhouette:",
52 | "code": ":computer:"
53 | }
54 | }
55 | }
56 |
57 |
58 | @pytest.fixture
59 | def sample_tasks():
60 | """Sample task data for testing."""
61 | return [
62 | {
63 | "id": 1,
64 | "uuid": "task-1-uuid",
65 | "description": "Write documentation",
66 | "estimated": "P2H",
67 | "time_map": "work",
68 | "urgency": 10.5,
69 | "status": "pending",
70 | "project": "docs",
71 | "entry": "20231201T090000Z"
72 | },
73 | {
74 | "id": 2,
75 | "uuid": "task-2-uuid",
76 | "description": "Code review meeting",
77 | "estimated": "P1H",
78 | "time_map": "work",
79 | "urgency": 15.2,
80 | "status": "pending",
81 | "project": "dev",
82 | "entry": "20231201T100000Z",
83 | "due": "20231210T170000Z"
84 | },
85 | {
86 | "id": 3,
87 | "uuid": "task-3-uuid",
88 | "description": "Personal project",
89 | "estimated": "P3H",
90 | "time_map": "personal",
91 | "urgency": 5.0,
92 | "status": "pending",
93 | "project": "hobby",
94 | "entry": "20231201T110000Z"
95 | }
96 | ]
97 |
98 |
99 | @pytest.fixture
100 | def sample_calendar_events():
101 | """Sample calendar events for testing."""
102 | today = datetime.now().date()
103 | return [
104 | {
105 | "start": (datetime.combine(today, datetime.min.time()) + timedelta(hours=14)).isoformat(),
106 | "end": (datetime.combine(today, datetime.min.time()) + timedelta(hours=15)).isoformat()
107 | },
108 | {
109 | "start": (datetime.combine(today + timedelta(days=1), datetime.min.time()) + timedelta(hours=10)).isoformat(),
110 | "end": (datetime.combine(today + timedelta(days=1), datetime.min.time()) + timedelta(hours=11)).isoformat()
111 | }
112 | ]
113 |
114 |
115 | @pytest.fixture
116 | def test_taskrc():
117 | """Provide a consistent test taskrc path."""
118 | return "/tmp/taskcheck/"
119 |
120 |
121 | @pytest.fixture
122 | def mock_subprocess_run():
123 | """Mock subprocess.run for Taskwarrior commands."""
124 | with patch('subprocess.run') as mock_run:
125 | yield mock_run
126 |
127 |
128 | @pytest.fixture
129 | def mock_task_export(sample_tasks):
130 | """Mock task export command."""
131 | def _mock_run(cmd, **kwargs):
132 | mock_result = Mock()
133 | if cmd == ["task", "export"]:
134 | mock_result.stdout = json.dumps(sample_tasks)
135 | elif cmd[0] == "task" and "_show" in cmd:
136 | mock_result.stdout = """urgency.uda.estimated.P1H.coefficient=5.0
137 | urgency.uda.estimated.P2H.coefficient=8.0
138 | urgency.uda.estimated.P3H.coefficient=10.0
139 | urgency.inherit=1
140 | urgency.active.coefficient=4.0
141 | urgency.age.max=365
142 | urgency.due.coefficient=12.0
143 | urgency.age.coefficient=2.0"""
144 | else:
145 | mock_result.stdout = ""
146 | mock_result.stderr = ""
147 | mock_result.returncode = 0
148 | return mock_result
149 |
150 | with patch('subprocess.run', side_effect=_mock_run):
151 | yield
152 |
153 |
154 | @pytest.fixture
155 | def mock_task_export_with_taskrc(sample_tasks, test_taskrc):
156 | """Mock task export command with taskrc verification."""
157 | def _mock_run(cmd, **kwargs):
158 | # Verify environment is passed correctly when using taskrc
159 | env = kwargs.get('env')
160 | if env and 'TASKRC' in env:
161 | assert env['TASKRC'] == test_taskrc
162 | assert env['TASKDATA'] == test_taskrc
163 |
164 | mock_result = Mock()
165 | if cmd == ["task", "export"]:
166 | mock_result.stdout = json.dumps(sample_tasks)
167 | elif cmd[0] == "task" and "_show" in cmd:
168 | mock_result.stdout = """urgency.uda.estimated.P1H.coefficient=5.0
169 | urgency.uda.estimated.P2H.coefficient=8.0
170 | urgency.uda.estimated.P3H.coefficient=10.0
171 | urgency.inherit=1
172 | urgency.active.coefficient=4.0
173 | urgency.age.max=365
174 | urgency.due.coefficient=12.0
175 | urgency.age.coefficient=2.0"""
176 | else:
177 | mock_result.stdout = ""
178 | mock_result.stderr = ""
179 | mock_result.returncode = 0
180 | return mock_result
181 |
182 | with patch('subprocess.run', side_effect=_mock_run):
183 | yield
184 |
185 |
186 | @pytest.fixture
187 | def temp_cache_dir():
188 | """Temporary directory for cache testing."""
189 | with tempfile.TemporaryDirectory() as temp_dir:
190 | with patch('taskcheck.ical.CACHE', Path(temp_dir)):
191 | yield Path(temp_dir)
192 |
193 |
194 | @pytest.fixture
195 | def mock_ical_response():
196 | """Mock iCal response data."""
197 | return """BEGIN:VCALENDAR
198 | VERSION:2.0
199 | PRODID:test
200 | BEGIN:VEVENT
201 | UID:test-event-1
202 | DTSTART:20231205T140000Z
203 | DTEND:20231205T150000Z
204 | SUMMARY:Test Meeting
205 | END:VEVENT
206 | BEGIN:VEVENT
207 | UID:test-event-2
208 | DTSTART:20231206T100000Z
209 | DTEND:20231206T110000Z
210 | SUMMARY:Another Meeting
211 | RRULE:FREQ=WEEKLY;COUNT=3
212 | END:VEVENT
213 | END:VCALENDAR"""
214 |
--------------------------------------------------------------------------------
/tests/test_common.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from datetime import datetime, timedelta, time
3 | from unittest.mock import patch, Mock
4 | import json
5 |
6 | from taskcheck.common import (
7 | hours_to_decimal,
8 | hours_to_time,
9 | time_to_decimal,
10 | get_available_hours,
11 | pdth_to_hours,
12 | hours_to_pdth,
13 | get_long_range_time_map,
14 | get_tasks,
15 | get_calendars,
16 | get_task_env
17 | )
18 |
19 |
20 | class TestTimeConversions:
21 | def test_hours_to_decimal(self):
22 | assert hours_to_decimal(9.0) == 9.0
23 | assert abs(hours_to_decimal(9.30) - 9.5) < 1e-10 # 9:30 -> 9.5 hours
24 | assert abs(hours_to_decimal(9.15) - 9.25) < 1e-10 # 9:15 -> 9.25 hours
25 |
26 | def test_hours_to_time(self):
27 | assert hours_to_time(9.0) == time(9, 0)
28 | assert hours_to_time(9.30) == time(9, 30) # 9.30 means 9:30
29 | assert hours_to_time(14.15) == time(14, 15) # 14.15 means 14:15
30 |
31 | def test_time_to_decimal(self):
32 | assert time_to_decimal(time(9, 0)) == 9.0
33 | assert time_to_decimal(time(9, 30)) == 9.5
34 | assert time_to_decimal(time(14, 15)) == 14.25
35 |
36 |
37 | class TestDurationConversions:
38 | def test_pdth_to_hours(self):
39 | assert pdth_to_hours("P1H") == 1.0
40 | assert pdth_to_hours("P2H30M") == 2.5
41 | assert pdth_to_hours("P1DT2H") == 26.0
42 | assert pdth_to_hours("PT30M") == 0.5
43 | assert pdth_to_hours("P1D") == 24.0
44 |
45 | def test_hours_to_pdth(self):
46 | assert hours_to_pdth(1.0) == "PT1H"
47 | assert hours_to_pdth(2.5) == "PT2H30M"
48 | assert hours_to_pdth(26.0) == "P1DT2H"
49 | assert hours_to_pdth(0.5) == "PT30M"
50 | assert hours_to_pdth(24.0) == "P1DT"
51 |
52 |
53 | class TestAvailableHours:
54 | def test_get_available_hours_no_events(self, sample_config):
55 | date = datetime(2023, 12, 5).date() # Tuesday
56 | time_map = sample_config["time_maps"]["work"]
57 | calendars = []
58 |
59 | available = get_available_hours(time_map, date, calendars)
60 | assert available == 8.0 # 9-17 = 8 hours
61 |
62 | def test_get_available_hours_with_blocking_event(self, sample_config):
63 | date = datetime(2023, 12, 5).date() # Tuesday
64 | time_map = sample_config["time_maps"]["work"]
65 |
66 | # Event from 14:00 to 15:00
67 | calendars = [[{
68 | "start": datetime(2023, 12, 5, 14, 0),
69 | "end": datetime(2023, 12, 5, 15, 0)
70 | }]]
71 |
72 | available = get_available_hours(time_map, date, calendars, verbose=True)
73 | assert available == 7.0 # 8 hours - 1 hour blocked
74 |
75 | def test_get_available_hours_weekend(self, sample_config):
76 | date = datetime(2023, 12, 3).date() # Sunday
77 | time_map = sample_config["time_maps"]["work"]
78 | calendars = []
79 |
80 | available = get_available_hours(time_map, date, calendars)
81 | assert available == 0.0
82 |
83 |
84 | class TestLongRangeTimeMap:
85 | def test_get_long_range_time_map(self, sample_config, sample_calendar_events):
86 | time_maps = sample_config["time_maps"]
87 | time_map_names = ["work"]
88 | days_ahead = 3
89 | calendars = [sample_calendar_events]
90 |
91 | task_time_map, today_used_hours = get_long_range_time_map(
92 | time_maps, time_map_names, days_ahead, calendars
93 | )
94 |
95 | assert len(task_time_map) == days_ahead
96 | assert all(isinstance(hours, (int, float)) for hours in task_time_map)
97 | assert isinstance(today_used_hours, (int, float))
98 |
99 |
100 | class TestGetTasks:
101 | def test_get_tasks(self, mock_task_export_with_taskrc, sample_tasks, test_taskrc):
102 | tasks = get_tasks(taskrc=test_taskrc)
103 |
104 | # Should only return tasks with estimated field
105 | estimated_tasks = [t for t in tasks if "estimated" in t]
106 | assert len(estimated_tasks) == len(sample_tasks)
107 |
108 | # Should be sorted by urgency (descending)
109 | urgencies = [t["urgency"] for t in tasks]
110 | assert urgencies == sorted(urgencies, reverse=True)
111 |
112 |
113 | class TestGetCalendars:
114 | @patch('taskcheck.common.ical_to_dict')
115 | def test_get_calendars(self, mock_ical, sample_config, sample_calendar_events):
116 | mock_ical.return_value = sample_calendar_events
117 |
118 | calendars = get_calendars(sample_config)
119 |
120 | assert len(calendars) == 1
121 | assert calendars[0] == sample_calendar_events
122 | mock_ical.assert_called_once()
123 |
124 |
125 | class TestEnvironmentVariables:
126 | def test_get_task_env_sets_both_variables(self, test_taskrc):
127 | """Test that get_task_env sets both TASKDATA and TASKRC."""
128 | env = get_task_env(taskrc=test_taskrc)
129 |
130 | assert env['TASKDATA'] == test_taskrc
131 | assert env['TASKRC'] == test_taskrc
132 |
133 | def test_get_task_env_without_taskrc(self):
134 | """Test that get_task_env returns unchanged environment when taskrc=None."""
135 | import os
136 | original_env = os.environ.copy()
137 | env = get_task_env(taskrc=None)
138 |
139 | # Should not add TASKDATA or TASKRC if not specified
140 | assert env == original_env
141 |
--------------------------------------------------------------------------------
/tests/test_ical.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from datetime import datetime, timedelta
3 | from unittest.mock import patch, Mock
4 | import json
5 | import tempfile
6 |
7 | from taskcheck.ical import (
8 | fetch_ical_data,
9 | parse_ical_events,
10 | ical_to_dict,
11 | get_cache_filename
12 | )
13 |
14 |
15 | class TestIcalFetching:
16 | @patch('requests.get')
17 | def test_fetch_ical_data_success(self, mock_get, mock_ical_response):
18 | mock_response = Mock()
19 | mock_response.text = mock_ical_response
20 | mock_response.raise_for_status = Mock()
21 | mock_get.return_value = mock_response
22 |
23 | result = fetch_ical_data("https://example.com/calendar.ics")
24 |
25 | assert result == mock_ical_response
26 | mock_get.assert_called_once_with("https://example.com/calendar.ics")
27 |
28 | @patch('requests.get')
29 | def test_fetch_ical_data_error(self, mock_get):
30 | mock_response = Mock()
31 | mock_response.raise_for_status.side_effect = Exception("HTTP Error")
32 | mock_get.return_value = mock_response
33 |
34 | with pytest.raises(Exception):
35 | fetch_ical_data("https://example.com/calendar.ics")
36 |
37 |
38 | class TestIcalParsing:
39 | @patch('taskcheck.ical.datetime')
40 | def test_parse_ical_events_simple(self, mock_datetime, mock_ical_response):
41 | # Mock datetime.now() to return a date that makes the test events valid
42 | mock_datetime.now.return_value = datetime(2023, 12, 1, 12, 0, 0)
43 | mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)
44 |
45 | events = parse_ical_events(mock_ical_response, days_ahead=7, all_day=False)
46 |
47 | assert len(events) >= 1
48 | for event in events:
49 | assert "start" in event
50 | assert "end" in event
51 | assert isinstance(event["start"], str)
52 | assert isinstance(event["end"], str)
53 |
54 | @patch('taskcheck.ical.datetime')
55 | def test_parse_ical_events_with_timezone(self, mock_datetime, mock_ical_response):
56 | mock_datetime.now.return_value = datetime(2023, 12, 1, 12, 0, 0)
57 | mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)
58 |
59 | events = parse_ical_events(
60 | mock_ical_response,
61 | days_ahead=7,
62 | all_day=False,
63 | tz_name="America/New_York"
64 | )
65 |
66 | assert len(events) >= 0
67 |
68 | @patch('taskcheck.ical.datetime')
69 | def test_parse_ical_events_recurring(self, mock_datetime):
70 | mock_datetime.now.return_value = datetime(2023, 12, 1, 12, 0, 0)
71 | mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)
72 |
73 | ical_with_recurring = """BEGIN:VCALENDAR
74 | VERSION:2.0
75 | PRODID:test
76 | BEGIN:VEVENT
77 | UID:recurring-event
78 | DTSTART:20231205T140000Z
79 | DTEND:20231205T150000Z
80 | SUMMARY:Weekly Meeting
81 | RRULE:FREQ=WEEKLY;COUNT=3
82 | END:VEVENT
83 | END:VCALENDAR"""
84 |
85 | events = parse_ical_events(ical_with_recurring, days_ahead=21, all_day=False)
86 |
87 | # Should have 3 occurrences
88 | assert len(events) == 3
89 |
90 | @patch('taskcheck.ical.datetime')
91 | def test_parse_ical_events_all_day(self, mock_datetime):
92 | mock_datetime.now.return_value = datetime(2023, 12, 1, 12, 0, 0)
93 | mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)
94 |
95 | ical_all_day = """BEGIN:VCALENDAR
96 | VERSION:2.0
97 | PRODID:test
98 | BEGIN:VEVENT
99 | UID:all-day-event
100 | DTSTART;VALUE=DATE:20231205
101 | DTEND;VALUE=DATE:20231206
102 | SUMMARY:All Day Event
103 | END:VEVENT
104 | END:VCALENDAR"""
105 |
106 | events_include = parse_ical_events(ical_all_day, days_ahead=7, all_day=True)
107 | events_exclude = parse_ical_events(ical_all_day, days_ahead=7, all_day=False)
108 |
109 | assert len(events_include) >= len(events_exclude)
110 |
111 |
112 | class TestIcalCaching:
113 | def test_get_cache_filename(self):
114 | url = "https://example.com/calendar.ics"
115 | filename = get_cache_filename(url)
116 |
117 | assert filename.suffix == ".json"
118 | assert len(filename.stem) == 64 # SHA256 hash length
119 |
120 | @patch('requests.get')
121 | def test_ical_to_dict_with_cache(self, mock_get, temp_cache_dir, mock_ical_response):
122 | mock_response = Mock()
123 | mock_response.text = mock_ical_response
124 | mock_response.raise_for_status = Mock()
125 | mock_get.return_value = mock_response
126 |
127 | url = "https://example.com/calendar.ics"
128 |
129 | # First call should fetch and cache
130 | events1 = ical_to_dict(url, days_ahead=7, all_day=False, expiration=1.0)
131 |
132 | # Second call should use cache
133 | events2 = ical_to_dict(url, days_ahead=7, all_day=False, expiration=1.0)
134 |
135 | assert events1 == events2
136 | # Should only make one HTTP request
137 | assert mock_get.call_count == 1
138 |
139 | @patch('requests.get')
140 | def test_ical_to_dict_force_update(self, mock_get, temp_cache_dir, mock_ical_response):
141 | mock_response = Mock()
142 | mock_response.text = mock_ical_response
143 | mock_response.raise_for_status = Mock()
144 | mock_get.return_value = mock_response
145 |
146 | url = "https://example.com/calendar.ics"
147 |
148 | # First call
149 | events1 = ical_to_dict(url, days_ahead=7, all_day=False, expiration=1.0)
150 |
151 | # Force update should bypass cache
152 | events2 = ical_to_dict(url, days_ahead=7, all_day=False, expiration=1.0, force_update=True)
153 |
154 | assert events1 == events2
155 | # Should make two HTTP requests
156 | assert mock_get.call_count == 2
157 |
158 |
159 | class TestExceptionHandling:
160 | @patch('requests.get')
161 | def test_ical_to_dict_malformed_ical(self, mock_get, temp_cache_dir):
162 | mock_response = Mock()
163 | mock_response.text = "INVALID ICAL DATA"
164 | mock_response.raise_for_status = Mock()
165 | mock_get.return_value = mock_response
166 |
167 | url = "https://example.com/calendar.ics"
168 |
169 | # Should handle malformed iCal gracefully
170 | with pytest.raises(Exception):
171 | ical_to_dict(url, days_ahead=7, all_day=False)
172 |
--------------------------------------------------------------------------------
/tests/test_install.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest.mock import patch, Mock, mock_open
3 | from pathlib import Path
4 |
5 | # Note: This assumes you have an install module. If not, create a basic test structure
6 | @pytest.fixture
7 | def mock_install_module():
8 | """Mock the install module if it doesn't exist."""
9 | with patch.dict('sys.modules', {'taskcheck.install': Mock()}):
10 | yield
11 |
12 |
13 | class TestInstallation:
14 | @patch('subprocess.run')
15 | @patch('pathlib.Path.mkdir')
16 | @patch('pathlib.Path.exists')
17 | def test_install_creates_directories(self, mock_exists, mock_mkdir, mock_run):
18 | mock_exists.return_value = False
19 | mock_result = Mock()
20 | mock_result.returncode = 0
21 | mock_run.return_value = mock_result
22 |
23 | # This would test your actual install function
24 | # from taskcheck.install import install
25 | # install()
26 |
27 | # For now, just test that the mock setup works
28 | assert True
29 |
30 | @patch('subprocess.run')
31 | def test_install_taskwarrior_config(self, mock_run):
32 | mock_result = Mock()
33 | mock_result.returncode = 0
34 | mock_run.return_value = mock_result
35 |
36 | # Test UDA installation commands
37 | expected_commands = [
38 | ["task", "config", "uda.estimated.type", "string"],
39 | ["task", "config", "uda.time_map.type", "string"],
40 | ["task", "config", "uda.scheduling.type", "string"],
41 | ["task", "config", "uda.completion_date.type", "date"]
42 | ]
43 |
44 | # This would test your actual install function
45 | # For now, just verify mock setup
46 | assert True
47 |
48 |
49 | # Add integration tests
50 | class TestIntegration:
51 | """Integration tests that test multiple components together."""
52 |
53 | @patch('taskcheck.parallel.get_calendars')
54 | @patch('taskcheck.parallel.get_tasks')
55 | @patch('subprocess.run')
56 | def test_full_scheduling_workflow(self, mock_run, mock_tasks, mock_calendars, sample_config, sample_tasks):
57 | """Test the complete scheduling workflow."""
58 | mock_tasks.return_value = sample_tasks
59 | mock_calendars.return_value = []
60 |
61 | mock_result = Mock()
62 | mock_result.stdout = """urgency.uda.estimated.P1H.coefficient=5.0
63 | urgency.uda.estimated.P2H.coefficient=8.0
64 | urgency.inherit=1
65 | urgency.active.coefficient=4.0
66 | urgency.age.max=365
67 | urgency.due.coefficient=12.0
68 | urgency.age.coefficient=2.0"""
69 | mock_result.returncode = 0
70 | mock_run.return_value = mock_result
71 |
72 | from taskcheck.parallel import check_tasks_parallel
73 |
74 | # Should complete without errors
75 | check_tasks_parallel(sample_config, verbose=True)
76 |
77 | # Verify task commands were called
78 | assert mock_run.called
79 |
--------------------------------------------------------------------------------
/tests/test_main.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest.mock import patch, Mock, mock_open
3 |
4 | from taskcheck.__main__ import main, load_config, arg_parser
5 |
6 |
7 | class TestArgumentParsing:
8 | def test_arg_parser_defaults(self):
9 | """Test default argument values."""
10 | args = arg_parser.parse_args([])
11 |
12 | assert args.verbose is False
13 | assert args.install is False
14 | assert args.report is None
15 | assert args.schedule is False
16 | assert args.force_update is False
17 | assert args.taskrc is None
18 | assert args.urgency_weight is None
19 | assert args.dry_run is False
20 | assert args.auto_adjust_urgency is True
21 |
22 | def test_arg_parser_all_flags(self):
23 | """Test all command line flags."""
24 | args = arg_parser.parse_args(
25 | [
26 | "-v",
27 | "-i",
28 | "-r",
29 | "today",
30 | "-s",
31 | "-f",
32 | "--taskrc",
33 | "/custom/path",
34 | "--urgency-weight",
35 | "0.7",
36 | ]
37 | )
38 |
39 | assert args.verbose is True
40 | assert args.install is True
41 | assert args.report == "today"
42 | assert args.schedule is True
43 | assert args.force_update is True
44 | assert args.taskrc == "/custom/path"
45 | assert args.urgency_weight == 0.7
46 |
47 | def test_arg_parser_long_form(self):
48 | """Test long form arguments."""
49 | args = arg_parser.parse_args(
50 | [
51 | "--verbose",
52 | "--install",
53 | "--report",
54 | "eow",
55 | "--schedule",
56 | "--force-update",
57 | "--taskrc",
58 | "/test",
59 | "--urgency-weight",
60 | "0.3",
61 | ]
62 | )
63 |
64 | assert args.verbose is True
65 | assert args.install is True
66 | assert args.report == "eow"
67 | assert args.schedule is True
68 | assert args.force_update is True
69 | assert args.taskrc == "/test"
70 | assert args.urgency_weight == 0.3
71 |
72 | def test_urgency_weight_argument(self):
73 | """Test urgency weight argument parsing."""
74 | args = arg_parser.parse_args(["--urgency-weight", "0.7"])
75 | assert args.urgency_weight == 0.7
76 |
77 | def test_urgency_weight_argument_validation(self):
78 | """Test urgency weight argument with valid boundary values."""
79 | # This should work
80 | args = arg_parser.parse_args(["--urgency-weight", "0.0"])
81 | assert args.urgency_weight == 0.0
82 |
83 | args = arg_parser.parse_args(["--urgency-weight", "1.0"])
84 | assert args.urgency_weight == 1.0
85 |
86 | def test_dry_run_argument(self):
87 | """Test dry-run argument parsing."""
88 | args = arg_parser.parse_args(["--dry-run"])
89 | assert args.dry_run is True
90 |
91 | args = arg_parser.parse_args([])
92 | assert args.dry_run is False
93 |
94 | def test_auto_adjust_urgency_argument(self):
95 | """Test auto-adjust-urgency argument parsing."""
96 | args = arg_parser.parse_args([])
97 | assert args.auto_adjust_urgency is True
98 |
99 | args = arg_parser.parse_args(["--no-auto-adjust-urgency"])
100 | assert args.auto_adjust_urgency is False
101 |
102 |
103 | class TestConfigLoading:
104 | @patch(
105 | "builtins.open",
106 | new_callable=mock_open,
107 | read_data=b"[scheduler]\ndays_ahead = 7",
108 | )
109 | @patch("tomllib.load")
110 | def test_load_config_success(self, mock_toml_load, mock_file, sample_config):
111 | """Test successful config loading."""
112 | mock_toml_load.return_value = sample_config
113 |
114 | config = load_config()
115 |
116 | assert config == sample_config
117 | mock_file.assert_called_once()
118 | mock_toml_load.assert_called_once()
119 |
120 | @patch("builtins.open")
121 | def test_load_config_file_not_found(self, mock_file):
122 | """Test config loading when file doesn't exist."""
123 | mock_file.side_effect = FileNotFoundError("Config file not found")
124 |
125 | with pytest.raises(FileNotFoundError):
126 | load_config()
127 |
128 | @patch("builtins.open", new_callable=mock_open, read_data=b"invalid toml content")
129 | @patch("tomllib.load")
130 | def test_load_config_invalid_toml(self, mock_toml_load, mock_file):
131 | """Test config loading with invalid TOML."""
132 | mock_toml_load.side_effect = Exception("Invalid TOML")
133 |
134 | with pytest.raises(Exception):
135 | load_config()
136 |
137 |
138 | class TestMainFunction:
139 | def test_main_no_args_shows_help(self, capsys):
140 | """Test that main shows help when no arguments provided."""
141 | with patch("sys.argv", ["taskcheck"]):
142 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
143 | mock_args = Mock()
144 | mock_args.install = False
145 | mock_args.schedule = False
146 | mock_args.report = None
147 | mock_args.auto_adjust_urgency = True
148 | mock_parse.return_value = mock_args
149 |
150 | with patch.object(arg_parser, "print_help") as mock_help:
151 | main()
152 | mock_help.assert_called_once()
153 |
154 | @patch("taskcheck.install.install")
155 | def test_main_install_command(self, mock_install):
156 | """Test install command execution."""
157 | with patch("sys.argv", ["taskcheck", "--install"]):
158 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
159 | mock_args = Mock()
160 | mock_args.install = True
161 | mock_args.schedule = False
162 | mock_args.report = None
163 | mock_args.auto_adjust_urgency = True
164 | mock_parse.return_value = mock_args
165 |
166 | main()
167 |
168 | mock_install.assert_called_once()
169 |
170 | @patch("taskcheck.__main__.load_config")
171 | @patch("taskcheck.__main__.check_tasks_parallel")
172 | def test_main_schedule_command(
173 | self,
174 | mock_check_tasks,
175 | mock_load_config,
176 | sample_config,
177 | test_taskrc,
178 | mock_task_export_with_taskrc,
179 | ):
180 | """Test schedule command execution."""
181 | mock_load_config.return_value = sample_config
182 |
183 | with patch("sys.argv", ["taskcheck", "--schedule", "--taskrc", test_taskrc]):
184 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
185 | mock_args = Mock()
186 | mock_args.install = False
187 | mock_args.schedule = True
188 | mock_args.report = None
189 | mock_args.verbose = False
190 | mock_args.force_update = False
191 | mock_args.taskrc = test_taskrc
192 | mock_args.urgency_weight = None
193 | mock_args.dry_run = False
194 | mock_args.auto_adjust_urgency = True
195 | mock_parse.return_value = mock_args
196 |
197 | main()
198 |
199 | mock_load_config.assert_called_once()
200 | mock_check_tasks.assert_called_once_with(
201 | sample_config,
202 | verbose=False,
203 | force_update=False,
204 | taskrc=test_taskrc,
205 | urgency_weight_override=None,
206 | dry_run=False,
207 | auto_adjust_urgency=True,
208 | )
209 |
210 | @patch("taskcheck.__main__.load_config")
211 | @patch("taskcheck.report.generate_report")
212 | def test_main_report_command(
213 | self, mock_generate_report, mock_load_config, sample_config, test_taskrc
214 | ):
215 | """Test report command execution."""
216 | mock_load_config.return_value = sample_config
217 |
218 | with patch(
219 | "sys.argv", ["taskcheck", "--report", "today", "--taskrc", test_taskrc]
220 | ):
221 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
222 | mock_args = Mock()
223 | mock_args.install = False
224 | mock_args.schedule = False
225 | mock_args.report = "today"
226 | mock_args.verbose = True
227 | mock_args.force_update = True
228 | mock_args.taskrc = test_taskrc
229 | mock_args.dry_run = False
230 | mock_args.auto_adjust_urgency = True
231 | mock_parse.return_value = mock_args
232 |
233 | main()
234 |
235 | mock_load_config.assert_called_once()
236 | mock_generate_report.assert_called_once_with(
237 | sample_config,
238 | "today",
239 | True,
240 | force_update=True,
241 | taskrc=test_taskrc,
242 | scheduling_results=None,
243 | )
244 |
245 | @patch("taskcheck.__main__.load_config")
246 | @patch("taskcheck.__main__.check_tasks_parallel")
247 | @patch("taskcheck.report.generate_report")
248 | def test_main_schedule_and_report(
249 | self,
250 | mock_generate_report,
251 | mock_check_tasks,
252 | mock_load_config,
253 | sample_config,
254 | test_taskrc,
255 | mock_task_export_with_taskrc,
256 | ):
257 | """Test both schedule and report commands together."""
258 | mock_load_config.return_value = sample_config
259 |
260 | with patch(
261 | "sys.argv",
262 | ["taskcheck", "--schedule", "--report", "eow", "--taskrc", test_taskrc],
263 | ):
264 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
265 | mock_args = Mock()
266 | mock_args.install = False
267 | mock_args.schedule = True
268 | mock_args.report = "eow"
269 | mock_args.verbose = False
270 | mock_args.force_update = False
271 | mock_args.taskrc = test_taskrc
272 | mock_args.urgency_weight = None
273 | mock_args.dry_run = False
274 | mock_args.auto_adjust_urgency = True
275 | mock_parse.return_value = mock_args
276 |
277 | main()
278 |
279 | # Config should be loaded twice (once for each command)
280 | assert mock_load_config.call_count == 2
281 | mock_check_tasks.assert_called_once()
282 | mock_generate_report.assert_called_once()
283 |
284 | @patch("taskcheck.__main__.load_config")
285 | @patch("taskcheck.__main__.check_tasks_parallel")
286 | def test_main_schedule_with_verbose_and_force_update(
287 | self,
288 | mock_check_tasks,
289 | mock_load_config,
290 | sample_config,
291 | test_taskrc,
292 | mock_task_export_with_taskrc,
293 | ):
294 | """Test schedule command with verbose and force update flags."""
295 | mock_load_config.return_value = sample_config
296 |
297 | with patch(
298 | "sys.argv",
299 | [
300 | "taskcheck",
301 | "--schedule",
302 | "--verbose",
303 | "--force-update",
304 | "--taskrc",
305 | test_taskrc,
306 | ],
307 | ):
308 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
309 | mock_args = Mock()
310 | mock_args.install = False
311 | mock_args.schedule = True
312 | mock_args.report = None
313 | mock_args.verbose = True
314 | mock_args.force_update = True
315 | mock_args.taskrc = test_taskrc
316 | mock_args.urgency_weight = None
317 | mock_args.dry_run = False
318 | mock_args.auto_adjust_urgency = True
319 | mock_parse.return_value = mock_args
320 |
321 | main()
322 |
323 | mock_check_tasks.assert_called_once_with(
324 | sample_config,
325 | verbose=True,
326 | force_update=True,
327 | taskrc=test_taskrc,
328 | urgency_weight_override=None,
329 | dry_run=False,
330 | auto_adjust_urgency=True,
331 | )
332 |
333 | @patch("taskcheck.__main__.load_config")
334 | @patch("taskcheck.__main__.check_tasks_parallel")
335 | def test_main_schedule_with_urgency_weight_override(
336 | self,
337 | mock_check_tasks,
338 | mock_load_config,
339 | sample_config,
340 | test_taskrc,
341 | mock_task_export_with_taskrc,
342 | ):
343 | """Test schedule command with urgency weight override."""
344 | mock_load_config.return_value = sample_config
345 |
346 | with patch(
347 | "sys.argv",
348 | [
349 | "taskcheck",
350 | "--schedule",
351 | "--urgency-weight",
352 | "0.3",
353 | "--taskrc",
354 | test_taskrc,
355 | ],
356 | ):
357 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
358 | mock_args = Mock()
359 | mock_args.install = False
360 | mock_args.schedule = True
361 | mock_args.report = None
362 | mock_args.verbose = False
363 | mock_args.force_update = False
364 | mock_args.taskrc = test_taskrc
365 | mock_args.urgency_weight = 0.3
366 | mock_args.dry_run = False
367 | mock_args.auto_adjust_urgency = True
368 | mock_parse.return_value = mock_args
369 |
370 | main()
371 |
372 | mock_check_tasks.assert_called_once_with(
373 | sample_config,
374 | verbose=False,
375 | force_update=False,
376 | taskrc=test_taskrc,
377 | urgency_weight_override=0.3,
378 | dry_run=False,
379 | auto_adjust_urgency=True,
380 | )
381 |
382 | @patch("taskcheck.__main__.load_config")
383 | @patch("taskcheck.__main__.check_tasks_parallel")
384 | def test_main_schedule_with_dry_run(
385 | self, mock_check_tasks, mock_load_config, sample_config, test_taskrc
386 | ):
387 | """Test that dry-run mode returns scheduling results without modifying tasks."""
388 | mock_load_config.return_value = sample_config
389 |
390 | # Mock dry-run results
391 | dry_run_results = [
392 | {
393 | "id": "1",
394 | "uuid": "test-uuid-1",
395 | "description": "Test task 1",
396 | "project": "test",
397 | "urgency": 5.0,
398 | "estimated": "PT2H",
399 | "due": "20241225T120000Z",
400 | "scheduled": "2024-12-20",
401 | "completion_date": "2024-12-20",
402 | "scheduling": "2024-12-20 - PT2H",
403 | }
404 | ]
405 | mock_check_tasks.return_value = dry_run_results
406 |
407 | with patch(
408 | "sys.argv",
409 | ["taskcheck", "--schedule", "--dry-run", "--taskrc", test_taskrc],
410 | ):
411 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
412 | mock_args = Mock()
413 | mock_args.install = False
414 | mock_args.schedule = True
415 | mock_args.report = None
416 | mock_args.verbose = False
417 | mock_args.force_update = False
418 | mock_args.taskrc = test_taskrc
419 | mock_args.urgency_weight = None
420 | mock_args.dry_run = True
421 | mock_args.auto_adjust_urgency = True
422 | mock_parse.return_value = mock_args
423 |
424 | main()
425 |
426 | # Verify that check_tasks_parallel was called with dry_run=True
427 | mock_check_tasks.assert_called_once_with(
428 | sample_config,
429 | verbose=False,
430 | force_update=False,
431 | taskrc=test_taskrc,
432 | urgency_weight_override=None,
433 | dry_run=True,
434 | auto_adjust_urgency=True,
435 | )
436 | mock_load_config.assert_called_once()
437 |
438 | @patch("taskcheck.__main__.load_config")
439 | @patch("taskcheck.__main__.check_tasks_parallel")
440 | @patch("taskcheck.report.generate_report")
441 | def test_main_schedule_dry_run_with_report(
442 | self,
443 | mock_generate_report,
444 | mock_check_tasks,
445 | mock_load_config,
446 | sample_config,
447 | test_taskrc,
448 | ):
449 | """Test that dry-run results are passed to report generation."""
450 | mock_load_config.return_value = sample_config
451 |
452 | # Mock dry-run results
453 | dry_run_results = [
454 | {
455 | "id": "1",
456 | "uuid": "test-uuid-1",
457 | "description": "Test task 1",
458 | "project": "test",
459 | "urgency": 5.0,
460 | "estimated": "PT2H",
461 | "due": "20241225T120000Z",
462 | "scheduled": "2024-12-20",
463 | "completion_date": "2024-12-20",
464 | "scheduling": "2024-12-20 - PT2H",
465 | }
466 | ]
467 | mock_check_tasks.return_value = dry_run_results
468 |
469 | with patch(
470 | "sys.argv",
471 | [
472 | "taskcheck",
473 | "--schedule",
474 | "--dry-run",
475 | "--report",
476 | "today",
477 | "--taskrc",
478 | test_taskrc,
479 | ],
480 | ):
481 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
482 | mock_args = Mock()
483 | mock_args.install = False
484 | mock_args.schedule = True
485 | mock_args.report = "today"
486 | mock_args.verbose = False
487 | mock_args.force_update = False
488 | mock_args.taskrc = test_taskrc
489 | mock_args.urgency_weight = None
490 | mock_args.dry_run = True
491 | mock_args.auto_adjust_urgency = True
492 | mock_parse.return_value = mock_args
493 |
494 | main()
495 |
496 | # Verify that generate_report was called with the dry-run results
497 | mock_generate_report.assert_called_once_with(
498 | sample_config,
499 | "today",
500 | False,
501 | force_update=False,
502 | taskrc=test_taskrc,
503 | scheduling_results=dry_run_results,
504 | )
505 |
506 | # Verify that check_tasks_parallel was called with dry_run=True
507 | mock_check_tasks.assert_called_once_with(
508 | sample_config,
509 | verbose=False,
510 | force_update=False,
511 | taskrc=test_taskrc,
512 | urgency_weight_override=None,
513 | dry_run=True,
514 | auto_adjust_urgency=True,
515 | )
516 |
517 | @patch("taskcheck.__main__.load_config")
518 | def test_main_config_loading_error(self, mock_load_config):
519 | """Test behavior when config loading fails."""
520 | mock_load_config.side_effect = FileNotFoundError("Config not found")
521 |
522 | with patch("sys.argv", ["taskcheck", "--schedule"]):
523 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
524 | mock_args = Mock()
525 | mock_args.install = False
526 | mock_args.schedule = True
527 | mock_args.report = None
528 | mock_args.auto_adjust_urgency = True
529 | mock_parse.return_value = mock_args
530 |
531 | with pytest.raises(FileNotFoundError):
532 | main()
533 |
534 | def test_main_help_display(self):
535 | """Test that help is displayed when no valid commands are given."""
536 | with patch("sys.argv", ["taskcheck"]):
537 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
538 | mock_args = Mock()
539 | mock_args.install = False
540 | mock_args.schedule = False
541 | mock_args.report = None
542 | mock_args.auto_adjust_urgency = True
543 | mock_parse.return_value = mock_args
544 |
545 | with patch.object(arg_parser, "print_help") as mock_help:
546 | main()
547 | mock_help.assert_called_once()
548 |
549 | @patch("taskcheck.install.install")
550 | def test_main_install_returns_early(self, mock_install):
551 | """Test that install command returns without processing other commands."""
552 | with patch("sys.argv", ["taskcheck", "--install", "--schedule"]):
553 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
554 | mock_args = Mock()
555 | mock_args.install = True
556 | mock_args.schedule = True
557 | mock_args.report = None
558 | mock_args.auto_adjust_urgency = True
559 | mock_parse.return_value = mock_args
560 |
561 | with patch("taskcheck.__main__.load_config") as mock_load:
562 | main()
563 |
564 | mock_install.assert_called_once()
565 | # load_config should not be called because install returns early
566 | mock_load.assert_not_called()
567 |
568 |
569 | class TestImportErrorHandling:
570 | def test_install_import_error(self):
571 | """Test behavior when install module cannot be imported."""
572 | with patch("sys.argv", ["taskcheck", "--install"]):
573 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
574 | mock_args = Mock()
575 | mock_args.install = True
576 | mock_args.schedule = False
577 | mock_args.report = None
578 | mock_args.auto_adjust_urgency = True
579 | mock_parse.return_value = mock_args
580 |
581 | with patch(
582 | "builtins.__import__",
583 | side_effect=ImportError("Install module not found"),
584 | ):
585 | with pytest.raises(ImportError):
586 | main()
587 |
588 | def test_report_import_error(self):
589 | """Test behavior when report module cannot be imported."""
590 | with patch("sys.argv", ["taskcheck", "--report", "today"]):
591 | with patch("taskcheck.__main__.arg_parser.parse_args") as mock_parse:
592 | mock_args = Mock()
593 | mock_args.install = False
594 | mock_args.schedule = False
595 | mock_args.report = "today"
596 | mock_args.auto_adjust_urgency = True
597 | mock_parse.return_value = mock_args
598 |
599 | with patch("taskcheck.__main__.load_config", return_value={}):
600 | with patch(
601 | "builtins.__import__",
602 | side_effect=ImportError("Report module not found"),
603 | ):
604 | with pytest.raises(ImportError):
605 | main()
606 |
--------------------------------------------------------------------------------
/tests/test_parallel.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | from unittest.mock import patch
3 |
4 | from taskcheck.parallel import (
5 | get_urgency_coefficients,
6 | check_tasks_parallel,
7 | initialize_task_info,
8 | allocate_time_for_day,
9 | urgency_due,
10 | urgency_age,
11 | urgency_estimated,
12 | recompute_urgencies,
13 | UrgencyCoefficients,
14 | )
15 |
16 |
17 | class TestUrgencyCoefficients:
18 | def test_get_urgency_coefficients(self, mock_task_export_with_taskrc, test_taskrc):
19 | coeffs = get_urgency_coefficients(taskrc=test_taskrc)
20 |
21 | assert isinstance(coeffs, UrgencyCoefficients)
22 | assert "P1H" in coeffs.estimated
23 | assert coeffs.estimated["P1H"] == 5.0
24 | assert coeffs.inherit is True
25 | assert coeffs.active == 4.0
26 |
27 |
28 | class TestUrgencyCalculations:
29 | def test_urgency_due_overdue(self):
30 | coeffs = UrgencyCoefficients({}, False, 0, 365, 12, 2)
31 | task_info = {
32 | "task": {
33 | "due": "20231201T170000Z" # Past due
34 | }
35 | }
36 | date = datetime(2023, 12, 10).date() # 9 days later
37 |
38 | urgency = urgency_due(task_info, date, coeffs)
39 | assert urgency == 12.0 # Max urgency for overdue
40 |
41 | def test_urgency_due_approaching(self):
42 | coeffs = UrgencyCoefficients({}, False, 0, 365, 12, 2)
43 | task_info = {
44 | "task": {
45 | "due": "20231210T170000Z" # Due in future
46 | }
47 | }
48 | date = datetime(2023, 12, 5).date() # 5 days before
49 |
50 | urgency = urgency_due(task_info, date, coeffs)
51 | assert 0 < urgency < 12.0
52 |
53 | def test_urgency_age(self):
54 | coeffs = UrgencyCoefficients({}, False, 0, 365, 12, 2)
55 | task_info = {
56 | "task": {
57 | "entry": "20231120T090000Z" # 15 days ago
58 | }
59 | }
60 | date = datetime(2023, 12, 5).date()
61 |
62 | urgency = urgency_age(task_info, date, coeffs)
63 | expected = 1.0 * 15 / 365 * 2 # age calculation
64 | assert abs(urgency - expected) < 0.01
65 |
66 | def test_urgency_estimated(self):
67 | coeffs = UrgencyCoefficients({"P1H": 5.0, "P2H": 8.0}, False, 0, 365, 12, 2)
68 | task_info = {"remaining_hours": 1.0}
69 |
70 | urgency = urgency_estimated(task_info, None, coeffs)
71 | assert urgency == 5.0
72 |
73 |
74 | class TestTaskInitialization:
75 | @patch("taskcheck.parallel.get_long_range_time_map")
76 | def test_initialize_task_info(self, mock_long_range, sample_tasks, sample_config):
77 | mock_long_range.return_value = ([8.0, 8.0, 8.0], 0.0)
78 |
79 | time_maps = sample_config["time_maps"]
80 | days_ahead = 3
81 | coeffs = UrgencyCoefficients(
82 | {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2
83 | )
84 | calendars = []
85 |
86 | task_info = initialize_task_info(
87 | sample_tasks, time_maps, days_ahead, coeffs, calendars
88 | )
89 |
90 | assert len(task_info) == len(sample_tasks)
91 | for uuid, info in task_info.items():
92 | assert "task" in info
93 | assert "remaining_hours" in info
94 | assert "task_time_map" in info
95 | assert "urgency" in info
96 |
97 |
98 | class TestTimeAllocation:
99 | def test_allocate_time_for_day_single_task(self, sample_config):
100 | task_info = {
101 | "task-1": {
102 | "task": {
103 | "id": 1,
104 | "uuid": "task-1",
105 | "description": "Test task",
106 | "estimated": "P2H",
107 | },
108 | "remaining_hours": 2.0,
109 | "task_time_map": [8.0, 8.0, 8.0],
110 | "today_used_hours": 0.0,
111 | "scheduling": {},
112 | "urgency": 10.0,
113 | "estimated_urgency": 8.0,
114 | "due_urgency": 0.0,
115 | "age_urgency": 1.0,
116 | "started": False,
117 | }
118 | }
119 |
120 | coeffs = UrgencyCoefficients({"P2H": 8.0}, False, 4.0, 365, 12, 2)
121 |
122 | allocate_time_for_day(task_info, 0, coeffs, verbose=True, weight_urgency=1.0)
123 |
124 | # Should allocate time and update scheduling
125 | assert task_info["task-1"]["remaining_hours"] < 2.0
126 | assert len(task_info["task-1"]["scheduling"]) > 0
127 |
128 |
129 | class TestDependencies:
130 | def test_task_with_dependencies(self, sample_config):
131 | task_info = {
132 | "task-1": {
133 | "task": {
134 | "id": 1,
135 | "uuid": "task-1",
136 | "description": "Dependent task",
137 | "depends": ["task-2"],
138 | "estimated": "P2H",
139 | },
140 | "remaining_hours": 2.0,
141 | "task_time_map": [8.0, 8.0, 8.0],
142 | "today_used_hours": 0.0,
143 | "scheduling": {},
144 | "urgency": 10.0,
145 | "estimated_urgency": 8.0,
146 | "due_urgency": 0.0,
147 | "age_urgency": 1.0,
148 | "started": False,
149 | },
150 | "task-2": {
151 | "task": {
152 | "id": 2,
153 | "uuid": "task-2",
154 | "description": "Dependency task",
155 | "estimated": "P1H",
156 | },
157 | "remaining_hours": 1.0,
158 | "task_time_map": [8.0, 8.0, 8.0],
159 | "today_used_hours": 0.0,
160 | "scheduling": {},
161 | "urgency": 15.0,
162 | "estimated_urgency": 5.0,
163 | "due_urgency": 0.0,
164 | "age_urgency": 1.0,
165 | "started": False,
166 | },
167 | }
168 |
169 | coeffs = UrgencyCoefficients({"P1H": 5.0, "P2H": 8.0}, False, 4.0, 365, 12, 2)
170 |
171 | allocate_time_for_day(task_info, 0, coeffs, verbose=True, weight_urgency=1.0)
172 |
173 | # task-2 should be scheduled first due to dependency
174 | if task_info["task-2"]["remaining_hours"] == 0:
175 | # task-2 completed, task-1 can now be scheduled
176 | assert task_info["task-1"]["remaining_hours"] <= 2.0
177 |
178 |
179 | class TestWeightConfiguration:
180 | @patch("taskcheck.parallel.get_calendars")
181 | @patch("taskcheck.parallel.get_tasks")
182 | @patch("taskcheck.parallel.get_urgency_coefficients")
183 | @patch("taskcheck.parallel.update_tasks_with_scheduling_info")
184 | def test_urgency_weight_override(
185 | self,
186 | mock_update,
187 | mock_coeffs,
188 | mock_tasks,
189 | mock_calendars,
190 | sample_config,
191 | sample_tasks,
192 | ):
193 | """Test that urgency_weight_override properly overrides config values."""
194 | # Set config values
195 | sample_config["scheduler"]["weight_urgency"] = 0.8
196 | sample_config["scheduler"]["weight_due_date"] = 0.2
197 |
198 | mock_tasks.return_value = sample_tasks
199 | mock_coeffs.return_value = UrgencyCoefficients(
200 | {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2
201 | )
202 | mock_calendars.return_value = []
203 |
204 | # Call with override
205 | check_tasks_parallel(sample_config, urgency_weight_override=0.3)
206 |
207 | # Verify the function was called - we'd need to check internal logic
208 | # This test would need access to the weights used internally
209 | mock_tasks.assert_called_once()
210 |
211 | @patch("taskcheck.parallel.get_calendars")
212 | @patch("taskcheck.parallel.get_tasks")
213 | @patch("taskcheck.parallel.get_urgency_coefficients")
214 | @patch("taskcheck.parallel.update_tasks_with_scheduling_info")
215 | def test_config_weights_used_when_no_override(
216 | self,
217 | mock_update,
218 | mock_coeffs,
219 | mock_tasks,
220 | mock_calendars,
221 | sample_config,
222 | sample_tasks,
223 | ):
224 | """Test that config weights are used when no override is provided."""
225 | sample_config["scheduler"]["weight_urgency"] = 0.6
226 | sample_config["scheduler"]["weight_due_date"] = 0.4
227 |
228 | mock_tasks.return_value = sample_tasks
229 | mock_coeffs.return_value = UrgencyCoefficients(
230 | {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2
231 | )
232 | mock_calendars.return_value = []
233 |
234 | # Call without override
235 | check_tasks_parallel(sample_config, urgency_weight_override=None)
236 |
237 | mock_tasks.assert_called_once()
238 |
239 | def test_recompute_urgencies_with_weights(self):
240 | """Test that recompute_urgencies applies weights correctly."""
241 | tasks_remaining = {
242 | "task-1": {
243 | "task": {"uuid": "task-1", "id": 1},
244 | "urgency": 10.0,
245 | "estimated_urgency": 5.0,
246 | "due_urgency": 3.0,
247 | "age_urgency": 1.0,
248 | "remaining_hours": 2.0,
249 | "started": False,
250 | }
251 | }
252 |
253 | coeffs = UrgencyCoefficients({"P1H": 5.0, "P2H": 8.0}, False, 0, 365, 12, 2)
254 | date = datetime.now().date()
255 | weight_urgency = 0.7
256 |
257 | # Store original urgency to calculate base
258 |
259 | recompute_urgencies(tasks_remaining, coeffs, date, weight_urgency)
260 |
261 | # Check that weights were applied to the NEW urgency values (after recomputation)
262 | task_info = tasks_remaining["task-1"]
263 |
264 | # The function recomputes all urgency components, so we must use the new values after recomputation.
265 | # The actual implementation does:
266 | # base_urgency = new_urgency - new_due_urgency
267 | # weighted_urgency = base_urgency * weight_urgency + new_due_urgency
268 | base_urgency = (
269 | (task_info["urgency"] - task_info["due_urgency"]) / weight_urgency
270 | if weight_urgency != 0
271 | else 0
272 | )
273 | expected_urgency = base_urgency * weight_urgency + task_info["due_urgency"]
274 |
275 | assert abs(task_info["urgency"] - expected_urgency) < 0.01
276 |
277 |
278 | class TestMainSchedulingFunction:
279 | @patch("taskcheck.parallel.get_calendars")
280 | @patch("taskcheck.parallel.get_tasks")
281 | @patch("taskcheck.parallel.get_urgency_coefficients")
282 | @patch("taskcheck.parallel.update_tasks_with_scheduling_info")
283 | def test_check_tasks_parallel(
284 | self,
285 | mock_update,
286 | mock_coeffs,
287 | mock_tasks,
288 | mock_calendars,
289 | sample_config,
290 | sample_tasks,
291 | test_taskrc,
292 | ):
293 | mock_tasks.return_value = sample_tasks
294 | mock_coeffs.return_value = UrgencyCoefficients(
295 | {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2
296 | )
297 | mock_calendars.return_value = []
298 |
299 | check_tasks_parallel(sample_config, verbose=True, taskrc=test_taskrc)
300 |
301 | mock_tasks.assert_called_once_with(taskrc=test_taskrc)
302 | mock_coeffs.assert_called_once_with(taskrc=test_taskrc)
303 | mock_calendars.assert_called_once()
304 | mock_update.assert_called_once()
305 |
306 |
307 | class TestAutoAdjustUrgency:
308 | @patch("taskcheck.parallel.get_calendars")
309 | @patch("taskcheck.parallel.get_tasks")
310 | @patch("taskcheck.parallel.get_urgency_coefficients")
311 | @patch("taskcheck.parallel.update_tasks_with_scheduling_info")
312 | def test_auto_adjust_urgency_enabled(
313 | self,
314 | mock_update,
315 | mock_coeffs,
316 | mock_tasks,
317 | mock_calendars,
318 | sample_config,
319 | test_taskrc,
320 | ):
321 | """Test that auto-adjust reduces urgency weight when tasks are overdue."""
322 | # Create tasks with tight deadlines that will cause conflicts
323 | overdue_tasks = [
324 | {
325 | "id": 1,
326 | "uuid": "task-1",
327 | "description": "Urgent task",
328 | "estimated": "P8H",
329 | "time_map": "work",
330 | "urgency": 20.0,
331 | "due": "20231206T170000Z", # Very soon
332 | "status": "pending",
333 | },
334 | {
335 | "id": 2,
336 | "uuid": "task-2",
337 | "description": "Also urgent task",
338 | "estimated": "P8H",
339 | "time_map": "work",
340 | "urgency": 15.0,
341 | "due": "20231206T170000Z", # Same deadline
342 | "status": "pending",
343 | },
344 | ]
345 |
346 | mock_tasks.return_value = overdue_tasks
347 | mock_coeffs.return_value = UrgencyCoefficients(
348 | {"P8H": 10.0}, False, 4.0, 365, 12, 2
349 | )
350 | mock_calendars.return_value = []
351 |
352 | # This should trigger auto-adjustment
353 | check_tasks_parallel(
354 | sample_config, verbose=True, taskrc=test_taskrc, auto_adjust_urgency=True
355 | )
356 |
357 | mock_tasks.assert_called_once_with(taskrc=test_taskrc)
358 |
359 | @patch("taskcheck.parallel.get_calendars")
360 | @patch("taskcheck.parallel.get_tasks")
361 | @patch("taskcheck.parallel.get_urgency_coefficients")
362 | @patch("taskcheck.parallel.update_tasks_with_scheduling_info")
363 | def test_auto_adjust_urgency_disabled(
364 | self,
365 | mock_update,
366 | mock_coeffs,
367 | mock_tasks,
368 | mock_calendars,
369 | sample_config,
370 | sample_tasks,
371 | test_taskrc,
372 | ):
373 | """Test that auto-adjust is ignored when disabled."""
374 | mock_tasks.return_value = sample_tasks
375 | mock_coeffs.return_value = UrgencyCoefficients(
376 | {"P1H": 5.0, "P2H": 8.0, "P3H": 10.0}, False, 4.0, 365, 12, 2
377 | )
378 | mock_calendars.return_value = []
379 |
380 | # This should not trigger auto-adjustment
381 | check_tasks_parallel(
382 | sample_config, verbose=True, taskrc=test_taskrc, auto_adjust_urgency=False
383 | )
384 |
385 | mock_tasks.assert_called_once_with(taskrc=test_taskrc)
386 |
387 | @patch("taskcheck.parallel.get_calendars")
388 | @patch("taskcheck.parallel.get_tasks")
389 | @patch("taskcheck.parallel.get_urgency_coefficients")
390 | @patch("taskcheck.parallel.get_long_range_time_map")
391 | @patch("taskcheck.parallel.update_tasks_with_scheduling_info")
392 | def test_auto_adjust_urgency_weight_reduction(
393 | self,
394 | mock_update,
395 | mock_long_range,
396 | mock_coeffs,
397 | mock_tasks,
398 | mock_calendars,
399 | sample_config,
400 | test_taskrc,
401 | ):
402 | """Test that auto_adjust_urgency reduces the urgency weight and stops at 0.0."""
403 | # Use relative dates based on current date
404 | from datetime import datetime, timedelta
405 |
406 | now = datetime.now()
407 | tomorrow = now + timedelta(hours=2)
408 |
409 | # Create tasks that cannot be completed on time due to insufficient available time
410 | overdue_tasks = [
411 | {
412 | "id": 1,
413 | "uuid": "task-1",
414 | "description": "Impossible task",
415 | "estimated": "P24H", # 24 hours
416 | "time_map": "work",
417 | "urgency": 20.0,
418 | "due": tomorrow.strftime(
419 | "%Y%m%dT%H%M%SZ"
420 | ), # Due tomorrow to trigger overdue detection
421 | "status": "pending",
422 | "entry": now.strftime("%Y%m%dT%H%M%SZ"), # Created today
423 | }
424 | ]
425 |
426 | mock_tasks.return_value = overdue_tasks
427 | mock_coeffs.return_value = UrgencyCoefficients(
428 | {"P24H": 10.0}, False, 4.0, 365, 12, 2
429 | )
430 | mock_calendars.return_value = []
431 | # Mock no available time at all to make it truly impossible
432 | mock_long_range.return_value = ([0.0] * 365, 0.0)
433 |
434 | # Patch the console.print to capture output
435 | with patch("taskcheck.parallel.console.print") as mock_console_print:
436 | check_tasks_parallel(
437 | sample_config,
438 | verbose=True,
439 | taskrc=test_taskrc,
440 | auto_adjust_urgency=True,
441 | )
442 |
443 | # Should print a warning about not finding a solution
444 | # Print all captured calls for debugging if the assertion fails
445 | found_warning = any(
446 | "cannot find a solution"
447 | in " ".join(str(arg).lower() for arg in call.args)
448 | for call in mock_console_print.call_args_list
449 | )
450 | if not found_warning:
451 | print("Captured console.print calls for debug:")
452 | for call in mock_console_print.call_args_list:
453 | print(str(call))
454 | assert found_warning
455 |
456 | @patch("taskcheck.parallel.get_calendars")
457 | @patch("taskcheck.parallel.get_tasks")
458 | @patch("taskcheck.parallel.get_urgency_coefficients")
459 | @patch("taskcheck.parallel.get_long_range_time_map")
460 | @patch("taskcheck.parallel.update_tasks_with_scheduling_info")
461 | def test_auto_adjust_urgency_final_weight_message(
462 | self,
463 | mock_update,
464 | mock_long_range,
465 | mock_coeffs,
466 | mock_tasks,
467 | mock_calendars,
468 | sample_config,
469 | test_taskrc,
470 | ):
471 | """Test that the final urgency weight message is printed when auto-adjust is used."""
472 | # Use relative dates based on current date
473 | from datetime import datetime, timedelta
474 |
475 | now = datetime.now()
476 | future_date_near = now + timedelta(days=3)
477 | future_date_far = now + timedelta(days=7)
478 |
479 | # Create tasks that will require at least one reduction in urgency weight
480 | overdue_tasks = [
481 | {
482 | "id": 1,
483 | "uuid": "task-1",
484 | "description": "Tight deadline",
485 | "estimated": "P16H", # 2 working days, due in 7 days
486 | "time_map": "work",
487 | "urgency": 20.0,
488 | "due": future_date_far.strftime(
489 | "%Y%m%dT%H%M%SZ"
490 | ), # Due in 7 days - tight deadline
491 | "status": "pending",
492 | "entry": now.strftime("%Y%m%dT%H%M%SZ"), # Created today
493 | },
494 | {
495 | "id": 2,
496 | "uuid": "task-2",
497 | "description": "Competing task",
498 | "estimated": "P16H", # 2 working days, due in 3 days
499 | "time_map": "work",
500 | "urgency": 15.0,
501 | "due": future_date_near.strftime(
502 | "%Y%m%dT%H%M%SZ"
503 | ), # Same deadline to create conflict
504 | "status": "pending",
505 | "entry": now.strftime("%Y%m%dT%H%M%SZ"), # Created today
506 | },
507 | ]
508 |
509 | mock_tasks.return_value = overdue_tasks
510 | mock_coeffs.return_value = UrgencyCoefficients(
511 | {"P16H": 10.0, "P8H": 8.0}, False, 4.0, 365, 12, 2
512 | )
513 | mock_calendars.return_value = []
514 | # Mock enough available time that the task CAN be completed with weight reduction
515 | mock_long_range.return_value = ([4.0] * 7, 0.0) # 28 total hours available
516 |
517 | with patch("taskcheck.parallel.console.print") as mock_console_print:
518 | check_tasks_parallel(
519 | sample_config,
520 | verbose=True,
521 | taskrc=test_taskrc,
522 | auto_adjust_urgency=True,
523 | )
524 |
525 | # Should print the final urgency weight used
526 | # Print all captured calls for debugging if the assertion fails
527 | found_final_weight = any(
528 | "final urgency weight"
529 | in " ".join(str(arg).lower() for arg in call.args)
530 | for call in mock_console_print.call_args_list
531 | )
532 | if not found_final_weight:
533 | print("Captured console.print calls for debug:")
534 | for call in mock_console_print.call_args_list:
535 | print(str(call))
536 | assert found_final_weight
537 |
--------------------------------------------------------------------------------
/tests/test_report.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from datetime import datetime, timedelta
3 | from unittest.mock import patch, Mock
4 | import json
5 |
6 | from taskcheck.report import (
7 | get_tasks,
8 | get_taskwarrior_date,
9 | get_days_in_constraint,
10 | generate_report,
11 | get_task_emoji,
12 | tostring,
13 | get_unplanned_tasks
14 | )
15 |
16 |
17 | class TestDateUtilities:
18 | @patch('subprocess.run')
19 | def test_get_taskwarrior_date_valid(self, mock_run, test_taskrc):
20 | mock_result = Mock()
21 | mock_result.stdout = "2023-12-05T14:30:00\n"
22 | mock_run.return_value = mock_result
23 |
24 | result = get_taskwarrior_date("today", taskrc=test_taskrc)
25 |
26 | assert result == datetime(2023, 12, 5, 14, 30, 0)
27 | mock_run.assert_called_once()
28 | # Verify environment was passed
29 | call_args = mock_run.call_args
30 | assert 'env' in call_args.kwargs
31 | assert call_args.kwargs['env']['TASKRC'] == test_taskrc
32 |
33 | @patch('subprocess.run')
34 | def test_get_taskwarrior_date_relative(self, mock_run, test_taskrc):
35 | # First call fails, second call with "today+" prefix succeeds
36 | mock_result_fail = Mock()
37 | mock_result_fail.stdout = "invalid\n"
38 |
39 | mock_result_success = Mock()
40 | mock_result_success.stdout = "2023-12-06T14:30:00\n"
41 |
42 | mock_run.side_effect = [mock_result_fail, mock_result_success]
43 |
44 | result = get_taskwarrior_date("1day", taskrc=test_taskrc)
45 |
46 | assert result == datetime(2023, 12, 6, 14, 30, 0)
47 | assert mock_run.call_count == 2
48 |
49 | def test_get_days_in_constraint(self, test_taskrc):
50 | with patch('taskcheck.report.get_taskwarrior_date') as mock_date:
51 | with patch('taskcheck.report.datetime') as mock_datetime:
52 | # Mock the constraint date (end of week)
53 | mock_date.return_value = datetime(2023, 12, 7, 0, 0, 0)
54 |
55 | # Mock datetime.today() to return an earlier date
56 | mock_datetime.today.return_value = datetime(2023, 12, 5, 0, 0, 0)
57 | mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)
58 |
59 | days = list(get_days_in_constraint("eow", taskrc=test_taskrc))
60 |
61 | # Should return days from Dec 5 to Dec 7 (3 days)
62 | assert len(days) == 3
63 | assert all(len(day) == 3 for day in days) # (year, month, day)
64 | mock_date.assert_called_once_with("eow", taskrc=test_taskrc)
65 |
66 |
67 | class TestTaskFiltering:
68 | def test_get_tasks_with_scheduling(self, sample_config):
69 | tasks_with_scheduling = [
70 | {
71 | "id": 1,
72 | "project": "test",
73 | "description": "Test task",
74 | "scheduling": "2023-12-05 - PT2H\n2023-12-06 - PT1H",
75 | "urgency": 10.0
76 | },
77 | {
78 | "id": 2,
79 | "project": "other",
80 | "description": "Another task",
81 | "scheduling": "2023-12-05 - PT30M",
82 | "urgency": 5.0
83 | }
84 | ]
85 |
86 | result = get_tasks(sample_config["report"], tasks_with_scheduling, 2023, 12, 5)
87 |
88 | assert len(result) == 2
89 | assert result[0]["urgency"] >= result[1]["urgency"] # Sorted by urgency
90 |
91 | @patch('subprocess.run')
92 | def test_get_unplanned_tasks(self, mock_run, sample_config, test_taskrc):
93 | unplanned_tasks = [
94 | {
95 | "id": 3,
96 | "description": "Unplanned task",
97 | "urgency": 8.0,
98 | "due": "20231210T170000Z"
99 | }
100 | ]
101 |
102 | mock_result = Mock()
103 | mock_result.stdout = json.dumps(unplanned_tasks)
104 | mock_run.return_value = mock_result
105 |
106 | result = get_unplanned_tasks(sample_config["report"], [], taskrc=test_taskrc)
107 |
108 | assert result == unplanned_tasks
109 | # Verify environment was passed
110 | call_args = mock_run.call_args
111 | assert 'env' in call_args.kwargs
112 | assert call_args.kwargs['env']['TASKRC'] == test_taskrc
113 |
114 |
115 | class TestStringFormatting:
116 | def test_tostring_boolean(self):
117 | assert tostring(True) == "Yes"
118 | assert tostring(False) == "No"
119 |
120 | def test_tostring_datetime(self):
121 | dt = datetime(2023, 12, 5, 14, 30, 0)
122 | assert tostring(dt) == "2023-12-05 14:30"
123 |
124 | def test_tostring_taskwarrior_date(self):
125 | tw_date = "20231205T143000Z"
126 | result = tostring(tw_date)
127 | assert "2023-12-05 14:30" == result
128 |
129 | def test_tostring_regular_string(self):
130 | assert tostring("hello") == "hello"
131 |
132 | def test_tostring_number(self):
133 | assert tostring(42) == "42"
134 | assert tostring(3.14) == "3.14"
135 |
136 |
137 | class TestEmojiGeneration:
138 | def test_get_task_emoji_keyword_match(self, sample_config):
139 | task = {"description": "Schedule a meeting with the team"}
140 | emoji = get_task_emoji(sample_config["report"], task)
141 |
142 | assert emoji == ":busts_in_silhouette:"
143 |
144 | def test_get_task_emoji_default_keyword(self, sample_config):
145 | task = {"description": "Write some code for the project"}
146 | emoji = get_task_emoji(sample_config["report"], task)
147 |
148 | assert emoji == ":computer:"
149 |
150 | def test_get_task_emoji_random(self, sample_config):
151 | task = {"description": "Some random task without keywords"}
152 | emoji = get_task_emoji(sample_config["report"], task)
153 |
154 | # Should return some emoji (deterministic based on description)
155 | assert len(emoji) >= 1
156 |
157 | # Same description should give same emoji
158 | emoji2 = get_task_emoji(sample_config["report"], task)
159 | assert emoji == emoji2
160 |
161 |
162 | class TestReportGeneration:
163 | @patch('taskcheck.report.fetch_tasks')
164 | @patch('taskcheck.report.get_days_in_constraint')
165 | @patch('taskcheck.report.get_unplanned_tasks')
166 | def test_generate_report_basic(self, mock_unplanned, mock_days, mock_fetch, sample_config, test_taskrc):
167 | mock_fetch.return_value = [
168 | {
169 | "id": 1,
170 | "description": "Test task",
171 | "scheduling": "2023-12-05 - PT2H",
172 | "urgency": 10.0,
173 | "project": "test"
174 | }
175 | ]
176 | mock_days.return_value = [(2023, 12, 5)]
177 | mock_unplanned.return_value = []
178 |
179 | # Should run without error
180 | generate_report(sample_config, "today", verbose=True, taskrc=test_taskrc)
181 |
182 | mock_fetch.assert_called_once_with(test_taskrc)
183 | mock_days.assert_called_once_with("today", taskrc=test_taskrc)
184 |
185 | @patch('taskcheck.report.fetch_tasks')
186 | @patch('taskcheck.report.get_days_in_constraint')
187 | @patch('taskcheck.report.get_unplanned_tasks')
188 | def test_generate_report_with_unplanned(self, mock_unplanned, mock_days, mock_fetch, sample_config, test_taskrc):
189 | mock_fetch.return_value = []
190 | mock_days.return_value = [(2023, 12, 5)]
191 | mock_unplanned.return_value = [
192 | {
193 | "id": 2,
194 | "description": "Unplanned task",
195 | "urgency": 5.0,
196 | "project": "urgent"
197 | }
198 | ]
199 |
200 | # Should run without error
201 | generate_report(sample_config, "today", verbose=True, taskrc=test_taskrc)
202 |
203 | mock_unplanned.assert_called_once_with(sample_config["report"], [], taskrc=test_taskrc)
204 |
--------------------------------------------------------------------------------