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, six.string_types):
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):
114 self._data = dict((key, self._deserialize(key, value))
115 for key, value in data.items())
116 # We need to use a copy for original data, so that changes
117 # are not propagated.
118 self._original_data = copy.deepcopy(self._data)
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.
126 self._data.update(dict((key, self._deserialize(key, value))
127 for key, value in data.items()))
130 self._original_data = copy.deepcopy(self._data)
133 def __getitem__(self, key):
134 # This is a workaround to make TaskResource non-iterable
135 # over simple index-based iteration
142 if key not in self._data:
143 self._data[key] = self._deserialize(key, None)
145 return self._data.get(key)
147 def __setitem__(self, key, value):
148 if key in self.read_only_fields:
149 raise RuntimeError('Field \'%s\' is read-only' % key)
150 self._data[key] = value
153 s = six.text_type(self.__unicode__())
155 s = s.encode('utf-8')
162 class TaskAnnotation(TaskResource):
163 read_only_fields = ['entry', 'description']
165 def __init__(self, task, data={}):
167 self._load_data(data)
170 self.task.remove_annotation(self)
172 def __unicode__(self):
173 return self['description']
175 def __eq__(self, other):
176 # consider 2 annotations equal if they belong to the same task, and
177 # their data dics are the same
178 return self.task == other.task and self._data == other._data
180 __repr__ = __unicode__
183 class Task(TaskResource):
184 read_only_fields = ['id', 'entry', 'urgency', 'uuid', 'modified']
186 class DoesNotExist(Exception):
189 class CompletedTask(Exception):
191 Raised when the operation cannot be performed on the completed task.
195 class DeletedTask(Exception):
197 Raised when the operation cannot be performed on the deleted task.
201 class NotSaved(Exception):
203 Raised when the operation cannot be performed on the task, because
204 it has not been saved to TaskWarrior yet.
208 def __init__(self, warrior, **kwargs):
209 self.warrior = warrior
211 # Check that user is not able to set read-only value in __init__
212 for key in kwargs.keys():
213 if key in self.read_only_fields:
214 raise RuntimeError('Field \'%s\' is read-only' % key)
216 # We serialize the data in kwargs so that users of the library
217 # do not have to pass different data formats via __setitem__ and
218 # __init__ methods, that would be confusing
220 # Rather unfortunate syntax due to python2.6 comaptiblity
221 self._load_data(dict((key, self._serialize(key, value))
222 for (key, value) in six.iteritems(kwargs)))
224 def __unicode__(self):
225 return self['description']
227 def __eq__(self, other):
228 if self['uuid'] and other['uuid']:
229 # For saved Tasks, just define equality by equality of uuids
230 return self['uuid'] == other['uuid']
232 # If the tasks are not saved, compare the actual instances
233 return id(self) == id(other)
238 # For saved Tasks, just define equality by equality of uuids
239 return self['uuid'].__hash__()
241 # If the tasks are not saved, return hash of instance id
242 return id(self).__hash__()
245 def _modified_fields(self):
246 writable_fields = set(self._data.keys()) - set(self.read_only_fields)
247 for key in writable_fields:
248 if self._data.get(key) != self._original_data.get(key):
252 def _is_modified(self):
253 return bool(list(self._modified_fields))
257 return self['status'] == six.text_type('completed')
261 return self['status'] == six.text_type('deleted')
265 return self['status'] == six.text_type('waiting')
269 return self['status'] == six.text_type('pending')
273 return self['uuid'] is not None or self['id'] is not None
275 def serialize_depends(self, cur_dependencies):
276 # Check that all the tasks are saved
277 for task in cur_dependencies:
279 raise Task.NotSaved('Task \'%s\' needs to be saved before '
280 'it can be set as dependency.' % task)
282 return super(Task, self).serialize_depends(cur_dependencies)
284 def format_depends(self):
285 # We need to generate added and removed dependencies list,
286 # since Taskwarrior does not accept redefining dependencies.
288 # This cannot be part of serialize_depends, since we need
289 # to keep a list of all depedencies in the _data dictionary,
290 # not just currently added/removed ones
292 old_dependencies = self._original_data.get('depends', set())
294 added = self['depends'] - old_dependencies
295 removed = old_dependencies - self['depends']
297 # Removed dependencies need to be prefixed with '-'
298 return 'depends:' + ','.join(
299 [t['uuid'] for t in added] +
300 ['-' + t['uuid'] for t in removed]
303 def format_description(self):
304 # Task version older than 2.4.0 ignores first word of the
305 # task description if description: prefix is used
306 if self.warrior.version < VERSION_2_4_0:
307 return self._data['description']
309 return "description:'{0}'".format(self._data['description'] or '')
313 raise Task.NotSaved("Task needs to be saved before it can be deleted")
315 # Refresh the status, and raise exception if the task is deleted
316 self.refresh(only_fields=['status'])
319 raise Task.DeletedTask("Task was already deleted")
321 self.warrior.execute_command([self['uuid'], 'delete'])
323 # Refresh the status again, so that we have updated info stored
324 self.refresh(only_fields=['status'])
329 raise Task.NotSaved("Task needs to be saved before it can be completed")
331 # Refresh, and raise exception if task is already completed/deleted
332 self.refresh(only_fields=['status'])
335 raise Task.CompletedTask("Cannot complete a completed task")
337 raise Task.DeletedTask("Deleted task cannot be completed")
339 self.warrior.execute_command([self['uuid'], 'done'])
341 # Refresh the status again, so that we have updated info stored
342 self.refresh(only_fields=['status'])
345 if self.saved and not self._is_modified:
348 args = [self['uuid'], 'modify'] if self.saved else ['add']
349 args.extend(self._get_modified_fields_as_args())
350 output = self.warrior.execute_command(args)
352 # Parse out the new ID, if the task is being added for the first time
354 id_lines = [l for l in output if l.startswith('Created task ')]
356 # Complain loudly if it seems that more tasks were created
358 if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
359 raise TaskWarriorException("Unexpected output when creating "
360 "task: %s" % '\n'.join(id_lines))
362 # Circumvent the ID storage, since ID is considered read-only
363 self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
367 def add_annotation(self, annotation):
369 raise Task.NotSaved("Task needs to be saved to add annotation")
371 args = [self['uuid'], 'annotate', annotation]
372 self.warrior.execute_command(args)
373 self.refresh(only_fields=['annotations'])
375 def remove_annotation(self, annotation):
377 raise Task.NotSaved("Task needs to be saved to remove annotation")
379 if isinstance(annotation, TaskAnnotation):
380 annotation = annotation['description']
381 args = [self['uuid'], 'denotate', annotation]
382 self.warrior.execute_command(args)
383 self.refresh(only_fields=['annotations'])
385 def _get_modified_fields_as_args(self):
388 def add_field(field):
389 # Add the output of format_field method to args list (defaults to
391 serialized_value = self._serialize(field, self._data[field]) or ''
392 format_default = lambda: "{0}:{1}".format(
394 "'{0}'".format(serialized_value) if serialized_value else ''
396 format_func = getattr(self, 'format_{0}'.format(field),
398 args.append(format_func())
400 # If we're modifying saved task, simply pass on all modified fields
402 for field in self._modified_fields:
404 # For new tasks, pass all fields that make sense
406 for field in self._data.keys():
407 if field in self.read_only_fields:
413 def refresh(self, only_fields=[]):
414 # Raise error when trying to refresh a task that has not been saved
416 raise Task.NotSaved("Task needs to be saved to be refreshed")
418 # We need to use ID as backup for uuid here for the refreshes
419 # of newly saved tasks. Any other place in the code is fine
420 # with using UUID only.
421 args = [self['uuid'] or self['id'], 'export']
422 new_data = json.loads(self.warrior.execute_command(args)[0])
425 [(k, new_data.get(k)) for k in only_fields])
426 self._update_data(to_update, update_original=True)
428 self._load_data(new_data)
431 class TaskFilter(SerializingObject):
433 A set of parameters to filter the task list with.
436 def __init__(self, filter_params=[]):
437 self.filter_params = filter_params
439 def add_filter(self, filter_str):
440 self.filter_params.append(filter_str)
442 def add_filter_param(self, key, value):
443 key = key.replace('__', '.')
445 # Replace the value with empty string, since that is the
446 # convention in TW for empty values
447 attribute_key = key.split('.')[0]
448 value = self._serialize(attribute_key, value)
450 # If we are filtering by uuid:, do not use uuid keyword
453 self.filter_params.insert(0, value)
455 # Surround value with aphostrophes unless it's a empty string
456 value = "'%s'" % value if value else ''
458 # We enforce equality match by using 'is' (or 'none') modifier
459 # Without using this syntax, filter fails due to TW-1479
460 modifier = '.is' if value else '.none'
461 key = key + modifier if '.' not in key else key
463 self.filter_params.append("{0}:{1}".format(key, value))
465 def get_filter_params(self):
466 return [f for f in self.filter_params if f]
470 c.filter_params = list(self.filter_params)
474 class TaskQuerySet(object):
476 Represents a lazy lookup for a task objects.
479 def __init__(self, warrior=None, filter_obj=None):
480 self.warrior = warrior
481 self._result_cache = None
482 self.filter_obj = filter_obj or TaskFilter()
484 def __deepcopy__(self, memo):
486 Deep copy of a QuerySet doesn't populate the cache
488 obj = self.__class__()
489 for k, v in self.__dict__.items():
490 if k in ('_iter', '_result_cache'):
491 obj.__dict__[k] = None
493 obj.__dict__[k] = copy.deepcopy(v, memo)
497 data = list(self[:REPR_OUTPUT_SIZE + 1])
498 if len(data) > REPR_OUTPUT_SIZE:
499 data[-1] = "...(remaining elements truncated)..."
503 if self._result_cache is None:
504 self._result_cache = list(self)
505 return len(self._result_cache)
508 if self._result_cache is None:
509 self._result_cache = self._execute()
510 return iter(self._result_cache)
512 def __getitem__(self, k):
513 if self._result_cache is None:
514 self._result_cache = list(self)
515 return self._result_cache.__getitem__(k)
518 if self._result_cache is not None:
519 return bool(self._result_cache)
522 except StopIteration:
526 def __nonzero__(self):
527 return type(self).__bool__(self)
529 def _clone(self, klass=None, **kwargs):
531 klass = self.__class__
532 filter_obj = self.filter_obj.clone()
533 c = klass(warrior=self.warrior, filter_obj=filter_obj)
534 c.__dict__.update(kwargs)
539 Fetch the tasks which match the current filters.
541 return self.warrior.filter_tasks(self.filter_obj)
545 Returns a new TaskQuerySet that is a copy of the current one.
550 return self.filter(status=PENDING)
553 return self.filter(status=COMPLETED)
555 def filter(self, *args, **kwargs):
557 Returns a new TaskQuerySet with the given filters added.
559 clone = self._clone()
561 clone.filter_obj.add_filter(f)
562 for key, value in kwargs.items():
563 clone.filter_obj.add_filter_param(key, value)
566 def get(self, **kwargs):
568 Performs the query and returns a single object matching the given
571 clone = self.filter(**kwargs)
574 return clone._result_cache[0]
576 raise Task.DoesNotExist(
577 'Task matching query does not exist. '
578 'Lookup parameters were {0}'.format(kwargs))
580 'get() returned more than one Task -- it returned {0}! '
581 'Lookup parameters were {1}'.format(num, kwargs))
584 class TaskWarrior(object):
585 def __init__(self, data_location='~/.task', create=True):
586 data_location = os.path.expanduser(data_location)
587 if create and not os.path.exists(data_location):
588 os.makedirs(data_location)
590 'data.location': os.path.expanduser(data_location),
591 'confirmation': 'no',
592 'dependency.confirmation': 'no', # See TW-1483 or taskrc man page
594 self.tasks = TaskQuerySet(self)
595 self.version = self._get_version()
597 def _get_command_args(self, args, config_override={}):
598 command_args = ['task', 'rc:/']
599 config = self.config.copy()
600 config.update(config_override)
601 for item in config.items():
602 command_args.append('rc.{0}={1}'.format(*item))
603 command_args.extend(map(str, args))
606 def _get_version(self):
607 p = subprocess.Popen(
608 ['task', '--version'],
609 stdout=subprocess.PIPE,
610 stderr=subprocess.PIPE)
611 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
612 return stdout.strip('\n')
614 def execute_command(self, args, config_override={}):
615 command_args = self._get_command_args(
616 args, config_override=config_override)
617 logger.debug(' '.join(command_args))
618 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
619 stderr=subprocess.PIPE)
620 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
623 error_msg = stderr.strip().splitlines()[-1]
625 error_msg = stdout.strip()
626 raise TaskWarriorException(error_msg)
627 return stdout.strip().split('\n')
629 def filter_tasks(self, filter_obj):
630 args = ['export', '--'] + filter_obj.get_filter_params()
632 for line in self.execute_command(args):
634 data = line.strip(',')
636 filtered_task = Task(self)
637 filtered_task._load_data(json.loads(data))
638 tasks.append(filtered_task)
640 raise TaskWarriorException('Invalid JSON: %s' % data)
643 def merge_with(self, path, push=False):
644 path = path.rstrip('/') + '/'
645 self.execute_command(['merge', path], config_override={
646 'merge.autopush': 'yes' if push else 'no',
650 self.execute_command(['undo'])