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.
8 DATE_FORMAT = '%Y%m%dT%H%M%SZ'
11 COMPLETED = 'completed'
13 logger = logging.getLogger(__name__)
16 class TaskWarriorException(Exception):
20 class TaskResource(object):
23 def _load_data(self, data):
26 def __getitem__(self, key):
27 hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
29 return hydrate_func(self._data.get(key))
31 def __setitem__(self, key, value):
32 if key in self.read_only_fields:
33 raise RuntimeError('Field \'%s\' is read-only' % key)
34 dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
36 self._data[key] = dehydrate_func(value)
37 self._modified_fields.add(key)
40 return self.__unicode__()
43 class TaskAnnotation(TaskResource):
44 read_only_fields = ['entry', 'description']
46 def __init__(self, task, data={}):
50 def deserialize_entry(self, data):
51 return datetime.datetime.strptime(data, DATE_FORMAT) if data else None
53 def serialize_entry(self, date):
54 return date.strftime(DATE_FORMAT) if date else ''
57 self.task.remove_annotation(self)
59 def __unicode__(self):
60 return self['description']
62 __repr__ = __unicode__
65 class Task(TaskResource):
66 read_only_fields = ['id', 'entry', 'urgency']
68 class DoesNotExist(Exception):
71 def __init__(self, warrior, data={}):
72 self.warrior = warrior
74 self._modified_fields = set()
76 def __unicode__(self):
77 return self['description']
79 def serialize_due(self, date):
80 return date.strftime(DATE_FORMAT)
82 def deserialize_due(self, date_str):
85 return datetime.datetime.strptime(date_str, DATE_FORMAT)
87 def deserialize_annotations(self, data):
88 return [TaskAnnotation(self, d) for d in data] if data else []
90 def deserialize_tags(self, tags):
91 if isinstance(tags, basestring):
92 return tags.split(',') if tags else []
95 def serialize_tags(self, tags):
96 return ','.join(tags) if tags else ''
99 self.warrior.execute_command([self['id'], 'delete'], config_override={
100 'confirmation': 'no',
104 self.warrior.execute_command([self['id'], 'done'])
107 args = [self['id'], 'modify'] if self['id'] else ['add']
108 args.extend(self._get_modified_fields_as_args())
109 self.warrior.execute_command(args)
110 self._modified_fields.clear()
112 def add_annotation(self, annotation):
113 args = [self['id'], 'annotate', annotation]
114 self.warrior.execute_command(args)
115 self.refresh(only_fields=['annotations'])
117 def remove_annotation(self, annotation):
118 if isinstance(annotation, TaskAnnotation):
119 annotation = annotation['description']
120 args = [self['id'], 'denotate', annotation]
121 self.warrior.execute_command(args)
122 self.refresh(only_fields=['annotations'])
124 def _get_modified_fields_as_args(self):
126 for field in self._modified_fields:
127 args.append('{}:{}'.format(field, self._data[field]))
130 def refresh(self, only_fields=[]):
131 args = [self['uuid'], 'export']
132 new_data = json.loads(self.warrior.execute_command(args)[0])
135 [(k, new_data.get(k)) for k in only_fields])
136 self._data.update(to_update)
138 self._data = new_data
141 class TaskFilter(object):
143 A set of parameters to filter the task list with.
146 def __init__(self, filter_params=[]):
147 self.filter_params = filter_params
149 def add_filter(self, filter_str):
150 self.filter_params.append(filter_str)
152 def add_filter_param(self, key, value):
153 key = key.replace('__', '.')
154 self.filter_params.append('{0}:{1}'.format(key, value))
156 def get_filter_params(self):
157 return [f for f in self.filter_params if f]
161 c.filter_params = list(self.filter_params)
165 class TaskQuerySet(object):
167 Represents a lazy lookup for a task objects.
170 def __init__(self, warrior=None, filter_obj=None):
171 self.warrior = warrior
172 self._result_cache = None
173 self.filter_obj = filter_obj or TaskFilter()
175 def __deepcopy__(self, memo):
177 Deep copy of a QuerySet doesn't populate the cache
179 obj = self.__class__()
180 for k, v in self.__dict__.items():
181 if k in ('_iter', '_result_cache'):
182 obj.__dict__[k] = None
184 obj.__dict__[k] = copy.deepcopy(v, memo)
188 data = list(self[:REPR_OUTPUT_SIZE + 1])
189 if len(data) > REPR_OUTPUT_SIZE:
190 data[-1] = "...(remaining elements truncated)..."
194 if self._result_cache is None:
195 self._result_cache = list(self)
196 return len(self._result_cache)
199 if self._result_cache is None:
200 self._result_cache = self._execute()
201 return iter(self._result_cache)
203 def __getitem__(self, k):
204 if self._result_cache is None:
205 self._result_cache = list(self)
206 return self._result_cache.__getitem__(k)
209 if self._result_cache is not None:
210 return bool(self._result_cache)
213 except StopIteration:
217 def __nonzero__(self):
218 return type(self).__bool__(self)
220 def _clone(self, klass=None, **kwargs):
222 klass = self.__class__
223 filter_obj = self.filter_obj.clone()
224 c = klass(warrior=self.warrior, filter_obj=filter_obj)
225 c.__dict__.update(kwargs)
230 Fetch the tasks which match the current filters.
232 return self.warrior.filter_tasks(self.filter_obj)
236 Returns a new TaskQuerySet that is a copy of the current one.
241 return self.filter(status=PENDING)
244 return self.filter(status=COMPLETED)
246 def filter(self, *args, **kwargs):
248 Returns a new TaskQuerySet with the given filters added.
250 clone = self._clone()
252 clone.filter_obj.add_filter(f)
253 for key, value in kwargs.items():
254 clone.filter_obj.add_filter_param(key, value)
257 def get(self, **kwargs):
259 Performs the query and returns a single object matching the given
262 clone = self.filter(**kwargs)
265 return clone._result_cache[0]
267 raise Task.DoesNotExist(
268 'Task matching query does not exist. '
269 'Lookup parameters were {0}'.format(kwargs))
271 'get() returned more than one Task -- it returned {0}! '
272 'Lookup parameters were {1}'.format(num, kwargs))
275 class TaskWarrior(object):
276 def __init__(self, data_location='~/.task', create=True):
277 data_location = os.path.expanduser(data_location)
278 if create and not os.path.exists(data_location):
279 os.makedirs(data_location)
281 'data.location': os.path.expanduser(data_location),
283 self.tasks = TaskQuerySet(self)
285 def _get_command_args(self, args, config_override={}):
286 command_args = ['task', 'rc:/']
287 config = self.config.copy()
288 config.update(config_override)
289 for item in config.items():
290 command_args.append('rc.{0}={1}'.format(*item))
291 command_args.extend(map(str, args))
294 def execute_command(self, args, config_override={}):
295 command_args = self._get_command_args(
296 args, config_override=config_override)
297 logger.debug(' '.join(command_args))
298 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
299 stderr=subprocess.PIPE)
300 stdout, stderr = [x.decode() for x in p.communicate()]
303 error_msg = stderr.strip().splitlines()[-1]
305 error_msg = stdout.strip()
306 raise TaskWarriorException(error_msg)
307 return stdout.strip().split('\n')
309 def filter_tasks(self, filter_obj):
310 args = ['export', '--'] + filter_obj.get_filter_params()
312 for line in self.execute_command(args):
314 data = line.strip(',')
316 tasks.append(Task(self, json.loads(data)))
318 raise TaskWarriorException('Invalid JSON: %s' % data)
321 def merge_with(self, path, push=False):
322 path = path.rstrip('/') + '/'
323 self.execute_command(['merge', path], config_override={
324 'merge.autopush': 'yes' if push else 'no',
328 self.execute_command(['undo'], config_override={
329 'confirmation': 'no',