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__())
48 class TaskAnnotation(TaskResource):
49 read_only_fields = ['entry', 'description']
51 def __init__(self, task, data={}):
55 def deserialize_entry(self, data):
56 return datetime.datetime.strptime(data, DATE_FORMAT) if data else None
58 def serialize_entry(self, date):
59 return date.strftime(DATE_FORMAT) if date else ''
62 self.task.remove_annotation(self)
64 def __unicode__(self):
65 return self['description']
67 __repr__ = __unicode__
70 class Task(TaskResource):
71 read_only_fields = ['id', 'entry', 'urgency']
73 class DoesNotExist(Exception):
76 def __init__(self, warrior, data={}):
77 self.warrior = warrior
79 self._modified_fields = set()
81 def __unicode__(self):
82 return self['description']
84 def serialize_due(self, date):
85 return date.strftime(DATE_FORMAT)
87 def deserialize_due(self, date_str):
90 return datetime.datetime.strptime(date_str, DATE_FORMAT)
92 def deserialize_annotations(self, data):
93 return [TaskAnnotation(self, d) for d in data] if data else []
95 def deserialize_tags(self, tags):
96 if isinstance(tags, basestring):
97 return tags.split(',') if tags else []
100 def serialize_tags(self, tags):
101 return ','.join(tags) if tags else ''
104 self.warrior.execute_command([self['id'], 'delete'], config_override={
105 'confirmation': 'no',
109 self.warrior.execute_command([self['id'], 'done'])
112 args = [self['id'], 'modify'] if self['id'] else ['add']
113 args.extend(self._get_modified_fields_as_args())
114 self.warrior.execute_command(args)
115 self._modified_fields.clear()
117 def add_annotation(self, annotation):
118 args = [self['id'], 'annotate', annotation]
119 self.warrior.execute_command(args)
120 self.refresh(only_fields=['annotations'])
122 def remove_annotation(self, annotation):
123 if isinstance(annotation, TaskAnnotation):
124 annotation = annotation['description']
125 args = [self['id'], 'denotate', annotation]
126 self.warrior.execute_command(args)
127 self.refresh(only_fields=['annotations'])
129 def _get_modified_fields_as_args(self):
131 for field in self._modified_fields:
132 args.append('{}:{}'.format(field, self._data[field]))
135 def refresh(self, only_fields=[]):
136 args = [self['uuid'], 'export']
137 new_data = json.loads(self.warrior.execute_command(args)[0])
140 [(k, new_data.get(k)) for k in only_fields])
141 self._data.update(to_update)
143 self._data = new_data
146 class TaskFilter(object):
148 A set of parameters to filter the task list with.
151 def __init__(self, filter_params=[]):
152 self.filter_params = filter_params
154 def add_filter(self, filter_str):
155 self.filter_params.append(filter_str)
157 def add_filter_param(self, key, value):
158 key = key.replace('__', '.')
159 self.filter_params.append('{0}:{1}'.format(key, value))
161 def get_filter_params(self):
162 return [f for f in self.filter_params if f]
166 c.filter_params = list(self.filter_params)
170 class TaskQuerySet(object):
172 Represents a lazy lookup for a task objects.
175 def __init__(self, warrior=None, filter_obj=None):
176 self.warrior = warrior
177 self._result_cache = None
178 self.filter_obj = filter_obj or TaskFilter()
180 def __deepcopy__(self, memo):
182 Deep copy of a QuerySet doesn't populate the cache
184 obj = self.__class__()
185 for k, v in self.__dict__.items():
186 if k in ('_iter', '_result_cache'):
187 obj.__dict__[k] = None
189 obj.__dict__[k] = copy.deepcopy(v, memo)
193 data = list(self[:REPR_OUTPUT_SIZE + 1])
194 if len(data) > REPR_OUTPUT_SIZE:
195 data[-1] = "...(remaining elements truncated)..."
199 if self._result_cache is None:
200 self._result_cache = list(self)
201 return len(self._result_cache)
204 if self._result_cache is None:
205 self._result_cache = self._execute()
206 return iter(self._result_cache)
208 def __getitem__(self, k):
209 if self._result_cache is None:
210 self._result_cache = list(self)
211 return self._result_cache.__getitem__(k)
214 if self._result_cache is not None:
215 return bool(self._result_cache)
218 except StopIteration:
222 def __nonzero__(self):
223 return type(self).__bool__(self)
225 def _clone(self, klass=None, **kwargs):
227 klass = self.__class__
228 filter_obj = self.filter_obj.clone()
229 c = klass(warrior=self.warrior, filter_obj=filter_obj)
230 c.__dict__.update(kwargs)
235 Fetch the tasks which match the current filters.
237 return self.warrior.filter_tasks(self.filter_obj)
241 Returns a new TaskQuerySet that is a copy of the current one.
246 return self.filter(status=PENDING)
249 return self.filter(status=COMPLETED)
251 def filter(self, *args, **kwargs):
253 Returns a new TaskQuerySet with the given filters added.
255 clone = self._clone()
257 clone.filter_obj.add_filter(f)
258 for key, value in kwargs.items():
259 clone.filter_obj.add_filter_param(key, value)
262 def get(self, **kwargs):
264 Performs the query and returns a single object matching the given
267 clone = self.filter(**kwargs)
270 return clone._result_cache[0]
272 raise Task.DoesNotExist(
273 'Task matching query does not exist. '
274 'Lookup parameters were {0}'.format(kwargs))
276 'get() returned more than one Task -- it returned {0}! '
277 'Lookup parameters were {1}'.format(num, kwargs))
280 class TaskWarrior(object):
281 def __init__(self, data_location='~/.task', create=True):
282 data_location = os.path.expanduser(data_location)
283 if create and not os.path.exists(data_location):
284 os.makedirs(data_location)
286 'data.location': os.path.expanduser(data_location),
288 self.tasks = TaskQuerySet(self)
290 def _get_command_args(self, args, config_override={}):
291 command_args = ['task', 'rc:/']
292 config = self.config.copy()
293 config.update(config_override)
294 for item in config.items():
295 command_args.append('rc.{0}={1}'.format(*item))
296 command_args.extend(map(str, args))
299 def execute_command(self, args, config_override={}):
300 command_args = self._get_command_args(
301 args, config_override=config_override)
302 logger.debug(' '.join(command_args))
303 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
304 stderr=subprocess.PIPE)
305 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
308 error_msg = stderr.strip().splitlines()[-1]
310 error_msg = stdout.strip()
311 raise TaskWarriorException(error_msg)
312 return stdout.strip().split('\n')
314 def filter_tasks(self, filter_obj):
315 args = ['export', '--'] + filter_obj.get_filter_params()
317 for line in self.execute_command(args):
319 data = line.strip(',')
321 tasks.append(Task(self, json.loads(data)))
323 raise TaskWarriorException('Invalid JSON: %s' % data)
326 def merge_with(self, path, push=False):
327 path = path.rstrip('/') + '/'
328 self.execute_command(['merge', path], config_override={
329 'merge.autopush': 'yes' if push else 'no',
333 self.execute_command(['undo'], config_override={
334 'confirmation': 'no',