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.
7 from tasklib.task import TaskQuerySet
8 from tasklib.filters import TaskWarriorFilter
9 from tasklib.serializing import local_zone
11 DATE_FORMAT_CALC = '%Y-%m-%dT%H:%M:%S'
13 VERSION_2_1_0 = six.u('2.1.0')
14 VERSION_2_2_0 = six.u('2.2.0')
15 VERSION_2_3_0 = six.u('2.3.0')
16 VERSION_2_4_0 = six.u('2.4.0')
17 VERSION_2_4_1 = six.u('2.4.1')
18 VERSION_2_4_2 = six.u('2.4.2')
19 VERSION_2_4_3 = six.u('2.4.3')
20 VERSION_2_4_4 = six.u('2.4.4')
21 VERSION_2_4_5 = six.u('2.4.5')
24 class Backend(object):
27 def filter_class(self):
28 """Returns the TaskFilter class used by this backend"""
32 def filter_tasks(self, filter_obj):
33 """Returns a list of Task objects matching the given filter"""
37 def save_task(self, task):
41 def delete_task(self, task):
45 def start_task(self, task):
49 def stop_task(self, task):
53 def complete_task(self, task):
57 def refresh_task(self, task, after_save=False):
59 Refreshes the given task. Returns new data dict with serialized
65 def annotate_task(self, task, annotation):
69 def denotate_task(self, task, annotation):
74 """Syncs the backend database with the taskd server"""
77 def convert_datetime_string(self, value):
79 Converts TW syntax datetime string to a localized datetime
80 object. This method is not mandatory.
85 class TaskWarriorException(Exception):
89 class TaskWarrior(object):
90 def __init__(self, data_location=None, create=True, taskrc_location='~/.taskrc'):
91 self.taskrc_location = os.path.expanduser(taskrc_location)
93 # If taskrc does not exist, pass / to use defaults and avoid creating
94 # dummy .taskrc file by TaskWarrior
95 if not os.path.exists(self.taskrc_location):
96 self.taskrc_location = '/'
98 self.version = self._get_version()
100 'confirmation': 'no',
101 'dependency.confirmation': 'no', # See TW-1483 or taskrc man page
102 'recurrence.confirmation': 'no', # Necessary for modifying R tasks
104 # Defaults to on since 2.4.5, we expect off during parsing
107 # 2.4.3 onwards supports 0 as infite bulk, otherwise set just
108 # arbitrary big number which is likely to be large enough
109 'bulk': 0 if self.version >= VERSION_2_4_3 else 100000,
112 # Set data.location override if passed via kwarg
113 if data_location is not None:
114 data_location = os.path.expanduser(data_location)
115 if create and not os.path.exists(data_location):
116 os.makedirs(data_location)
117 self.config['data.location'] = data_location
119 self.tasks = TaskQuerySet(self)
121 def _get_command_args(self, args, config_override=None):
122 command_args = ['task', 'rc:{0}'.format(self.taskrc_location)]
123 config = self.config.copy()
124 config.update(config_override or dict())
125 for item in config.items():
126 command_args.append('rc.{0}={1}'.format(*item))
127 command_args.extend(map(six.text_type, args))
130 def _get_version(self):
131 p = subprocess.Popen(
132 ['task', '--version'],
133 stdout=subprocess.PIPE,
134 stderr=subprocess.PIPE)
135 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
136 return stdout.strip('\n')
138 def _get_modified_task_fields_as_args(self, task):
141 def add_field(field):
142 # Add the output of format_field method to args list (defaults to
144 serialized_value = task._serialize(field, task._data[field])
146 # Empty values should not be enclosed in quotation marks, see
148 if serialized_value is '':
149 escaped_serialized_value = ''
151 escaped_serialized_value = six.u("'{0}'").format(serialized_value)
153 format_default = lambda: six.u("{0}:{1}").format(field,
154 escaped_serialized_value)
156 format_func = getattr(self, 'format_{0}'.format(field),
159 args.append(format_func(task))
161 # If we're modifying saved task, simply pass on all modified fields
163 for field in task._modified_fields:
165 # For new tasks, pass all fields that make sense
167 for field in task._data.keys():
168 if field in task.read_only_fields:
174 def format_depends(self, task):
175 # We need to generate added and removed dependencies list,
176 # since Taskwarrior does not accept redefining dependencies.
178 # This cannot be part of serialize_depends, since we need
179 # to keep a list of all depedencies in the _data dictionary,
180 # not just currently added/removed ones
182 old_dependencies = task._original_data.get('depends', set())
184 added = self['depends'] - old_dependencies
185 removed = old_dependencies - self['depends']
187 # Removed dependencies need to be prefixed with '-'
188 return 'depends:' + ','.join(
189 [t['uuid'] for t in added] +
190 ['-' + t['uuid'] for t in removed]
193 def format_description(self, task):
194 # Task version older than 2.4.0 ignores first word of the
195 # task description if description: prefix is used
196 if self.version < VERSION_2_4_0:
197 return task._data['description']
199 return six.u("description:'{0}'").format(task._data['description'] or '')
201 def convert_datetime_string(self, value):
203 if self.version >= VERSION_2_4_0:
204 # For strings, use 'task calc' to evaluate the string to datetime
205 # available since TW 2.4.0
207 result = self.execute_command(['calc'] + args)
208 naive = datetime.datetime.strptime(result[0], DATE_FORMAT_CALC)
209 localized = local_zone.localize(naive)
211 raise ValueError("Provided value could not be converted to "
212 "datetime, its type is not supported: {}"
213 .format(type(value)))
216 def filter_class(self):
217 return TaskWarriorFilter
221 def get_config(self):
222 raw_output = self.execute_command(
224 config_override={'verbose': 'nothing'}
228 config_regex = re.compile(r'^(?P<key>[^\s]+)\s+(?P<value>[^\s].+$)')
230 for line in raw_output:
231 match = config_regex.match(line)
233 config[match.group('key')] = match.group('value').strip()
237 def execute_command(self, args, config_override=None, allow_failure=True,
239 command_args = self._get_command_args(
240 args, config_override=config_override)
241 logger.debug(' '.join(command_args))
242 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
243 stderr=subprocess.PIPE)
244 stdout, stderr = [x.decode('utf-8') for x in p.communicate()]
245 if p.returncode and allow_failure:
247 error_msg = stderr.strip()
249 error_msg = stdout.strip()
250 raise TaskWarriorException(error_msg)
252 # Return all whole triplet only if explicitly asked for
254 return stdout.rstrip().split('\n')
256 return (stdout.rstrip().split('\n'),
257 stderr.rstrip().split('\n'),
260 def enforce_recurrence(self):
261 # Run arbitrary report command which will trigger generation
262 # of recurrent tasks.
264 # Only necessary for TW up to 2.4.1, fixed in 2.4.2.
265 if self.version < VERSION_2_4_2:
266 self.execute_command(['next'], allow_failure=False)
268 def merge_with(self, path, push=False):
269 path = path.rstrip('/') + '/'
270 self.execute_command(['merge', path], config_override={
271 'merge.autopush': 'yes' if push else 'no',
275 self.execute_command(['undo'])
277 # Backend interface implementation
279 def filter_tasks(self, filter_obj):
280 self.enforce_recurrence()
281 args = ['export', '--'] + filter_obj.get_filter_params()
283 for line in self.execute_command(args):
285 data = line.strip(',')
287 filtered_task = Task(self)
288 filtered_task._load_data(json.loads(data))
289 tasks.append(filtered_task)
291 raise TaskWarriorException('Invalid JSON: %s' % data)
294 def save_task(self, task):
295 """Save a task into TaskWarrior database using add/modify call"""
297 args = [task['uuid'], 'modify'] if task.saved else ['add']
298 args.extend(self._get_modified_task_fields_as_args(task))
299 output = self.execute_command(args)
301 # Parse out the new ID, if the task is being added for the first time
303 id_lines = [l for l in output if l.startswith('Created task ')]
305 # Complain loudly if it seems that more tasks were created
307 if len(id_lines) != 1 or len(id_lines[0].split(' ')) != 3:
308 raise TaskWarriorException("Unexpected output when creating "
309 "task: %s" % '\n'.join(id_lines))
311 # Circumvent the ID storage, since ID is considered read-only
312 identifier = id_lines[0].split(' ')[2].rstrip('.')
314 # Identifier can be either ID or UUID for completed tasks
316 task._data['id'] = int(identifier)
318 task._data['uuid'] = identifier
320 # Refreshing is very important here, as not only modification time
321 # is updated, but arbitrary attribute may have changed due hooks
322 # altering the data before saving
323 task.refresh(after_save=True)
325 def delete_task(self, task):
326 self.execute_command([task['uuid'], 'delete'])
328 def start_task(self, task):
329 self.execute_command([task['uuid'], 'start'])
331 def stop_task(self, task):
332 self.execute_command([task['uuid'], 'stop'])
334 def complete_task(self, task):
335 # Older versions of TW do not stop active task at completion
336 if self.version < VERSION_2_4_0 and task.active:
339 self.execute_command([task['uuid'], 'done'])
341 def annotate_task(self, task, annotation):
342 args = [task['uuid'], 'annotate', annotation]
343 self.execute_command(args)
345 def denotate_task(self, task, annotation):
346 args = [task['uuid'], 'denotate', annotation]
347 self.execute_command(args)
349 def refresh_task(self, task, after_save=False):
350 # We need to use ID as backup for uuid here for the refreshes
351 # of newly saved tasks. Any other place in the code is fine
352 # with using UUID only.
353 args = [task['uuid'] or task['id'], 'export']
354 output = self.execute_command(args)
357 return len(output) == 1 and output[0].startswith('{')
359 # For older TW versions attempt to uniquely locate the task
360 # using the data we have if it has been just saved.
361 # This can happen when adding a completed task on older TW versions.
362 if (not valid(output) and self.version < VERSION_2_4_5
365 # Make a copy, removing ID and UUID. It's most likely invalid
366 # (ID 0) if it failed to match a unique task.
367 data = copy.deepcopy(task._data)
369 data.pop('uuid', None)
371 taskfilter = self.filter_class(self)
372 for key, value in data.items():
373 taskfilter.add_filter_param(key, value)
375 output = self.execute_command(['export', '--'] +
376 taskfilter.get_filter_params())
378 # If more than 1 task has been matched still, raise an exception
379 if not valid(output):
380 raise TaskWarriorException(
381 "Unique identifiers {0} with description: {1} matches "
382 "multiple tasks: {2}".format(
383 task['uuid'] or task['id'], task['description'], output)
386 return json.loads(output[0])
389 self.execute_command(['sync'])