Olivier Bourdon | 99c9bcb | 2017-09-07 17:58:42 +0200 | [diff] [blame^] | 1 | # -*- coding: utf-8 -*- |
| 2 | ''' |
| 3 | Module for defining new filter for sorting |
| 4 | host names/alias by FQDN first and alphabetically |
| 5 | ''' |
| 6 | |
| 7 | from jinja2 import Undefined |
| 8 | |
| 9 | def fqdn_sort_fn(n1, n2): |
| 10 | l1 = n1.split('.') |
| 11 | l2 = n2.split('.') |
| 12 | if len(l1) > len(l2): |
| 13 | return -1 |
| 14 | if len(l1) < len(l2): |
| 15 | return 1 |
| 16 | for i1, i2 in zip(l1, l2): |
| 17 | if i1 < i2: |
| 18 | return -1 |
| 19 | if i1 > i2: |
| 20 | return 1 |
| 21 | return 0 |
| 22 | |
| 23 | def fqdn_sort_filter(iterable): |
| 24 | if iterable is None or isinstance(iterable, Undefined): |
| 25 | return iterable |
| 26 | # Do effective custom sorting of iterable here |
| 27 | return sorted(iterable, cmp=fqdn_sort_fn) |