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

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