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
34 self._original_data = data.copy()
36 def __getitem__(self, key):
37 # This is a workaround to make TaskResource non-iterable
38 # over simple index-based iteration
45 hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
47 return hydrate_func(self._data.get(key))
49 def __setitem__(self, key, value):
50 if key in self.read_only_fields:
51 raise RuntimeError('Field \'%s\' is read-only' % key)
52 dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
54 self._data[key] = dehydrate_func(value)
57 s = six.text_type(self.__unicode__())
66 class TaskAnnotation(TaskResource):
67 read_only_fields = ['entry', 'description']
69 def __init__(self, task, data={}):
73 def deserialize_entry(self, data):
74 return datetime.datetime.strptime(data, DATE_FORMAT) if data else None
76 def serialize_entry(self, date):
77 return date.strftime(DATE_FORMAT) if date else ''
80 self.task.remove_annotation(self)
82 def __unicode__(self):
83 return self['description']
85 __repr__ = __unicode__
88 class Task(TaskResource):
89 read_only_fields = ['id', 'entry', 'urgency', 'uuid']
91 class DoesNotExist(Exception):
94 class CompletedTask(Exception):
96 Raised when the operation cannot be performed on the completed task.
100 class DeletedTask(Exception):
102 Raised when the operation cannot be performed on the deleted task.
106 class NotSaved(Exception):
108 Raised when the operation cannot be performed on the task, because
109 it has not been saved to TaskWarrior yet.
113 def __init__(self, warrior, data={}, **kwargs):
114 self.warrior = warrior
116 # We keep data for backwards compatibility
119 self._load_data(kwargs)
121 def __unicode__(self):
122 return self['description']
124 def __eq__(self, other):
125 if self['uuid'] and other['uuid']:
126 # For saved Tasks, just define equality by equality of uuids
127 return self['uuid'] == other['uuid']
129 # If the tasks are not saved, compare the actual instances
130 return id(self) == id(other)
135 # For saved Tasks, just define equality by equality of uuids
136 return self['uuid'].__hash__()
138 # If the tasks are not saved, return hash of instance id
139 return id(self).__hash__()
142 def _modified_fields(self):
143 for key in self._data.keys():
144 if self._data.get(key) != self._original_data.get(key):
149 return self['status'] == six.text_type('completed')
153 return self['status'] == six.text_type('deleted')
157 return self['status'] == six.text_type('waiting')
161 return self['status'] == six.text_type('pending')
165 return self['uuid'] is not None or self['id'] is not None
167 def serialize_due(self, date):
168 return date.strftime(DATE_FORMAT)
170 def deserialize_due(self, date_str):
173 return datetime.datetime.strptime(date_str, DATE_FORMAT)
175 def serialize_depends(self, cur_dependencies):
176 # Check that all the tasks are saved
177 for task in cur_dependencies:
179 raise Task.NotSaved('Task \'%s\' needs to be saved before '
180 'it can be set as dependency.' % task)
182 # Return the list of uuids
183 return ','.join(task['uuid'] for task in cur_dependencies)
185 def deserialize_depends(self, raw_uuids):
186 raw_uuids = raw_uuids or '' # Convert None to empty string
187 uuids = raw_uuids.split(',')
188 return set(self.warrior.tasks.get(uuid=uuid) for uuid in uuids if uuid)
190 def format_depends(self):
191 # We need to generate added and removed dependencies list,
192 # since Taskwarrior does not accept redefining dependencies.
194 # This cannot be part of serialize_depends, since we need
195 # to keep a list of all depedencies in the _data dictionary,
196 # not just currently added/removed ones
198 old_dependencies_raw = self._original_data.get('depends','')
199 old_dependencies = self.deserialize_depends(old_dependencies_raw)
201 added = self['depends'] - old_dependencies
202 removed = old_dependencies - self['depends']
204 # Removed dependencies need to be prefixed with '-'
206 [t['uuid'] for t in added] +
207 ['-' + t['uuid'] for t in removed]
210 def deserialize_annotations(self, data):
211 return [TaskAnnotation(self, d) for d in data] if data else []
213 def deserialize_tags(self, tags):
214 if isinstance(tags, basestring):
215 return tags.split(',') if tags else []
218 def serialize_tags(self, tags):
219 return ','.join(tags) if tags else ''
223 raise Task.NotSaved("Task needs to be saved before it can be deleted")
225 # Refresh the status, and raise exception if the task is deleted
226 self.refresh(only_fields=['status'])
229 raise Task.DeletedTask("Task was already deleted")
231 self.warrior.execute_command([self['uuid'], 'delete'], config_override={
232 'confirmation': 'no',
235 # Refresh the status again, so that we have updated info stored
236 self.refresh(only_fields=['status'])
241 raise Task.NotSaved("Task needs to be saved before it can be completed")
243 # Refresh, and raise exception if task is already completed/deleted
244 self.refresh(only_fields=['status'])
247 raise Task.CompletedTask("Cannot complete a completed task")
249 raise Task.DeletedTask("Deleted task cannot be completed")
251 self.warrior.execute_command([self['uuid'], 'done'])
253 # Refresh the status again, so that we have updated info stored
254 self.refresh(only_fields=['status'])
257 args = [self['uuid'], 'modify'] if self.saved else ['add']
258 args.extend(self._get_modified_fields_as_args())
259 output = self.warrior.execute_command(args)
261 # Parse out the new ID, if the task is being added for the first time
263 id_lines = [l for l in output if l.startswith('Created task ')]
265 # Complain loudly if it seems that more tasks were created
267 if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
268 raise TaskWarriorException("Unexpected output when creating "
269 "task: %s" % '\n'.join(id_lines))
271 # Circumvent the ID storage, since ID is considered read-only
272 self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
276 def add_annotation(self, annotation):
278 raise Task.NotSaved("Task needs to be saved to add annotation")
280 args = [self['uuid'], 'annotate', annotation]
281 self.warrior.execute_command(args)
282 self.refresh(only_fields=['annotations'])
284 def remove_annotation(self, annotation):
286 raise Task.NotSaved("Task needs to be saved to add annotation")
288 if isinstance(annotation, TaskAnnotation):
289 annotation = annotation['description']
290 args = [self['uuid'], 'denotate', annotation]
291 self.warrior.execute_command(args)
292 self.refresh(only_fields=['annotations'])
294 def _get_modified_fields_as_args(self):
297 def add_field(field):
298 # Task version older than 2.4.0 ignores first word of the
299 # task description if description: prefix is used
300 if self.warrior.version < VERSION_2_4_0 and field == 'description':
301 args.append(self._data[field])
302 elif field == 'depends':
303 args.append('{0}:{1}'.format(field, self.format_depends()))
305 args.append('{0}:{1}'.format(field, self._data[field]))
307 # If we're modifying saved task, simply pass on all modified fields
309 for field in self._modified_fields:
311 # For new tasks, pass all fields that make sense
313 for field in self._data.keys():
314 if field in self.read_only_fields:
320 def refresh(self, only_fields=[]):
321 # Raise error when trying to refresh a task that has not been saved
323 raise Task.NotSaved("Task needs to be saved to be refreshed")
325 # We need to use ID as backup for uuid here for the refreshes
326 # of newly saved tasks. Any other place in the code is fine
327 # with using UUID only.
328 args = [self['uuid'] or self['id'], 'export']
329 new_data = json.loads(self.warrior.execute_command(args)[0])
332 [(k, new_data.get(k)) for k in only_fields])
333 self._data.update(to_update)
334 self._original_data.update(to_update)
336 self._data = new_data
337 # We need to create a clone for original_data though
338 # Shallow copy is alright, since data dict uses only
339 # primitive data types
340 self._original_data = new_data.copy()
343 class TaskFilter(object):
345 A set of parameters to filter the task list with.
348 def __init__(self, filter_params=[]):
349 self.filter_params = filter_params
351 def add_filter(self, filter_str):
352 self.filter_params.append(filter_str)
354 def add_filter_param(self, key, value):
355 key = key.replace('__', '.')
357 # Replace the value with empty string, since that is the
358 # convention in TW for empty values
359 value = value if value is not None else ''
361 # If we are filtering by uuid:, do not use uuid keyword
364 self.filter_params.insert(0, value)
366 self.filter_params.append('{0}:{1}'.format(key, value))
368 def get_filter_params(self):
369 return [f for f in self.filter_params if f]
373 c.filter_params = list(self.filter_params)
377 class TaskQuerySet(object):
379 Represents a lazy lookup for a task objects.
382 def __init__(self, warrior=None, filter_obj=None):
383 self.warrior = warrior
384 self._result_cache = None
385 self.filter_obj = filter_obj or TaskFilter()
387 def __deepcopy__(self, memo):
389 Deep copy of a QuerySet doesn't populate the cache
391 obj = self.__class__()
392 for k, v in self.__dict__.items():
393 if k in ('_iter', '_result_cache'):
394 obj.__dict__[k] = None
396 obj.__dict__[k] = copy.deepcopy(v, memo)
400 data = list(self[:REPR_OUTPUT_SIZE + 1])
401 if len(data) > REPR_OUTPUT_SIZE:
402 data[-1] = "...(remaining elements truncated)..."
406 if self._result_cache is None:
407 self._result_cache = list(self)
408 return len(self._result_cache)
411 if self._result_cache is None:
412 self._result_cache = self._execute()
413 return iter(self._result_cache)
415 def __getitem__(self, k):
416 if self._result_cache is None:
417 self._result_cache = list(self)
418 return self._result_cache.__getitem__(k)
421 if self._result_cache is not None:
422 return bool(self._result_cache)
425 except StopIteration:
429 def __nonzero__(self):
430 return type(self).__bool__(self)
432 def _clone(self, klass=None, **kwargs):
434 klass = self.__class__
435 filter_obj = self.filter_obj.clone()
436 c = klass(warrior=self.warrior, filter_obj=filter_obj)
437 c.__dict__.update(kwargs)
442 Fetch the tasks which match the current filters.
444 return self.warrior.filter_tasks(self.filter_obj)
448 Returns a new TaskQuerySet that is a copy of the current one.
453 return self.filter(status=PENDING)
456 return self.filter(status=COMPLETED)
458 def filter(self, *args, **kwargs):
460 Returns a new TaskQuerySet with the given filters added.
462 clone = self._clone()
464 clone.filter_obj.add_filter(f)
465 for key, value in kwargs.items():
466 clone.filter_obj.add_filter_param(key, value)
469 def get(self, **kwargs):
471 Performs the query and returns a single object matching the given
474 clone = self.filter(**kwargs)
477 return clone._result_cache[0]
479 raise Task.DoesNotExist(
480 'Task matching query does not exist. '
481 'Lookup parameters were {0}'.format(kwargs))
483 'get() returned more than one Task -- it returned {0}! '
484 'Lookup parameters were {1}'.format(num, kwargs))
487 class TaskWarrior(object):
488 def __init__(self, data_location='~/.task', create=True):
489 data_location = os.path.expanduser(data_location)
490 if create and not os.path.exists(data_location):
491 os.makedirs(data_location)
493 'data.location': os.path.expanduser(data_location),
495 self.tasks = TaskQuerySet(self)
496 self.version = self._get_version()
498 def _get_command_args(self, args, config_override={}):
499 command_args = ['task', 'rc:/']
500 config = self.config.copy()
501 config.update(config_override)
502 for item in config.items():
503 command_args.append('rc.{0}={1}'.format(*item))
504 command_args.extend(map(str, args))
507 def _get_version(self):
508 p = subprocess.Popen(
509 ['task', '--version'],
510 stdout=subprocess.PIPE,
511 stderr=subprocess.PIPE)
512 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
513 return stdout.strip('\n')
515 def execute_command(self, args, config_override={}):
516 command_args = self._get_command_args(
517 args, config_override=config_override)
518 logger.debug(' '.join(command_args))
519 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
520 stderr=subprocess.PIPE)
521 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
524 error_msg = stderr.strip().splitlines()[-1]
526 error_msg = stdout.strip()
527 raise TaskWarriorException(error_msg)
528 return stdout.strip().split('\n')
530 def filter_tasks(self, filter_obj):
531 args = ['export', '--'] + filter_obj.get_filter_params()
533 for line in self.execute_command(args):
535 data = line.strip(',')
537 tasks.append(Task(self, json.loads(data)))
539 raise TaskWarriorException('Invalid JSON: %s' % data)
542 def merge_with(self, path, push=False):
543 path = path.rstrip('/') + '/'
544 self.execute_command(['merge', path], config_override={
545 'merge.autopush': 'yes' if push else 'no',
549 self.execute_command(['undo'], config_override={
550 'confirmation': 'no',