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

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