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):
33 def __getitem__(self, key):
34 hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
36 return hydrate_func(self._data.get(key))
38 def __setitem__(self, key, value):
39 if key in self.read_only_fields:
40 raise RuntimeError('Field \'%s\' is read-only' % key)
41 dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
43 self._data[key] = dehydrate_func(value)
44 self._modified_fields.add(key)
47 s = six.text_type(self.__unicode__())
56 class TaskAnnotation(TaskResource):
57 read_only_fields = ['entry', 'description']
59 def __init__(self, task, data={}):
63 def deserialize_entry(self, data):
64 return datetime.datetime.strptime(data, DATE_FORMAT) if data else None
66 def serialize_entry(self, date):
67 return date.strftime(DATE_FORMAT) if date else ''
70 self.task.remove_annotation(self)
72 def __unicode__(self):
73 return self['description']
75 __repr__ = __unicode__
78 class Task(TaskResource):
79 read_only_fields = ['id', 'entry', 'urgency', 'uuid']
81 class DoesNotExist(Exception):
84 class CompletedTask(Exception):
86 Raised when the operation cannot be performed on the completed task.
90 class DeletedTask(Exception):
92 Raised when the operation cannot be performed on the deleted task.
96 class NotSaved(Exception):
98 Raised when the operation cannot be performed on the task, because
99 it has not been saved to TaskWarrior yet.
103 def __init__(self, warrior, data={}, **kwargs):
104 self.warrior = warrior
106 # We keep data for backwards compatibility
109 self._load_data(kwargs)
110 self._modified_fields = set()
112 def __unicode__(self):
113 return self['description']
117 return self['status'] == six.text_type('completed')
121 return self['status'] == six.text_type('deleted')
125 return self['status'] == six.text_type('waiting')
129 return self['status'] == six.text_type('pending')
133 return self['uuid'] is not None or self['id'] is not None
135 def serialize_due(self, date):
136 return date.strftime(DATE_FORMAT)
138 def deserialize_due(self, date_str):
141 return datetime.datetime.strptime(date_str, DATE_FORMAT)
143 def deserialize_annotations(self, data):
144 return [TaskAnnotation(self, d) for d in data] if data else []
146 def deserialize_tags(self, tags):
147 if isinstance(tags, basestring):
148 return tags.split(',') if tags else []
151 def serialize_tags(self, tags):
152 return ','.join(tags) if tags else ''
156 raise Task.NotSaved("Task needs to be saved before it can be deleted")
158 # Refresh the status, and raise exception if the task is deleted
159 self.refresh(only_fields=['status'])
162 raise Task.DeletedTask("Task was already deleted")
164 self.warrior.execute_command([self['uuid'], 'delete'], config_override={
165 'confirmation': 'no',
168 # Refresh the status again, so that we have updated info stored
169 self.refresh(only_fields=['status'])
174 raise Task.NotSaved("Task needs to be saved before it can be completed")
176 # Refresh, and raise exception if task is already completed/deleted
177 self.refresh(only_fields=['status'])
180 raise Task.CompletedTask("Cannot complete a completed task")
182 raise Task.DeletedTask("Deleted task cannot be completed")
184 self.warrior.execute_command([self['uuid'], 'done'])
186 # Refresh the status again, so that we have updated info stored
187 self.refresh(only_fields=['status'])
190 args = [self['uuid'], 'modify'] if self.saved else ['add']
191 args.extend(self._get_modified_fields_as_args())
192 output = self.warrior.execute_command(args)
194 # Parse out the new ID, if the task is being added for the first time
196 id_lines = [l for l in output if l.startswith('Created task ')]
198 # Complain loudly if it seems that more tasks were created
200 if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
201 raise TaskWarriorException("Unexpected output when creating "
202 "task: %s" % '\n'.join(id_lines))
204 # Circumvent the ID storage, since ID is considered read-only
205 self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
207 self._modified_fields.clear()
210 def add_annotation(self, annotation):
212 raise Task.NotSaved("Task needs to be saved to add annotation")
214 args = [self['uuid'], 'annotate', annotation]
215 self.warrior.execute_command(args)
216 self.refresh(only_fields=['annotations'])
218 def remove_annotation(self, annotation):
220 raise Task.NotSaved("Task needs to be saved to add annotation")
222 if isinstance(annotation, TaskAnnotation):
223 annotation = annotation['description']
224 args = [self['uuid'], 'denotate', annotation]
225 self.warrior.execute_command(args)
226 self.refresh(only_fields=['annotations'])
228 def _get_modified_fields_as_args(self):
231 def add_field(field):
232 # Task version older than 2.4.0 ignores first word of the
233 # task description if description: prefix is used
234 if self.warrior.version < VERSION_2_4_0 and field == 'description':
235 args.append(self._data[field])
237 args.append('{0}:{1}'.format(field, self._data[field]))
239 # If we're modifying saved task, simply pass on all modified fields
241 for field in self._modified_fields:
243 # For new tasks, pass all fields that make sense
245 for field in self._data.keys():
246 if field in self.read_only_fields:
252 def refresh(self, only_fields=[]):
253 # Raise error when trying to refresh a task that has not been saved
255 raise Task.NotSaved("Task needs to be saved to be refreshed")
257 # We need to use ID as backup for uuid here for the refreshes
258 # of newly saved tasks. Any other place in the code is fine
259 # with using UUID only.
260 args = [self['uuid'] or self['id'], 'export']
261 new_data = json.loads(self.warrior.execute_command(args)[0])
264 [(k, new_data.get(k)) for k in only_fields])
265 self._data.update(to_update)
267 self._data = new_data
270 class TaskFilter(object):
272 A set of parameters to filter the task list with.
275 def __init__(self, filter_params=[]):
276 self.filter_params = filter_params
278 def add_filter(self, filter_str):
279 self.filter_params.append(filter_str)
281 def add_filter_param(self, key, value):
282 key = key.replace('__', '.')
284 # Replace the value with empty string, since that is the
285 # convention in TW for empty values
286 value = value if value is not None else ''
287 self.filter_params.append('{0}:{1}'.format(key, value))
289 def get_filter_params(self):
290 return [f for f in self.filter_params if f]
294 c.filter_params = list(self.filter_params)
298 class TaskQuerySet(object):
300 Represents a lazy lookup for a task objects.
303 def __init__(self, warrior=None, filter_obj=None):
304 self.warrior = warrior
305 self._result_cache = None
306 self.filter_obj = filter_obj or TaskFilter()
308 def __deepcopy__(self, memo):
310 Deep copy of a QuerySet doesn't populate the cache
312 obj = self.__class__()
313 for k, v in self.__dict__.items():
314 if k in ('_iter', '_result_cache'):
315 obj.__dict__[k] = None
317 obj.__dict__[k] = copy.deepcopy(v, memo)
321 data = list(self[:REPR_OUTPUT_SIZE + 1])
322 if len(data) > REPR_OUTPUT_SIZE:
323 data[-1] = "...(remaining elements truncated)..."
327 if self._result_cache is None:
328 self._result_cache = list(self)
329 return len(self._result_cache)
332 if self._result_cache is None:
333 self._result_cache = self._execute()
334 return iter(self._result_cache)
336 def __getitem__(self, k):
337 if self._result_cache is None:
338 self._result_cache = list(self)
339 return self._result_cache.__getitem__(k)
342 if self._result_cache is not None:
343 return bool(self._result_cache)
346 except StopIteration:
350 def __nonzero__(self):
351 return type(self).__bool__(self)
353 def _clone(self, klass=None, **kwargs):
355 klass = self.__class__
356 filter_obj = self.filter_obj.clone()
357 c = klass(warrior=self.warrior, filter_obj=filter_obj)
358 c.__dict__.update(kwargs)
363 Fetch the tasks which match the current filters.
365 return self.warrior.filter_tasks(self.filter_obj)
369 Returns a new TaskQuerySet that is a copy of the current one.
374 return self.filter(status=PENDING)
377 return self.filter(status=COMPLETED)
379 def filter(self, *args, **kwargs):
381 Returns a new TaskQuerySet with the given filters added.
383 clone = self._clone()
385 clone.filter_obj.add_filter(f)
386 for key, value in kwargs.items():
387 clone.filter_obj.add_filter_param(key, value)
390 def get(self, **kwargs):
392 Performs the query and returns a single object matching the given
395 clone = self.filter(**kwargs)
398 return clone._result_cache[0]
400 raise Task.DoesNotExist(
401 'Task matching query does not exist. '
402 'Lookup parameters were {0}'.format(kwargs))
404 'get() returned more than one Task -- it returned {0}! '
405 'Lookup parameters were {1}'.format(num, kwargs))
408 class TaskWarrior(object):
409 def __init__(self, data_location='~/.task', create=True):
410 data_location = os.path.expanduser(data_location)
411 if create and not os.path.exists(data_location):
412 os.makedirs(data_location)
414 'data.location': os.path.expanduser(data_location),
416 self.tasks = TaskQuerySet(self)
417 self.version = self._get_version()
419 def _get_command_args(self, args, config_override={}):
420 command_args = ['task', 'rc:/']
421 config = self.config.copy()
422 config.update(config_override)
423 for item in config.items():
424 command_args.append('rc.{0}={1}'.format(*item))
425 command_args.extend(map(str, args))
428 def _get_version(self):
429 p = subprocess.Popen(
430 ['task', '--version'],
431 stdout=subprocess.PIPE,
432 stderr=subprocess.PIPE)
433 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
434 return stdout.strip('\n')
436 def execute_command(self, args, config_override={}):
437 command_args = self._get_command_args(
438 args, config_override=config_override)
439 logger.debug(' '.join(command_args))
440 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
441 stderr=subprocess.PIPE)
442 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
445 error_msg = stderr.strip().splitlines()[-1]
447 error_msg = stdout.strip()
448 raise TaskWarriorException(error_msg)
449 return stdout.strip().split('\n')
451 def filter_tasks(self, filter_obj):
452 args = ['export', '--'] + filter_obj.get_filter_params()
454 for line in self.execute_command(args):
456 data = line.strip(',')
458 tasks.append(Task(self, json.loads(data)))
460 raise TaskWarriorException('Invalid JSON: %s' % data)
463 def merge_with(self, path, push=False):
464 path = path.rstrip('/') + '/'
465 self.execute_command(['merge', path], config_override={
466 'merge.autopush': 'yes' if push else 'no',
470 self.execute_command(['undo'], config_override={
471 'confirmation': 'no',