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 logger = logging.getLogger(__name__)
18 class TaskWarriorException(Exception):
22 class TaskResource(object):
25 def _load_data(self, data):
28 def __getitem__(self, key):
29 hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
31 return hydrate_func(self._data.get(key))
33 def __setitem__(self, key, value):
34 if key in self.read_only_fields:
35 raise RuntimeError('Field \'%s\' is read-only' % key)
36 dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
38 self._data[key] = dehydrate_func(value)
39 self._modified_fields.add(key)
42 s = six.text_type(self.__unicode__())
51 class TaskAnnotation(TaskResource):
52 read_only_fields = ['entry', 'description']
54 def __init__(self, task, data={}):
58 def deserialize_entry(self, data):
59 return datetime.datetime.strptime(data, DATE_FORMAT) if data else None
61 def serialize_entry(self, date):
62 return date.strftime(DATE_FORMAT) if date else ''
65 self.task.remove_annotation(self)
67 def __unicode__(self):
68 return self['description']
70 __repr__ = __unicode__
73 class Task(TaskResource):
74 read_only_fields = ['id', 'entry', 'urgency', 'uuid']
76 class DoesNotExist(Exception):
79 class CompletedTask(Exception):
81 Raised when the operation cannot be performed on the completed task.
85 class DeletedTask(Exception):
87 Raised when the operation cannot be performed on the deleted task.
91 class NotSaved(Exception):
93 Raised when the operation cannot be performed on the task, because
94 it has not been saved to TaskWarrior yet.
98 def __init__(self, warrior, data={}, **kwargs):
99 self.warrior = warrior
101 # We keep data for backwards compatibility
104 self._load_data(kwargs)
105 self._modified_fields = set()
107 def __unicode__(self):
108 return self['description']
112 return self['status'] == six.text_type('completed')
116 return self['status'] == six.text_type('deleted')
120 return self['status'] == six.text_type('waiting')
124 return self['status'] == six.text_type('pending')
128 return self['uuid'] is not None or self['id'] is not None
130 def serialize_due(self, date):
131 return date.strftime(DATE_FORMAT)
133 def deserialize_due(self, date_str):
136 return datetime.datetime.strptime(date_str, DATE_FORMAT)
138 def deserialize_annotations(self, data):
139 return [TaskAnnotation(self, d) for d in data] if data else []
141 def deserialize_tags(self, tags):
142 if isinstance(tags, basestring):
143 return tags.split(',') if tags else []
146 def serialize_tags(self, tags):
147 return ','.join(tags) if tags else ''
151 raise self.NotSaved("Task needs to be saved before it can be deleted")
153 # Refresh the status, and raise exception if the task is deleted
154 self.refresh(only_fields=['status'])
157 raise self.DeletedTask("Task was already deleted")
159 self.warrior.execute_command([self['uuid'], 'delete'], config_override={
160 'confirmation': 'no',
163 # Refresh the status again, so that we have updated info stored
164 self.refresh(only_fields=['status'])
169 raise self.NotSaved("Task needs to be saved before it can be completed")
171 # Refresh, and raise exception if task is already completed/deleted
172 self.refresh(only_fields=['status'])
175 raise self.CompletedTask("Cannot complete a completed task")
177 raise self.DeletedTask("Deleted task cannot be completed")
179 self.warrior.execute_command([self['uuid'], 'done'])
181 # Refresh the status again, so that we have updated info stored
182 self.refresh(only_fields=['status'])
185 args = [self['uuid'], 'modify'] if self.saved else ['add']
186 args.extend(self._get_modified_fields_as_args())
187 output = self.warrior.execute_command(args)
189 # Parse out the new ID, if the task is being added for the first time
191 id_lines = [l for l in output if l.startswith('Created task ')]
193 # Complain loudly if it seems that more tasks were created
195 if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
196 raise TaskWarriorException("Unexpected output when creating "
197 "task: %s" % '\n'.join(id_lines))
199 # Circumvent the ID storage, since ID is considered read-only
200 self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
202 self._modified_fields.clear()
205 def add_annotation(self, annotation):
207 raise self.NotSaved("Task needs to be saved to add annotation")
209 args = [self['uuid'], 'annotate', annotation]
210 self.warrior.execute_command(args)
211 self.refresh(only_fields=['annotations'])
213 def remove_annotation(self, annotation):
215 raise self.NotSaved("Task needs to be saved to add annotation")
217 if isinstance(annotation, TaskAnnotation):
218 annotation = annotation['description']
219 args = [self['uuid'], 'denotate', annotation]
220 self.warrior.execute_command(args)
221 self.refresh(only_fields=['annotations'])
223 def _get_modified_fields_as_args(self):
226 # If we're modifying saved task, simply pass on all modified fields
228 for field in self._modified_fields:
229 args.append('{0}:{1}'.format(field, self._data[field]))
230 # For new tasks, pass all fields that make sense
232 for field in self._data.keys():
233 if field in self.read_only_fields:
235 args.append('{0}:{1}'.format(field, self._data[field]))
239 def refresh(self, only_fields=[]):
240 # Raise error when trying to refresh a task that has not been saved
242 raise self.NotSaved("Task needs to be saved to be refreshed")
244 # We need to use ID as backup for uuid here for the refreshes
245 # of newly saved tasks. Any other place in the code is fine
246 # with using UUID only.
247 args = [self['uuid'] or self['id'], 'export']
248 new_data = json.loads(self.warrior.execute_command(args)[0])
251 [(k, new_data.get(k)) for k in only_fields])
252 self._data.update(to_update)
254 self._data = new_data
257 class TaskFilter(object):
259 A set of parameters to filter the task list with.
262 def __init__(self, filter_params=[]):
263 self.filter_params = filter_params
265 def add_filter(self, filter_str):
266 self.filter_params.append(filter_str)
268 def add_filter_param(self, key, value):
269 key = key.replace('__', '.')
271 # Replace the value with empty string, since that is the
272 # convention in TW for empty values
273 value = value if value is not None else ''
274 self.filter_params.append('{0}:{1}'.format(key, value))
276 def get_filter_params(self):
277 return [f for f in self.filter_params if f]
281 c.filter_params = list(self.filter_params)
285 class TaskQuerySet(object):
287 Represents a lazy lookup for a task objects.
290 def __init__(self, warrior=None, filter_obj=None):
291 self.warrior = warrior
292 self._result_cache = None
293 self.filter_obj = filter_obj or TaskFilter()
295 def __deepcopy__(self, memo):
297 Deep copy of a QuerySet doesn't populate the cache
299 obj = self.__class__()
300 for k, v in self.__dict__.items():
301 if k in ('_iter', '_result_cache'):
302 obj.__dict__[k] = None
304 obj.__dict__[k] = copy.deepcopy(v, memo)
308 data = list(self[:REPR_OUTPUT_SIZE + 1])
309 if len(data) > REPR_OUTPUT_SIZE:
310 data[-1] = "...(remaining elements truncated)..."
314 if self._result_cache is None:
315 self._result_cache = list(self)
316 return len(self._result_cache)
319 if self._result_cache is None:
320 self._result_cache = self._execute()
321 return iter(self._result_cache)
323 def __getitem__(self, k):
324 if self._result_cache is None:
325 self._result_cache = list(self)
326 return self._result_cache.__getitem__(k)
329 if self._result_cache is not None:
330 return bool(self._result_cache)
333 except StopIteration:
337 def __nonzero__(self):
338 return type(self).__bool__(self)
340 def _clone(self, klass=None, **kwargs):
342 klass = self.__class__
343 filter_obj = self.filter_obj.clone()
344 c = klass(warrior=self.warrior, filter_obj=filter_obj)
345 c.__dict__.update(kwargs)
350 Fetch the tasks which match the current filters.
352 return self.warrior.filter_tasks(self.filter_obj)
356 Returns a new TaskQuerySet that is a copy of the current one.
361 return self.filter(status=PENDING)
364 return self.filter(status=COMPLETED)
366 def filter(self, *args, **kwargs):
368 Returns a new TaskQuerySet with the given filters added.
370 clone = self._clone()
372 clone.filter_obj.add_filter(f)
373 for key, value in kwargs.items():
374 clone.filter_obj.add_filter_param(key, value)
377 def get(self, **kwargs):
379 Performs the query and returns a single object matching the given
382 clone = self.filter(**kwargs)
385 return clone._result_cache[0]
387 raise Task.DoesNotExist(
388 'Task matching query does not exist. '
389 'Lookup parameters were {0}'.format(kwargs))
391 'get() returned more than one Task -- it returned {0}! '
392 'Lookup parameters were {1}'.format(num, kwargs))
395 class TaskWarrior(object):
396 def __init__(self, data_location='~/.task', create=True):
397 data_location = os.path.expanduser(data_location)
398 if create and not os.path.exists(data_location):
399 os.makedirs(data_location)
401 'data.location': os.path.expanduser(data_location),
403 self.tasks = TaskQuerySet(self)
405 def _get_command_args(self, args, config_override={}):
406 command_args = ['task', 'rc:/']
407 config = self.config.copy()
408 config.update(config_override)
409 for item in config.items():
410 command_args.append('rc.{0}={1}'.format(*item))
411 command_args.extend(map(str, args))
414 def execute_command(self, args, config_override={}):
415 command_args = self._get_command_args(
416 args, config_override=config_override)
417 logger.debug(' '.join(command_args))
418 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
419 stderr=subprocess.PIPE)
420 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
423 error_msg = stderr.strip().splitlines()[-1]
425 error_msg = stdout.strip()
426 raise TaskWarriorException(error_msg)
427 return stdout.strip().split('\n')
429 def filter_tasks(self, filter_obj):
430 args = ['export', '--'] + filter_obj.get_filter_params()
432 for line in self.execute_command(args):
434 data = line.strip(',')
436 tasks.append(Task(self, json.loads(data)))
438 raise TaskWarriorException('Invalid JSON: %s' % data)
441 def merge_with(self, path, push=False):
442 path = path.rstrip('/') + '/'
443 self.execute_command(['merge', path], config_override={
444 'merge.autopush': 'yes' if push else 'no',
448 self.execute_command(['undo'], config_override={
449 'confirmation': 'no',