]> git.madduck.net Git - etc/taskwarrior.git/blob - tasklib/task.py

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

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.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

TaskResource: Do not serialize annotations as a list in a string
[etc/taskwarrior.git] / tasklib / task.py
1 from __future__ import print_function
2 import copy
3 import datetime
4 import json
5 import logging
6 import os
7 import six
8 import sys
9 import subprocess
10
11 DATE_FORMAT = '%Y%m%dT%H%M%SZ'
12 REPR_OUTPUT_SIZE = 10
13 PENDING = 'pending'
14 COMPLETED = 'completed'
15
16 VERSION_2_1_0 = six.u('2.1.0')
17 VERSION_2_2_0 = six.u('2.2.0')
18 VERSION_2_3_0 = six.u('2.3.0')
19 VERSION_2_4_0 = six.u('2.4.0')
20
21 logger = logging.getLogger(__name__)
22
23
24 class TaskWarriorException(Exception):
25     pass
26
27
28 class SerializingObject(object):
29     """
30     Common ancestor for TaskResource & TaskFilter, since they both
31     need to serialize arguments.
32
33     Serializing method should hold the following contract:
34       - any empty value (meaning removal of the attribute)
35         is deserialized into a empty string
36       - None denotes a empty value for any attribute
37
38     Deserializing method should hold the following contract:
39       - None denotes a empty value for any attribute (however,
40         this is here as a safeguard, TaskWarrior currently does
41         not export empty-valued attributes) if the attribute
42         is not iterable (e.g. list or set), in which case
43         a empty iterable should be used.
44     """
45
46     def _deserialize(self, key, value):
47         hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
48                                lambda x: x if x != '' else None)
49         return hydrate_func(value)
50
51     def _serialize(self, key, value):
52         dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
53                                  lambda x: x if x is not None else '')
54         return dehydrate_func(value)
55
56     def timestamp_serializer(self, date):
57         if not date:
58             return ''
59         return date.strftime(DATE_FORMAT)
60
61     def timestamp_deserializer(self, date_str):
62         if not date_str:
63             return None
64         return datetime.datetime.strptime(date_str, DATE_FORMAT)
65
66     def serialize_entry(self, value):
67         return self.timestamp_serializer(value)
68
69     def deserialize_entry(self, value):
70         return self.timestamp_deserializer(value)
71
72     def serialize_modified(self, value):
73         return self.timestamp_serializer(value)
74
75     def deserialize_modified(self, value):
76         return self.timestamp_deserializer(value)
77
78     def serialize_due(self, value):
79         return self.timestamp_serializer(value)
80
81     def deserialize_due(self, value):
82         return self.timestamp_deserializer(value)
83
84     def serialize_scheduled(self, value):
85         return self.timestamp_serializer(value)
86
87     def deserialize_scheduled(self, value):
88         return self.timestamp_deserializer(value)
89
90     def serialize_until(self, value):
91         return self.timestamp_serializer(value)
92
93     def deserialize_until(self, value):
94         return self.timestamp_deserializer(value)
95
96     def serialize_wait(self, value):
97         return self.timestamp_serializer(value)
98
99     def deserialize_wait(self, value):
100         return self.timestamp_deserializer(value)
101
102     def serialize_annotations(self, value):
103         value = value if value is not None else []
104
105         # This may seem weird, but it's correct, we want to export
106         # a list of dicts as serialized value
107         serialized_annotations = [json.loads(annotation.export_data())
108                                   for annotation in value]
109         return serialized_annotations if serialized_annotations else ''
110
111     def deserialize_annotations(self, data):
112         return [TaskAnnotation(self, d) for d in data] if data else []
113
114     def serialize_tags(self, tags):
115         return ','.join(tags) if tags else ''
116
117     def deserialize_tags(self, tags):
118         if isinstance(tags, six.string_types):
119             return tags.split(',') if tags else []
120         return tags or []
121
122     def serialize_depends(self, value):
123         # Return the list of uuids
124         value = value if value is not None else set()
125         return ','.join(task['uuid'] for task in value)
126
127     def deserialize_depends(self, raw_uuids):
128         raw_uuids = raw_uuids or ''  # Convert None to empty string
129         uuids = raw_uuids.split(',')
130         return set(self.warrior.tasks.get(uuid=uuid) for uuid in uuids if uuid)
131
132
133 class TaskResource(SerializingObject):
134     read_only_fields = []
135
136     def _load_data(self, data):
137         self._data = dict((key, self._deserialize(key, value))
138                           for key, value in data.items())
139         # We need to use a copy for original data, so that changes
140         # are not propagated.
141         self._original_data = copy.deepcopy(self._data)
142
143     def _update_data(self, data, update_original=False):
144         """
145         Low level update of the internal _data dict. Data which are coming as
146         updates should already be serialized. If update_original is True, the
147         original_data dict is updated as well.
148         """
149         self._data.update(dict((key, self._deserialize(key, value))
150                                for key, value in data.items()))
151
152         if update_original:
153             self._original_data = copy.deepcopy(self._data)
154
155
156     def __getitem__(self, key):
157         # This is a workaround to make TaskResource non-iterable
158         # over simple index-based iteration
159         try:
160             int(key)
161             raise StopIteration
162         except ValueError:
163             pass
164
165         if key not in self._data:
166             self._data[key] = self._deserialize(key, None)
167
168         return self._data.get(key)
169
170     def __setitem__(self, key, value):
171         if key in self.read_only_fields:
172             raise RuntimeError('Field \'%s\' is read-only' % key)
173         self._data[key] = value
174
175     def __str__(self):
176         s = six.text_type(self.__unicode__())
177         if not six.PY3:
178             s = s.encode('utf-8')
179         return s
180
181     def __repr__(self):
182         return str(self)
183
184     def export_data(self):
185         """
186         Exports current data contained in the Task as JSON
187         """
188
189         # We need to remove spaces for TW-1504, use custom separators
190         data_tuples = ((key, self._serialize(key, value))
191                        for key, value in six.iteritems(self._data))
192
193         # Empty string denotes empty serialized value, we do not want
194         # to pass that to TaskWarrior.
195         data_tuples = filter(lambda t: t[1] is not '', data_tuples)
196         data = dict(data_tuples)
197         return json.dumps(data, separators=(',',':'))
198
199     @property
200     def _modified_fields(self):
201         writable_fields = set(self._data.keys()) - set(self.read_only_fields)
202         for key in writable_fields:
203             new_value = self._data.get(key)
204             old_value = self._original_data.get(key)
205
206             # Make sure not to mark data removal as modified field if the
207             # field originally had some empty value
208             if key in self._data and not new_value and not old_value:
209                 continue
210
211             if new_value != old_value:
212                 yield key
213
214     @property
215     def modified(self):
216         return bool(list(self._modified_fields))
217
218
219 class TaskAnnotation(TaskResource):
220     read_only_fields = ['entry', 'description']
221
222     def __init__(self, task, data={}):
223         self.task = task
224         self._load_data(data)
225
226     def remove(self):
227         self.task.remove_annotation(self)
228
229     def __unicode__(self):
230         return self['description']
231
232     def __eq__(self, other):
233         # consider 2 annotations equal if they belong to the same task, and
234         # their data dics are the same
235         return self.task == other.task and self._data == other._data
236
237     __repr__ = __unicode__
238
239
240 class Task(TaskResource):
241     read_only_fields = ['id', 'entry', 'urgency', 'uuid', 'modified']
242
243     class DoesNotExist(Exception):
244         pass
245
246     class CompletedTask(Exception):
247         """
248         Raised when the operation cannot be performed on the completed task.
249         """
250         pass
251
252     class DeletedTask(Exception):
253         """
254         Raised when the operation cannot be performed on the deleted task.
255         """
256         pass
257
258     class NotSaved(Exception):
259         """
260         Raised when the operation cannot be performed on the task, because
261         it has not been saved to TaskWarrior yet.
262         """
263         pass
264
265     @classmethod
266     def from_input(cls, input_file=sys.stdin, modify=None):
267         """
268         Creates a Task object, directly from the stdin, by reading one line.
269         If modify=True, two lines are used, first line interpreted as the
270         original state of the Task object, and second line as its new,
271         modified value. This is consistent with the TaskWarrior's hook
272         system.
273
274         Object created by this method should not be saved, deleted
275         or refreshed, as t could create a infinite loop. For this
276         reason, TaskWarrior instance is set to None.
277
278         Input_file argument can be used to specify the input file,
279         but defaults to sys.stdin.
280         """
281
282         # TaskWarrior instance is set to None
283         task = cls(None)
284
285         # Detect the hook type if not given directly
286         name = os.path.basename(sys.argv[0])
287         modify = name.startswith('on-modify') if modify is None else modify
288
289         # Load the data from the input
290         task._load_data(json.loads(input_file.readline().strip()))
291
292         # If this is a on-modify event, we are provided with additional
293         # line of input, which provides updated data
294         if modify:
295             task._update_data(json.loads(input_file.readline().strip()))
296
297         return task
298
299     def __init__(self, warrior, **kwargs):
300         self.warrior = warrior
301
302         # Check that user is not able to set read-only value in __init__
303         for key in kwargs.keys():
304             if key in self.read_only_fields:
305                 raise RuntimeError('Field \'%s\' is read-only' % key)
306
307         # We serialize the data in kwargs so that users of the library
308         # do not have to pass different data formats via __setitem__ and
309         # __init__ methods, that would be confusing
310
311         # Rather unfortunate syntax due to python2.6 comaptiblity
312         self._load_data(dict((key, self._serialize(key, value))
313                         for (key, value) in six.iteritems(kwargs)))
314
315     def __unicode__(self):
316         return self['description']
317
318     def __eq__(self, other):
319         if self['uuid'] and other['uuid']:
320             # For saved Tasks, just define equality by equality of uuids
321             return self['uuid'] == other['uuid']
322         else:
323             # If the tasks are not saved, compare the actual instances
324             return id(self) == id(other)
325
326
327     def __hash__(self):
328         if self['uuid']:
329             # For saved Tasks, just define equality by equality of uuids
330             return self['uuid'].__hash__()
331         else:
332             # If the tasks are not saved, return hash of instance id
333             return id(self).__hash__()
334
335     @property
336     def completed(self):
337         return self['status'] == six.text_type('completed')
338
339     @property
340     def deleted(self):
341         return self['status'] == six.text_type('deleted')
342
343     @property
344     def waiting(self):
345         return self['status'] == six.text_type('waiting')
346
347     @property
348     def pending(self):
349         return self['status'] == six.text_type('pending')
350
351     @property
352     def saved(self):
353         return self['uuid'] is not None or self['id'] is not None
354
355     def serialize_depends(self, cur_dependencies):
356         # Check that all the tasks are saved
357         for task in (cur_dependencies or set()):
358             if not task.saved:
359                 raise Task.NotSaved('Task \'%s\' needs to be saved before '
360                                     'it can be set as dependency.' % task)
361
362         return super(Task, self).serialize_depends(cur_dependencies)
363
364     def format_depends(self):
365         # We need to generate added and removed dependencies list,
366         # since Taskwarrior does not accept redefining dependencies.
367
368         # This cannot be part of serialize_depends, since we need
369         # to keep a list of all depedencies in the _data dictionary,
370         # not just currently added/removed ones
371
372         old_dependencies = self._original_data.get('depends', set())
373
374         added = self['depends'] - old_dependencies
375         removed = old_dependencies - self['depends']
376
377         # Removed dependencies need to be prefixed with '-'
378         return 'depends:' + ','.join(
379                 [t['uuid'] for t in added] +
380                 ['-' + t['uuid'] for t in removed]
381             )
382
383     def format_description(self):
384         # Task version older than 2.4.0 ignores first word of the
385         # task description if description: prefix is used
386         if self.warrior.version < VERSION_2_4_0:
387             return self._data['description']
388         else:
389             return "description:'{0}'".format(self._data['description'] or '')
390
391     def delete(self):
392         if not self.saved:
393             raise Task.NotSaved("Task needs to be saved before it can be deleted")
394
395         # Refresh the status, and raise exception if the task is deleted
396         self.refresh(only_fields=['status'])
397
398         if self.deleted:
399             raise Task.DeletedTask("Task was already deleted")
400
401         self.warrior.execute_command([self['uuid'], 'delete'])
402
403         # Refresh the status again, so that we have updated info stored
404         self.refresh(only_fields=['status'])
405
406
407     def done(self):
408         if not self.saved:
409             raise Task.NotSaved("Task needs to be saved before it can be completed")
410
411         # Refresh, and raise exception if task is already completed/deleted
412         self.refresh(only_fields=['status'])
413
414         if self.completed:
415             raise Task.CompletedTask("Cannot complete a completed task")
416         elif self.deleted:
417             raise Task.DeletedTask("Deleted task cannot be completed")
418
419         self.warrior.execute_command([self['uuid'], 'done'])
420
421         # Refresh the status again, so that we have updated info stored
422         self.refresh(only_fields=['status'])
423
424     def save(self):
425         if self.saved and not self.modified:
426             return
427
428         args = [self['uuid'], 'modify'] if self.saved else ['add']
429         args.extend(self._get_modified_fields_as_args())
430         output = self.warrior.execute_command(args)
431
432         # Parse out the new ID, if the task is being added for the first time
433         if not self.saved:
434             id_lines = [l for l in output if l.startswith('Created task ')]
435
436             # Complain loudly if it seems that more tasks were created
437             # Should not happen
438             if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
439                 raise TaskWarriorException("Unexpected output when creating "
440                                            "task: %s" % '\n'.join(id_lines))
441
442             # Circumvent the ID storage, since ID is considered read-only
443             self._data['id'] = int(id_lines[0].split(' ')[2].rstrip('.'))
444
445         # Refreshing is very important here, as not only modification time
446         # is updated, but arbitrary attribute may have changed due hooks
447         # altering the data before saving
448         self.refresh()
449
450     def add_annotation(self, annotation):
451         if not self.saved:
452             raise Task.NotSaved("Task needs to be saved to add annotation")
453
454         args = [self['uuid'], 'annotate', annotation]
455         self.warrior.execute_command(args)
456         self.refresh(only_fields=['annotations'])
457
458     def remove_annotation(self, annotation):
459         if not self.saved:
460             raise Task.NotSaved("Task needs to be saved to remove annotation")
461
462         if isinstance(annotation, TaskAnnotation):
463             annotation = annotation['description']
464         args = [self['uuid'], 'denotate', annotation]
465         self.warrior.execute_command(args)
466         self.refresh(only_fields=['annotations'])
467
468     def _get_modified_fields_as_args(self):
469         args = []
470
471         def add_field(field):
472             # Add the output of format_field method to args list (defaults to
473             # field:value)
474             serialized_value = self._serialize(field, self._data[field])
475
476             # Empty values should not be enclosed in quotation marks, see
477             # TW-1510
478             if serialized_value is '':
479                 escaped_serialized_value = ''
480             else:
481                 escaped_serialized_value = "'{0}'".format(serialized_value)
482
483             format_default = lambda: "{0}:{1}".format(field,
484                                                       escaped_serialized_value)
485
486             format_func = getattr(self, 'format_{0}'.format(field),
487                                   format_default)
488
489             args.append(format_func())
490
491         # If we're modifying saved task, simply pass on all modified fields
492         if self.saved:
493             for field in self._modified_fields:
494                 add_field(field)
495         # For new tasks, pass all fields that make sense
496         else:
497             for field in self._data.keys():
498                 if field in self.read_only_fields:
499                     continue
500                 add_field(field)
501
502         return args
503
504     def refresh(self, only_fields=[]):
505         # Raise error when trying to refresh a task that has not been saved
506         if not self.saved:
507             raise Task.NotSaved("Task needs to be saved to be refreshed")
508
509         # We need to use ID as backup for uuid here for the refreshes
510         # of newly saved tasks. Any other place in the code is fine
511         # with using UUID only.
512         args = [self['uuid'] or self['id'], 'export']
513         new_data = json.loads(self.warrior.execute_command(args)[0])
514         if only_fields:
515             to_update = dict(
516                 [(k, new_data.get(k)) for k in only_fields])
517             self._update_data(to_update, update_original=True)
518         else:
519             self._load_data(new_data)
520
521 class TaskFilter(SerializingObject):
522     """
523     A set of parameters to filter the task list with.
524     """
525
526     def __init__(self, filter_params=[]):
527         self.filter_params = filter_params
528
529     def add_filter(self, filter_str):
530         self.filter_params.append(filter_str)
531
532     def add_filter_param(self, key, value):
533         key = key.replace('__', '.')
534
535         # Replace the value with empty string, since that is the
536         # convention in TW for empty values
537         attribute_key = key.split('.')[0]
538         value = self._serialize(attribute_key, value)
539
540         # If we are filtering by uuid:, do not use uuid keyword
541         # due to TW-1452 bug
542         if key == 'uuid':
543             self.filter_params.insert(0, value)
544         else:
545             # Surround value with aphostrophes unless it's a empty string
546             value = "'%s'" % value if value else ''
547
548             # We enforce equality match by using 'is' (or 'none') modifier
549             # Without using this syntax, filter fails due to TW-1479
550             modifier = '.is' if value else '.none'
551             key = key + modifier if '.' not in key else key
552
553             self.filter_params.append("{0}:{1}".format(key, value))
554
555     def get_filter_params(self):
556         return [f for f in self.filter_params if f]
557
558     def clone(self):
559         c = self.__class__()
560         c.filter_params = list(self.filter_params)
561         return c
562
563
564 class TaskQuerySet(object):
565     """
566     Represents a lazy lookup for a task objects.
567     """
568
569     def __init__(self, warrior=None, filter_obj=None):
570         self.warrior = warrior
571         self._result_cache = None
572         self.filter_obj = filter_obj or TaskFilter()
573
574     def __deepcopy__(self, memo):
575         """
576         Deep copy of a QuerySet doesn't populate the cache
577         """
578         obj = self.__class__()
579         for k, v in self.__dict__.items():
580             if k in ('_iter', '_result_cache'):
581                 obj.__dict__[k] = None
582             else:
583                 obj.__dict__[k] = copy.deepcopy(v, memo)
584         return obj
585
586     def __repr__(self):
587         data = list(self[:REPR_OUTPUT_SIZE + 1])
588         if len(data) > REPR_OUTPUT_SIZE:
589             data[-1] = "...(remaining elements truncated)..."
590         return repr(data)
591
592     def __len__(self):
593         if self._result_cache is None:
594             self._result_cache = list(self)
595         return len(self._result_cache)
596
597     def __iter__(self):
598         if self._result_cache is None:
599             self._result_cache = self._execute()
600         return iter(self._result_cache)
601
602     def __getitem__(self, k):
603         if self._result_cache is None:
604             self._result_cache = list(self)
605         return self._result_cache.__getitem__(k)
606
607     def __bool__(self):
608         if self._result_cache is not None:
609             return bool(self._result_cache)
610         try:
611             next(iter(self))
612         except StopIteration:
613             return False
614         return True
615
616     def __nonzero__(self):
617         return type(self).__bool__(self)
618
619     def _clone(self, klass=None, **kwargs):
620         if klass is None:
621             klass = self.__class__
622         filter_obj = self.filter_obj.clone()
623         c = klass(warrior=self.warrior, filter_obj=filter_obj)
624         c.__dict__.update(kwargs)
625         return c
626
627     def _execute(self):
628         """
629         Fetch the tasks which match the current filters.
630         """
631         return self.warrior.filter_tasks(self.filter_obj)
632
633     def all(self):
634         """
635         Returns a new TaskQuerySet that is a copy of the current one.
636         """
637         return self._clone()
638
639     def pending(self):
640         return self.filter(status=PENDING)
641
642     def completed(self):
643         return self.filter(status=COMPLETED)
644
645     def filter(self, *args, **kwargs):
646         """
647         Returns a new TaskQuerySet with the given filters added.
648         """
649         clone = self._clone()
650         for f in args:
651             clone.filter_obj.add_filter(f)
652         for key, value in kwargs.items():
653             clone.filter_obj.add_filter_param(key, value)
654         return clone
655
656     def get(self, **kwargs):
657         """
658         Performs the query and returns a single object matching the given
659         keyword arguments.
660         """
661         clone = self.filter(**kwargs)
662         num = len(clone)
663         if num == 1:
664             return clone._result_cache[0]
665         if not num:
666             raise Task.DoesNotExist(
667                 'Task matching query does not exist. '
668                 'Lookup parameters were {0}'.format(kwargs))
669         raise ValueError(
670             'get() returned more than one Task -- it returned {0}! '
671             'Lookup parameters were {1}'.format(num, kwargs))
672
673
674 class TaskWarrior(object):
675     def __init__(self, data_location='~/.task', create=True):
676         data_location = os.path.expanduser(data_location)
677         if create and not os.path.exists(data_location):
678             os.makedirs(data_location)
679         self.config = {
680             'data.location': os.path.expanduser(data_location),
681             'confirmation': 'no',
682             'dependency.confirmation': 'no',  # See TW-1483 or taskrc man page
683             'recurrence.confirmation': 'no',  # Necessary for modifying R tasks
684         }
685         self.tasks = TaskQuerySet(self)
686         self.version = self._get_version()
687
688     def _get_command_args(self, args, config_override={}):
689         command_args = ['task', 'rc:/']
690         config = self.config.copy()
691         config.update(config_override)
692         for item in config.items():
693             command_args.append('rc.{0}={1}'.format(*item))
694         command_args.extend(map(str, args))
695         return command_args
696
697     def _get_version(self):
698         p = subprocess.Popen(
699                 ['task', '--version'],
700                 stdout=subprocess.PIPE,
701                 stderr=subprocess.PIPE)
702         stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
703         return stdout.strip('\n')
704
705     def execute_command(self, args, config_override={}):
706         command_args = self._get_command_args(
707             args, config_override=config_override)
708         logger.debug(' '.join(command_args))
709         p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
710                              stderr=subprocess.PIPE)
711         stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
712         if p.returncode:
713             if stderr.strip():
714                 error_msg = stderr.strip().splitlines()[-1]
715             else:
716                 error_msg = stdout.strip()
717             raise TaskWarriorException(error_msg)
718         return stdout.strip().split('\n')
719
720     def filter_tasks(self, filter_obj):
721         args = ['export', '--'] + filter_obj.get_filter_params()
722         tasks = []
723         for line in self.execute_command(args):
724             if line:
725                 data = line.strip(',')
726                 try:
727                     filtered_task = Task(self)
728                     filtered_task._load_data(json.loads(data))
729                     tasks.append(filtered_task)
730                 except ValueError:
731                     raise TaskWarriorException('Invalid JSON: %s' % data)
732         return tasks
733
734     def merge_with(self, path, push=False):
735         path = path.rstrip('/') + '/'
736         self.execute_command(['merge', path], config_override={
737             'merge.autopush': 'yes' if push else 'no',
738         })
739
740     def undo(self):
741         self.execute_command(['undo'])