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 def __init__(self, warrior, data={}):
92 self.warrior = warrior
94 self._modified_fields = set()
96 def __unicode__(self):
97 return self['description']
101 return self['status'] == six.text_type('completed')
105 return self['status'] == six.text_type('deleted')
109 return self['status'] == six.text_type('waiting')
113 return self['status'] == six.text_type('pending')
117 return self['uuid'] is not None or self['id'] is not None
119 def serialize_due(self, date):
120 return date.strftime(DATE_FORMAT)
122 def deserialize_due(self, date_str):
125 return datetime.datetime.strptime(date_str, DATE_FORMAT)
127 def deserialize_annotations(self, data):
128 return [TaskAnnotation(self, d) for d in data] if data else []
130 def deserialize_tags(self, tags):
131 if isinstance(tags, basestring):
132 return tags.split(',') if tags else []
135 def serialize_tags(self, tags):
136 return ','.join(tags) if tags else ''
139 # Refresh the status, and raise exception if the task is deleted
140 self.refresh(only_fields=['status'])
143 raise self.DeletedTask("Task was already deleted")
145 self.warrior.execute_command([self['uuid'], 'delete'], config_override={
146 'confirmation': 'no',
149 # Refresh the status again, so that we have updated info stored
150 self.refresh(only_fields=['status'])
154 # Refresh, and raise exception if task is already completed/deleted
155 self.refresh(only_fields=['status'])
158 raise self.CompletedTask("Cannot complete a completed task")
160 raise self.DeletedTask("Deleted task cannot be completed")
162 self.warrior.execute_command([self['uuid'], 'done'])
164 # Refresh the status again, so that we have updated info stored
165 self.refresh(only_fields=['status'])
168 args = [self['uuid'], 'modify'] if self.saved else ['add']
169 args.extend(self._get_modified_fields_as_args())
170 output = self.warrior.execute_command(args)
172 # Parse out the new ID, if the task is being added for the first time
174 id_lines = [l for l in output if l.startswith('Created task ')]
176 # Complain loudly if it seems that more tasks were created
178 if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
179 raise TaskWarriorException("Unexpected output when creating "
180 "task: %s" % '\n'.join(id_lines))
182 # Circumvent the ID storage, since ID is considered read-only
183 self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
185 self._modified_fields.clear()
188 def add_annotation(self, annotation):
189 args = [self['uuid'], 'annotate', annotation]
190 self.warrior.execute_command(args)
191 # TODO: This will not work with the tasks that are not yet saved
192 self.refresh(only_fields=['annotations'])
194 def remove_annotation(self, annotation):
195 if isinstance(annotation, TaskAnnotation):
196 annotation = annotation['description']
197 args = [self['uuid'], 'denotate', annotation]
198 self.warrior.execute_command(args)
199 # TODO: This will not work with the tasks that are not yet saved
200 self.refresh(only_fields=['annotations'])
202 def _get_modified_fields_as_args(self):
205 # If we're modifying saved task, simply pass on all modified fields
207 for field in self._modified_fields:
208 args.append('{0}:{1}'.format(field, self._data[field]))
209 # For new tasks, pass all fields that make sense
211 for field in self._data.keys():
212 if field in self.read_only_fields:
214 args.append('{0}:{1}'.format(field, self._data[field]))
218 def refresh(self, only_fields=[]):
219 # Do not refresh for tasks that are not yet saved in the TW
223 # We need to use ID as backup for uuid here for the refreshes
224 # of newly saved tasks. Any other place in the code is fine
225 # with using UUID only.
226 args = [self['uuid'] or self['id'], 'export']
227 new_data = json.loads(self.warrior.execute_command(args)[0])
230 [(k, new_data.get(k)) for k in only_fields])
231 self._data.update(to_update)
233 self._data = new_data
236 class TaskFilter(object):
238 A set of parameters to filter the task list with.
241 def __init__(self, filter_params=[]):
242 self.filter_params = filter_params
244 def add_filter(self, filter_str):
245 self.filter_params.append(filter_str)
247 def add_filter_param(self, key, value):
248 key = key.replace('__', '.')
250 # Replace the value with empty string, since that is the
251 # convention in TW for empty values
252 value = value if value is not None else ''
253 self.filter_params.append('{0}:{1}'.format(key, value))
255 def get_filter_params(self):
256 return [f for f in self.filter_params if f]
260 c.filter_params = list(self.filter_params)
264 class TaskQuerySet(object):
266 Represents a lazy lookup for a task objects.
269 def __init__(self, warrior=None, filter_obj=None):
270 self.warrior = warrior
271 self._result_cache = None
272 self.filter_obj = filter_obj or TaskFilter()
274 def __deepcopy__(self, memo):
276 Deep copy of a QuerySet doesn't populate the cache
278 obj = self.__class__()
279 for k, v in self.__dict__.items():
280 if k in ('_iter', '_result_cache'):
281 obj.__dict__[k] = None
283 obj.__dict__[k] = copy.deepcopy(v, memo)
287 data = list(self[:REPR_OUTPUT_SIZE + 1])
288 if len(data) > REPR_OUTPUT_SIZE:
289 data[-1] = "...(remaining elements truncated)..."
293 if self._result_cache is None:
294 self._result_cache = list(self)
295 return len(self._result_cache)
298 if self._result_cache is None:
299 self._result_cache = self._execute()
300 return iter(self._result_cache)
302 def __getitem__(self, k):
303 if self._result_cache is None:
304 self._result_cache = list(self)
305 return self._result_cache.__getitem__(k)
308 if self._result_cache is not None:
309 return bool(self._result_cache)
312 except StopIteration:
316 def __nonzero__(self):
317 return type(self).__bool__(self)
319 def _clone(self, klass=None, **kwargs):
321 klass = self.__class__
322 filter_obj = self.filter_obj.clone()
323 c = klass(warrior=self.warrior, filter_obj=filter_obj)
324 c.__dict__.update(kwargs)
329 Fetch the tasks which match the current filters.
331 return self.warrior.filter_tasks(self.filter_obj)
335 Returns a new TaskQuerySet that is a copy of the current one.
340 return self.filter(status=PENDING)
343 return self.filter(status=COMPLETED)
345 def filter(self, *args, **kwargs):
347 Returns a new TaskQuerySet with the given filters added.
349 clone = self._clone()
351 clone.filter_obj.add_filter(f)
352 for key, value in kwargs.items():
353 clone.filter_obj.add_filter_param(key, value)
356 def get(self, **kwargs):
358 Performs the query and returns a single object matching the given
361 clone = self.filter(**kwargs)
364 return clone._result_cache[0]
366 raise Task.DoesNotExist(
367 'Task matching query does not exist. '
368 'Lookup parameters were {0}'.format(kwargs))
370 'get() returned more than one Task -- it returned {0}! '
371 'Lookup parameters were {1}'.format(num, kwargs))
374 class TaskWarrior(object):
375 def __init__(self, data_location='~/.task', create=True):
376 data_location = os.path.expanduser(data_location)
377 if create and not os.path.exists(data_location):
378 os.makedirs(data_location)
380 'data.location': os.path.expanduser(data_location),
382 self.tasks = TaskQuerySet(self)
384 def _get_command_args(self, args, config_override={}):
385 command_args = ['task', 'rc:/']
386 config = self.config.copy()
387 config.update(config_override)
388 for item in config.items():
389 command_args.append('rc.{0}={1}'.format(*item))
390 command_args.extend(map(str, args))
393 def execute_command(self, args, config_override={}):
394 command_args = self._get_command_args(
395 args, config_override=config_override)
396 logger.debug(' '.join(command_args))
397 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
398 stderr=subprocess.PIPE)
399 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
402 error_msg = stderr.strip().splitlines()[-1]
404 error_msg = stdout.strip()
405 raise TaskWarriorException(error_msg)
406 return stdout.strip().split('\n')
408 def filter_tasks(self, filter_obj):
409 args = ['export', '--'] + filter_obj.get_filter_params()
411 for line in self.execute_command(args):
413 data = line.strip(',')
415 tasks.append(Task(self, json.loads(data)))
417 raise TaskWarriorException('Invalid JSON: %s' % data)
420 def merge_with(self, path, push=False):
421 path = path.rstrip('/') + '/'
422 self.execute_command(['merge', path], config_override={
423 'merge.autopush': 'yes' if push else 'no',
427 self.execute_command(['undo'], config_override={
428 'confirmation': 'no',