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 TaskResource(object):
30 def _load_data(self, data):
32 # We need to use a copy for original data, so that changes
33 # are not propagated. Shallow copy is alright, since data dict uses only
34 # primitive data types
35 self._original_data = data.copy()
37 def _update_data(self, data, update_original=False):
39 Low level update of the internal _data dict. Data which are coming as
40 updates should already be serialized. If update_original is True, the
41 original_data dict is updated as well.
44 self._data.update(data)
47 self._original_data.update(data)
49 def __getitem__(self, key):
50 # This is a workaround to make TaskResource non-iterable
51 # over simple index-based iteration
58 return self._deserialize(key, self._data.get(key))
60 def __setitem__(self, key, value):
61 if key in self.read_only_fields:
62 raise RuntimeError('Field \'%s\' is read-only' % key)
63 self._data[key] = self._serialize(key, value)
65 def _deserialize(self, key, value):
66 hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
68 return hydrate_func(value)
70 def _serialize(self, key, value):
71 dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
73 return dehydrate_func(value)
76 s = six.text_type(self.__unicode__())
85 class TaskAnnotation(TaskResource):
86 read_only_fields = ['entry', 'description']
88 def __init__(self, task, data={}):
92 def deserialize_entry(self, data):
93 return datetime.datetime.strptime(data, DATE_FORMAT) if data else None
95 def serialize_entry(self, date):
96 return date.strftime(DATE_FORMAT) if date else ''
99 self.task.remove_annotation(self)
101 def __unicode__(self):
102 return self['description']
104 __repr__ = __unicode__
107 class Task(TaskResource):
108 read_only_fields = ['id', 'entry', 'urgency', 'uuid', 'modified']
110 class DoesNotExist(Exception):
113 class CompletedTask(Exception):
115 Raised when the operation cannot be performed on the completed task.
119 class DeletedTask(Exception):
121 Raised when the operation cannot be performed on the deleted task.
125 class NotSaved(Exception):
127 Raised when the operation cannot be performed on the task, because
128 it has not been saved to TaskWarrior yet.
132 def __init__(self, warrior, **kwargs):
133 self.warrior = warrior
135 # Check that user is not able to set read-only value in __init__
136 for key in kwargs.keys():
137 if key in self.read_only_fields:
138 raise RuntimeError('Field \'%s\' is read-only' % key)
140 # We serialize the data in kwargs so that users of the library
141 # do not have to pass different data formats via __setitem__ and
142 # __init__ methods, that would be confusing
144 # Rather unfortunate syntax due to python2.6 comaptiblity
145 self._load_data(dict((key, self._serialize(key, value))
146 for (key, value) in six.iteritems(kwargs)))
148 def __unicode__(self):
149 return self['description']
151 def __eq__(self, other):
152 if self['uuid'] and other['uuid']:
153 # For saved Tasks, just define equality by equality of uuids
154 return self['uuid'] == other['uuid']
156 # If the tasks are not saved, compare the actual instances
157 return id(self) == id(other)
162 # For saved Tasks, just define equality by equality of uuids
163 return self['uuid'].__hash__()
165 # If the tasks are not saved, return hash of instance id
166 return id(self).__hash__()
169 def _modified_fields(self):
170 writable_fields = set(self._data.keys()) - set(self.read_only_fields)
171 for key in writable_fields:
172 if self._data.get(key) != self._original_data.get(key):
177 return self['status'] == six.text_type('completed')
181 return self['status'] == six.text_type('deleted')
185 return self['status'] == six.text_type('waiting')
189 return self['status'] == six.text_type('pending')
193 return self['uuid'] is not None or self['id'] is not None
195 def serialize_due(self, date):
198 return date.strftime(DATE_FORMAT)
200 def deserialize_due(self, date_str):
203 return datetime.datetime.strptime(date_str, DATE_FORMAT)
205 def serialize_depends(self, cur_dependencies):
206 # Check that all the tasks are saved
207 for task in cur_dependencies:
209 raise Task.NotSaved('Task \'%s\' needs to be saved before '
210 'it can be set as dependency.' % task)
212 # Return the list of uuids
213 return ','.join(task['uuid'] for task in cur_dependencies)
215 def deserialize_depends(self, raw_uuids):
216 raw_uuids = raw_uuids or '' # Convert None to empty string
217 uuids = raw_uuids.split(',')
218 return set(self.warrior.tasks.get(uuid=uuid) for uuid in uuids if uuid)
220 def format_depends(self):
221 # We need to generate added and removed dependencies list,
222 # since Taskwarrior does not accept redefining dependencies.
224 # This cannot be part of serialize_depends, since we need
225 # to keep a list of all depedencies in the _data dictionary,
226 # not just currently added/removed ones
228 old_dependencies_raw = self._original_data.get('depends','')
229 old_dependencies = self.deserialize_depends(old_dependencies_raw)
231 added = self['depends'] - old_dependencies
232 removed = old_dependencies - self['depends']
234 # Removed dependencies need to be prefixed with '-'
235 return 'depends:' + ','.join(
236 [t['uuid'] for t in added] +
237 ['-' + t['uuid'] for t in removed]
240 def deserialize_annotations(self, data):
241 return [TaskAnnotation(self, d) for d in data] if data else []
243 def deserialize_tags(self, tags):
244 if isinstance(tags, basestring):
245 return tags.split(',') if tags else []
248 def serialize_tags(self, tags):
249 return ','.join(tags) if tags else ''
251 def format_description(self):
252 # Task version older than 2.4.0 ignores first word of the
253 # task description if description: prefix is used
254 if self.warrior.version < VERSION_2_4_0:
255 return self._data['description']
257 return "description:'{0}'".format(self._data['description'] or '')
261 raise Task.NotSaved("Task needs to be saved before it can be deleted")
263 # Refresh the status, and raise exception if the task is deleted
264 self.refresh(only_fields=['status'])
267 raise Task.DeletedTask("Task was already deleted")
269 self.warrior.execute_command([self['uuid'], 'delete'])
271 # Refresh the status again, so that we have updated info stored
272 self.refresh(only_fields=['status'])
277 raise Task.NotSaved("Task needs to be saved before it can be completed")
279 # Refresh, and raise exception if task is already completed/deleted
280 self.refresh(only_fields=['status'])
283 raise Task.CompletedTask("Cannot complete a completed task")
285 raise Task.DeletedTask("Deleted task cannot be completed")
287 self.warrior.execute_command([self['uuid'], 'done'])
289 # Refresh the status again, so that we have updated info stored
290 self.refresh(only_fields=['status'])
293 args = [self['uuid'], 'modify'] if self.saved else ['add']
294 args.extend(self._get_modified_fields_as_args())
295 output = self.warrior.execute_command(args)
297 # Parse out the new ID, if the task is being added for the first time
299 id_lines = [l for l in output if l.startswith('Created task ')]
301 # Complain loudly if it seems that more tasks were created
303 if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
304 raise TaskWarriorException("Unexpected output when creating "
305 "task: %s" % '\n'.join(id_lines))
307 # Circumvent the ID storage, since ID is considered read-only
308 self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
312 def add_annotation(self, annotation):
314 raise Task.NotSaved("Task needs to be saved to add annotation")
316 args = [self['uuid'], 'annotate', annotation]
317 self.warrior.execute_command(args)
318 self.refresh(only_fields=['annotations'])
320 def remove_annotation(self, annotation):
322 raise Task.NotSaved("Task needs to be saved to add annotation")
324 if isinstance(annotation, TaskAnnotation):
325 annotation = annotation['description']
326 args = [self['uuid'], 'denotate', annotation]
327 self.warrior.execute_command(args)
328 self.refresh(only_fields=['annotations'])
330 def _get_modified_fields_as_args(self):
333 def add_field(field):
334 # Add the output of format_field method to args list (defaults to
336 format_default = lambda k: "{0}:'{1}'".format(k, self._data[k] or '')
337 format_func = getattr(self, 'format_{0}'.format(field),
338 lambda: format_default(field))
339 args.append(format_func())
341 # If we're modifying saved task, simply pass on all modified fields
343 for field in self._modified_fields:
345 # For new tasks, pass all fields that make sense
347 for field in self._data.keys():
348 if field in self.read_only_fields:
354 def refresh(self, only_fields=[]):
355 # Raise error when trying to refresh a task that has not been saved
357 raise Task.NotSaved("Task needs to be saved to be refreshed")
359 # We need to use ID as backup for uuid here for the refreshes
360 # of newly saved tasks. Any other place in the code is fine
361 # with using UUID only.
362 args = [self['uuid'] or self['id'], 'export']
363 new_data = json.loads(self.warrior.execute_command(args)[0])
366 [(k, new_data.get(k)) for k in only_fields])
367 self._update_data(to_update, update_original=True)
369 self._load_data(new_data)
372 class TaskFilter(object):
374 A set of parameters to filter the task list with.
377 def __init__(self, filter_params=[]):
378 self.filter_params = filter_params
380 def add_filter(self, filter_str):
381 self.filter_params.append(filter_str)
383 def add_filter_param(self, key, value):
384 key = key.replace('__', '.')
386 # Replace the value with empty string, since that is the
387 # convention in TW for empty values
388 value = value if value is not None else ''
390 # If we are filtering by uuid:, do not use uuid keyword
393 self.filter_params.insert(0, value)
395 self.filter_params.append('{0}:{1}'.format(key, value))
397 def get_filter_params(self):
398 return [f for f in self.filter_params if f]
402 c.filter_params = list(self.filter_params)
406 class TaskQuerySet(object):
408 Represents a lazy lookup for a task objects.
411 def __init__(self, warrior=None, filter_obj=None):
412 self.warrior = warrior
413 self._result_cache = None
414 self.filter_obj = filter_obj or TaskFilter()
416 def __deepcopy__(self, memo):
418 Deep copy of a QuerySet doesn't populate the cache
420 obj = self.__class__()
421 for k, v in self.__dict__.items():
422 if k in ('_iter', '_result_cache'):
423 obj.__dict__[k] = None
425 obj.__dict__[k] = copy.deepcopy(v, memo)
429 data = list(self[:REPR_OUTPUT_SIZE + 1])
430 if len(data) > REPR_OUTPUT_SIZE:
431 data[-1] = "...(remaining elements truncated)..."
435 if self._result_cache is None:
436 self._result_cache = list(self)
437 return len(self._result_cache)
440 if self._result_cache is None:
441 self._result_cache = self._execute()
442 return iter(self._result_cache)
444 def __getitem__(self, k):
445 if self._result_cache is None:
446 self._result_cache = list(self)
447 return self._result_cache.__getitem__(k)
450 if self._result_cache is not None:
451 return bool(self._result_cache)
454 except StopIteration:
458 def __nonzero__(self):
459 return type(self).__bool__(self)
461 def _clone(self, klass=None, **kwargs):
463 klass = self.__class__
464 filter_obj = self.filter_obj.clone()
465 c = klass(warrior=self.warrior, filter_obj=filter_obj)
466 c.__dict__.update(kwargs)
471 Fetch the tasks which match the current filters.
473 return self.warrior.filter_tasks(self.filter_obj)
477 Returns a new TaskQuerySet that is a copy of the current one.
482 return self.filter(status=PENDING)
485 return self.filter(status=COMPLETED)
487 def filter(self, *args, **kwargs):
489 Returns a new TaskQuerySet with the given filters added.
491 clone = self._clone()
493 clone.filter_obj.add_filter(f)
494 for key, value in kwargs.items():
495 clone.filter_obj.add_filter_param(key, value)
498 def get(self, **kwargs):
500 Performs the query and returns a single object matching the given
503 clone = self.filter(**kwargs)
506 return clone._result_cache[0]
508 raise Task.DoesNotExist(
509 'Task matching query does not exist. '
510 'Lookup parameters were {0}'.format(kwargs))
512 'get() returned more than one Task -- it returned {0}! '
513 'Lookup parameters were {1}'.format(num, kwargs))
516 class TaskWarrior(object):
517 def __init__(self, data_location='~/.task', create=True):
518 data_location = os.path.expanduser(data_location)
519 if create and not os.path.exists(data_location):
520 os.makedirs(data_location)
522 'data.location': os.path.expanduser(data_location),
523 'confirmation': 'no',
525 self.tasks = TaskQuerySet(self)
526 self.version = self._get_version()
528 def _get_command_args(self, args, config_override={}):
529 command_args = ['task', 'rc:/']
530 config = self.config.copy()
531 config.update(config_override)
532 for item in config.items():
533 command_args.append('rc.{0}={1}'.format(*item))
534 command_args.extend(map(str, args))
537 def _get_version(self):
538 p = subprocess.Popen(
539 ['task', '--version'],
540 stdout=subprocess.PIPE,
541 stderr=subprocess.PIPE)
542 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
543 return stdout.strip('\n')
545 def execute_command(self, args, config_override={}):
546 command_args = self._get_command_args(
547 args, config_override=config_override)
548 logger.debug(' '.join(command_args))
549 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
550 stderr=subprocess.PIPE)
551 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
554 error_msg = stderr.strip().splitlines()[-1]
556 error_msg = stdout.strip()
557 raise TaskWarriorException(error_msg)
558 return stdout.strip().split('\n')
560 def filter_tasks(self, filter_obj):
561 args = ['export', '--'] + filter_obj.get_filter_params()
563 for line in self.execute_command(args):
565 data = line.strip(',')
567 filtered_task = Task(self)
568 filtered_task._load_data(json.loads(data))
569 tasks.append(filtered_task)
571 raise TaskWarriorException('Invalid JSON: %s' % data)
574 def merge_with(self, path, push=False):
575 path = path.rstrip('/') + '/'
576 self.execute_command(['merge', path], config_override={
577 'merge.autopush': 'yes' if push else 'no',
581 self.execute_command(['undo'])