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