Commit a6e3dc95 authored by Bram Schoenmakers's avatar Bram Schoenmakers

Add grouping support to the Sorter

parent ac982b13
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
""" This module provides functionality to sort lists with todo items. """ """ This module provides functionality to sort lists with todo items. """
from itertools import groupby
import re import re
from datetime import date from datetime import date
...@@ -93,10 +94,9 @@ class Sorter(object): ...@@ -93,10 +94,9 @@ class Sorter(object):
stable. stable.
""" """
def __init__(self, p_sortstring="desc:priority"): def __init__(self, p_sortstring="desc:priority", p_groupstring=""):
self.sortstring = p_sortstring self.groupfunctions = self._parse(p_groupstring) if p_groupstring else []
self.functions = [] self.sortfunctions = self._parse(p_groupstring + ',' + p_sortstring)
self._parse()
def sort(self, p_todos): def sort(self, p_todos):
""" """
...@@ -108,18 +108,34 @@ class Sorter(object): ...@@ -108,18 +108,34 @@ class Sorter(object):
function. function.
""" """
sorted_todos = p_todos sorted_todos = p_todos
for function, order in reversed(self.functions): for function, order in reversed(self.sortfunctions):
sorted_todos = sorted(sorted_todos, key=function, sorted_todos = sorted(sorted_todos, key=function,
reverse=(order == 'desc')) reverse=(order == 'desc'))
return sorted_todos return sorted_todos
def _parse(self): def group(self, p_todos):
result = [([], self.sort(p_todos))]
for function, _ in self.groupfunctions:
oldresult = result
result = []
for oldkey, oldgroup in oldresult:
for key, group in groupby(oldgroup, function):
newkey = oldkey + [key]
newgroup = list(group)
result.append((newkey, newgroup))
return result
def _parse(self, p_string):
""" """
Parses a sort string and returns a list of functions and the Parses a sort string and returns a list of functions and the
desired order. desired order.
""" """
fields = self.sortstring.lower().split(',') result = []
fields = p_string.lower().split(',')
for field in fields: for field in fields:
parsed_field = re.match( parsed_field = re.match(
...@@ -141,4 +157,23 @@ class Sorter(object): ...@@ -141,4 +157,23 @@ class Sorter(object):
if is_priority_field(field): if is_priority_field(field):
order = 'asc' if order == 'desc' else 'desc' order = 'asc' if order == 'desc' else 'desc'
self.functions.append((function, order)) result.append((function, order))
return result
if __name__ == '__main__':
from topydo.lib.Todo import Todo
todos = [
Todo('Foo +A @A type:a'),
Todo('Foo +A @B type:b'),
Todo('Bar +B @B type:b'),
Todo('Baz +A @B'),
]
s = Sorter('desc:context', 'project,type')
for key, group in s.group(todos):
print(key)
for item2 in group:
print(item2.source())
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment