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('__', '.')
162 self.filter_params.append('{0}:{1}'.format(key, value))
164 def get_filter_params(self):
165 return [f for f in self.filter_params if f]
169 c.filter_params = list(self.filter_params)
173 class TaskQuerySet(object):
175 Represents a lazy lookup for a task objects.
178 def __init__(self, warrior=None, filter_obj=None):
179 self.warrior = warrior
180 self._result_cache = None
181 self.filter_obj = filter_obj or TaskFilter()
183 def __deepcopy__(self, memo):
185 Deep copy of a QuerySet doesn't populate the cache
187 obj = self.__class__()
188 for k, v in self.__dict__.items():
189 if k in ('_iter', '_result_cache'):
190 obj.__dict__[k] = None
192 obj.__dict__[k] = copy.deepcopy(v, memo)
196 data = list(self[:REPR_OUTPUT_SIZE + 1])
197 if len(data) > REPR_OUTPUT_SIZE:
198 data[-1] = "...(remaining elements truncated)..."
202 if self._result_cache is None:
203 self._result_cache = list(self)
204 return len(self._result_cache)
207 if self._result_cache is None:
208 self._result_cache = self._execute()
209 return iter(self._result_cache)
211 def __getitem__(self, k):
212 if self._result_cache is None:
213 self._result_cache = list(self)
214 return self._result_cache.__getitem__(k)
217 if self._result_cache is not None:
218 return bool(self._result_cache)
221 except StopIteration:
225 def __nonzero__(self):
226 return type(self).__bool__(self)
228 def _clone(self, klass=None, **kwargs):
230 klass = self.__class__
231 filter_obj = self.filter_obj.clone()
232 c = klass(warrior=self.warrior, filter_obj=filter_obj)
233 c.__dict__.update(kwargs)
238 Fetch the tasks which match the current filters.
240 return self.warrior.filter_tasks(self.filter_obj)
244 Returns a new TaskQuerySet that is a copy of the current one.
249 return self.filter(status=PENDING)
252 return self.filter(status=COMPLETED)
254 def filter(self, *args, **kwargs):
256 Returns a new TaskQuerySet with the given filters added.
258 clone = self._clone()
260 clone.filter_obj.add_filter(f)
261 for key, value in kwargs.items():
262 clone.filter_obj.add_filter_param(key, value)
265 def get(self, **kwargs):
267 Performs the query and returns a single object matching the given
270 clone = self.filter(**kwargs)
273 return clone._result_cache[0]
275 raise Task.DoesNotExist(
276 'Task matching query does not exist. '
277 'Lookup parameters were {0}'.format(kwargs))
279 'get() returned more than one Task -- it returned {0}! '
280 'Lookup parameters were {1}'.format(num, kwargs))
283 class TaskWarrior(object):
284 def __init__(self, data_location='~/.task', create=True):
285 data_location = os.path.expanduser(data_location)
286 if create and not os.path.exists(data_location):
287 os.makedirs(data_location)
289 'data.location': os.path.expanduser(data_location),
291 self.tasks = TaskQuerySet(self)
293 def _get_command_args(self, args, config_override={}):
294 command_args = ['task', 'rc:/']
295 config = self.config.copy()
296 config.update(config_override)
297 for item in config.items():
298 command_args.append('rc.{0}={1}'.format(*item))
299 command_args.extend(map(str, args))
302 def execute_command(self, args, config_override={}):
303 command_args = self._get_command_args(
304 args, config_override=config_override)
305 logger.debug(' '.join(command_args))
306 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
307 stderr=subprocess.PIPE)
308 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
311 error_msg = stderr.strip().splitlines()[-1]
313 error_msg = stdout.strip()
314 raise TaskWarriorException(error_msg)
315 return stdout.strip().split('\n')
317 def filter_tasks(self, filter_obj):
318 args = ['export', '--'] + filter_obj.get_filter_params()
320 for line in self.execute_command(args):
322 data = line.strip(',')
324 tasks.append(Task(self, json.loads(data)))
326 raise TaskWarriorException('Invalid JSON: %s' % data)
329 def merge_with(self, path, push=False):
330 path = path.rstrip('/') + '/'
331 self.execute_command(['merge', path], config_override={
332 'merge.autopush': 'yes' if push else 'no',
336 self.execute_command(['undo'], config_override={
337 'confirmation': 'no',