+ def deserialize_tags(self, tags):
+ if isinstance(tags, six.string_types):
+ return tags.split(',') if tags else []
+ return tags or []
+
+ def serialize_depends(self, cur_dependencies):
+ # Return the list of uuids
+ return ','.join(task['uuid'] for task in cur_dependencies)
+
+ def deserialize_depends(self, raw_uuids):
+ raw_uuids = raw_uuids or '' # Convert None to empty string
+ uuids = raw_uuids.split(',')
+ return set(self.warrior.tasks.get(uuid=uuid) for uuid in uuids if uuid)
+
+
+class TaskResource(SerializingObject):
+ read_only_fields = []
+
+ def _load_data(self, data):
+ self._data = dict((key, self._deserialize(key, value))
+ for key, value in data.items())
+ # We need to use a copy for original data, so that changes
+ # are not propagated.
+ self._original_data = copy.deepcopy(self._data)
+
+ def _update_data(self, data, update_original=False):
+ """
+ Low level update of the internal _data dict. Data which are coming as
+ updates should already be serialized. If update_original is True, the
+ original_data dict is updated as well.
+ """
+ self._data.update(dict((key, self._deserialize(key, value))
+ for key, value in data.items()))
+
+ if update_original:
+ self._original_data = copy.deepcopy(self._data)
+
+
+ def __getitem__(self, key):
+ # This is a workaround to make TaskResource non-iterable
+ # over simple index-based iteration
+ try:
+ int(key)
+ raise StopIteration
+ except ValueError:
+ pass
+
+ if key not in self._data:
+ self._data[key] = self._deserialize(key, None)
+
+ return self._data.get(key)
+
+ def __setitem__(self, key, value):
+ if key in self.read_only_fields:
+ raise RuntimeError('Field \'%s\' is read-only' % key)
+ self._data[key] = value
+
+ def __str__(self):
+ s = six.text_type(self.__unicode__())
+ if not six.PY3:
+ s = s.encode('utf-8')
+ return s
+
+ def __repr__(self):
+ return str(self)
+
+
+class TaskAnnotation(TaskResource):
+ read_only_fields = ['entry', 'description']
+
+ def __init__(self, task, data={}):
+ self.task = task
+ self._load_data(data)
+
+ def remove(self):
+ self.task.remove_annotation(self)
+
+ def __unicode__(self):
+ return self['description']
+
+ def __eq__(self, other):
+ # consider 2 annotations equal if they belong to the same task, and
+ # their data dics are the same
+ return self.task == other.task and self._data == other._data
+
+ __repr__ = __unicode__
+
+
+class Task(TaskResource):
+ read_only_fields = ['id', 'entry', 'urgency', 'uuid', 'modified']
+
+ class DoesNotExist(Exception):
+ pass
+
+ class CompletedTask(Exception):
+ """
+ Raised when the operation cannot be performed on the completed task.
+ """
+ pass
+
+ class DeletedTask(Exception):
+ """
+ Raised when the operation cannot be performed on the deleted task.
+ """
+ pass
+
+ class NotSaved(Exception):
+ """
+ Raised when the operation cannot be performed on the task, because
+ it has not been saved to TaskWarrior yet.
+ """
+ pass
+
+ @classmethod
+ def from_input(cls, modify=False):
+ """
+ Creates a Task object, directly from the stdin, by reading one line.
+ If modify=True, two lines are used, first line interpreted as the
+ original state of the Task object, and second line as its new,
+ modified value. This is consistent with the TaskWarrior's hook
+ system.
+
+ Object created by this method should not be saved, deleted
+ or refreshed, as t could create a infinite loop. For this
+ reason, TaskWarrior instance is set to None.
+ """
+
+ # TaskWarrior instance is set to None
+ task = cls(None)
+
+ # Load the data from the input
+ task._load_data(json.loads(sys.stdin.readline().strip()))
+
+ # If this is a on-modify event, we are provided with additional
+ # line of input, which provides updated data
+ if modify:
+ task._update_data(json.loads(sys.stdin.readline().strip()))
+
+ return task
+
+ def __init__(self, warrior, **kwargs):
+ self.warrior = warrior
+
+ # Check that user is not able to set read-only value in __init__
+ for key in kwargs.keys():
+ if key in self.read_only_fields:
+ raise RuntimeError('Field \'%s\' is read-only' % key)
+
+ # We serialize the data in kwargs so that users of the library
+ # do not have to pass different data formats via __setitem__ and
+ # __init__ methods, that would be confusing
+
+ # Rather unfortunate syntax due to python2.6 comaptiblity
+ self._load_data(dict((key, self._serialize(key, value))
+ for (key, value) in six.iteritems(kwargs)))
+
+ def __unicode__(self):
+ return self['description']
+
+ def __eq__(self, other):
+ if self['uuid'] and other['uuid']:
+ # For saved Tasks, just define equality by equality of uuids
+ return self['uuid'] == other['uuid']
+ else:
+ # If the tasks are not saved, compare the actual instances
+ return id(self) == id(other)
+
+
+ def __hash__(self):
+ if self['uuid']:
+ # For saved Tasks, just define equality by equality of uuids
+ return self['uuid'].__hash__()
+ else:
+ # If the tasks are not saved, return hash of instance id
+ return id(self).__hash__()
+
+ @property
+ def _modified_fields(self):
+ writable_fields = set(self._data.keys()) - set(self.read_only_fields)
+ for key in writable_fields:
+ if self._data.get(key) != self._original_data.get(key):
+ yield key
+
+ @property
+ def _is_modified(self):
+ return bool(list(self._modified_fields))
+
+ @property
+ def completed(self):
+ return self['status'] == six.text_type('completed')
+
+ @property
+ def deleted(self):
+ return self['status'] == six.text_type('deleted')
+
+ @property
+ def waiting(self):
+ return self['status'] == six.text_type('waiting')
+
+ @property
+ def pending(self):
+ return self['status'] == six.text_type('pending')
+
+ @property
+ def saved(self):
+ return self['uuid'] is not None or self['id'] is not None
+
+ def serialize_depends(self, cur_dependencies):
+ # Check that all the tasks are saved
+ for task in cur_dependencies:
+ if not task.saved:
+ raise Task.NotSaved('Task \'%s\' needs to be saved before '
+ 'it can be set as dependency.' % task)
+
+ return super(Task, self).serialize_depends(cur_dependencies)
+
+ def format_depends(self):
+ # We need to generate added and removed dependencies list,
+ # since Taskwarrior does not accept redefining dependencies.
+
+ # This cannot be part of serialize_depends, since we need
+ # to keep a list of all depedencies in the _data dictionary,
+ # not just currently added/removed ones
+
+ old_dependencies = self._original_data.get('depends', set())
+
+ added = self['depends'] - old_dependencies
+ removed = old_dependencies - self['depends']
+
+ # Removed dependencies need to be prefixed with '-'
+ return 'depends:' + ','.join(
+ [t['uuid'] for t in added] +
+ ['-' + t['uuid'] for t in removed]
+ )
+
+ def format_description(self):
+ # Task version older than 2.4.0 ignores first word of the
+ # task description if description: prefix is used
+ if self.warrior.version < VERSION_2_4_0:
+ return self._data['description']
+ else:
+ return "description:'{0}'".format(self._data['description'] or '')
+