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
10 DATE_FORMAT = '%Y%m%dT%H%M%SZ'
13 COMPLETED = 'completed'
15 VERSION_2_1_0 = six.u('2.1.0')
16 VERSION_2_2_0 = six.u('2.2.0')
17 VERSION_2_3_0 = six.u('2.3.0')
18 VERSION_2_4_0 = six.u('2.4.0')
20 logger = logging.getLogger(__name__)
23 class TaskWarriorException(Exception):
27 class SerializingObject(object):
29 Common ancestor for TaskResource & TaskFilter, since they both
30 need to serialize arguments.
33 def _deserialize(self, key, value):
34 hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
35 lambda x: x if x != '' else None)
36 return hydrate_func(value)
38 def _serialize(self, key, value):
39 dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
40 lambda x: x if x is not None else '')
41 return dehydrate_func(value)
43 def timestamp_serializer(self, date):
46 return date.strftime(DATE_FORMAT)
48 def timestamp_deserializer(self, date_str):
51 return datetime.datetime.strptime(date_str, DATE_FORMAT)
53 def serialize_entry(self, value):
54 return self.timestamp_serializer(value)
56 def deserialize_entry(self, value):
57 return self.timestamp_deserializer(value)
59 def serialize_modified(self, value):
60 return self.timestamp_serializer(value)
62 def deserialize_modified(self, value):
63 return self.timestamp_deserializer(value)
65 def serialize_due(self, value):
66 return self.timestamp_serializer(value)
68 def deserialize_due(self, value):
69 return self.timestamp_deserializer(value)
71 def serialize_scheduled(self, value):
72 return self.timestamp_serializer(value)
74 def deserialize_scheduled(self, value):
75 return self.timestamp_deserializer(value)
77 def serialize_until(self, value):
78 return self.timestamp_serializer(value)
80 def deserialize_until(self, value):
81 return self.timestamp_deserializer(value)
83 def serialize_wait(self, value):
84 return self.timestamp_serializer(value)
86 def deserialize_wait(self, value):
87 return self.timestamp_deserializer(value)
89 def deserialize_annotations(self, data):
90 return [TaskAnnotation(self, d) for d in data] if data else []
92 def serialize_tags(self, tags):
93 return ','.join(tags) if tags else ''
95 def deserialize_tags(self, tags):
96 if isinstance(tags, basestring):
97 return tags.split(',') if tags else []
100 def serialize_depends(self, cur_dependencies):
101 # Return the list of uuids
102 return ','.join(task['uuid'] for task in cur_dependencies)
104 def deserialize_depends(self, raw_uuids):
105 raw_uuids = raw_uuids or '' # Convert None to empty string
106 uuids = raw_uuids.split(',')
107 return set(self.warrior.tasks.get(uuid=uuid) for uuid in uuids if uuid)
110 class TaskResource(SerializingObject):
111 read_only_fields = []
113 def _load_data(self, data):
115 # We need to use a copy for original data, so that changes
116 # are not propagated. Shallow copy is alright, since data dict uses only
117 # primitive data types
118 self._original_data = data.copy()
120 def _update_data(self, data, update_original=False):
122 Low level update of the internal _data dict. Data which are coming as
123 updates should already be serialized. If update_original is True, the
124 original_data dict is updated as well.
127 self._data.update(data)
130 self._original_data.update(data)
132 def __getitem__(self, key):
133 # This is a workaround to make TaskResource non-iterable
134 # over simple index-based iteration
141 return self._deserialize(key, self._data.get(key))
143 def __setitem__(self, key, value):
144 if key in self.read_only_fields:
145 raise RuntimeError('Field \'%s\' is read-only' % key)
146 self._data[key] = self._serialize(key, value)
149 s = six.text_type(self.__unicode__())
151 s = s.encode('utf-8')
158 class TaskAnnotation(TaskResource):
159 read_only_fields = ['entry', 'description']
161 def __init__(self, task, data={}):
163 self._load_data(data)
166 self.task.remove_annotation(self)
168 def __unicode__(self):
169 return self['description']
171 __repr__ = __unicode__
174 class Task(TaskResource):
175 read_only_fields = ['id', 'entry', 'urgency', 'uuid', 'modified']
177 class DoesNotExist(Exception):
180 class CompletedTask(Exception):
182 Raised when the operation cannot be performed on the completed task.
186 class DeletedTask(Exception):
188 Raised when the operation cannot be performed on the deleted task.
192 class NotSaved(Exception):
194 Raised when the operation cannot be performed on the task, because
195 it has not been saved to TaskWarrior yet.
199 def __init__(self, warrior, **kwargs):
200 self.warrior = warrior
202 # Check that user is not able to set read-only value in __init__
203 for key in kwargs.keys():
204 if key in self.read_only_fields:
205 raise RuntimeError('Field \'%s\' is read-only' % key)
207 # We serialize the data in kwargs so that users of the library
208 # do not have to pass different data formats via __setitem__ and
209 # __init__ methods, that would be confusing
211 # Rather unfortunate syntax due to python2.6 comaptiblity
212 self._load_data(dict((key, self._serialize(key, value))
213 for (key, value) in six.iteritems(kwargs)))
215 def __unicode__(self):
216 return self['description']
218 def __eq__(self, other):
219 if self['uuid'] and other['uuid']:
220 # For saved Tasks, just define equality by equality of uuids
221 return self['uuid'] == other['uuid']
223 # If the tasks are not saved, compare the actual instances
224 return id(self) == id(other)
229 # For saved Tasks, just define equality by equality of uuids
230 return self['uuid'].__hash__()
232 # If the tasks are not saved, return hash of instance id
233 return id(self).__hash__()
236 def _modified_fields(self):
237 writable_fields = set(self._data.keys()) - set(self.read_only_fields)
238 for key in writable_fields:
239 if self._data.get(key) != self._original_data.get(key):
244 return self['status'] == six.text_type('completed')
248 return self['status'] == six.text_type('deleted')
252 return self['status'] == six.text_type('waiting')
256 return self['status'] == six.text_type('pending')
260 return self['uuid'] is not None or self['id'] is not None
262 def serialize_depends(self, cur_dependencies):
263 # Check that all the tasks are saved
264 for task in cur_dependencies:
266 raise Task.NotSaved('Task \'%s\' needs to be saved before '
267 'it can be set as dependency.' % task)
269 return super(Task, self).serialize_depends(cur_dependencies)
271 def format_depends(self):
272 # We need to generate added and removed dependencies list,
273 # since Taskwarrior does not accept redefining dependencies.
275 # This cannot be part of serialize_depends, since we need
276 # to keep a list of all depedencies in the _data dictionary,
277 # not just currently added/removed ones
279 old_dependencies_raw = self._original_data.get('depends','')
280 old_dependencies = self.deserialize_depends(old_dependencies_raw)
282 added = self['depends'] - old_dependencies
283 removed = old_dependencies - self['depends']
285 # Removed dependencies need to be prefixed with '-'
286 return 'depends:' + ','.join(
287 [t['uuid'] for t in added] +
288 ['-' + t['uuid'] for t in removed]
291 def format_description(self):
292 # Task version older than 2.4.0 ignores first word of the
293 # task description if description: prefix is used
294 if self.warrior.version < VERSION_2_4_0:
295 return self._data['description']
297 return "description:'{0}'".format(self._data['description'] or '')
301 raise Task.NotSaved("Task needs to be saved before it can be deleted")
303 # Refresh the status, and raise exception if the task is deleted
304 self.refresh(only_fields=['status'])
307 raise Task.DeletedTask("Task was already deleted")
309 self.warrior.execute_command([self['uuid'], 'delete'])
311 # Refresh the status again, so that we have updated info stored
312 self.refresh(only_fields=['status'])
317 raise Task.NotSaved("Task needs to be saved before it can be completed")
319 # Refresh, and raise exception if task is already completed/deleted
320 self.refresh(only_fields=['status'])
323 raise Task.CompletedTask("Cannot complete a completed task")
325 raise Task.DeletedTask("Deleted task cannot be completed")
327 self.warrior.execute_command([self['uuid'], 'done'])
329 # Refresh the status again, so that we have updated info stored
330 self.refresh(only_fields=['status'])
333 args = [self['uuid'], 'modify'] if self.saved else ['add']
334 args.extend(self._get_modified_fields_as_args())
335 output = self.warrior.execute_command(args)
337 # Parse out the new ID, if the task is being added for the first time
339 id_lines = [l for l in output if l.startswith('Created task ')]
341 # Complain loudly if it seems that more tasks were created
343 if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
344 raise TaskWarriorException("Unexpected output when creating "
345 "task: %s" % '\n'.join(id_lines))
347 # Circumvent the ID storage, since ID is considered read-only
348 self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
352 def add_annotation(self, annotation):
354 raise Task.NotSaved("Task needs to be saved to add annotation")
356 args = [self['uuid'], 'annotate', annotation]
357 self.warrior.execute_command(args)
358 self.refresh(only_fields=['annotations'])
360 def remove_annotation(self, annotation):
362 raise Task.NotSaved("Task needs to be saved to remove annotation")
364 if isinstance(annotation, TaskAnnotation):
365 annotation = annotation['description']
366 args = [self['uuid'], 'denotate', annotation]
367 self.warrior.execute_command(args)
368 self.refresh(only_fields=['annotations'])
370 def _get_modified_fields_as_args(self):
373 def add_field(field):
374 # Add the output of format_field method to args list (defaults to
376 format_default = lambda k: "{0}:'{1}'".format(k, self._data[k] or '')
377 format_func = getattr(self, 'format_{0}'.format(field),
378 lambda: format_default(field))
379 args.append(format_func())
381 # If we're modifying saved task, simply pass on all modified fields
383 for field in self._modified_fields:
385 # For new tasks, pass all fields that make sense
387 for field in self._data.keys():
388 if field in self.read_only_fields:
394 def refresh(self, only_fields=[]):
395 # Raise error when trying to refresh a task that has not been saved
397 raise Task.NotSaved("Task needs to be saved to be refreshed")
399 # We need to use ID as backup for uuid here for the refreshes
400 # of newly saved tasks. Any other place in the code is fine
401 # with using UUID only.
402 args = [self['uuid'] or self['id'], 'export']
403 new_data = json.loads(self.warrior.execute_command(args)[0])
406 [(k, new_data.get(k)) for k in only_fields])
407 self._update_data(to_update, update_original=True)
409 self._load_data(new_data)
412 class TaskFilter(SerializingObject):
414 A set of parameters to filter the task list with.
417 def __init__(self, filter_params=[]):
418 self.filter_params = filter_params
420 def add_filter(self, filter_str):
421 self.filter_params.append(filter_str)
423 def add_filter_param(self, key, value):
424 key = key.replace('__', '.')
426 # Replace the value with empty string, since that is the
427 # convention in TW for empty values
428 attribute_key = key.split('.')[0]
429 value = self._serialize(attribute_key, value)
431 # If we are filtering by uuid:, do not use uuid keyword
434 self.filter_params.insert(0, value)
436 # We enforce equality match by using is keyword
437 # Also, without using this syntax, filter fails due to TW-1479
438 self.filter_params.append("{0}.is:'{1}'".format(key, value))
440 def get_filter_params(self):
441 return [f for f in self.filter_params if f]
445 c.filter_params = list(self.filter_params)
449 class TaskQuerySet(object):
451 Represents a lazy lookup for a task objects.
454 def __init__(self, warrior=None, filter_obj=None):
455 self.warrior = warrior
456 self._result_cache = None
457 self.filter_obj = filter_obj or TaskFilter()
459 def __deepcopy__(self, memo):
461 Deep copy of a QuerySet doesn't populate the cache
463 obj = self.__class__()
464 for k, v in self.__dict__.items():
465 if k in ('_iter', '_result_cache'):
466 obj.__dict__[k] = None
468 obj.__dict__[k] = copy.deepcopy(v, memo)
472 data = list(self[:REPR_OUTPUT_SIZE + 1])
473 if len(data) > REPR_OUTPUT_SIZE:
474 data[-1] = "...(remaining elements truncated)..."
478 if self._result_cache is None:
479 self._result_cache = list(self)
480 return len(self._result_cache)
483 if self._result_cache is None:
484 self._result_cache = self._execute()
485 return iter(self._result_cache)
487 def __getitem__(self, k):
488 if self._result_cache is None:
489 self._result_cache = list(self)
490 return self._result_cache.__getitem__(k)
493 if self._result_cache is not None:
494 return bool(self._result_cache)
497 except StopIteration:
501 def __nonzero__(self):
502 return type(self).__bool__(self)
504 def _clone(self, klass=None, **kwargs):
506 klass = self.__class__
507 filter_obj = self.filter_obj.clone()
508 c = klass(warrior=self.warrior, filter_obj=filter_obj)
509 c.__dict__.update(kwargs)
514 Fetch the tasks which match the current filters.
516 return self.warrior.filter_tasks(self.filter_obj)
520 Returns a new TaskQuerySet that is a copy of the current one.
525 return self.filter(status=PENDING)
528 return self.filter(status=COMPLETED)
530 def filter(self, *args, **kwargs):
532 Returns a new TaskQuerySet with the given filters added.
534 clone = self._clone()
536 clone.filter_obj.add_filter(f)
537 for key, value in kwargs.items():
538 clone.filter_obj.add_filter_param(key, value)
541 def get(self, **kwargs):
543 Performs the query and returns a single object matching the given
546 clone = self.filter(**kwargs)
549 return clone._result_cache[0]
551 raise Task.DoesNotExist(
552 'Task matching query does not exist. '
553 'Lookup parameters were {0}'.format(kwargs))
555 'get() returned more than one Task -- it returned {0}! '
556 'Lookup parameters were {1}'.format(num, kwargs))
559 class TaskWarrior(object):
560 def __init__(self, data_location='~/.task', create=True):
561 data_location = os.path.expanduser(data_location)
562 if create and not os.path.exists(data_location):
563 os.makedirs(data_location)
565 'data.location': os.path.expanduser(data_location),
566 'confirmation': 'no',
568 self.tasks = TaskQuerySet(self)
569 self.version = self._get_version()
571 def _get_command_args(self, args, config_override={}):
572 command_args = ['task', 'rc:/']
573 config = self.config.copy()
574 config.update(config_override)
575 for item in config.items():
576 command_args.append('rc.{0}={1}'.format(*item))
577 command_args.extend(map(str, args))
580 def _get_version(self):
581 p = subprocess.Popen(
582 ['task', '--version'],
583 stdout=subprocess.PIPE,
584 stderr=subprocess.PIPE)
585 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
586 return stdout.strip('\n')
588 def execute_command(self, args, config_override={}):
589 command_args = self._get_command_args(
590 args, config_override=config_override)
591 logger.debug(' '.join(command_args))
592 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
593 stderr=subprocess.PIPE)
594 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
597 error_msg = stderr.strip().splitlines()[-1]
599 error_msg = stdout.strip()
600 raise TaskWarriorException(error_msg)
601 return stdout.strip().split('\n')
603 def filter_tasks(self, filter_obj):
604 args = ['export', '--'] + filter_obj.get_filter_params()
606 for line in self.execute_command(args):
608 data = line.strip(',')
610 filtered_task = Task(self)
611 filtered_task._load_data(json.loads(data))
612 tasks.append(filtered_task)
614 raise TaskWarriorException('Invalid JSON: %s' % data)
617 def merge_with(self, path, push=False):
618 path = path.rstrip('/') + '/'
619 self.execute_command(['merge', path], config_override={
620 'merge.autopush': 'yes' if push else 'no',
624 self.execute_command(['undo'])