]> 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:

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