]> git.madduck.net Git - etc/taskwarrior.git/blob - docs/index.rst

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Docs: Update docs about reading .taskrc
[etc/taskwarrior.git] / docs / index.rst
1 Welcome to tasklib's documentation!
2 ===================================
3
4 tasklib is a Python library for interacting with taskwarrior_ databases, using
5 a queryset API similar to that of Django's ORM.
6
7 Supports Python 2.6, 2.7, 3.2, 3.3 and 3.4 with taskwarrior 2.1.x and above.
8 Older versions of taskwarrior are untested and may not work.
9
10 Requirements
11 ------------
12
13 * taskwarrior_ v2.1.x or above.
14
15 Installation
16 ------------
17
18 Install via pip (recommended)::
19
20     pip install tasklib
21
22 Or clone from github::
23
24     git clone https://github.com/robgolding63/tasklib.git
25     cd tasklib
26     python setup.py install
27
28 Initialization
29 --------------
30
31 Optionally initialize the ``TaskWarrior`` instance with ``data_location`` (the
32 database directory). If it doesn't already exist, this will be created
33 automatically unless ``create=False``.
34
35 The default location is the same as taskwarrior's::
36
37     >>> tw = TaskWarrior(data_location='~/.task', create=True)
38
39 The ``TaskWarrior`` instance will also use your .taskrc configuration (so that
40 it recognizes the same UDAs as your task binary, uses the same configuration,
41 etc.). To override the location of the .taskrc, use
42 ``taskrc_location=~/some/different/path``.
43
44 Creating Tasks
45 --------------
46
47 To create a task, simply create a new ``Task`` object::
48
49     >>> new_task = Task(tw, description="throw out the trash")
50
51 This task is not yet saved to TaskWarrior (same as in Django), not until
52 you call ``.save()`` method::
53
54     >>> new_task.save()
55
56 You can set any attribute as a keyword argument to the Task object::
57
58     >>> complex_task = Task(tw, description="finally fix the shower", due=datetime(2015,2,14,8,0,0), priority='H')
59
60 or by setting the attributes one by one::
61
62     >>> complex_task = Task(tw)
63     >>> complex_task['description'] = "finally fix the shower"
64     >>> complex_task['due'] = datetime(2015,2,14,8,0,0)
65     >>> complex_task['priority'] = 'H'
66
67 Modifying Task
68 --------------
69
70 To modify a created or retrieved ``Task`` object, use dictionary-like access::
71
72     >>> homework = tw.tasks.get(tags=['chores'])
73     >>> homework['project'] = 'Home'
74
75 The change is not propagated to the TaskWarrior until you run the ``save()`` method::
76
77     >>> homework.save()
78
79 Attributes, which map to native Python objects are converted. See Task Attributes section.
80
81 Task Attributes
82 ---------------
83
84 Attributes of task objects are accessible through indices, like so::
85
86     >>> task = tw.tasks.pending().get(tags__contain='work')  # There is only one pending task with 'work' tag
87     >>> task['description']
88     'Upgrade Ubuntu Server'
89     >>> task['id']
90     15
91     >>> task['due']
92     datetime.datetime(2015, 2, 5, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
93     >>> task['tags']
94     ['work', 'servers']
95
96 The following fields are deserialized into Python objects:
97
98 * ``due``, ``wait``, ``scheduled``, ``until``, ``entry``: deserialized to a ``datetime`` object
99 * ``annotations``: deserialized to a list of ``TaskAnnotation`` objects
100 * ``tags``: deserialized to a list of strings
101 * ``depends``: deserialized to a set of ``Task`` objects
102
103 Attributes should be set using the correct Python representation, which will be
104 serialized into the correct format when the task is saved.
105
106 Operations on Tasks
107 -------------------
108
109 After modifying one or more attributes, simple call ``save()`` to write those
110 changes to the database::
111
112     >>> task = tw.tasks.pending().get(tags__contain='work')
113     >>> task['due'] = datetime(year=2014, month=1, day=5)
114     >>> task.save()
115
116 To mark a task as complete, use ``done()``::
117
118     >>> task = tw.tasks.pending().get(tags__contain='work')
119     >>> task.done()
120     >>> len(tw.tasks.pending().filter(tags__contain='work'))
121     0
122
123 To delete a task, use ``delete()``::
124
125     >>> task = tw.tasks.get(description="task added by mistake")
126     >>> task.delete()
127
128 To update a task object with values from TaskWarrior database, use ``refresh()``. Example::
129
130     >>> task = Task(tw, description="learn to cook")
131     >>> task.save()
132     >>> task['id']
133     5
134     >>> task['tags']
135     []
136
137 Now, suppose the we modify the task using the TaskWarrior interface in another terminal::
138
139     $ task 5 modify +someday
140     Task 5 modified.
141
142 Switching back to the open python process::
143
144    >>> task['tags']
145    []
146    >>> task.refresh()
147    >>> task['tags']
148    ['someday']
149
150
151 Retrieving Tasks
152 ----------------
153
154 ``tw.tasks`` is a ``TaskQuerySet`` object which emulates the Django QuerySet
155 API. To get all tasks (including completed ones)::
156
157     >>> tw.tasks.all()
158     ['First task', 'Completed task', 'Deleted task', ...]
159
160 Filtering
161 ---------
162
163 Filter tasks using the same familiar syntax::
164
165     >>> tw.tasks.filter(status='pending', tags__contains=['work'])
166     ['Upgrade Ubuntu Server']
167
168 Filter arguments are passed to the ``task`` command (``__`` is replaced by
169 a period) so the above example is equivalent to the following command::
170
171     $ task status:pending tags.contain=work
172
173 Tasks can also be filtered using raw commands, like so::
174
175     >>> tw.tasks.filter('status:pending +work')
176     ['Upgrade Ubuntu Server']
177
178 Although this practice is discouraged, as by using raw commands you may lose
179 some of the portablility of your commands over different TaskWarrior versions.
180
181 However, you can mix raw commands with keyword filters, as in the given example::
182
183     >>> tw.tasks.filter('+BLOCKING', project='Home')  # Gets all blocking tasks in project Home
184     ['Fix the toilette']
185
186 This can be a neat way how to use syntax not yet supported by tasklib. The above
187 is excellent example, since virtual tags do not work the same way as the ordinary ones, that is::
188
189     >>> tw.tasks.filter(tags=['BLOCKING'])
190     >>> []
191
192 will not work.
193
194 There are built-in functions for retrieving pending & completed tasks::
195
196     >>> tw.tasks.pending().filter(tags__contain='work')
197     ['Upgrade Ubuntu Server']
198     >>> len(tw.tasks.completed())
199     227
200
201 Use ``get()`` to return the only task in a ``TaskQuerySet``, or raise an
202 exception::
203
204     >>> tw.tasks.get(tags__contain='work')['status']
205     'pending'
206     >>> tw.tasks.get(status='completed', tags__contains='work')  # Status of only task with the work tag is pending, so this should fail
207     Traceback (most recent call last):
208       File "<stdin>", line 1, in <module>
209       File "tasklib/task.py", line 224, in get
210         'Lookup parameters were {0}'.format(kwargs))
211     tasklib.task.DoesNotExist: Task matching query does not exist. Lookup parameters were {'status': 'completed', 'tags__contains': ['work']}
212     >>> tw.tasks.get(status='pending')
213     Traceback (most recent call last):
214       File "<stdin>", line 1, in <module>
215       File "tasklib/task.py", line 227, in get
216         'Lookup parameters were {1}'.format(num, kwargs))
217     ValueError: get() returned more than one Task -- it returned 23! Lookup parameters were {'status': 'pending'}
218
219 Additionally, since filters return ``TaskQuerySets`` you can stack filters on top of each other::
220
221     >>> home_tasks = tw.tasks.filter(project='Wife')
222     >>> home_tasks.filter(due__before=datetime(2015,2,14,14,14,14))  # What I have to do until Valentine's day
223     ['Prepare surprise birthday party']
224
225 Equality of Task objects
226 ------------------------
227
228 Two Tasks are considered equal if they have the same UUIDs::
229
230     >>> task1 = Task(tw, description="Pet the dog")
231     >>> task1.save()
232     >>> task2 = tw.tasks.get(description="Pet the dog")
233     >>> task1 == task2
234     True
235
236 If you compare the two unsaved tasks, they are considered equal only if it's the
237 same Python object::
238
239     >>> task1 = Task(tw, description="Pet the cat")
240     >>> task2 = Task(tw, description="Pet the cat")
241     >>> task1 == task2
242     False
243     >>> task3 = task1
244     >>> task3 == task1
245     True
246
247 Accessing original values
248 -------------------------
249
250 To access the saved state of the Task, use dict-like access using the
251 ``original`` attribute:
252
253     >>> t = Task(tw, description="tidy up")
254     >>> t.save()
255     >>> t['description'] = "tidy up the kitchen and bathroom"
256     >>> t['description']
257     "tidy up the kitchen and bathroom"
258     >>> t.original['description']
259     "tidy up"
260
261 When you save the task, original values are refreshed to reflect the
262 saved state of the task:
263
264     >>> t.save()
265     >>> t.original['description']
266     "tidy up the kitchen and bathroom"
267
268 Dealing with dates and time
269 ---------------------------
270
271 Any timestamp-like attributes of the tasks are converted to timezone-aware
272 datetime objects. To achieve this, Tasklib leverages ``pytz`` Python module,
273 which brings the Olsen timezone databaze to Python.
274
275 This shields you from annoying details of Daylight Saving Time shifts
276 or conversion between different timezones. For example, to list all the
277 tasks which are due midnight if you're currently in Berlin:
278
279     >>> myzone = pytz.timezone('Europe/Berlin')
280     >>> midnight = myzone.localize(datetime(2015,2,2,0,0,0))
281     >>> tw.tasks.filter(due__before=midnight)
282
283 However, this is still a little bit tedious. That's why TaskWarrior object
284 is capable of automatic timezone detection, using the ``tzlocal`` Python
285 module. If your system timezone is set to 'Europe/Berlin', following example
286 will work the same way as the previous one:
287
288     >>> tw.tasks.filter(due__before=datetime(2015,2,2,0,0,0))
289
290 You can also use simple dates when filtering:
291
292     >>> tw.tasks.filter(due__before=date(2015,2,2))
293
294 In such case, a 00:00:00 is used as the time component.
295
296 Of course, you can use datetime naive objects when initializing Task object
297 or assigning values to datetime atrributes:
298
299     >>> t = Task(tw, description="Buy new shoes", due=date(2015,2,5))
300     >>> t['due']
301     datetime.datetime(2015, 2, 5, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
302     >>> t['due'] = date(2015,2,6,15,15,15)
303     >>> t['due']
304     datetime.datetime(2015, 2, 6, 15, 15, 15, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
305
306 However, since timezone-aware and timezone-naive datetimes are not comparable
307 in Python, this can cause some unexpected behaviour:
308
309     >>> from datetime import datetime
310     >>> now = datetime.now()
311     >>> t = Task(tw, description="take out the trash now") 
312     >>> t['due'] = now
313     >>> now
314     datetime.datetime(2015, 2, 1, 19, 44, 4, 770001)
315     >>> t['due']
316     datetime.datetime(2015, 2, 1, 19, 44, 4, 770001, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
317     >>> t['due'] == now
318     Traceback (most recent call last):
319       File "<stdin>", line 1, in <module>
320       TypeError: can't compare offset-naive and offset-aware datetimes
321
322 If you want to compare datetime aware value with datetime naive value, you need
323 to localize the naive value first:
324
325     >>> from datetime import datetime
326     >>> from tasklib.task import local_zone
327     >>> now = local_zone.localize(datetime.now())
328     >>> t['due'] = now
329     >>> now
330     datetime.datetime(2015, 2, 1, 19, 44, 4, 770001, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
331     >>> t['due'] == now
332     True
333
334 Also, note that it does not matter whether the timezone aware datetime objects
335 are set in the same timezone:
336
337     >>> import pytz
338     >>> t['due']
339     datetime.datetime(2015, 2, 1, 19, 44, 4, 770001, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
340     >>> now.astimezone(pytz.utc)
341     datetime.datetime(2015, 2, 1, 18, 44, 4, 770001, tzinfo=<UTC>)
342     >>> t['due'] == now.astimezone(pytz.utc)
343     True
344
345
346 Working with annotations
347 ------------------------
348
349 Annotations of the tasks are represented in tasklib by ``TaskAnnotation`` objects. These
350 are much like ``Task`` objects, albeit very simplified.
351
352     >>> annotated_task = tw.tasks.get(description='Annotated task')
353     >>> annotated_task['annotations']
354     [Yeah, I am annotated!]
355
356 Annotations have only defined ``entry`` and ``description`` values::
357
358     >>> annotation = annotated_task['annotations'][0]
359     >>> annotation['entry']
360     datetime.datetime(2015, 1, 3, 21, 13, 55, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
361     >>> annotation['description']
362     u'Yeah, I am annotated!'
363
364 To add a annotation to a Task, use ``add_annotation()``::
365
366     >>> task = Task(tw, description="new task")
367     >>> task.add_annotation("we can annotate any task")
368     Traceback (most recent call last):
369       File "<stdin>", line 1, in <module>
370         File "build/bdist.linux-x86_64/egg/tasklib/task.py", line 355, in add_annotation
371     tasklib.task.NotSaved: Task needs to be saved to add annotation
372
373 However, Task needs to be saved before you can add a annotation to it::
374
375     >>> task.save()
376     >>> task.add_annotation("we can annotate saved tasks")
377     >>> task['annotations']
378     [we can annotate saved tasks]
379
380 To remove the annotation, pass its description to ``remove_annotation()`` method::
381
382     >>> task.remove_annotation("we can annotate saved tasks")
383
384 Alternatively, you can pass the ``TaskAnnotation`` object itself::
385
386     >>> task.remove_annotation(task['annotations'][0])
387
388
389 Running custom commands
390 -----------------------
391
392 To run a custom commands, use ``execute_command()`` method of ``TaskWarrior`` object::
393
394     >>> tw = TaskWarrior()
395     >>> tw.execute_command(['log', 'Finish high school.'])
396     [u'Logged task.']
397
398 You can use ``config_override`` keyword argument to specify a dictionary of configuration overrides::
399
400     >>> tw.execute_command(['3', 'done'], config_override={'gc': 'off'}) # Will mark 3 as completed and it will retain its ID
401
402 Setting custom configuration values
403 -----------------------------------
404
405 By default, TaskWarrior uses configuration values stored in your .taskrc.
406 To see what configuration value overrides are passed to each executed
407 task command, have a peek into ``config`` attribute of ``TaskWarrior`` object::
408
409     >>> tw.config
410     {'confirmation': 'no', 'data.location': '/home/tbabej/.task'}
411
412 To pass your own configuration overrides, you just need to update this dictionary::
413
414     >>> tw.config.update({'hooks': 'off'})  # tasklib will not trigger hooks
415
416 Creating hook scripts
417 ---------------------
418
419 From version 2.4.0, TaskWarrior has support for hook scripts. Tasklib provides
420 some very useful helpers to write those. With tasklib, writing these becomes
421 a breeze::
422
423     #!/usr/bin/python
424
425     from tasklib.task import Task
426     task = Task.from_input()
427     # ... <custom logic>
428     print task.export_data()
429
430 For example, plugin which would assign the priority "H" to any task containing
431 three exclamation marks in the description, would go like this::
432
433     #!/usr/bin/python
434
435     from tasklib.task import Task
436     task = Task.from_input()
437
438     if "!!!" in task['description']:
439         task['priority'] = "H"
440
441     print task.export_data()
442
443 Tasklib can automatically detect whether it's running in the ``on-modify`` event,
444 which provides more input than ``on-add`` event and reads the data accordingly.
445
446 This means the example above works both for ``on-add`` and ``on-modify`` events!
447
448 Consenquently, you can create just one hook file for both ``on-add`` and
449 ``on-modify`` events, and you just need to create a symlink for the other one.
450 This removes the need for maintaining two copies of the same code base and/or
451 boilerplate code.
452
453 In ``on-modify`` events, tasklib loads both the original version and the modified
454 version of the task to the returned ``Task`` object. To access the original data
455 (in read-only manner), use ``original`` dict-like attribute:
456
457     >>> t = Task.from_input()
458     >>> t['description']
459     "Modified description"
460     >>> t.original['description']
461     "Original description"
462
463 Working with UDAs
464 -----------------
465
466 Since TaskWarrior does read your .taskrc, you need not to define any UDAs
467 in the TaskWarrior's config dictionary, as described above. Suppose we have
468 a estimate UDA in the .taskrc::
469
470     uda.estimate.type = numeric
471
472 We can simply filter and create tasks using the estimate UDA out of the box::
473
474     >>> tw = TaskWarrior()
475     >>> task = Task(tw, description="Long task", estimate=1000)
476     >>> task.save()
477     >>> task['id']
478     1
479
480 This is saved as UDA in the TaskWarrior::
481
482     $ task 1 export
483     {"id":1,"description":"Long task","estimate":1000, ...}
484
485 We can also speficy UDAs as arguments in the TaskFilter::
486
487     >>> tw.tasks.filter(estimate=1000)
488     Long task
489
490 Syncing
491 -------
492
493 If you have configurated the needed config variables in your .taskrc, syncing
494 is as easy as::
495
496     >>> tw = TaskWarrior()
497     >>> tw.execute_command(['sync'])
498
499 If you want to use non-standard server/credentials, you'll need to provide configuration
500 overrides to the ``TaskWarrior`` instance. Update the ``config`` dictionary with the
501 values you desire to override, and then we can run the sync command using
502 the ``execute_command()`` method::
503
504     >>> tw = TaskWarrior()
505     >>> sync_config = {
506     ...     'taskd.certificate': '/home/tbabej/.task/tbabej.cert.pem',
507     ...     'taskd.credentials': 'Public/tbabej/34af54de-3cb2-4d3d-82be-33ddb8fd3e66',
508     ...     'taskd.server': 'task.server.com:53589',
509     ...     'taskd.ca': '/home/tbabej/.task/ca.cert.pem',
510     ...     'taskd.trust': 'ignore hostname'}
511     >>> tw.config.update(sync_config)
512     >>> tw.execute_command(['sync'])
513
514
515 .. _taskwarrior: http://taskwarrior.org