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']
76 class DoesNotExist(Exception):
79 def __init__(self, warrior, data={}):
80 self.warrior = warrior
82 self._modified_fields = set()
84 def __unicode__(self):
85 return self['description']
87 def serialize_due(self, date):
88 return date.strftime(DATE_FORMAT)
90 def deserialize_due(self, date_str):
93 return datetime.datetime.strptime(date_str, DATE_FORMAT)
95 def deserialize_annotations(self, data):
96 return [TaskAnnotation(self, d) for d in data] if data else []
98 def deserialize_tags(self, tags):
99 if isinstance(tags, basestring):
100 return tags.split(',') if tags else []
103 def serialize_tags(self, tags):
104 return ','.join(tags) if tags else ''
107 self.warrior.execute_command([self['id'], 'delete'], config_override={
108 'confirmation': 'no',
112 self.warrior.execute_command([self['id'], 'done'])
115 args = [self['id'], 'modify'] if self['id'] else ['add']
116 args.extend(self._get_modified_fields_as_args())
117 self.warrior.execute_command(args)
118 self._modified_fields.clear()
120 def add_annotation(self, annotation):
121 args = [self['id'], 'annotate', annotation]
122 self.warrior.execute_command(args)
123 self.refresh(only_fields=['annotations'])
125 def remove_annotation(self, annotation):
126 if isinstance(annotation, TaskAnnotation):
127 annotation = annotation['description']
128 args = [self['id'], 'denotate', annotation]
129 self.warrior.execute_command(args)
130 self.refresh(only_fields=['annotations'])
132 def _get_modified_fields_as_args(self):
134 for field in self._modified_fields:
135 args.append('{}:{}'.format(field, self._data[field]))
138 def refresh(self, only_fields=[]):
139 args = [self['uuid'], 'export']
140 new_data = json.loads(self.warrior.execute_command(args)[0])
143 [(k, new_data.get(k)) for k in only_fields])
144 self._data.update(to_update)
146 self._data = new_data
149 class TaskFilter(object):
151 A set of parameters to filter the task list with.
154 def __init__(self, filter_params=[]):
155 self.filter_params = filter_params
157 def add_filter(self, filter_str):
158 self.filter_params.append(filter_str)
160 def add_filter_param(self, key, value):
161 key = key.replace('__', '.')
163 # Replace the value with empty string, since that is the
164 # convention in TW for empty values
165 value = value if value is not None else ''
167 # If we are filtering by uuid:, do not use uuid keyword
170 self.filter_params.insert(0, value)
172 self.filter_params.append('{0}:{1}'.format(key, value))
174 def get_filter_params(self):
175 return [f for f in self.filter_params if f]
179 c.filter_params = list(self.filter_params)
183 class TaskQuerySet(object):
185 Represents a lazy lookup for a task objects.
188 def __init__(self, warrior=None, filter_obj=None):
189 self.warrior = warrior
190 self._result_cache = None
191 self.filter_obj = filter_obj or TaskFilter()
193 def __deepcopy__(self, memo):
195 Deep copy of a QuerySet doesn't populate the cache
197 obj = self.__class__()
198 for k, v in self.__dict__.items():
199 if k in ('_iter', '_result_cache'):
200 obj.__dict__[k] = None
202 obj.__dict__[k] = copy.deepcopy(v, memo)
206 data = list(self[:REPR_OUTPUT_SIZE + 1])
207 if len(data) > REPR_OUTPUT_SIZE:
208 data[-1] = "...(remaining elements truncated)..."
212 if self._result_cache is None:
213 self._result_cache = list(self)
214 return len(self._result_cache)
217 if self._result_cache is None:
218 self._result_cache = self._execute()
219 return iter(self._result_cache)
221 def __getitem__(self, k):
222 if self._result_cache is None:
223 self._result_cache = list(self)
224 return self._result_cache.__getitem__(k)
227 if self._result_cache is not None:
228 return bool(self._result_cache)
231 except StopIteration:
235 def __nonzero__(self):
236 return type(self).__bool__(self)
238 def _clone(self, klass=None, **kwargs):
240 klass = self.__class__
241 filter_obj = self.filter_obj.clone()
242 c = klass(warrior=self.warrior, filter_obj=filter_obj)
243 c.__dict__.update(kwargs)
248 Fetch the tasks which match the current filters.
250 return self.warrior.filter_tasks(self.filter_obj)
254 Returns a new TaskQuerySet that is a copy of the current one.
259 return self.filter(status=PENDING)
262 return self.filter(status=COMPLETED)
264 def filter(self, *args, **kwargs):
266 Returns a new TaskQuerySet with the given filters added.
268 clone = self._clone()
270 clone.filter_obj.add_filter(f)
271 for key, value in kwargs.items():
272 clone.filter_obj.add_filter_param(key, value)
275 def get(self, **kwargs):
277 Performs the query and returns a single object matching the given
280 clone = self.filter(**kwargs)
283 return clone._result_cache[0]
285 raise Task.DoesNotExist(
286 'Task matching query does not exist. '
287 'Lookup parameters were {0}'.format(kwargs))
289 'get() returned more than one Task -- it returned {0}! '
290 'Lookup parameters were {1}'.format(num, kwargs))
293 class TaskWarrior(object):
294 def __init__(self, data_location='~/.task', create=True):
295 data_location = os.path.expanduser(data_location)
296 if create and not os.path.exists(data_location):
297 os.makedirs(data_location)
299 'data.location': os.path.expanduser(data_location),
301 self.tasks = TaskQuerySet(self)
303 def _get_command_args(self, args, config_override={}):
304 command_args = ['task', 'rc:/']
305 config = self.config.copy()
306 config.update(config_override)
307 for item in config.items():
308 command_args.append('rc.{0}={1}'.format(*item))
309 command_args.extend(map(str, args))
312 def execute_command(self, args, config_override={}):
313 command_args = self._get_command_args(
314 args, config_override=config_override)
315 logger.debug(' '.join(command_args))
316 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
317 stderr=subprocess.PIPE)
318 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
321 error_msg = stderr.strip().splitlines()[-1]
323 error_msg = stdout.strip()
324 raise TaskWarriorException(error_msg)
325 return stdout.strip().split('\n')
327 def filter_tasks(self, filter_obj):
328 args = ['export', '--'] + filter_obj.get_filter_params()
330 for line in self.execute_command(args):
332 data = line.strip(',')
334 tasks.append(Task(self, json.loads(data)))
336 raise TaskWarriorException('Invalid JSON: %s' % data)
339 def merge_with(self, path, push=False):
340 path = path.rstrip('/') + '/'
341 self.execute_command(['merge', path], config_override={
342 'merge.autopush': 'yes' if push else 'no',
346 self.execute_command(['undo'], config_override={
347 'confirmation': 'no',