1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Fix invalid string escape sequences.

This commit is contained in:
Matt Clay 2017-11-20 19:08:30 -08:00
parent f9cd50411f
commit e45c763b64
48 changed files with 77 additions and 77 deletions

View file

@ -327,7 +327,7 @@ class LibcloudInventory(object):
used as Ansible groups used as Ansible groups
''' '''
return re.sub("[^A-Za-z0-9\-]", "_", word) return re.sub(r"[^A-Za-z0-9\-]", "_", word)
def json_format_dict(self, data, pretty=False): def json_format_dict(self, data, pretty=False):
''' '''

View file

@ -572,7 +572,7 @@ class AosInventory(object):
- Converting to lowercase - Converting to lowercase
""" """
rx = re.compile('\W+') rx = re.compile(r'\W+')
clean_group = rx.sub('_', group_name).lower() clean_group = rx.sub('_', group_name).lower()
return clean_group return clean_group

View file

@ -842,9 +842,9 @@ class AzureInventory(object):
def _to_safe(self, word): def _to_safe(self, word):
''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups '''
regex = "[^A-Za-z0-9\_" regex = r"[^A-Za-z0-9\_"
if not self.replace_dash_in_groups: if not self.replace_dash_in_groups:
regex += "\-" regex += r"\-"
return re.sub(regex + "]", "_", word) return re.sub(regex + "]", "_", word)

View file

@ -444,7 +444,7 @@ class CloudFormsInventory(object):
Converts 'bad' characters in a string to underscores so they can be used as Ansible groups Converts 'bad' characters in a string to underscores so they can be used as Ansible groups
""" """
if self.cloudforms_clean_group_keys: if self.cloudforms_clean_group_keys:
regex = "[^A-Za-z0-9\_]" regex = r"[^A-Za-z0-9\_]"
return re.sub(regex, "_", word.replace(" ", "")) return re.sub(regex, "_", word.replace(" ", ""))
else: else:
return word return word

View file

@ -271,7 +271,7 @@ class CobblerInventory(object):
def to_safe(self, word): def to_safe(self, word):
""" Converts 'bad' characters in a string to underscores so they can be used as Ansible groups """ """ Converts 'bad' characters in a string to underscores so they can be used as Ansible groups """
return re.sub("[^A-Za-z0-9\-]", "_", word) return re.sub(r"[^A-Za-z0-9\-]", "_", word)
def json_format_dict(self, data, pretty=False): def json_format_dict(self, data, pretty=False):
""" Converts a dict to a JSON object and dumps it as a formatted string """ """ Converts a dict to a JSON object and dumps it as a formatted string """

View file

@ -423,7 +423,7 @@ class CollinsInventory(object):
""" Converts 'bad' characters in a string to underscores so they """ Converts 'bad' characters in a string to underscores so they
can be used as Ansible groups """ can be used as Ansible groups """
return re.sub("[^A-Za-z0-9\-]", "_", word) return re.sub(r"[^A-Za-z0-9\-]", "_", word)
def json_format_dict(self, data, pretty=False): def json_format_dict(self, data, pretty=False):
""" Converts a dict to a JSON object and dumps it as a formatted string """ """ Converts a dict to a JSON object and dumps it as a formatted string """

View file

@ -394,7 +394,7 @@ class ConsulInventory(object):
def to_safe(self, word): def to_safe(self, word):
''' Converts 'bad' characters in a string to underscores so they can be used ''' Converts 'bad' characters in a string to underscores so they can be used
as Ansible groups ''' as Ansible groups '''
return re.sub('[^A-Za-z0-9\-\.]', '_', word) return re.sub(r'[^A-Za-z0-9\-\.]', '_', word)
def sanitize_dict(self, d): def sanitize_dict(self, d):

View file

@ -460,7 +460,7 @@ or environment variables (DO_API_TOKEN)\n''')
def to_safe(self, word): def to_safe(self, word):
''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups '''
return re.sub("[^A-Za-z0-9\-\.]", "_", word) return re.sub(r"[^A-Za-z0-9\-\.]", "_", word)
def do_namespace(self, data): def do_namespace(self, data):
''' Returns a copy of the dictionary with all the keys put in a 'do_' namespace ''' ''' Returns a copy of the dictionary with all the keys put in a 'do_' namespace '''

View file

@ -656,7 +656,7 @@ class DockerInventory(object):
self.hostvars[name].update(facts) self.hostvars[name].update(facts)
def _slugify(self, value): def _slugify(self, value):
return 'docker_%s' % (re.sub('[^\w-]', '_', value).lower().lstrip('_')) return 'docker_%s' % (re.sub(r'[^\w-]', '_', value).lower().lstrip('_'))
def get_hosts(self, config): def get_hosts(self, config):
''' '''

View file

@ -1680,9 +1680,9 @@ class Ec2Inventory(object):
def to_safe(self, word): def to_safe(self, word):
''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups '''
regex = "[^A-Za-z0-9\_" regex = r"[^A-Za-z0-9\_"
if not self.replace_dash_in_groups: if not self.replace_dash_in_groups:
regex += "\-" regex += r"\-"
return re.sub(regex + "]", "_", word) return re.sub(regex + "]", "_", word)
def json_format_dict(self, data, pretty=False): def json_format_dict(self, data, pretty=False):

View file

@ -61,7 +61,7 @@ def get_ssh_config():
def list_running_boxes(): def list_running_boxes():
boxes = [] boxes = []
for line in subprocess.check_output(["fleetctl", "list-machines"]).split('\n'): for line in subprocess.check_output(["fleetctl", "list-machines"]).split('\n'):
matcher = re.search("[^\s]+[\s]+([^\s]+).+", line) matcher = re.search(r"[^\s]+[\s]+([^\s]+).+", line)
if matcher and matcher.group(1) != "IP": if matcher and matcher.group(1) != "IP":
boxes.append(matcher.group(1)) boxes.append(matcher.group(1))

View file

@ -264,7 +264,7 @@ class ForemanInventory(object):
>>> ForemanInventory.to_safe("foo-bar baz") >>> ForemanInventory.to_safe("foo-bar baz")
'foo_barbaz' 'foo_barbaz'
''' '''
regex = "[^A-Za-z0-9\_]" regex = r"[^A-Za-z0-9\_]"
return re.sub(regex, "_", word.replace(" ", "")) return re.sub(regex, "_", word.replace(" ", ""))
def update_cache(self): def update_cache(self):

View file

@ -338,7 +338,7 @@ class LinodeInventory(object):
def to_safe(self, word): def to_safe(self, word):
"""Escapes any characters that would be invalid in an ansible group name.""" """Escapes any characters that would be invalid in an ansible group name."""
return re.sub("[^A-Za-z0-9\-]", "_", word) return re.sub(r"[^A-Za-z0-9\-]", "_", word)
def json_format_dict(self, data, pretty=False): def json_format_dict(self, data, pretty=False):
"""Converts a dict to a JSON object and dumps it as a formatted string.""" """Converts a dict to a JSON object and dumps it as a formatted string."""

View file

@ -480,9 +480,9 @@ class PacketInventory(object):
def to_safe(self, word): def to_safe(self, word):
''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups '''
regex = "[^A-Za-z0-9\_" regex = r"[^A-Za-z0-9\_"
if not self.replace_dash_in_groups: if not self.replace_dash_in_groups:
regex += "\-" regex += r"\-"
return re.sub(regex + "]", "_", word) return re.sub(regex + "]", "_", word)
def json_format_dict(self, data, pretty=False): def json_format_dict(self, data, pretty=False):

View file

@ -189,7 +189,7 @@ p = load_config_file()
def rax_slugify(value): def rax_slugify(value):
return 'rax_%s' % (re.sub('[^\w-]', '_', value).lower().lstrip('_')) return 'rax_%s' % (re.sub(r'[^\w-]', '_', value).lower().lstrip('_'))
def to_dict(obj): def to_dict(obj):

View file

@ -292,7 +292,7 @@ class RudderInventory(object):
''' Converts 'bad' characters in a string to underscores so they can be ''' Converts 'bad' characters in a string to underscores so they can be
used as Ansible variable names ''' used as Ansible variable names '''
return re.sub('[^A-Za-z0-9\_]', '_', word) return re.sub(r'[^A-Za-z0-9\_]', '_', word)
# Run the script # Run the script
RudderInventory() RudderInventory()

View file

@ -91,7 +91,7 @@ class SoftLayerInventory(object):
def to_safe(self, word): def to_safe(self, word):
'''Converts 'bad' characters in a string to underscores so they can be used as Ansible groups''' '''Converts 'bad' characters in a string to underscores so they can be used as Ansible groups'''
return re.sub("[^A-Za-z0-9\-\.]", "_", word) return re.sub(r"[^A-Za-z0-9\-\.]", "_", word)
def push(self, my_dict, key, element): def push(self, my_dict, key, element):
'''Push an element onto an array that may not have been defined in the dict''' '''Push an element onto an array that may not have been defined in the dict'''

View file

@ -79,7 +79,7 @@ def list_running_boxes():
boxes = [] boxes = []
for line in output: for line in output:
matcher = re.search("([^\s]+)[\s]+running \(.+", line) matcher = re.search(r"([^\s]+)[\s]+running \(.+", line)
if matcher: if matcher:
boxes.append(matcher.group(1)) boxes.append(matcher.group(1))

View file

@ -271,7 +271,7 @@ class AzureInventory(object):
def to_safe(self, word): def to_safe(self, word):
"""Escapes any characters that would be invalid in an ansible group name.""" """Escapes any characters that would be invalid in an ansible group name."""
return re.sub("[^A-Za-z0-9\-]", "_", word) return re.sub(r"[^A-Za-z0-9\-]", "_", word)
def json_format_dict(self, data, pretty=False): def json_format_dict(self, data, pretty=False):
"""Converts a dict to a JSON object and dumps it as a formatted string.""" """Converts a dict to a JSON object and dumps it as a formatted string."""

View file

@ -627,9 +627,9 @@ def _find_module_utils(module_name, b_module_data, module_path, module_args, tas
module_style = 'new' module_style = 'new'
module_substyle = 'powershell' module_substyle = 'powershell'
b_module_data = b_module_data.replace(REPLACER_WINDOWS, b'#Requires -Module Ansible.ModuleUtils.Legacy') b_module_data = b_module_data.replace(REPLACER_WINDOWS, b'#Requires -Module Ansible.ModuleUtils.Legacy')
elif re.search(b'#Requires \-Module', b_module_data, re.IGNORECASE) \ elif re.search(b'#Requires -Module', b_module_data, re.IGNORECASE) \
or re.search(b'#Requires \-Version', b_module_data, re.IGNORECASE)\ or re.search(b'#Requires -Version', b_module_data, re.IGNORECASE)\
or re.search(b'#AnsibleRequires \-OSVersion', b_module_data, re.IGNORECASE): or re.search(b'#AnsibleRequires -OSVersion', b_module_data, re.IGNORECASE):
module_style = 'new' module_style = 'new'
module_substyle = 'powershell' module_substyle = 'powershell'
elif REPLACER_JSONARGS in b_module_data: elif REPLACER_JSONARGS in b_module_data:
@ -796,9 +796,9 @@ def _find_module_utils(module_name, b_module_data, module_path, module_args, tas
min_ps_version = None min_ps_version = None
requires_module_list = re.compile(to_bytes(r'(?i)^#\s*requires\s+\-module(?:s?)\s*(Ansible\.ModuleUtils\..+)')) requires_module_list = re.compile(to_bytes(r'(?i)^#\s*requires\s+\-module(?:s?)\s*(Ansible\.ModuleUtils\..+)'))
requires_ps_version = re.compile(to_bytes('(?i)^#requires\s+\-version\s+([0-9]+(\.[0-9]+){0,3})$')) requires_ps_version = re.compile(to_bytes(r'(?i)^#requires\s+\-version\s+([0-9]+(\.[0-9]+){0,3})$'))
requires_os_version = re.compile(to_bytes('(?i)^#ansiblerequires\s+\-osversion\s+([0-9]+(\.[0-9]+){0,3})$')) requires_os_version = re.compile(to_bytes(r'(?i)^#ansiblerequires\s+\-osversion\s+([0-9]+(\.[0-9]+){0,3})$'))
requires_become = re.compile(to_bytes('(?i)^#ansiblerequires\s+\-become$')) requires_become = re.compile(to_bytes(r'(?i)^#ansiblerequires\s+\-become$'))
for line in lines: for line in lines:
module_util_line_match = requires_module_list.match(line) module_util_line_match = requires_module_list.match(line)

View file

@ -39,7 +39,7 @@ except ImportError:
from ansible.utils.display import Display from ansible.utils.display import Display
display = Display() display = Display()
IGNORED_ALWAYS = [b"^\.", b"^host_vars$", b"^group_vars$", b"^vars_plugins$"] IGNORED_ALWAYS = [br"^\.", b"^host_vars$", b"^group_vars$", b"^vars_plugins$"]
IGNORED_PATTERNS = [to_bytes(x) for x in C.INVENTORY_IGNORE_PATTERNS] IGNORED_PATTERNS = [to_bytes(x) for x in C.INVENTORY_IGNORE_PATTERNS]
IGNORED_EXTS = [b'%s$' % to_bytes(re.escape(x)) for x in C.INVENTORY_IGNORE_EXTS] IGNORED_EXTS = [b'%s$' % to_bytes(re.escape(x)) for x in C.INVENTORY_IGNORE_EXTS]

View file

@ -71,8 +71,8 @@ AZURE_COMMON_REQUIRED_IF = [
ANSIBLE_USER_AGENT = 'Ansible/{0}'.format(ANSIBLE_VERSION) ANSIBLE_USER_AGENT = 'Ansible/{0}'.format(ANSIBLE_VERSION)
CLOUDSHELL_USER_AGENT_KEY = 'AZURE_HTTP_USER_AGENT' CLOUDSHELL_USER_AGENT_KEY = 'AZURE_HTTP_USER_AGENT'
CIDR_PATTERN = re.compile("(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1" CIDR_PATTERN = re.compile(r"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1"
"[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))") r"[0-9]{2}|2[0-4][0-9]|25[0-5])(/([0-9]|[1-2][0-9]|3[0-2]))")
AZURE_SUCCESS_STATE = "Succeeded" AZURE_SUCCESS_STATE = "Succeeded"
AZURE_FAILED_STATE = "Failed" AZURE_FAILED_STATE = "Failed"

View file

@ -586,7 +586,7 @@ def human_to_bytes(number, default_unit=None, isbits=False):
ex: ex:
human_to_bytes('10M') <=> human_to_bytes(10, 'M') human_to_bytes('10M') <=> human_to_bytes(10, 'M')
''' '''
m = re.search('^\s*(\d*\.?\d*)\s*([A-Za-z]+)?', str(number), flags=re.IGNORECASE) m = re.search(r'^\s*(\d*\.?\d*)\s*([A-Za-z]+)?', str(number), flags=re.IGNORECASE)
if m is None: if m is None:
raise ValueError("human_to_bytes() can't interpret following string: %s" % str(number)) raise ValueError("human_to_bytes() can't interpret following string: %s" % str(number))
try: try:

View file

@ -79,7 +79,7 @@ DOCKER_REQUIRED_TOGETHER = [
] ]
DEFAULT_DOCKER_REGISTRY = 'https://index.docker.io/v1/' DEFAULT_DOCKER_REGISTRY = 'https://index.docker.io/v1/'
EMAIL_REGEX = '[^@]+@[^@]+\.[^@]+' EMAIL_REGEX = r'[^@]+@[^@]+\.[^@]+'
BYTE_SUFFIXES = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] BYTE_SUFFIXES = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']

View file

@ -136,8 +136,8 @@ class FreeBSDHardware(Hardware):
sysdir = '/dev' sysdir = '/dev'
device_facts['devices'] = {} device_facts['devices'] = {}
drives = re.compile('(ada?\d+|da\d+|a?cd\d+)') # TODO: rc, disks, err = self.module.run_command("/sbin/sysctl kern.disks") drives = re.compile(r'(ada?\d+|da\d+|a?cd\d+)') # TODO: rc, disks, err = self.module.run_command("/sbin/sysctl kern.disks")
slices = re.compile('(ada?\d+s\d+\w*|da\d+s\d+\w*)') slices = re.compile(r'(ada?\d+s\d+\w*|da\d+s\d+\w*)')
if os.path.isdir(sysdir): if os.path.isdir(sysdir):
dirlist = sorted(os.listdir(sysdir)) dirlist = sorted(os.listdir(sysdir))
for device in dirlist: for device in dirlist:

View file

@ -127,7 +127,7 @@ class HPUXHardware(Hardware):
memory_facts['memtotal_mb'] = int(data) / 256 memory_facts['memtotal_mb'] = int(data) / 256
else: else:
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Memory", use_unsafe_shell=True) rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Memory", use_unsafe_shell=True)
data = re.search('Memory[\ :=]*([0-9]*).*MB.*', out).groups()[0].strip() data = re.search(r'Memory[\ :=]*([0-9]*).*MB.*', out).groups()[0].strip()
memory_facts['memtotal_mb'] = int(data) memory_facts['memtotal_mb'] = int(data)
rc, out, err = self.module.run_command("/usr/sbin/swapinfo -m -d -f -q") rc, out, err = self.module.run_command("/usr/sbin/swapinfo -m -d -f -q")
memory_facts['swaptotal_mb'] = int(out.strip()) memory_facts['swaptotal_mb'] = int(out.strip())

View file

@ -568,7 +568,7 @@ class LinuxHardware(Hardware):
device = "/dev/%s" % (block) device = "/dev/%s" % (block)
rc, drivedata, err = self.module.run_command([sg_inq, device]) rc, drivedata, err = self.module.run_command([sg_inq, device])
if rc == 0: if rc == 0:
serial = re.search("Unit serial number:\s+(\w+)", drivedata) serial = re.search(r"Unit serial number:\s+(\w+)", drivedata)
if serial: if serial:
d['serial'] = serial.group(1) d['serial'] = serial.group(1)
@ -585,7 +585,7 @@ class LinuxHardware(Hardware):
d['partitions'] = {} d['partitions'] = {}
for folder in os.listdir(sysdir): for folder in os.listdir(sysdir):
m = re.search("(" + diskname + "\d+)", folder) m = re.search("(" + diskname + r"\d+)", folder)
if m: if m:
part = {} part = {}
partname = m.group(1) partname = m.group(1)
@ -611,7 +611,7 @@ class LinuxHardware(Hardware):
d['scheduler_mode'] = "" d['scheduler_mode'] = ""
scheduler = get_file_content(sysdir + "/queue/scheduler") scheduler = get_file_content(sysdir + "/queue/scheduler")
if scheduler is not None: if scheduler is not None:
m = re.match(".*?(\[(.*)\])", scheduler) m = re.match(r".*?(\[(.*)\])", scheduler)
if m: if m:
d['scheduler_mode'] = m.group(2) d['scheduler_mode'] = m.group(2)
@ -626,11 +626,11 @@ class LinuxHardware(Hardware):
d['host'] = "" d['host'] = ""
# domains are numbered (0 to ffff), bus (0 to ff), slot (0 to 1f), and function (0 to 7). # domains are numbered (0 to ffff), bus (0 to ff), slot (0 to 1f), and function (0 to 7).
m = re.match(".+/([a-f0-9]{4}:[a-f0-9]{2}:[0|1][a-f0-9]\.[0-7])/", sysdir) m = re.match(r".+/([a-f0-9]{4}:[a-f0-9]{2}:[0|1][a-f0-9]\.[0-7])/", sysdir)
if m and pcidata: if m and pcidata:
pciid = m.group(1) pciid = m.group(1)
did = re.escape(pciid) did = re.escape(pciid)
m = re.search("^" + did + "\s(.*)$", pcidata, re.MULTILINE) m = re.search("^" + did + r"\s(.*)$", pcidata, re.MULTILINE)
if m: if m:
d['host'] = m.group(1) d['host'] = m.group(1)

View file

@ -73,7 +73,7 @@ class AIXNetwork(GenericBsdIfconfigNetwork):
words = line.split() words = line.split()
# only this condition differs from GenericBsdIfconfigNetwork # only this condition differs from GenericBsdIfconfigNetwork
if re.match('^\w*\d*:', line): if re.match(r'^\w*\d*:', line):
current_if = self.parse_interface_line(words) current_if = self.parse_interface_line(words)
interfaces[current_if['device']] = current_if interfaces[current_if['device']] = current_if
elif words[0].startswith('options='): elif words[0].startswith('options='):

View file

@ -121,7 +121,7 @@ class GenericBsdIfconfigNetwork(Network):
if words[0] == 'pass': if words[0] == 'pass':
continue continue
elif re.match('^\S', line) and len(words) > 3: elif re.match(r'^\S', line) and len(words) > 3:
current_if = self.parse_interface_line(words) current_if = self.parse_interface_line(words)
interfaces[current_if['device']] = current_if interfaces[current_if['device']] = current_if
elif words[0].startswith('options='): elif words[0].startswith('options='):

View file

@ -297,9 +297,9 @@ class LinuxNetwork(Network):
args = [ethtool_path, '-T', device] args = [ethtool_path, '-T', device]
rc, stdout, stderr = self.module.run_command(args, errors='surrogate_then_replace') rc, stdout, stderr = self.module.run_command(args, errors='surrogate_then_replace')
if rc == 0: if rc == 0:
data['timestamping'] = [m.lower() for m in re.findall('SOF_TIMESTAMPING_(\w+)', stdout)] data['timestamping'] = [m.lower() for m in re.findall(r'SOF_TIMESTAMPING_(\w+)', stdout)]
data['hw_timestamp_filters'] = [m.lower() for m in re.findall('HWTSTAMP_FILTER_(\w+)', stdout)] data['hw_timestamp_filters'] = [m.lower() for m in re.findall(r'HWTSTAMP_FILTER_(\w+)', stdout)]
m = re.search('PTP Hardware Clock: (\d+)', stdout) m = re.search(r'PTP Hardware Clock: (\d+)', stdout)
if m: if m:
data['phc_index'] = int(m.groups()[0]) data['phc_index'] = int(m.groups()[0])

View file

@ -50,7 +50,7 @@ class SunOSNetwork(GenericBsdIfconfigNetwork):
if line: if line:
words = line.split() words = line.split()
if re.match('^\S', line) and len(words) > 3: if re.match(r'^\S', line) and len(words) > 3:
current_if = self.parse_interface_line(words, current_if, interfaces) current_if = self.parse_interface_line(words, current_if, interfaces)
interfaces[current_if['device']] = current_if interfaces[current_if['device']] = current_if
elif words[0].startswith('options='): elif words[0].startswith('options='):

View file

@ -29,7 +29,7 @@ def get_sysctl(module, prefixes):
for line in out.splitlines(): for line in out.splitlines():
if not line: if not line:
continue continue
(key, value) = re.split('\s?=\s?|: ', line, maxsplit=1) (key, value) = re.split(r'\s?=\s?|: ', line, maxsplit=1)
sysctl[key] = value.strip() sysctl[key] = value.strip()
return sysctl return sysctl

View file

@ -208,7 +208,7 @@ class DistributionFiles:
if 'Slackware' not in data: if 'Slackware' not in data:
return False, slackware_facts # TODO: remove return False, slackware_facts # TODO: remove
slackware_facts['distribution'] = name slackware_facts['distribution'] = name
version = re.findall('\w+[.]\w+', data) version = re.findall(r'\w+[.]\w+', data)
if version: if version:
slackware_facts['distribution_version'] = version[0] slackware_facts['distribution_version'] = version[0]
return True, slackware_facts return True, slackware_facts
@ -251,16 +251,16 @@ class DistributionFiles:
if distribution: if distribution:
suse_facts['distribution'] = distribution.group(1).strip('"') suse_facts['distribution'] = distribution.group(1).strip('"')
# example pattern are 13.04 13.0 13 # example pattern are 13.04 13.0 13
distribution_version = re.search('^VERSION_ID="?([0-9]+\.?[0-9]*)"?', line) distribution_version = re.search(r'^VERSION_ID="?([0-9]+\.?[0-9]*)"?', line)
if distribution_version: if distribution_version:
suse_facts['distribution_version'] = distribution_version.group(1) suse_facts['distribution_version'] = distribution_version.group(1)
if 'open' in data.lower(): if 'open' in data.lower():
release = re.search('^VERSION_ID="?[0-9]+\.?([0-9]*)"?', line) release = re.search(r'^VERSION_ID="?[0-9]+\.?([0-9]*)"?', line)
if release: if release:
suse_facts['distribution_release'] = release.groups()[0] suse_facts['distribution_release'] = release.groups()[0]
elif 'enterprise' in data.lower() and 'VERSION_ID' in line: elif 'enterprise' in data.lower() and 'VERSION_ID' in line:
# SLES doesn't got funny release names # SLES doesn't got funny release names
release = re.search('^VERSION_ID="?[0-9]+\.?([0-9]*)"?', line) release = re.search(r'^VERSION_ID="?[0-9]+\.?([0-9]*)"?', line)
if release.group(1): if release.group(1):
release = release.group(1) release = release.group(1)
else: else:
@ -294,7 +294,7 @@ class DistributionFiles:
debian_facts = {} debian_facts = {}
if 'Debian' in data or 'Raspbian' in data: if 'Debian' in data or 'Raspbian' in data:
debian_facts['distribution'] = 'Debian' debian_facts['distribution'] = 'Debian'
release = re.search("PRETTY_NAME=[^(]+ \(?([^)]+?)\)", data) release = re.search(r"PRETTY_NAME=[^(]+ \(?([^)]+?)\)", data)
if release: if release:
debian_facts['distribution_release'] = release.groups()[0] debian_facts['distribution_release'] = release.groups()[0]
@ -475,8 +475,8 @@ class Distribution(object):
def get_distribution_HPUX(self): def get_distribution_HPUX(self):
hpux_facts = {} hpux_facts = {}
rc, out, err = self.module.run_command("/usr/sbin/swlist |egrep 'HPUX.*OE.*[AB].[0-9]+\.[0-9]+'", use_unsafe_shell=True) rc, out, err = self.module.run_command(r"/usr/sbin/swlist |egrep 'HPUX.*OE.*[AB].[0-9]+\.[0-9]+'", use_unsafe_shell=True)
data = re.search('HPUX.*OE.*([AB].[0-9]+\.[0-9]+)\.([0-9]+).*', out) data = re.search(r'HPUX.*OE.*([AB].[0-9]+\.[0-9]+)\.([0-9]+).*', out)
if data: if data:
hpux_facts['distribution_version'] = data.groups()[0] hpux_facts['distribution_version'] = data.groups()[0]
hpux_facts['distribution_release'] = data.groups()[1] hpux_facts['distribution_release'] = data.groups()[1]
@ -495,7 +495,7 @@ class Distribution(object):
def get_distribution_FreeBSD(self): def get_distribution_FreeBSD(self):
freebsd_facts = {} freebsd_facts = {}
freebsd_facts['distribution_release'] = platform.release() freebsd_facts['distribution_release'] = platform.release()
data = re.search('(\d+)\.(\d+)-RELEASE.*', freebsd_facts['distribution_release']) data = re.search(r'(\d+)\.(\d+)-RELEASE.*', freebsd_facts['distribution_release'])
if data: if data:
freebsd_facts['distribution_major_version'] = data.group(1) freebsd_facts['distribution_major_version'] = data.group(1)
freebsd_facts['distribution_version'] = '%s.%s' % (data.group(1), data.group(2)) freebsd_facts['distribution_version'] = '%s.%s' % (data.group(1), data.group(2))
@ -505,7 +505,7 @@ class Distribution(object):
openbsd_facts = {} openbsd_facts = {}
openbsd_facts['distribution_version'] = platform.release() openbsd_facts['distribution_version'] = platform.release()
rc, out, err = self.module.run_command("/sbin/sysctl -n kern.version") rc, out, err = self.module.run_command("/sbin/sysctl -n kern.version")
match = re.match('OpenBSD\s[0-9]+.[0-9]+-(\S+)\s.*', out) match = re.match(r'OpenBSD\s[0-9]+.[0-9]+-(\S+)\s.*', out)
if match: if match:
openbsd_facts['distribution_release'] = match.groups()[0] openbsd_facts['distribution_release'] = match.groups()[0]
else: else:

View file

@ -144,9 +144,9 @@ class LinuxVirtual(Virtual):
if os.path.exists('/proc/self/status'): if os.path.exists('/proc/self/status'):
for line in get_file_lines('/proc/self/status'): for line in get_file_lines('/proc/self/status'):
if re.match('^VxID: \d+', line): if re.match(r'^VxID: \d+', line):
virtual_facts['virtualization_type'] = 'linux_vserver' virtual_facts['virtualization_type'] = 'linux_vserver'
if re.match('^VxID: 0', line): if re.match(r'^VxID: 0', line):
virtual_facts['virtualization_role'] = 'host' virtual_facts['virtualization_role'] = 'host'
else: else:
virtual_facts['virtualization_role'] = 'guest' virtual_facts['virtualization_role'] = 'guest'

View file

@ -58,7 +58,7 @@ def get_fqdn_and_port(repo_url):
fqdn = None fqdn = None
port = None port = None
ipv6_re = re.compile('(\[[^]]*\])(?::([0-9]+))?') ipv6_re = re.compile(r'(\[[^]]*\])(?::([0-9]+))?')
if "@" in repo_url and "://" not in repo_url: if "@" in repo_url and "://" not in repo_url:
# most likely an user@host:path or user@host/path type URL # most likely an user@host:path or user@host/path type URL
repo_url = repo_url.split("@", 1)[1] repo_url = repo_url.split("@", 1)[1]

View file

@ -35,9 +35,9 @@ from ansible.module_utils.network_common import to_list
DEFAULT_COMMENT_TOKENS = ['#', '!', '/*', '*/', 'echo'] DEFAULT_COMMENT_TOKENS = ['#', '!', '/*', '*/', 'echo']
DEFAULT_IGNORE_LINES_RE = set([ DEFAULT_IGNORE_LINES_RE = set([
re.compile("Using \d+ out of \d+ bytes"), re.compile(r"Using \d+ out of \d+ bytes"),
re.compile("Building configuration"), re.compile(r"Building configuration"),
re.compile("Current configuration : \d+ bytes") re.compile(r"Current configuration : \d+ bytes")
]) ])

View file

@ -305,7 +305,7 @@ def dict_merge(base, other):
def conditional(expr, val, cast=None): def conditional(expr, val, cast=None):
match = re.match('^(.+)\((.+)\)$', str(expr), re.I) match = re.match(r'^(.+)\((.+)\)$', str(expr), re.I)
if match: if match:
op, arg = match.groups() op, arg = match.groups()
else: else:

View file

@ -51,7 +51,7 @@ SERVICE_NET_ID = "11111111-1111-1111-1111-111111111111"
def rax_slugify(value): def rax_slugify(value):
"""Prepend a key with rax_ and normalize the key name""" """Prepend a key with rax_ and normalize the key name"""
return 'rax_%s' % (re.sub('[^\w-]', '_', value).lower().lstrip('_')) return 'rax_%s' % (re.sub(r'[^\w-]', '_', value).lower().lstrip('_'))
def rax_clb_node_to_dict(obj): def rax_clb_node_to_dict(obj):

View file

@ -501,7 +501,7 @@ class PlayContext(Base):
# passing code ref to examine prompt as simple string comparisson isn't good enough with su # passing code ref to examine prompt as simple string comparisson isn't good enough with su
def detect_su_prompt(b_data): def detect_su_prompt(b_data):
b_password_string = b"|".join([b'(\w+\'s )?' + x for x in b_SU_PROMPT_LOCALIZATIONS]) b_password_string = b"|".join([br'(\w+\'s )?' + x for x in b_SU_PROMPT_LOCALIZATIONS])
# Colon or unicode fullwidth colon # Colon or unicode fullwidth colon
b_password_string = b_password_string + to_bytes(u' ?(:|) ?') b_password_string = b_password_string + to_bytes(u' ?(:|) ?')
b_SU_PROMPT_LOCALIZATIONS_RE = re.compile(b_password_string, flags=re.IGNORECASE) b_SU_PROMPT_LOCALIZATIONS_RE = re.compile(b_password_string, flags=re.IGNORECASE)

View file

@ -171,7 +171,7 @@ class CallbackModule(CallbackBase):
duration = host_data.finish - task_data.start duration = host_data.finish - task_data.start
if self._task_class == 'true': if self._task_class == 'true':
junit_classname = re.sub('\.yml:[0-9]+$', '', task_data.path) junit_classname = re.sub(r'\.yml:[0-9]+$', '', task_data.path)
else: else:
junit_classname = task_data.path junit_classname = task_data.path

View file

@ -115,7 +115,7 @@ class Connection(ConnectionBase):
@staticmethod @staticmethod
def _sanitize_version(version): def _sanitize_version(version):
return re.sub(u'[^0-9a-zA-Z\.]', u'', version) return re.sub(u'[^0-9a-zA-Z.]', u'', version)
def _old_docker_version(self): def _old_docker_version(self):
cmd_args = [] cmd_args = []

View file

@ -39,7 +39,7 @@ except ImportError:
from ansible.utils.display import Display from ansible.utils.display import Display
display = Display() display = Display()
_SAFE_GROUP = re.compile("[^A-Za-z0-9\_]") _SAFE_GROUP = re.compile("[^A-Za-z0-9_]")
# Helper methods # Helper methods

View file

@ -51,7 +51,7 @@ requirements:
- netapp-lib (2015.9.25). Install using 'pip install netapp-lib' - netapp-lib (2015.9.25). Install using 'pip install netapp-lib'
notes: notes:
- The modules prefixed with C(netapp\_cdot) are built to support the ONTAP storage platform. - The modules prefixed with C(netapp\\_cdot) are built to support the ONTAP storage platform.
""" """
@ -75,7 +75,7 @@ requirements:
- solidfire-sdk-python (1.1.0.92) - solidfire-sdk-python (1.1.0.92)
notes: notes:
- The modules prefixed with C(sf\_) are built to support the SolidFire storage platform. - The modules prefixed with C(sf\\_) are built to support the SolidFire storage platform.
""" """

View file

@ -70,7 +70,7 @@ BLACKLIST_IMPORTS = {
'ansible.module_utils.urls instead') 'ansible.module_utils.urls instead')
} }
}, },
'boto(?:\.|$)': { r'boto(?:\.|$)': {
'new_only': True, 'new_only': True,
'error': { 'error': {
'code': 204, 'code': 204,

View file

@ -269,7 +269,7 @@ class TestGetCollectorNames(unittest.TestCase):
minimal_gather_subset = frozenset(['my_fact']) minimal_gather_subset = frozenset(['my_fact'])
self.assertRaisesRegexp(TypeError, self.assertRaisesRegexp(TypeError,
'Bad subset .* given to Ansible.*allowed\:.*all,.*my_fact.*', r'Bad subset .* given to Ansible.*allowed\:.*all,.*my_fact.*',
collector.get_collector_names, collector.get_collector_names,
valid_subsets=valid_subsets, valid_subsets=valid_subsets,
minimal_gather_subset=minimal_gather_subset, minimal_gather_subset=minimal_gather_subset,
@ -341,7 +341,7 @@ class TestCollectorClassesFromGatherSubset(unittest.TestCase):
# something claims 'unknown_collector' is a valid gather_subset, but there is # something claims 'unknown_collector' is a valid gather_subset, but there is
# no FactCollector mapped to 'unknown_collector' # no FactCollector mapped to 'unknown_collector'
self.assertRaisesRegexp(TypeError, self.assertRaisesRegexp(TypeError,
'Bad subset.*unknown_collector.*given to Ansible.*allowed\:.*all,.*env.*', r'Bad subset.*unknown_collector.*given to Ansible.*allowed\:.*all,.*env.*',
self._classes, self._classes,
all_collector_classes=default_collectors.collectors, all_collector_classes=default_collectors.collectors,
gather_subset=['env', 'unknown_collector']) gather_subset=['env', 'unknown_collector'])

View file

@ -285,7 +285,7 @@ class TestScriptVaultSecret(unittest.TestCase):
with patch.object(secret, 'loader') as mock_loader: with patch.object(secret, 'loader') as mock_loader:
mock_loader.is_executable = MagicMock(return_value=True) mock_loader.is_executable = MagicMock(return_value=True)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegexp(errors.AnsibleError,
'Vault password script.*returned non-zero \(%s\): %s' % (rc, stderr), r'Vault password script.*returned non-zero \(%s\): %s' % (rc, stderr),
secret.load) secret.load)

View file

@ -99,7 +99,7 @@ class TestConditional(unittest.TestCase):
when = [u"some_dict.some_dict_key1 == hostvars['host3']"] when = [u"some_dict.some_dict_key1 == hostvars['host3']"]
# self._eval_con(when, variables) # self._eval_con(when, variables)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegexp(errors.AnsibleError,
"The conditional check 'some_dict.some_dict_key1 == hostvars\['host3'\]' failed", r"The conditional check 'some_dict.some_dict_key1 == hostvars\['host3'\]' failed",
# "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed", # "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed",
# "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed.", # "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed.",
self._eval_con, self._eval_con,

View file

@ -307,7 +307,7 @@ class TestTemplarMisc(BaseTemplar, unittest.TestCase):
class TestTemplarLookup(BaseTemplar, unittest.TestCase): class TestTemplarLookup(BaseTemplar, unittest.TestCase):
def test_lookup_missing_plugin(self): def test_lookup_missing_plugin(self):
self.assertRaisesRegexp(AnsibleError, self.assertRaisesRegexp(AnsibleError,
'lookup plugin \(not_a_real_lookup_plugin\) not found', r'lookup plugin \(not_a_real_lookup_plugin\) not found',
self.templar._lookup, self.templar._lookup,
'not_a_real_lookup_plugin', 'not_a_real_lookup_plugin',
'an_arg', a_keyword_arg='a_keyword_arg_value') 'an_arg', a_keyword_arg='a_keyword_arg_value')