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 # If we're modifying saved task, simply pass on all modified fields
233 for field in self._modified_fields:
234 args.append('{0}:{1}'.format(field, self._data[field]))
235 # For new tasks, pass all fields that make sense
237 for field in self._data.keys():
238 if field in self.read_only_fields:
240 args.append('{0}:{1}'.format(field, self._data[field]))
244 def refresh(self, only_fields=[]):
245 # Raise error when trying to refresh a task that has not been saved
247 raise Task.NotSaved("Task needs to be saved to be refreshed")
249 # We need to use ID as backup for uuid here for the refreshes
250 # of newly saved tasks. Any other place in the code is fine
251 # with using UUID only.
252 args = [self['uuid'] or self['id'], 'export']
253 new_data = json.loads(self.warrior.execute_command(args)[0])
256 [(k, new_data.get(k)) for k in only_fields])
257 self._data.update(to_update)
259 self._data = new_data
262 class TaskFilter(object):
264 A set of parameters to filter the task list with.
267 def __init__(self, filter_params=[]):
268 self.filter_params = filter_params
270 def add_filter(self, filter_str):
271 self.filter_params.append(filter_str)
273 def add_filter_param(self, key, value):
274 key = key.replace('__', '.')
276 # Replace the value with empty string, since that is the
277 # convention in TW for empty values
278 value = value if value is not None else ''
279 self.filter_params.append('{0}:{1}'.format(key, value))
281 def get_filter_params(self):
282 return [f for f in self.filter_params if f]
286 c.filter_params = list(self.filter_params)
290 class TaskQuerySet(object):
292 Represents a lazy lookup for a task objects.
295 def __init__(self, warrior=None, filter_obj=None):
296 self.warrior = warrior
297 self._result_cache = None
298 self.filter_obj = filter_obj or TaskFilter()
300 def __deepcopy__(self, memo):
302 Deep copy of a QuerySet doesn't populate the cache
304 obj = self.__class__()
305 for k, v in self.__dict__.items():
306 if k in ('_iter', '_result_cache'):
307 obj.__dict__[k] = None
309 obj.__dict__[k] = copy.deepcopy(v, memo)
313 data = list(self[:REPR_OUTPUT_SIZE + 1])
314 if len(data) > REPR_OUTPUT_SIZE:
315 data[-1] = "...(remaining elements truncated)..."
319 if self._result_cache is None:
320 self._result_cache = list(self)
321 return len(self._result_cache)
324 if self._result_cache is None:
325 self._result_cache = self._execute()
326 return iter(self._result_cache)
328 def __getitem__(self, k):
329 if self._result_cache is None:
330 self._result_cache = list(self)
331 return self._result_cache.__getitem__(k)
334 if self._result_cache is not None:
335 return bool(self._result_cache)
338 except StopIteration:
342 def __nonzero__(self):
343 return type(self).__bool__(self)
345 def _clone(self, klass=None, **kwargs):
347 klass = self.__class__
348 filter_obj = self.filter_obj.clone()
349 c = klass(warrior=self.warrior, filter_obj=filter_obj)
350 c.__dict__.update(kwargs)
355 Fetch the tasks which match the current filters.
357 return self.warrior.filter_tasks(self.filter_obj)
361 Returns a new TaskQuerySet that is a copy of the current one.
366 return self.filter(status=PENDING)
369 return self.filter(status=COMPLETED)
371 def filter(self, *args, **kwargs):
373 Returns a new TaskQuerySet with the given filters added.
375 clone = self._clone()
377 clone.filter_obj.add_filter(f)
378 for key, value in kwargs.items():
379 clone.filter_obj.add_filter_param(key, value)
382 def get(self, **kwargs):
384 Performs the query and returns a single object matching the given
387 clone = self.filter(**kwargs)
390 return clone._result_cache[0]
392 raise Task.DoesNotExist(
393 'Task matching query does not exist. '
394 'Lookup parameters were {0}'.format(kwargs))
396 'get() returned more than one Task -- it returned {0}! '
397 'Lookup parameters were {1}'.format(num, kwargs))
400 class TaskWarrior(object):
401 def __init__(self, data_location='~/.task', create=True):
402 data_location = os.path.expanduser(data_location)
403 if create and not os.path.exists(data_location):
404 os.makedirs(data_location)
406 'data.location': os.path.expanduser(data_location),
408 self.tasks = TaskQuerySet(self)
409 self.version = self._get_version()
411 def _get_command_args(self, args, config_override={}):
412 command_args = ['task', 'rc:/']
413 config = self.config.copy()
414 config.update(config_override)
415 for item in config.items():
416 command_args.append('rc.{0}={1}'.format(*item))
417 command_args.extend(map(str, args))
420 def _get_version(self):
421 p = subprocess.Popen(
422 ['task', '--version'],
423 stdout=subprocess.PIPE,
424 stderr=subprocess.PIPE)
425 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
426 return stdout.strip('\n')
428 def execute_command(self, args, config_override={}):
429 command_args = self._get_command_args(
430 args, config_override=config_override)
431 logger.debug(' '.join(command_args))
432 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
433 stderr=subprocess.PIPE)
434 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
437 error_msg = stderr.strip().splitlines()[-1]
439 error_msg = stdout.strip()
440 raise TaskWarriorException(error_msg)
441 return stdout.strip().split('\n')
443 def filter_tasks(self, filter_obj):
444 args = ['export', '--'] + filter_obj.get_filter_params()
446 for line in self.execute_command(args):
448 data = line.strip(',')
450 tasks.append(Task(self, json.loads(data)))
452 raise TaskWarriorException('Invalid JSON: %s' % data)
455 def merge_with(self, path, push=False):
456 path = path.rstrip('/') + '/'
457 self.execute_command(['merge', path], config_override={
458 'merge.autopush': 'yes' if push else 'no',
462 self.execute_command(['undo'], config_override={
463 'confirmation': 'no',