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 | |
azvyagintsev | 42b64a1 | 2018-08-17 11:47:45 +0300 | [diff] [blame] | 9 | def __virtual__(): |
| 10 | return 'linux_hosts' |
| 11 | |
Olivier Bourdon | 99c9bcb | 2017-09-07 17:58:42 +0200 | [diff] [blame] | 12 | def fqdn_sort_fn(n1, n2): |
| 13 | l1 = n1.split('.') |
| 14 | l2 = n2.split('.') |
| 15 | if len(l1) > len(l2): |
| 16 | return -1 |
| 17 | if len(l1) < len(l2): |
| 18 | return 1 |
| 19 | for i1, i2 in zip(l1, l2): |
| 20 | if i1 < i2: |
| 21 | return -1 |
| 22 | if i1 > i2: |
| 23 | return 1 |
| 24 | return 0 |
| 25 | |
| 26 | def fqdn_sort_filter(iterable): |
| 27 | if iterable is None or isinstance(iterable, Undefined): |
| 28 | return iterable |
| 29 | # Do effective custom sorting of iterable here |
Olivier Bourdon | c8f6882 | 2017-09-13 13:35:22 +0200 | [diff] [blame] | 30 | return sorted(set(iterable), cmp=fqdn_sort_fn) |