From ca0ec800d8b6d2dee99d5e13ae8891f8cd455277 Mon Sep 17 00:00:00 2001 From: James Cammarata Date: Wed, 5 Feb 2014 13:43:52 -0600 Subject: [PATCH] Revising method for parsing ranges from --limit subsets Also added a new test (test_subset_range) for future validation. Fixes #4620 --- lib/ansible/inventory/__init__.py | 29 ++++++++++++----------------- test/TestInventory.py | 5 +++++ 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/lib/ansible/inventory/__init__.py b/lib/ansible/inventory/__init__.py index ed945ce50c2..551ab72d229 100644 --- a/lib/ansible/inventory/__init__.py +++ b/lib/ansible/inventory/__init__.py @@ -207,24 +207,19 @@ class Inventory(object): a tuple of (start, stop) or None """ - if not "[" in pattern or pattern.startswith('~'): - return (pattern, None) - (first, rest) = pattern.split("[") - rest = rest.replace("]","") - try: - # support selectors like webservers[0] - x = int(rest) - return (first, (x,x)) - except: - pass - if "-" in rest: - (left, right) = rest.split("-",1) - return (first, (left, right)) - elif ":" in rest: - (left, right) = rest.split(":",1) - return (first, (left, right)) + # The regex used to match on the range, which can be [x] or [x-y]. + pattern_re = re.compile("^(.*)\[([0-9]+)(?:(?:-)([0-9]+))?\](.*)$") + m = pattern_re.match(pattern) + if m: + (target, first, last, rest) = m.groups() + first = int(first) + if last: + last = int(last) + else: + last = first + return (target, (first, last)) else: - return (first, (rest, rest)) + return (pattern, None) def _apply_ranges(self, pat, hosts): """ diff --git a/test/TestInventory.py b/test/TestInventory.py index 60ebeb7fc2e..5ddfc0fcf49 100644 --- a/test/TestInventory.py +++ b/test/TestInventory.py @@ -206,6 +206,11 @@ class TestInventory(unittest.TestCase): inventory.subset('odin;thor,loki') self.assertEqual(sorted(inventory.list_hosts()), sorted(['thor','odin','loki'])) + def test_subset_range(self): + inventory = self.simple_inventory() + inventory.subset('greek[0-2];norse[0]') + self.assertEqual(sorted(inventory.list_hosts()), sorted(['zeus','hera','thor'])) + def test_subset_filename(self): inventory = self.simple_inventory() inventory.subset('@' + os.path.join(self.test_dir, 'restrict_pattern'))