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.
   1 from __future__ import print_function
 
  13 DATE_FORMAT = '%Y%m%dT%H%M%SZ'
 
  14 DATE_FORMAT_CALC = '%Y-%m-%dT%H:%M:%S'
 
  17 COMPLETED = 'completed'
 
  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')
 
  27 logger = logging.getLogger(__name__)
 
  28 local_zone = tzlocal.get_localzone()
 
  31 class TaskWarriorException(Exception):
 
  35 class ReadOnlyDictView(object):
 
  37     Provides simplified read-only view upon dict object.
 
  40     def __init__(self, viewed_dict):
 
  41         self.viewed_dict = viewed_dict
 
  43     def __getitem__(self, key):
 
  44         return copy.deepcopy(self.viewed_dict.__getitem__(key))
 
  46     def __contains__(self, k):
 
  47         return self.viewed_dict.__contains__(k)
 
  50         for value in self.viewed_dict:
 
  51             yield copy.deepcopy(value)
 
  54         return len(self.viewed_dict)
 
  56     def get(self, key, default=None):
 
  57         return copy.deepcopy(self.viewed_dict.get(key, default))
 
  60         return [copy.deepcopy(v) for v in self.viewed_dict.items()]
 
  63         return [copy.deepcopy(v) for v in self.viewed_dict.values()]
 
  66 class SerializingObject(object):
 
  68     Common ancestor for TaskResource & TaskFilter, since they both
 
  69     need to serialize arguments.
 
  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
 
  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.
 
  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
 
  93     def __init__(self, warrior):
 
  94         self.warrior = warrior
 
  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)
 
 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)
 
 106     def _normalize(self, key, value):
 
 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.
 
 113         # None value should not be converted by normalizer
 
 117         normalize_func = getattr(self, 'normalize_{0}'.format(key),
 
 120         return normalize_func(value)
 
 122     def timestamp_serializer(self, date):
 
 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)
 
 130         return date.strftime(DATE_FORMAT)
 
 132     def timestamp_deserializer(self, date_str):
 
 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)
 
 141     def serialize_entry(self, value):
 
 142         return self.timestamp_serializer(value)
 
 144     def deserialize_entry(self, value):
 
 145         return self.timestamp_deserializer(value)
 
 147     def normalize_entry(self, value):
 
 148         return self.datetime_normalizer(value)
 
 150     def serialize_modified(self, value):
 
 151         return self.timestamp_serializer(value)
 
 153     def deserialize_modified(self, value):
 
 154         return self.timestamp_deserializer(value)
 
 156     def normalize_modified(self, value):
 
 157         return self.datetime_normalizer(value)
 
 159     def serialize_start(self, value):
 
 160         return self.timestamp_serializer(value)
 
 162     def deserialize_start(self, value):
 
 163         return self.timestamp_deserializer(value)
 
 165     def normalize_start(self, value):
 
 166         return self.datetime_normalizer(value)
 
 168     def serialize_end(self, value):
 
 169         return self.timestamp_serializer(value)
 
 171     def deserialize_end(self, value):
 
 172         return self.timestamp_deserializer(value)
 
 174     def normalize_end(self, value):
 
 175         return self.datetime_normalizer(value)
 
 177     def serialize_due(self, value):
 
 178         return self.timestamp_serializer(value)
 
 180     def deserialize_due(self, value):
 
 181         return self.timestamp_deserializer(value)
 
 183     def normalize_due(self, value):
 
 184         return self.datetime_normalizer(value)
 
 186     def serialize_scheduled(self, value):
 
 187         return self.timestamp_serializer(value)
 
 189     def deserialize_scheduled(self, value):
 
 190         return self.timestamp_deserializer(value)
 
 192     def normalize_scheduled(self, value):
 
 193         return self.datetime_normalizer(value)
 
 195     def serialize_until(self, value):
 
 196         return self.timestamp_serializer(value)
 
 198     def deserialize_until(self, value):
 
 199         return self.timestamp_deserializer(value)
 
 201     def normalize_until(self, value):
 
 202         return self.datetime_normalizer(value)
 
 204     def serialize_wait(self, value):
 
 205         return self.timestamp_serializer(value)
 
 207     def deserialize_wait(self, value):
 
 208         return self.timestamp_deserializer(value)
 
 210     def normalize_wait(self, value):
 
 211         return self.datetime_normalizer(value)
 
 213     def serialize_annotations(self, value):
 
 214         value = value if value is not None else []
 
 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 ''
 
 222     def deserialize_annotations(self, data):
 
 223         return [TaskAnnotation(self, d) for d in data] if data else []
 
 225     def serialize_tags(self, tags):
 
 226         return ','.join(tags) if tags else ''
 
 228     def deserialize_tags(self, tags):
 
 229         if isinstance(tags, six.string_types):
 
 230             return tags.split(',') if tags else []
 
 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)
 
 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)
 
 243     def datetime_normalizer(self, value):
 
 245         Normalizes date/datetime value (considered to come from user input)
 
 246         to localized datetime value. Following conversions happen:
 
 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)
 
 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)
 
 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.
 
 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
 
 271             result = self.warrior.execute_command(['calc'] + args)
 
 272             naive = datetime.datetime.strptime(result[0], DATE_FORMAT_CALC)
 
 273             localized = local_zone.localize(naive)
 
 275             raise ValueError("Provided value could not be converted to "
 
 276                              "datetime, its type is not supported: {}"
 
 277                              .format(type(value)))
 
 281     def normalize_uuid(self, value):
 
 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))
 
 290 class TaskResource(SerializingObject):
 
 291     read_only_fields = []
 
 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)
 
 300     def _update_data(self, data, update_original=False):
 
 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.
 
 306         self._data.update(dict((key, self._deserialize(key, value))
 
 307                                for key, value in data.items()))
 
 310             self._original_data = copy.deepcopy(self._data)
 
 313     def __getitem__(self, key):
 
 314         # This is a workaround to make TaskResource non-iterable
 
 315         # over simple index-based iteration
 
 322         if key not in self._data:
 
 323             self._data[key] = self._deserialize(key, None)
 
 325         return self._data.get(key)
 
 327     def __setitem__(self, key, value):
 
 328         if key in self.read_only_fields:
 
 329             raise RuntimeError('Field \'%s\' is read-only' % key)
 
 331         # Normalize the user input before saving it
 
 332         value = self._normalize(key, value)
 
 333         self._data[key] = value
 
 336         s = six.text_type(self.__unicode__())
 
 338             s = s.encode('utf-8')
 
 344     def export_data(self):
 
 346         Exports current data contained in the Task as JSON
 
 349         # We need to remove spaces for TW-1504, use custom separators
 
 350         data_tuples = ((key, self._serialize(key, value))
 
 351                        for key, value in six.iteritems(self._data))
 
 353         # Empty string denotes empty serialized value, we do not want
 
 354         # to pass that to TaskWarrior.
 
 355         data_tuples = filter(lambda t: t[1] is not '', data_tuples)
 
 356         data = dict(data_tuples)
 
 357         return json.dumps(data, separators=(',',':'))
 
 360     def _modified_fields(self):
 
 361         writable_fields = set(self._data.keys()) - set(self.read_only_fields)
 
 362         for key in writable_fields:
 
 363             new_value = self._data.get(key)
 
 364             old_value = self._original_data.get(key)
 
 366             # Make sure not to mark data removal as modified field if the
 
 367             # field originally had some empty value
 
 368             if key in self._data and not new_value and not old_value:
 
 371             if new_value != old_value:
 
 376         return bool(list(self._modified_fields))
 
 379 class TaskAnnotation(TaskResource):
 
 380     read_only_fields = ['entry', 'description']
 
 382     def __init__(self, task, data={}):
 
 384         self._load_data(data)
 
 385         super(TaskAnnotation, self).__init__(task.warrior)
 
 388         self.task.remove_annotation(self)
 
 390     def __unicode__(self):
 
 391         return self['description']
 
 393     def __eq__(self, other):
 
 394         # consider 2 annotations equal if they belong to the same task, and
 
 395         # their data dics are the same
 
 396         return self.task == other.task and self._data == other._data
 
 398     __repr__ = __unicode__
 
 401 class Task(TaskResource):
 
 402     read_only_fields = ['id', 'entry', 'urgency', 'uuid', 'modified']
 
 404     class DoesNotExist(Exception):
 
 407     class CompletedTask(Exception):
 
 409         Raised when the operation cannot be performed on the completed task.
 
 413     class DeletedTask(Exception):
 
 415         Raised when the operation cannot be performed on the deleted task.
 
 419     class InactiveTask(Exception):
 
 421         Raised when the operation cannot be performed on an inactive task.
 
 425     class NotSaved(Exception):
 
 427         Raised when the operation cannot be performed on the task, because
 
 428         it has not been saved to TaskWarrior yet.
 
 433     def from_input(cls, input_file=sys.stdin, modify=None, warrior=None):
 
 435         Creates a Task object, directly from the stdin, by reading one line.
 
 436         If modify=True, two lines are used, first line interpreted as the
 
 437         original state of the Task object, and second line as its new,
 
 438         modified value. This is consistent with the TaskWarrior's hook
 
 441         Object created by this method should not be saved, deleted
 
 442         or refreshed, as t could create a infinite loop. For this
 
 443         reason, TaskWarrior instance is set to None.
 
 445         Input_file argument can be used to specify the input file,
 
 446         but defaults to sys.stdin.
 
 449         # Detect the hook type if not given directly
 
 450         name = os.path.basename(sys.argv[0])
 
 451         modify = name.startswith('on-modify') if modify is None else modify
 
 453         # Create the TaskWarrior instance if none passed
 
 455             hook_parent_dir = os.path.dirname(os.path.dirname(sys.argv[0]))
 
 456             warrior = TaskWarrior(data_location=hook_parent_dir)
 
 458         # TaskWarrior instance is set to None
 
 461         # Load the data from the input
 
 462         task._load_data(json.loads(input_file.readline().strip()))
 
 464         # If this is a on-modify event, we are provided with additional
 
 465         # line of input, which provides updated data
 
 467             task._update_data(json.loads(input_file.readline().strip()))
 
 471     def __init__(self, warrior, **kwargs):
 
 472         super(Task, self).__init__(warrior)
 
 474         # Check that user is not able to set read-only value in __init__
 
 475         for key in kwargs.keys():
 
 476             if key in self.read_only_fields:
 
 477                 raise RuntimeError('Field \'%s\' is read-only' % key)
 
 479         # We serialize the data in kwargs so that users of the library
 
 480         # do not have to pass different data formats via __setitem__ and
 
 481         # __init__ methods, that would be confusing
 
 483         # Rather unfortunate syntax due to python2.6 comaptiblity
 
 484         self._data = dict((key, self._normalize(key, value))
 
 485                           for (key, value) in six.iteritems(kwargs))
 
 486         self._original_data = copy.deepcopy(self._data)
 
 488         # Provide read only access to the original data
 
 489         self.original = ReadOnlyDictView(self._original_data)
 
 491     def __unicode__(self):
 
 492         return self['description']
 
 494     def __eq__(self, other):
 
 495         if self['uuid'] and other['uuid']:
 
 496             # For saved Tasks, just define equality by equality of uuids
 
 497             return self['uuid'] == other['uuid']
 
 499             # If the tasks are not saved, compare the actual instances
 
 500             return id(self) == id(other)
 
 505             # For saved Tasks, just define equality by equality of uuids
 
 506             return self['uuid'].__hash__()
 
 508             # If the tasks are not saved, return hash of instance id
 
 509             return id(self).__hash__()
 
 513         return self['status'] == six.text_type('completed')
 
 517         return self['status'] == six.text_type('deleted')
 
 521         return self['status'] == six.text_type('waiting')
 
 525         return self['status'] == six.text_type('pending')
 
 529         return self['start'] is not None
 
 533         return self['uuid'] is not None or self['id'] is not None
 
 535     def serialize_depends(self, cur_dependencies):
 
 536         # Check that all the tasks are saved
 
 537         for task in (cur_dependencies or set()):
 
 539                 raise Task.NotSaved('Task \'%s\' needs to be saved before '
 
 540                                     'it can be set as dependency.' % task)
 
 542         return super(Task, self).serialize_depends(cur_dependencies)
 
 544     def format_depends(self):
 
 545         # We need to generate added and removed dependencies list,
 
 546         # since Taskwarrior does not accept redefining dependencies.
 
 548         # This cannot be part of serialize_depends, since we need
 
 549         # to keep a list of all depedencies in the _data dictionary,
 
 550         # not just currently added/removed ones
 
 552         old_dependencies = self._original_data.get('depends', set())
 
 554         added = self['depends'] - old_dependencies
 
 555         removed = old_dependencies - self['depends']
 
 557         # Removed dependencies need to be prefixed with '-'
 
 558         return 'depends:' + ','.join(
 
 559                 [t['uuid'] for t in added] +
 
 560                 ['-' + t['uuid'] for t in removed]
 
 563     def format_description(self):
 
 564         # Task version older than 2.4.0 ignores first word of the
 
 565         # task description if description: prefix is used
 
 566         if self.warrior.version < VERSION_2_4_0:
 
 567             return self._data['description']
 
 569             return six.u("description:'{0}'").format(self._data['description'] or '')
 
 573             raise Task.NotSaved("Task needs to be saved before it can be deleted")
 
 575         # Refresh the status, and raise exception if the task is deleted
 
 576         self.refresh(only_fields=['status'])
 
 579             raise Task.DeletedTask("Task was already deleted")
 
 581         self.warrior.execute_command([self['uuid'], 'delete'])
 
 583         # Refresh the status again, so that we have updated info stored
 
 584         self.refresh(only_fields=['status', 'start', 'end'])
 
 588             raise Task.NotSaved("Task needs to be saved before it can be started")
 
 590         # Refresh, and raise exception if task is already completed/deleted
 
 591         self.refresh(only_fields=['status'])
 
 594             raise Task.CompletedTask("Cannot start a completed task")
 
 596             raise Task.DeletedTask("Deleted task cannot be started")
 
 598         self.warrior.execute_command([self['uuid'], 'start'])
 
 600         # Refresh the status again, so that we have updated info stored
 
 601         self.refresh(only_fields=['status', 'start'])
 
 605             raise Task.NotSaved("Task needs to be saved before it can be stopped")
 
 607         # Refresh, and raise exception if task is already completed/deleted
 
 608         self.refresh(only_fields=['status'])
 
 611             raise Task.InactiveTask("Cannot stop an inactive task")
 
 613         self.warrior.execute_command([self['uuid'], 'stop'])
 
 615         # Refresh the status again, so that we have updated info stored
 
 616         self.refresh(only_fields=['status', 'start'])
 
 620             raise Task.NotSaved("Task needs to be saved before it can be completed")
 
 622         # Refresh, and raise exception if task is already completed/deleted
 
 623         self.refresh(only_fields=['status'])
 
 626             raise Task.CompletedTask("Cannot complete a completed task")
 
 628             raise Task.DeletedTask("Deleted task cannot be completed")
 
 630         self.warrior.execute_command([self['uuid'], 'done'])
 
 632         # Refresh the status again, so that we have updated info stored
 
 633         self.refresh(only_fields=['status', 'start', 'end'])
 
 636         if self.saved and not self.modified:
 
 639         args = [self['uuid'], 'modify'] if self.saved else ['add']
 
 640         args.extend(self._get_modified_fields_as_args())
 
 641         output = self.warrior.execute_command(args)
 
 643         # Parse out the new ID, if the task is being added for the first time
 
 645             id_lines = [l for l in output if l.startswith('Created task ')]
 
 647             # Complain loudly if it seems that more tasks were created
 
 649             if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
 
 650                 raise TaskWarriorException("Unexpected output when creating "
 
 651                                            "task: %s" % '\n'.join(id_lines))
 
 653             # Circumvent the ID storage, since ID is considered read-only
 
 654             self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
 
 656         # Refreshing is very important here, as not only modification time
 
 657         # is updated, but arbitrary attribute may have changed due hooks
 
 658         # altering the data before saving
 
 661     def add_annotation(self, annotation):
 
 663             raise Task.NotSaved("Task needs to be saved to add annotation")
 
 665         args = [self['uuid'], 'annotate', annotation]
 
 666         self.warrior.execute_command(args)
 
 667         self.refresh(only_fields=['annotations'])
 
 669     def remove_annotation(self, annotation):
 
 671             raise Task.NotSaved("Task needs to be saved to remove annotation")
 
 673         if isinstance(annotation, TaskAnnotation):
 
 674             annotation = annotation['description']
 
 675         args = [self['uuid'], 'denotate', annotation]
 
 676         self.warrior.execute_command(args)
 
 677         self.refresh(only_fields=['annotations'])
 
 679     def _get_modified_fields_as_args(self):
 
 682         def add_field(field):
 
 683             # Add the output of format_field method to args list (defaults to
 
 685             serialized_value = self._serialize(field, self._data[field])
 
 687             # Empty values should not be enclosed in quotation marks, see
 
 689             if serialized_value is '':
 
 690                 escaped_serialized_value = ''
 
 692                 escaped_serialized_value = six.u("'{0}'").format(serialized_value)
 
 694             format_default = lambda: six.u("{0}:{1}").format(field,
 
 695                                                       escaped_serialized_value)
 
 697             format_func = getattr(self, 'format_{0}'.format(field),
 
 700             args.append(format_func())
 
 702         # If we're modifying saved task, simply pass on all modified fields
 
 704             for field in self._modified_fields:
 
 706         # For new tasks, pass all fields that make sense
 
 708             for field in self._data.keys():
 
 709                 if field in self.read_only_fields:
 
 715     def refresh(self, only_fields=[]):
 
 716         # Raise error when trying to refresh a task that has not been saved
 
 718             raise Task.NotSaved("Task needs to be saved to be refreshed")
 
 720         # We need to use ID as backup for uuid here for the refreshes
 
 721         # of newly saved tasks. Any other place in the code is fine
 
 722         # with using UUID only.
 
 723         args = [self['uuid'] or self['id'], 'export']
 
 724         new_data = json.loads(self.warrior.execute_command(args)[0])
 
 727                 [(k, new_data.get(k)) for k in only_fields])
 
 728             self._update_data(to_update, update_original=True)
 
 730             self._load_data(new_data)
 
 732 class TaskFilter(SerializingObject):
 
 734     A set of parameters to filter the task list with.
 
 737     def __init__(self, warrior, filter_params=[]):
 
 738         self.filter_params = filter_params
 
 739         super(TaskFilter, self).__init__(warrior)
 
 741     def add_filter(self, filter_str):
 
 742         self.filter_params.append(filter_str)
 
 744     def add_filter_param(self, key, value):
 
 745         key = key.replace('__', '.')
 
 747         # Replace the value with empty string, since that is the
 
 748         # convention in TW for empty values
 
 749         attribute_key = key.split('.')[0]
 
 751         # Since this is user input, we need to normalize before we serialize
 
 752         value = self._normalize(attribute_key, value)
 
 753         value = self._serialize(attribute_key, value)
 
 755         # If we are filtering by uuid:, do not use uuid keyword
 
 758             self.filter_params.insert(0, value)
 
 760             # Surround value with aphostrophes unless it's a empty string
 
 761             value = "'%s'" % value if value else ''
 
 763             # We enforce equality match by using 'is' (or 'none') modifier
 
 764             # Without using this syntax, filter fails due to TW-1479
 
 765             modifier = '.is' if value else '.none'
 
 766             key = key + modifier if '.' not in key else key
 
 768             self.filter_params.append(six.u("{0}:{1}").format(key, value))
 
 770     def get_filter_params(self):
 
 771         return [f for f in self.filter_params if f]
 
 774         c = self.__class__(self.warrior)
 
 775         c.filter_params = list(self.filter_params)
 
 779 class TaskQuerySet(object):
 
 781     Represents a lazy lookup for a task objects.
 
 784     def __init__(self, warrior=None, filter_obj=None):
 
 785         self.warrior = warrior
 
 786         self._result_cache = None
 
 787         self.filter_obj = filter_obj or TaskFilter(warrior)
 
 789     def __deepcopy__(self, memo):
 
 791         Deep copy of a QuerySet doesn't populate the cache
 
 793         obj = self.__class__()
 
 794         for k, v in self.__dict__.items():
 
 795             if k in ('_iter', '_result_cache'):
 
 796                 obj.__dict__[k] = None
 
 798                 obj.__dict__[k] = copy.deepcopy(v, memo)
 
 802         data = list(self[:REPR_OUTPUT_SIZE + 1])
 
 803         if len(data) > REPR_OUTPUT_SIZE:
 
 804             data[-1] = "...(remaining elements truncated)..."
 
 808         if self._result_cache is None:
 
 809             self._result_cache = list(self)
 
 810         return len(self._result_cache)
 
 813         if self._result_cache is None:
 
 814             self._result_cache = self._execute()
 
 815         return iter(self._result_cache)
 
 817     def __getitem__(self, k):
 
 818         if self._result_cache is None:
 
 819             self._result_cache = list(self)
 
 820         return self._result_cache.__getitem__(k)
 
 823         if self._result_cache is not None:
 
 824             return bool(self._result_cache)
 
 827         except StopIteration:
 
 831     def __nonzero__(self):
 
 832         return type(self).__bool__(self)
 
 834     def _clone(self, klass=None, **kwargs):
 
 836             klass = self.__class__
 
 837         filter_obj = self.filter_obj.clone()
 
 838         c = klass(warrior=self.warrior, filter_obj=filter_obj)
 
 839         c.__dict__.update(kwargs)
 
 844         Fetch the tasks which match the current filters.
 
 846         return self.warrior.filter_tasks(self.filter_obj)
 
 850         Returns a new TaskQuerySet that is a copy of the current one.
 
 855         return self.filter(status=PENDING)
 
 858         return self.filter(status=COMPLETED)
 
 860     def filter(self, *args, **kwargs):
 
 862         Returns a new TaskQuerySet with the given filters added.
 
 864         clone = self._clone()
 
 866             clone.filter_obj.add_filter(f)
 
 867         for key, value in kwargs.items():
 
 868             clone.filter_obj.add_filter_param(key, value)
 
 871     def get(self, **kwargs):
 
 873         Performs the query and returns a single object matching the given
 
 876         clone = self.filter(**kwargs)
 
 879             return clone._result_cache[0]
 
 881             raise Task.DoesNotExist(
 
 882                 'Task matching query does not exist. '
 
 883                 'Lookup parameters were {0}'.format(kwargs))
 
 885             'get() returned more than one Task -- it returned {0}! '
 
 886             'Lookup parameters were {1}'.format(num, kwargs))
 
 889 class TaskWarrior(object):
 
 890     def __init__(self, data_location=None, create=True, taskrc_location='~/.taskrc'):
 
 891         self.taskrc_location = os.path.expanduser(taskrc_location)
 
 893         # If taskrc does not exist, pass / to use defaults and avoid creating
 
 894         # dummy .taskrc file by TaskWarrior
 
 895         if not os.path.exists(self.taskrc_location):
 
 896             self.taskrc_location = '/'
 
 898         self.version = self._get_version()
 
 900             'confirmation': 'no',
 
 901             'dependency.confirmation': 'no',  # See TW-1483 or taskrc man page
 
 902             'recurrence.confirmation': 'no',  # Necessary for modifying R tasks
 
 903             # 2.4.3 onwards supports 0 as infite bulk, otherwise set just
 
 904             # arbitrary big number which is likely to be large enough
 
 905             'bulk': 0 if self.version >= VERSION_2_4_3 else 100000,
 
 908         # Set data.location override if passed via kwarg
 
 909         if data_location is not None:
 
 910             data_location = os.path.expanduser(data_location)
 
 911             if create and not os.path.exists(data_location):
 
 912                 os.makedirs(data_location)
 
 913             self.config['data.location'] = data_location
 
 915         self.tasks = TaskQuerySet(self)
 
 917     def _get_command_args(self, args, config_override={}):
 
 918         command_args = ['task', 'rc:{0}'.format(self.taskrc_location)]
 
 919         config = self.config.copy()
 
 920         config.update(config_override)
 
 921         for item in config.items():
 
 922             command_args.append('rc.{0}={1}'.format(*item))
 
 923         command_args.extend(map(six.text_type, args))
 
 926     def _get_version(self):
 
 927         p = subprocess.Popen(
 
 928                 ['task', '--version'],
 
 929                 stdout=subprocess.PIPE,
 
 930                 stderr=subprocess.PIPE)
 
 931         stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
 
 932         return stdout.strip('\n')
 
 934     def execute_command(self, args, config_override={}, allow_failure=True,
 
 936         command_args = self._get_command_args(
 
 937             args, config_override=config_override)
 
 938         logger.debug(' '.join(command_args))
 
 939         p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
 
 940                              stderr=subprocess.PIPE)
 
 941         stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
 
 942         if p.returncode and allow_failure:
 
 944                 error_msg = stderr.strip()
 
 946                 error_msg = stdout.strip()
 
 947             raise TaskWarriorException(error_msg)
 
 949         # Return all whole triplet only if explicitly asked for
 
 951             return stdout.rstrip().split('\n')
 
 953             return (stdout.rstrip().split('\n'),
 
 954                     stderr.rstrip().split('\n'),
 
 957     def enforce_recurrence(self):
 
 958         # Run arbitrary report command which will trigger generation
 
 959         # of recurrent tasks.
 
 961         # Only necessary for TW up to 2.4.1, fixed in 2.4.2.
 
 962         if self.version < VERSION_2_4_2:
 
 963             self.execute_command(['next'], allow_failure=False)
 
 965     def filter_tasks(self, filter_obj):
 
 966         self.enforce_recurrence()
 
 967         args = ['export', '--'] + filter_obj.get_filter_params()
 
 969         for line in self.execute_command(args):
 
 971                 data = line.strip(',')
 
 973                     filtered_task = Task(self)
 
 974                     filtered_task._load_data(json.loads(data))
 
 975                     tasks.append(filtered_task)
 
 977                     raise TaskWarriorException('Invalid JSON: %s' % data)
 
 980     def merge_with(self, path, push=False):
 
 981         path = path.rstrip('/') + '/'
 
 982         self.execute_command(['merge', path], config_override={
 
 983             'merge.autopush': 'yes' if push else 'no',
 
 987         self.execute_command(['undo'])