Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions plugins/module_utils/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,32 @@
# Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)


# NOTE: It does not validate character classes or character count!
# EXAMPLES:
# pci -> match_address('0000:0*:00.*', sep='[:.]')
# mac -> match_address('52:54:*:*:*:0*', sep='[:]')
def match_address(address, pattern, sep=None):
"""Tests if a split string matches a set of simple glob patterns."""

import fnmatch
import re

# In case no separator is provided simply match the whole string.
if sep is None:
return fnmatch.fnmatch(address, pattern)

# Make sure both address and pattern contain identical separators.
if re.findall(sep, address) != re.findall(sep, pattern):
return False

# Try matching (glob) each segment separately.
for x, y in zip(re.split(sep, address), re.split(sep, pattern)):
if not fnmatch.fnmatch(x, y):
return False

return True


def flatten(to_flatten, extract=False):
"""Flattens nested lists (with optional value extraction)."""

Expand Down
30 changes: 2 additions & 28 deletions plugins/test/main.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,6 @@
#!/usr/bin/env python
from ansible_collections.opennebula.deploy.plugins.module_utils.main import match_address

import fnmatch
import re

class TestModule(object):
def tests(self):
return {
'match_address': self.match_address,
}

# NOTE: It does not validate character classes or character count!
# EXAMPLES:
# pci -> match_address('0000:0*:00.*', sep='[:.]')
# mac -> match_address('52:54:*:*:*:0*', sep='[:]')
def match_address(self, address, pattern, sep=None):
"""Tests if a split string matches a set of simple glob patterns."""

# In case no separator is provided simply match the whole string.
if sep is None:
return fnmatch.fnmatch(address, pattern)

# Make sure both address and pattern contain identical separators.
if re.findall(sep, address) != re.findall(sep, pattern):
return False

# Try matching (glob) each segment separately.
for x, y in zip(re.split(sep, address), re.split(sep, pattern)):
if not fnmatch.fnmatch(x, y):
return False

return True
return dict(match_address=match_address)
5 changes: 5 additions & 0 deletions plugins/test/match_address.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ DOCUMENTATION:
- An address to match.
type: string
required: true
pattern:
description:
- A string containing a sequence of glob patterns.
type: string
required: true
sep:
description:
- A regex expression used to split the input string (optional).
Expand Down