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

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