18
18
from ansible import errors
19
19
import jinja2
20
20
import re
21
+ import pprint
21
22
22
23
# Pattern to match a hostname with numerical ending
23
24
pattern = re .compile ("^(.*\D(?=\d))(\d+)$" )
@@ -49,6 +50,8 @@ def hostlist_expression(hosts):
49
50
Then "{{ groups[compute] | hostlist_expression }}" will return:
50
51
51
52
['dev-foo-[00,04-05,3]', 'dev-compute-[000-001]', 'my-random-host']
53
+
54
+ NB: This does not guranteed to return parts in the same order as `scontrol hostlist`, but its output should return the same hosts when passed to `scontrol hostnames`.
52
55
"""
53
56
54
57
results = {}
@@ -57,24 +60,25 @@ def hostlist_expression(hosts):
57
60
m = pattern .match (v )
58
61
if m :
59
62
prefix , suffix = m .groups ()
60
- print (prefix ,suffix )
61
63
r = results .setdefault (prefix , [])
62
64
r .append (suffix )
63
65
else :
64
66
unmatchable .append (v )
65
67
return ['{}[{}]' .format (k , _group_numbers (v )) for k , v in results .items ()] + unmatchable
66
68
67
69
def _group_numbers (numbers ):
68
- print ('numbers:' , sorted (numbers ))
69
70
units = []
70
- prev = min (int (n ) for n in numbers )
71
- for v in sorted (numbers ):
72
- if int (v ) == prev + 1 :
73
- units [- 1 ].append (v )
71
+ ints = [int (n ) for n in numbers ]
72
+ lengths = [len (n ) for n in numbers ]
73
+ # sort numbers by int value and length:
74
+ ints , lengths , numbers = zip (* sorted (zip (ints , lengths , numbers )))
75
+ prev = min (ints )
76
+ for i , v in enumerate (sorted (ints )):
77
+ if v == prev + 1 :
78
+ units [- 1 ].append (numbers [i ])
74
79
else :
75
- units .append ([v ])
76
- print ('units:' , units )
77
- prev = int (v )
80
+ units .append ([numbers [i ]])
81
+ prev = v
78
82
return ',' .join (['{}-{}' .format (u [0 ], u [- 1 ]) if len (u ) > 1 else str (u [0 ]) for u in units ])
79
83
80
84
def error (condition , msg ):
0 commit comments