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

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