Commit 7a338612 authored by Antoine Millet's avatar Antoine Millet
Browse files

Sorting operator is now done with a natural sorting algorithm

parent 0c2f2af5
Loading
Loading
Loading
Loading
+14 −1
Original line number Diff line number Diff line
""" Main class of the TQL database.
"""

import re
import time
from copy import copy
from fnmatch import fnmatch
from functools import partial

import ply.yacc as yacc

@@ -17,6 +19,17 @@ from cloudcontrol.common.tql.parser.ast import (Filter, FilterPresence,
                                                ShowOperator, LimitOperator,
                                                SortOperator)


RE_NATURAL_SORTING = re.compile('([0-9]+|[^0-9]+)')


def natural_tag_sorter(tag, obj):
    """ Natural sorter for a tag in an object.
    """
    value = obj.get(tag) if tag in obj else ''
    return tuple(int(x) if x.isdigit() else x
                 for x in RE_NATURAL_SORTING.findall(value))

#
# Response objects:
#
@@ -193,7 +206,7 @@ class TqlResponse(object):
        """ Return a new TqlResponse with objects sorted by provided tag.
        """
        self.fetch(tag)
        sorter = lambda obj: obj.get(tag) if tag in obj else lambda obj: None
        sorter = partial(natural_tag_sorter, tag)
        objects = tuple(sorted(self._objects.itervalues(), key=sorter, reverse=reverse))
        for obj in objects:
            obj.show.add(tag)