]> git.madduck.net Git - etc/taskwarrior.git/blob - tasklib/task.py

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:

Do not use mutable lists in function definitions
[etc/taskwarrior.git] / tasklib / task.py
1 from __future__ import print_function
2 import copy
3 import datetime
4 import json
5 import logging
6 import os
7 import pytz
8 import re
9 import six
10 import sys
11 import subprocess
12 import tzlocal
13
14 DATE_FORMAT = '%Y%m%dT%H%M%SZ'
15 DATE_FORMAT_CALC = '%Y-%m-%dT%H:%M:%S'
16 REPR_OUTPUT_SIZE = 10
17 PENDING = 'pending'
18 COMPLETED = 'completed'
19
20 VERSION_2_1_0 = six.u('2.1.0')
21 VERSION_2_2_0 = six.u('2.2.0')
22 VERSION_2_3_0 = six.u('2.3.0')
23 VERSION_2_4_0 = six.u('2.4.0')
24 VERSION_2_4_1 = six.u('2.4.1')
25 VERSION_2_4_2 = six.u('2.4.2')
26 VERSION_2_4_3 = six.u('2.4.3')
27
28 logger = logging.getLogger(__name__)
29 local_zone = tzlocal.get_localzone()
30
31
32 class TaskWarriorException(Exception):
33     pass
34
35
36 class ReadOnlyDictView(object):
37     """
38     Provides simplified read-only view upon dict object.
39     """
40
41     def __init__(self, viewed_dict):
42         self.viewed_dict = viewed_dict
43
44     def __getitem__(self, key):
45         return copy.deepcopy(self.viewed_dict.__getitem__(key))
46
47     def __contains__(self, k):
48         return self.viewed_dict.__contains__(k)
49
50     def __iter__(self):
51         for value in self.viewed_dict:
52             yield copy.deepcopy(value)
53
54     def __len__(self):
55         return len(self.viewed_dict)
56
57     def get(self, key, default=None):
58         return copy.deepcopy(self.viewed_dict.get(key, default))
59
60     def items(self):
61         return [copy.deepcopy(v) for v in self.viewed_dict.items()]
62
63     def values(self):
64         return [copy.deepcopy(v) for v in self.viewed_dict.values()]
65
66
67 class SerializingObject(object):
68     """
69     Common ancestor for TaskResource & TaskFilter, since they both
70     need to serialize arguments.
71
72     Serializing method should hold the following contract:
73       - any empty value (meaning removal of the attribute)
74         is deserialized into a empty string
75       - None denotes a empty value for any attribute
76
77     Deserializing method should hold the following contract:
78       - None denotes a empty value for any attribute (however,
79         this is here as a safeguard, TaskWarrior currently does
80         not export empty-valued attributes) if the attribute
81         is not iterable (e.g. list or set), in which case
82         a empty iterable should be used.
83
84     Normalizing methods should hold the following contract:
85       - They are used to validate and normalize the user input.
86         Any attribute value that comes from the user (during Task
87         initialization, assignign values to Task attributes, or
88         filtering by user-provided values of attributes) is first
89         validated and normalized using the normalize_{key} method.
90       - If validation or normalization fails, normalizer is expected
91         to raise ValueError.
92     """
93
94     def __init__(self, warrior):
95         self.warrior = warrior
96
97     def _deserialize(self, key, value):
98         hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
99                                lambda x: x if x != '' else None)
100         return hydrate_func(value)
101
102     def _serialize(self, key, value):
103         dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
104                                  lambda x: x if x is not None else '')
105         return dehydrate_func(value)
106
107     def _normalize(self, key, value):
108         """
109         Use normalize_<key> methods to normalize user input. Any user
110         input will be normalized at the moment it is used as filter,
111         or entered as a value of Task attribute.
112         """
113
114         # None value should not be converted by normalizer
115         if value is None:
116             return None
117
118         normalize_func = getattr(self, 'normalize_{0}'.format(key),
119                                  lambda x: x)
120
121         return normalize_func(value)
122
123     def timestamp_serializer(self, date):
124         if not date:
125             return ''
126
127         # Any serialized timestamp should be localized, we need to
128         # convert to UTC before converting to string (DATE_FORMAT uses UTC)
129         date = date.astimezone(pytz.utc)
130
131         return date.strftime(DATE_FORMAT)
132
133     def timestamp_deserializer(self, date_str):
134         if not date_str:
135             return None
136
137         # Return timestamp localized in the local zone
138         naive_timestamp = datetime.datetime.strptime(date_str, DATE_FORMAT)
139         localized_timestamp = pytz.utc.localize(naive_timestamp)
140         return localized_timestamp.astimezone(local_zone)
141
142     def serialize_entry(self, value):
143         return self.timestamp_serializer(value)
144
145     def deserialize_entry(self, value):
146         return self.timestamp_deserializer(value)
147
148     def normalize_entry(self, value):
149         return self.datetime_normalizer(value)
150
151     def serialize_modified(self, value):
152         return self.timestamp_serializer(value)
153
154     def deserialize_modified(self, value):
155         return self.timestamp_deserializer(value)
156
157     def normalize_modified(self, value):
158         return self.datetime_normalizer(value)
159
160     def serialize_start(self, value):
161         return self.timestamp_serializer(value)
162
163     def deserialize_start(self, value):
164         return self.timestamp_deserializer(value)
165
166     def normalize_start(self, value):
167         return self.datetime_normalizer(value)
168
169     def serialize_end(self, value):
170         return self.timestamp_serializer(value)
171
172     def deserialize_end(self, value):
173         return self.timestamp_deserializer(value)
174
175     def normalize_end(self, value):
176         return self.datetime_normalizer(value)
177
178     def serialize_due(self, value):
179         return self.timestamp_serializer(value)
180
181     def deserialize_due(self, value):
182         return self.timestamp_deserializer(value)
183
184     def normalize_due(self, value):
185         return self.datetime_normalizer(value)
186
187     def serialize_scheduled(self, value):
188         return self.timestamp_serializer(value)
189
190     def deserialize_scheduled(self, value):
191         return self.timestamp_deserializer(value)
192
193     def normalize_scheduled(self, value):
194         return self.datetime_normalizer(value)
195
196     def serialize_until(self, value):
197         return self.timestamp_serializer(value)
198
199     def deserialize_until(self, value):
200         return self.timestamp_deserializer(value)
201
202     def normalize_until(self, value):
203         return self.datetime_normalizer(value)
204
205     def serialize_wait(self, value):
206         return self.timestamp_serializer(value)
207
208     def deserialize_wait(self, value):
209         return self.timestamp_deserializer(value)
210
211     def normalize_wait(self, value):
212         return self.datetime_normalizer(value)
213
214     def serialize_annotations(self, value):
215         value = value if value is not None else []
216
217         # This may seem weird, but it's correct, we want to export
218         # a list of dicts as serialized value
219         serialized_annotations = [json.loads(annotation.export_data())
220                                   for annotation in value]
221         return serialized_annotations if serialized_annotations else ''
222
223     def deserialize_annotations(self, data):
224         return [TaskAnnotation(self, d) for d in data] if data else []
225
226     def serialize_tags(self, tags):
227         return ','.join(tags) if tags else ''
228
229     def deserialize_tags(self, tags):
230         if isinstance(tags, six.string_types):
231             return tags.split(',') if tags else []
232         return tags or []
233
234     def serialize_depends(self, value):
235         # Return the list of uuids
236         value = value if value is not None else set()
237         return ','.join(task['uuid'] for task in value)
238
239     def deserialize_depends(self, raw_uuids):
240         raw_uuids = raw_uuids or []  # Convert None to empty list
241
242         # TW 2.4.4 encodes list of dependencies as a single string
243         if type(raw_uuids) is not list:
244             uuids = raw_uuids.split(',')
245         # TW 2.4.5 and later exports them as a list, no conversion needed
246         else:
247             uuids = raw_uuids
248
249         return set(self.warrior.tasks.get(uuid=uuid) for uuid in uuids if uuid)
250
251     def datetime_normalizer(self, value):
252         """
253         Normalizes date/datetime value (considered to come from user input)
254         to localized datetime value. Following conversions happen:
255
256         naive date -> localized datetime with the same date, and time=midnight
257         naive datetime -> localized datetime with the same value
258         localized datetime -> localized datetime (no conversion)
259         """
260
261         if (isinstance(value, datetime.date)
262             and not isinstance(value, datetime.datetime)):
263             # Convert to local midnight
264             value_full = datetime.datetime.combine(value, datetime.time.min)
265             localized = local_zone.localize(value_full)
266         elif isinstance(value, datetime.datetime):
267             if value.tzinfo is None:
268                 # Convert to localized datetime object
269                 localized = local_zone.localize(value)
270             else:
271                 # If the value is already localized, there is no need to change
272                 # time zone at this point. Also None is a valid value too.
273                 localized = value
274         elif (isinstance(value, six.string_types)
275                 and self.warrior.version >= VERSION_2_4_0):
276             # For strings, use 'task calc' to evaluate the string to datetime
277             # available since TW 2.4.0
278             args = value.split()
279             result = self.warrior.execute_command(['calc'] + args)
280             naive = datetime.datetime.strptime(result[0], DATE_FORMAT_CALC)
281             localized = local_zone.localize(naive)
282         else:
283             raise ValueError("Provided value could not be converted to "
284                              "datetime, its type is not supported: {}"
285                              .format(type(value)))
286
287         return localized
288
289     def normalize_uuid(self, value):
290         # Enforce sane UUID
291         if not isinstance(value, six.string_types) or value == '':
292             raise ValueError("UUID must be a valid non-empty string, "
293                              "not: {}".format(value))
294
295         return value
296
297
298 class TaskResource(SerializingObject):
299     read_only_fields = []
300
301     def _load_data(self, data):
302         self._data = dict((key, self._deserialize(key, value))
303                           for key, value in data.items())
304         # We need to use a copy for original data, so that changes
305         # are not propagated.
306         self._original_data = copy.deepcopy(self._data)
307
308     def _update_data(self, data, update_original=False, remove_missing=False):
309         """
310         Low level update of the internal _data dict. Data which are coming as
311         updates should already be serialized. If update_original is True, the
312         original_data dict is updated as well.
313         """
314         self._data.update(dict((key, self._deserialize(key, value))
315                                for key, value in data.items()))
316
317         # In certain situations, we want to treat missing keys as removals
318         if remove_missing:
319             for key in set(self._data.keys()) - set(data.keys()):
320                 self._data[key] = None
321
322         if update_original:
323             self._original_data = copy.deepcopy(self._data)
324
325
326     def __getitem__(self, key):
327         # This is a workaround to make TaskResource non-iterable
328         # over simple index-based iteration
329         try:
330             int(key)
331             raise StopIteration
332         except ValueError:
333             pass
334
335         if key not in self._data:
336             self._data[key] = self._deserialize(key, None)
337
338         return self._data.get(key)
339
340     def __setitem__(self, key, value):
341         if key in self.read_only_fields:
342             raise RuntimeError('Field \'%s\' is read-only' % key)
343
344         # Normalize the user input before saving it
345         value = self._normalize(key, value)
346         self._data[key] = value
347
348     def __str__(self):
349         s = six.text_type(self.__unicode__())
350         if not six.PY3:
351             s = s.encode('utf-8')
352         return s
353
354     def __repr__(self):
355         return str(self)
356
357     def export_data(self):
358         """
359         Exports current data contained in the Task as JSON
360         """
361
362         # We need to remove spaces for TW-1504, use custom separators
363         data_tuples = ((key, self._serialize(key, value))
364                        for key, value in six.iteritems(self._data))
365
366         # Empty string denotes empty serialized value, we do not want
367         # to pass that to TaskWarrior.
368         data_tuples = filter(lambda t: t[1] is not '', data_tuples)
369         data = dict(data_tuples)
370         return json.dumps(data, separators=(',',':'))
371
372     @property
373     def _modified_fields(self):
374         writable_fields = set(self._data.keys()) - set(self.read_only_fields)
375         for key in writable_fields:
376             new_value = self._data.get(key)
377             old_value = self._original_data.get(key)
378
379             # Make sure not to mark data removal as modified field if the
380             # field originally had some empty value
381             if key in self._data and not new_value and not old_value:
382                 continue
383
384             if new_value != old_value:
385                 yield key
386
387     @property
388     def modified(self):
389         return bool(list(self._modified_fields))
390
391
392 class TaskAnnotation(TaskResource):
393     read_only_fields = ['entry', 'description']
394
395     def __init__(self, task, data={}):
396         self.task = task
397         self._load_data(data)
398         super(TaskAnnotation, self).__init__(task.warrior)
399
400     def remove(self):
401         self.task.remove_annotation(self)
402
403     def __unicode__(self):
404         return self['description']
405
406     def __eq__(self, other):
407         # consider 2 annotations equal if they belong to the same task, and
408         # their data dics are the same
409         return self.task == other.task and self._data == other._data
410
411     __repr__ = __unicode__
412
413
414 class Task(TaskResource):
415     read_only_fields = ['id', 'entry', 'urgency', 'uuid', 'modified']
416
417     class DoesNotExist(Exception):
418         pass
419
420     class CompletedTask(Exception):
421         """
422         Raised when the operation cannot be performed on the completed task.
423         """
424         pass
425
426     class DeletedTask(Exception):
427         """
428         Raised when the operation cannot be performed on the deleted task.
429         """
430         pass
431
432     class ActiveTask(Exception):
433         """
434         Raised when the operation cannot be performed on the active task.
435         """
436         pass
437
438     class InactiveTask(Exception):
439         """
440         Raised when the operation cannot be performed on an inactive task.
441         """
442         pass
443
444     class NotSaved(Exception):
445         """
446         Raised when the operation cannot be performed on the task, because
447         it has not been saved to TaskWarrior yet.
448         """
449         pass
450
451     @classmethod
452     def from_input(cls, input_file=sys.stdin, modify=None, warrior=None):
453         """
454         Creates a Task object, directly from the stdin, by reading one line.
455         If modify=True, two lines are used, first line interpreted as the
456         original state of the Task object, and second line as its new,
457         modified value. This is consistent with the TaskWarrior's hook
458         system.
459
460         Object created by this method should not be saved, deleted
461         or refreshed, as t could create a infinite loop. For this
462         reason, TaskWarrior instance is set to None.
463
464         Input_file argument can be used to specify the input file,
465         but defaults to sys.stdin.
466         """
467
468         # Detect the hook type if not given directly
469         name = os.path.basename(sys.argv[0])
470         modify = name.startswith('on-modify') if modify is None else modify
471
472         # Create the TaskWarrior instance if none passed
473         if warrior is None:
474             hook_parent_dir = os.path.dirname(os.path.dirname(sys.argv[0]))
475             warrior = TaskWarrior(data_location=hook_parent_dir)
476
477         # TaskWarrior instance is set to None
478         task = cls(warrior)
479
480         # Load the data from the input
481         task._load_data(json.loads(input_file.readline().strip()))
482
483         # If this is a on-modify event, we are provided with additional
484         # line of input, which provides updated data
485         if modify:
486             task._update_data(json.loads(input_file.readline().strip()),
487                               remove_missing=True)
488
489         return task
490
491     def __init__(self, warrior, **kwargs):
492         super(Task, self).__init__(warrior)
493
494         # Check that user is not able to set read-only value in __init__
495         for key in kwargs.keys():
496             if key in self.read_only_fields:
497                 raise RuntimeError('Field \'%s\' is read-only' % key)
498
499         # We serialize the data in kwargs so that users of the library
500         # do not have to pass different data formats via __setitem__ and
501         # __init__ methods, that would be confusing
502
503         # Rather unfortunate syntax due to python2.6 comaptiblity
504         self._data = dict((key, self._normalize(key, value))
505                           for (key, value) in six.iteritems(kwargs))
506         self._original_data = copy.deepcopy(self._data)
507
508         # Provide read only access to the original data
509         self.original = ReadOnlyDictView(self._original_data)
510
511     def __unicode__(self):
512         return self['description']
513
514     def __eq__(self, other):
515         if self['uuid'] and other['uuid']:
516             # For saved Tasks, just define equality by equality of uuids
517             return self['uuid'] == other['uuid']
518         else:
519             # If the tasks are not saved, compare the actual instances
520             return id(self) == id(other)
521
522
523     def __hash__(self):
524         if self['uuid']:
525             # For saved Tasks, just define equality by equality of uuids
526             return self['uuid'].__hash__()
527         else:
528             # If the tasks are not saved, return hash of instance id
529             return id(self).__hash__()
530
531     @property
532     def completed(self):
533         return self['status'] == six.text_type('completed')
534
535     @property
536     def deleted(self):
537         return self['status'] == six.text_type('deleted')
538
539     @property
540     def waiting(self):
541         return self['status'] == six.text_type('waiting')
542
543     @property
544     def pending(self):
545         return self['status'] == six.text_type('pending')
546
547     @property
548     def active(self):
549         return self['start'] is not None
550
551     @property
552     def saved(self):
553         return self['uuid'] is not None or self['id'] is not None
554
555     def serialize_depends(self, cur_dependencies):
556         # Check that all the tasks are saved
557         for task in (cur_dependencies or set()):
558             if not task.saved:
559                 raise Task.NotSaved('Task \'%s\' needs to be saved before '
560                                     'it can be set as dependency.' % task)
561
562         return super(Task, self).serialize_depends(cur_dependencies)
563
564     def format_depends(self):
565         # We need to generate added and removed dependencies list,
566         # since Taskwarrior does not accept redefining dependencies.
567
568         # This cannot be part of serialize_depends, since we need
569         # to keep a list of all depedencies in the _data dictionary,
570         # not just currently added/removed ones
571
572         old_dependencies = self._original_data.get('depends', set())
573
574         added = self['depends'] - old_dependencies
575         removed = old_dependencies - self['depends']
576
577         # Removed dependencies need to be prefixed with '-'
578         return 'depends:' + ','.join(
579                 [t['uuid'] for t in added] +
580                 ['-' + t['uuid'] for t in removed]
581             )
582
583     def format_description(self):
584         # Task version older than 2.4.0 ignores first word of the
585         # task description if description: prefix is used
586         if self.warrior.version < VERSION_2_4_0:
587             return self._data['description']
588         else:
589             return six.u("description:'{0}'").format(self._data['description'] or '')
590
591     def delete(self):
592         if not self.saved:
593             raise Task.NotSaved("Task needs to be saved before it can be deleted")
594
595         # Refresh the status, and raise exception if the task is deleted
596         self.refresh(only_fields=['status'])
597
598         if self.deleted:
599             raise Task.DeletedTask("Task was already deleted")
600
601         self.warrior.execute_command([self['uuid'], 'delete'])
602
603         # Refresh the status again, so that we have updated info stored
604         self.refresh(only_fields=['status', 'start', 'end'])
605
606     def start(self):
607         if not self.saved:
608             raise Task.NotSaved("Task needs to be saved before it can be started")
609
610         # Refresh, and raise exception if task is already completed/deleted
611         self.refresh(only_fields=['status'])
612
613         if self.completed:
614             raise Task.CompletedTask("Cannot start a completed task")
615         elif self.deleted:
616             raise Task.DeletedTask("Deleted task cannot be started")
617         elif self.active:
618             raise Task.ActiveTask("Task is already active")
619
620         self.warrior.execute_command([self['uuid'], 'start'])
621
622         # Refresh the status again, so that we have updated info stored
623         self.refresh(only_fields=['status', 'start'])
624
625     def stop(self):
626         if not self.saved:
627             raise Task.NotSaved("Task needs to be saved before it can be stopped")
628
629         # Refresh, and raise exception if task is already completed/deleted
630         self.refresh(only_fields=['status'])
631
632         if not self.active:
633             raise Task.InactiveTask("Cannot stop an inactive task")
634
635         self.warrior.execute_command([self['uuid'], 'stop'])
636
637         # Refresh the status again, so that we have updated info stored
638         self.refresh(only_fields=['status', 'start'])
639
640     def done(self):
641         if not self.saved:
642             raise Task.NotSaved("Task needs to be saved before it can be completed")
643
644         # Refresh, and raise exception if task is already completed/deleted
645         self.refresh(only_fields=['status'])
646
647         if self.completed:
648             raise Task.CompletedTask("Cannot complete a completed task")
649         elif self.deleted:
650             raise Task.DeletedTask("Deleted task cannot be completed")
651
652         # Older versions of TW do not stop active task at completion
653         if self.warrior.version < VERSION_2_4_0 and self.active:
654             self.stop()
655
656         self.warrior.execute_command([self['uuid'], 'done'])
657
658         # Refresh the status again, so that we have updated info stored
659         self.refresh(only_fields=['status', 'start', 'end'])
660
661     def save(self):
662         if self.saved and not self.modified:
663             return
664
665         args = [self['uuid'], 'modify'] if self.saved else ['add']
666         args.extend(self._get_modified_fields_as_args())
667         output = self.warrior.execute_command(args)
668
669         # Parse out the new ID, if the task is being added for the first time
670         if not self.saved:
671             id_lines = [l for l in output if l.startswith('Created task ')]
672
673             # Complain loudly if it seems that more tasks were created
674             # Should not happen
675             if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
676                 raise TaskWarriorException("Unexpected output when creating "
677                                            "task: %s" % '\n'.join(id_lines))
678
679             # Circumvent the ID storage, since ID is considered read-only
680             identifier = id_lines[0].split(' ')[2].rstrip('.')
681
682             # Identifier can be either ID or UUID for completed tasks
683             try:
684                 self._data['id'] = int(identifier)
685             except ValueError:
686                 self._data['uuid'] = identifier
687
688         # Refreshing is very important here, as not only modification time
689         # is updated, but arbitrary attribute may have changed due hooks
690         # altering the data before saving
691         self.refresh(after_save=True)
692
693     def add_annotation(self, annotation):
694         if not self.saved:
695             raise Task.NotSaved("Task needs to be saved to add annotation")
696
697         args = [self['uuid'], 'annotate', annotation]
698         self.warrior.execute_command(args)
699         self.refresh(only_fields=['annotations'])
700
701     def remove_annotation(self, annotation):
702         if not self.saved:
703             raise Task.NotSaved("Task needs to be saved to remove annotation")
704
705         if isinstance(annotation, TaskAnnotation):
706             annotation = annotation['description']
707         args = [self['uuid'], 'denotate', annotation]
708         self.warrior.execute_command(args)
709         self.refresh(only_fields=['annotations'])
710
711     def _get_modified_fields_as_args(self):
712         args = []
713
714         def add_field(field):
715             # Add the output of format_field method to args list (defaults to
716             # field:value)
717             serialized_value = self._serialize(field, self._data[field])
718
719             # Empty values should not be enclosed in quotation marks, see
720             # TW-1510
721             if serialized_value is '':
722                 escaped_serialized_value = ''
723             else:
724                 escaped_serialized_value = six.u("'{0}'").format(serialized_value)
725
726             format_default = lambda: six.u("{0}:{1}").format(field,
727                                                       escaped_serialized_value)
728
729             format_func = getattr(self, 'format_{0}'.format(field),
730                                   format_default)
731
732             args.append(format_func())
733
734         # If we're modifying saved task, simply pass on all modified fields
735         if self.saved:
736             for field in self._modified_fields:
737                 add_field(field)
738         # For new tasks, pass all fields that make sense
739         else:
740             for field in self._data.keys():
741                 if field in self.read_only_fields:
742                     continue
743                 add_field(field)
744
745         return args
746
747     def refresh(self, only_fields=None, after_save=False):
748         # Raise error when trying to refresh a task that has not been saved
749         if not self.saved:
750             raise Task.NotSaved("Task needs to be saved to be refreshed")
751
752         # We need to use ID as backup for uuid here for the refreshes
753         # of newly saved tasks. Any other place in the code is fine
754         # with using UUID only.
755         args = [self['uuid'] or self['id'], 'export']
756         output = self.warrior.execute_command(args)
757
758         def valid(output):
759             return len(output) == 1 and output[0].startswith('{')
760
761         # For older TW versions attempt to uniquely locate the task
762         # using the data we have if it has been just saved.
763         # This can happen when adding a completed task on older TW versions.
764         if (not valid(output) and self.warrior.version < six.text_type(u'2.4.5')
765                 and after_save):
766
767             # Make a copy, removing ID and UUID. It's most likely invalid
768             # (ID 0) if it failed to match a unique task.
769             data = copy.deepcopy(self._data)
770             data.pop('id', None)
771             data.pop('uuid', None)
772
773             taskfilter = TaskFilter(self.warrior)
774             for key, value in data.items():
775                 taskfilter.add_filter_param(key, value)
776
777             output = self.warrior.execute_command(['export', '--'] +
778                 taskfilter.get_filter_params())
779
780         # If more than 1 task has been matched still, raise an exception
781         if not valid(output):
782             raise TaskWarriorException(
783                 "Unique identifiers {0} with description: {1} matches "
784                 "multiple tasks: {2}".format(
785                 self['uuid'] or self['id'], self['description'], output)
786             )
787
788         new_data = json.loads(output[0])
789         if only_fields:
790             to_update = dict(
791                 [(k, new_data.get(k)) for k in only_fields])
792             self._update_data(to_update, update_original=True)
793         else:
794             self._load_data(new_data)
795
796 class TaskFilter(SerializingObject):
797     """
798     A set of parameters to filter the task list with.
799     """
800
801     def __init__(self, warrior, filter_params=None):
802         self.filter_params = filter_params or []
803         super(TaskFilter, self).__init__(warrior)
804
805     def add_filter(self, filter_str):
806         self.filter_params.append(filter_str)
807
808     def add_filter_param(self, key, value):
809         key = key.replace('__', '.')
810
811         # Replace the value with empty string, since that is the
812         # convention in TW for empty values
813         attribute_key = key.split('.')[0]
814
815         # Since this is user input, we need to normalize before we serialize
816         value = self._normalize(attribute_key, value)
817         value = self._serialize(attribute_key, value)
818
819         # If we are filtering by uuid:, do not use uuid keyword
820         # due to TW-1452 bug
821         if key == 'uuid':
822             self.filter_params.insert(0, value)
823         else:
824             # Surround value with aphostrophes unless it's a empty string
825             value = "'%s'" % value if value else ''
826
827             # We enforce equality match by using 'is' (or 'none') modifier
828             # Without using this syntax, filter fails due to TW-1479
829             modifier = '.is' if value else '.none'
830             key = key + modifier if '.' not in key else key
831
832             self.filter_params.append(six.u("{0}:{1}").format(key, value))
833
834     def get_filter_params(self):
835         return [f for f in self.filter_params if f]
836
837     def clone(self):
838         c = self.__class__(self.warrior)
839         c.filter_params = list(self.filter_params)
840         return c
841
842
843 class TaskQuerySet(object):
844     """
845     Represents a lazy lookup for a task objects.
846     """
847
848     def __init__(self, warrior=None, filter_obj=None):
849         self.warrior = warrior
850         self._result_cache = None
851         self.filter_obj = filter_obj or TaskFilter(warrior)
852
853     def __deepcopy__(self, memo):
854         """
855         Deep copy of a QuerySet doesn't populate the cache
856         """
857         obj = self.__class__()
858         for k, v in self.__dict__.items():
859             if k in ('_iter', '_result_cache'):
860                 obj.__dict__[k] = None
861             else:
862                 obj.__dict__[k] = copy.deepcopy(v, memo)
863         return obj
864
865     def __repr__(self):
866         data = list(self[:REPR_OUTPUT_SIZE + 1])
867         if len(data) > REPR_OUTPUT_SIZE:
868             data[-1] = "...(remaining elements truncated)..."
869         return repr(data)
870
871     def __len__(self):
872         if self._result_cache is None:
873             self._result_cache = list(self)
874         return len(self._result_cache)
875
876     def __iter__(self):
877         if self._result_cache is None:
878             self._result_cache = self._execute()
879         return iter(self._result_cache)
880
881     def __getitem__(self, k):
882         if self._result_cache is None:
883             self._result_cache = list(self)
884         return self._result_cache.__getitem__(k)
885
886     def __bool__(self):
887         if self._result_cache is not None:
888             return bool(self._result_cache)
889         try:
890             next(iter(self))
891         except StopIteration:
892             return False
893         return True
894
895     def __nonzero__(self):
896         return type(self).__bool__(self)
897
898     def _clone(self, klass=None, **kwargs):
899         if klass is None:
900             klass = self.__class__
901         filter_obj = self.filter_obj.clone()
902         c = klass(warrior=self.warrior, filter_obj=filter_obj)
903         c.__dict__.update(kwargs)
904         return c
905
906     def _execute(self):
907         """
908         Fetch the tasks which match the current filters.
909         """
910         return self.warrior.filter_tasks(self.filter_obj)
911
912     def all(self):
913         """
914         Returns a new TaskQuerySet that is a copy of the current one.
915         """
916         return self._clone()
917
918     def pending(self):
919         return self.filter(status=PENDING)
920
921     def completed(self):
922         return self.filter(status=COMPLETED)
923
924     def filter(self, *args, **kwargs):
925         """
926         Returns a new TaskQuerySet with the given filters added.
927         """
928         clone = self._clone()
929         for f in args:
930             clone.filter_obj.add_filter(f)
931         for key, value in kwargs.items():
932             clone.filter_obj.add_filter_param(key, value)
933         return clone
934
935     def get(self, **kwargs):
936         """
937         Performs the query and returns a single object matching the given
938         keyword arguments.
939         """
940         clone = self.filter(**kwargs)
941         num = len(clone)
942         if num == 1:
943             return clone._result_cache[0]
944         if not num:
945             raise Task.DoesNotExist(
946                 'Task matching query does not exist. '
947                 'Lookup parameters were {0}'.format(kwargs))
948         raise ValueError(
949             'get() returned more than one Task -- it returned {0}! '
950             'Lookup parameters were {1}'.format(num, kwargs))
951
952
953 class TaskWarrior(object):
954     def __init__(self, data_location=None, create=True, taskrc_location='~/.taskrc'):
955         self.taskrc_location = os.path.expanduser(taskrc_location)
956
957         # If taskrc does not exist, pass / to use defaults and avoid creating
958         # dummy .taskrc file by TaskWarrior
959         if not os.path.exists(self.taskrc_location):
960             self.taskrc_location = '/'
961
962         self.version = self._get_version()
963         self.config = {
964             'confirmation': 'no',
965             'dependency.confirmation': 'no',  # See TW-1483 or taskrc man page
966             'recurrence.confirmation': 'no',  # Necessary for modifying R tasks
967
968             # Defaults to on since 2.4.5, we expect off during parsing
969             'json.array': 'off',
970
971             # 2.4.3 onwards supports 0 as infite bulk, otherwise set just
972             # arbitrary big number which is likely to be large enough
973             'bulk': 0 if self.version >= VERSION_2_4_3 else 100000,
974         }
975
976         # Set data.location override if passed via kwarg
977         if data_location is not None:
978             data_location = os.path.expanduser(data_location)
979             if create and not os.path.exists(data_location):
980                 os.makedirs(data_location)
981             self.config['data.location'] = data_location
982
983         self.tasks = TaskQuerySet(self)
984
985     def _get_command_args(self, args, config_override={}):
986         command_args = ['task', 'rc:{0}'.format(self.taskrc_location)]
987         config = self.config.copy()
988         config.update(config_override)
989         for item in config.items():
990             command_args.append('rc.{0}={1}'.format(*item))
991         command_args.extend(map(six.text_type, args))
992         return command_args
993
994     def _get_version(self):
995         p = subprocess.Popen(
996                 ['task', '--version'],
997                 stdout=subprocess.PIPE,
998                 stderr=subprocess.PIPE)
999         stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
1000         return stdout.strip('\n')
1001
1002     def get_config(self):
1003         raw_output = self.execute_command(
1004                 ['show'],
1005                 config_override={'verbose': 'nothing'}
1006             )
1007
1008         config = dict()
1009         config_regex = re.compile(r'^(?P<key>[^\s]+)\s+(?P<value>[^\s].+$)')
1010
1011         for line in raw_output:
1012             match = config_regex.match(line)
1013             if match:
1014                 config[match.group('key')] = match.group('value').strip()
1015
1016         return config
1017
1018     def execute_command(self, args, config_override={}, allow_failure=True,
1019                         return_all=False):
1020         command_args = self._get_command_args(
1021             args, config_override=config_override)
1022         logger.debug(' '.join(command_args))
1023         p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
1024                              stderr=subprocess.PIPE)
1025         stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
1026         if p.returncode and allow_failure:
1027             if stderr.strip():
1028                 error_msg = stderr.strip()
1029             else:
1030                 error_msg = stdout.strip()
1031             raise TaskWarriorException(error_msg)
1032
1033         # Return all whole triplet only if explicitly asked for
1034         if not return_all:
1035             return stdout.rstrip().split('\n')
1036         else:
1037             return (stdout.rstrip().split('\n'),
1038                     stderr.rstrip().split('\n'),
1039                     p.returncode)
1040
1041     def enforce_recurrence(self):
1042         # Run arbitrary report command which will trigger generation
1043         # of recurrent tasks.
1044
1045         # Only necessary for TW up to 2.4.1, fixed in 2.4.2.
1046         if self.version < VERSION_2_4_2:
1047             self.execute_command(['next'], allow_failure=False)
1048
1049     def filter_tasks(self, filter_obj):
1050         self.enforce_recurrence()
1051         args = ['export', '--'] + filter_obj.get_filter_params()
1052         tasks = []
1053         for line in self.execute_command(args):
1054             if line:
1055                 data = line.strip(',')
1056                 try:
1057                     filtered_task = Task(self)
1058                     filtered_task._load_data(json.loads(data))
1059                     tasks.append(filtered_task)
1060                 except ValueError:
1061                     raise TaskWarriorException('Invalid JSON: %s' % data)
1062         return tasks
1063
1064     def merge_with(self, path, push=False):
1065         path = path.rstrip('/') + '/'
1066         self.execute_command(['merge', path], config_override={
1067             'merge.autopush': 'yes' if push else 'no',
1068         })
1069
1070     def undo(self):
1071         self.execute_command(['undo'])