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):
22 class DoesNotExist(Exception):
25 def __init__(self, warrior, data={}):
26 self.warrior = warrior
29 self._modified_fields = set()
31 def __unicode__(self):
32 return self['description']
34 def __getitem__(self, key):
35 hydrate_func = getattr(self, 'deserialize_{0}'.format(key),
37 return hydrate_func(self._data.get(key))
39 def __setitem__(self, key, value):
40 dehydrate_func = getattr(self, 'serialize_{0}'.format(key),
42 self._data[key] = dehydrate_func(value)
43 self._modified_fields.add(key)
45 def serialize_due(self, date):
46 return date.strftime(DATE_FORMAT)
48 def deserialize_due(self, date_str):
51 return datetime.datetime.strptime(date_str, DATE_FORMAT)
53 def serialize_annotations(self, annotations):
54 ann_list = list(annotations)
56 ann['entry'] = ann['entry'].strftime(DATE_FORMAT)
59 def deserialize_annotations(self, annotations):
60 ann_list = list(annotations)
62 ann['entry'] = datetime.datetime.strptime(
63 ann['entry'], DATE_FORMAT)
66 def deserialize_tags(self, tags):
67 if isinstance(tags, basestring):
68 return tags.split(',') if tags else []
71 def serialize_tags(self, tags):
72 return ','.join(tags) if tags else ''
75 self.warrior.execute_command([self['id'], 'delete'], config_override={
80 self.warrior.execute_command([self['id'], 'done'])
83 args = [self['id'], 'modify'] if self['id'] else ['add']
84 args.extend(self._get_modified_fields_as_args())
85 self.warrior.execute_command(args)
86 self._modified_fields.clear()
88 def _get_modified_fields_as_args(self):
90 for field in self._modified_fields:
91 args.append('{}:{}'.format(field, self._data[field]))
94 __repr__ = __unicode__
97 class TaskFilter(object):
99 A set of parameters to filter the task list with.
102 def __init__(self, filter_params=[]):
103 self.filter_params = filter_params
105 def add_filter(self, filter_str):
106 self.filter_params.append(filter_str)
108 def add_filter_param(self, key, value):
109 key = key.replace('__', '.')
110 self.filter_params.append('{0}:{1}'.format(key, value))
112 def get_filter_params(self):
113 return [f for f in self.filter_params if f]
117 c.filter_params = list(self.filter_params)
121 class TaskQuerySet(object):
123 Represents a lazy lookup for a task objects.
126 def __init__(self, warrior=None, filter_obj=None):
127 self.warrior = warrior
128 self._result_cache = None
129 self.filter_obj = filter_obj or TaskFilter()
131 def __deepcopy__(self, memo):
133 Deep copy of a QuerySet doesn't populate the cache
135 obj = self.__class__()
136 for k, v in self.__dict__.items():
137 if k in ('_iter', '_result_cache'):
138 obj.__dict__[k] = None
140 obj.__dict__[k] = copy.deepcopy(v, memo)
144 data = list(self[:REPR_OUTPUT_SIZE + 1])
145 if len(data) > REPR_OUTPUT_SIZE:
146 data[-1] = "...(remaining elements truncated)..."
150 if self._result_cache is None:
151 self._result_cache = list(self)
152 return len(self._result_cache)
155 if self._result_cache is None:
156 self._result_cache = self._execute()
157 return iter(self._result_cache)
159 def __getitem__(self, k):
160 if self._result_cache is None:
161 self._result_cache = list(self)
162 return self._result_cache.__getitem__(k)
165 if self._result_cache is not None:
166 return bool(self._result_cache)
169 except StopIteration:
173 def __nonzero__(self):
174 return type(self).__bool__(self)
176 def _clone(self, klass=None, **kwargs):
178 klass = self.__class__
179 filter_obj = self.filter_obj.clone()
180 c = klass(warrior=self.warrior, filter_obj=filter_obj)
181 c.__dict__.update(kwargs)
186 Fetch the tasks which match the current filters.
188 return self.warrior.filter_tasks(self.filter_obj)
192 Returns a new TaskQuerySet that is a copy of the current one.
197 return self.filter(status=PENDING)
200 return self.filter(status=COMPLETED)
202 def filter(self, *args, **kwargs):
204 Returns a new TaskQuerySet with the given filters added.
206 clone = self._clone()
208 clone.filter_obj.add_filter(f)
209 for key, value in kwargs.items():
210 clone.filter_obj.add_filter_param(key, value)
213 def get(self, **kwargs):
215 Performs the query and returns a single object matching the given
218 clone = self.filter(**kwargs)
221 return clone._result_cache[0]
223 raise Task.DoesNotExist(
224 'Task matching query does not exist. '
225 'Lookup parameters were {0}'.format(kwargs))
227 'get() returned more than one Task -- it returned {0}! '
228 'Lookup parameters were {1}'.format(num, kwargs))
231 class TaskWarrior(object):
232 def __init__(self, data_location='~/.task', create=True):
233 data_location = os.path.expanduser(data_location)
234 if not os.path.exists(data_location):
235 os.makedirs(data_location)
237 'data.location': os.path.expanduser(data_location),
239 self.tasks = TaskQuerySet(self)
241 def _get_command_args(self, args, config_override={}):
242 command_args = ['task', 'rc:/']
243 config = self.config.copy()
244 config.update(config_override)
245 for item in config.items():
246 command_args.append('rc.{0}={1}'.format(*item))
247 command_args.extend(map(str, args))
250 def execute_command(self, args, config_override={}):
251 command_args = self._get_command_args(
252 args, config_override=config_override)
253 logger.debug(' '.join(command_args))
254 p = subprocess.Popen(command_args, stdout=subprocess.PIPE,
255 stderr=subprocess.PIPE)
256 stdout, stderr = p.communicate()
258 error_msg = stderr.strip().splitlines()[-1]
259 raise TaskWarriorException(error_msg)
260 return stdout.strip().split('\n')
262 def filter_tasks(self, filter_obj):
263 args = ['export', '--'] + filter_obj.get_filter_params()
265 for line in self.execute_command(args):
267 tasks.append(Task(self, json.loads(line.strip(','))))
270 def merge_with(self, path, push=False):
271 path = path.rstrip('/') + '/'
272 self.execute_command(['merge', path], config_override={
273 'merge.autopush': 'yes' if push else 'no',
277 self.execute_command(['undo'], config_override={
278 'confirmation': 'no',