Skip to content

Commit

Permalink
Use raw strings with re functions
Browse files Browse the repository at this point in the history
Fixes lots of complaints with ruff 0.8 like

> RUF039 First argument to `re.match()` is not raw string
  • Loading branch information
martinpitt committed Dec 9, 2024
1 parent 7fb8d6c commit 35192bd
Show file tree
Hide file tree
Showing 13 changed files with 26 additions and 23 deletions.
2 changes: 1 addition & 1 deletion containers/flatpak/add-release
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def element(tag, text=None, children=(), **kwargs):


def points_from_body(body):
for text in re.split('^ *-', body, flags=re.MULTILINE):
for text in re.split(r'^ *-', body, flags=re.MULTILINE):
if point := ' '.join(text.split()).strip():
yield element('li', point)

Expand Down
8 changes: 4 additions & 4 deletions pkg/storaged/btrfs/btrfs-tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def get_subvolume_info(mp):
lines = subprocess.check_output(["btrfs", "subvolume", "list", "-apuq", mp]).splitlines()
subvols = []
for line in lines:
match = re.match(b"ID (\\d+).*parent (\\d+).*parent_uuid (.*)uuid (.*) path (<FS_TREE>/)?(.*)", line)
match = re.match(rb"ID (\d+).*parent (\d+).*parent_uuid (.*)uuid (.*) path (<FS_TREE>/)?(.*)", line)
if match:
pathname = match[6].decode(errors='replace')
# Ignore podman btrfs subvolumes, they are an implementation detail.
Expand All @@ -169,13 +169,13 @@ def get_subvolume_info(mp):
'uuid': match[4].decode(),
'parent_uuid': None if match[3][0] == ord("-") else match[3].decode().strip()
}
]
]
return subvols


def get_default_subvolume(mp):
output = subprocess.check_output(["btrfs", "subvolume", "get-default", mp])
match = re.match(b"ID (\\d+).*", output)
match = re.match(rb"ID (\d+).*", output)
if match:
return int(match[1])
else:
Expand All @@ -186,7 +186,7 @@ def get_usages(uuid):
output = subprocess.check_output(["btrfs", "filesystem", "show", "--raw", uuid])
usages = {}
for line in output.splitlines():
match = re.match(b".*used\\s+(\\d+)\\s+path\\s+([\\w/]+).*", line)
match = re.match(rb".*used\s+(\d+)\s+path\s+([\w/]+).*", line)
if match:
usages[match[2].decode()] = int(match[1])
return usages
Expand Down
6 changes: 3 additions & 3 deletions pkg/storaged/crypto/luksmeta-monitor-hack.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ def info(dev):
in_luks2_token_section = True

if in_luks2_slot_section:
match = re.match(b" ([0-9]+): luks2$", line)
match = re.match(rb" ([0-9]+): luks2$", line)
else:
match = re.match(b"Key Slot ([0-9]+): ENABLED$", line)
match = re.match(rb"Key Slot ([0-9]+): ENABLED$", line)
if match:
slot = int(match.group(1))
entry = {"Index": {"v": slot}}
Expand All @@ -93,7 +93,7 @@ def info(dev):
slots[slot] = entry

if in_luks2_token_section:
match = re.match(b" ([0-9]+): clevis$", line)
match = re.match(rb" ([0-9]+): clevis$", line)
if match:
try:
token = subprocess.check_output(["cryptsetup", "token", "export",
Expand Down
8 changes: 4 additions & 4 deletions pkg/storaged/nfs/nfs-mounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ def event(_wd, mask, name):


def field_escape(field):
return field.replace("\\", "\\134").replace(" ", "\\040").replace("\t", "\\011")
return field.replace("\\", r"\134").replace(" ", r"\040").replace("\t", r"\011")


def field_unescape(field):
return re.sub("\\\\([0-7]{1,3})", lambda m: chr(int(m.group(1), 8)), field)
return re.sub(r"\\([0-7]{1,3})", lambda m: chr(int(m.group(1), 8)), field)


def parse_tab(name):
Expand All @@ -50,7 +50,7 @@ def parse_tab(name):
sline = line.strip()
if sline == "" or sline[0] == "#":
continue
fields = list(map(field_unescape, re.split("[ \t]+", sline)))
fields = list(map(field_unescape, re.split(r"[ \t]+", sline)))
if len(fields) > 2 and ":" in fields[0] and fields[2].startswith("nfs"):
entries.append(fields)
return entries
Expand All @@ -75,7 +75,7 @@ def modify_tab(name, modify):
if sline == "" or sline[0] == "#":
new_lines.append(line)
else:
fields = list(map(field_unescape, re.split("[ \t]+", sline)))
fields = list(map(field_unescape, re.split(r"[ \t]+", sline)))
if len(fields) > 0 and ":" in fields[0]:
new_fields = modify(fields)
if new_fields:
Expand Down
2 changes: 1 addition & 1 deletion src/cockpit/packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ def ensure_scanned(self) -> None:
self.translations[f'{basename}.js'][lower_locale] = name
else:
# strip out trailing '.gz' components
basename = re.sub('.gz$', '', name)
basename = re.sub(r'.gz$', '', name)
logger.debug('Adding content %r -> %r', basename, name)
self.files[basename] = name

Expand Down
2 changes: 1 addition & 1 deletion test/common/lcov.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ def is_interesting_line(text):
# Don't complain about lines that contain only punctuation, or
# nothing but "else". We don't seem to get reliable
# information for them.
if not re.search('[a-zA-Z0-9]', text.replace("else", "")):
if not re.search(r'[a-zA-Z0-9]', text.replace("else", "")):
return False
return True

Expand Down
2 changes: 1 addition & 1 deletion test/common/netlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def cleanupDevs():

ver = self.machine.execute(
"busctl --system get-property org.freedesktop.NetworkManager /org/freedesktop/NetworkManager org.freedesktop.NetworkManager Version || true")
ver_match = re.match('s "(.*)"', ver)
ver_match = re.match(r's "(.*)"', ver)
if ver_match:
self.networkmanager_version = [int(x) for x in ver_match.group(1).split(".")]
else:
Expand Down
2 changes: 1 addition & 1 deletion test/common/storagelib.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,7 @@ def setUp(self):
super().setUp()

ver = self.machine.execute("busctl --system get-property org.freedesktop.UDisks2 /org/freedesktop/UDisks2/Manager org.freedesktop.UDisks2.Manager Version || true")
m = re.match('s "(.*)"', ver)
m = re.match(r's "(.*)"', ver)
if m:
self.storaged_version = list(map(int, m.group(1).split(".")))
else:
Expand Down
2 changes: 1 addition & 1 deletion test/common/typecheck
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def show_error(lines):


def consider(lines, js_error_codes):
m = re.match("([^:]*)\\(.*\\): error ([^:]*): .*", lines[0])
m = re.match(r"([^:]*)\(.*\): error ([^:]*): .*", lines[0])
if m and not should_ignore(m[1]):
relaxed = is_relaxed(m[1])
is_js = m[1].endswith(('.js', '.jsx'))
Expand Down
2 changes: 1 addition & 1 deletion test/verify/check-shell-multi-machine-key
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class TestMultiMachineKeyAuth(testlib.MachineCase):

def check_keys(self, keys_md5, keys):
def normalize(k):
return re.sub("/home/admin/\\.ssh/[^ ]*|test@test|ecdsa w/o comment", "", k)
return re.sub(r"/home/admin/\.ssh/[^ ]*|test@test|ecdsa w/o comment", "", k)
self.assertIn(normalize(self.browser.eval_js("cockpit.spawn([ 'ssh-add', '-l' ])")),
[normalize("\n".join(keys_md5) + "\n"),
normalize("\n".join(keys) + "\n")])
Expand Down
4 changes: 2 additions & 2 deletions test/verify/check-system-info
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class TestSystemInfo(testlib.MachineCase):
# Most OSes don't set nosmt by default, but there are some exceptions
self.expect_smt_default = self.machine.image in ["fedora-coreos"]

self.supportsFIPS = re.match('fedora|((centos|rhel)-(8|9)).*', self.machine.image)
self.supportsFIPS = re.match(r'fedora|((centos|rhel)-(8|9)).*', self.machine.image)
# HACK: temporary: we are in the middle of transitioning centos/rhel-10 images away from fips-mode-setup;
# until https://github.com/cockpit-project/bots/pull/7095 and https://github.com/cockpit-project/bots/pull/7091
# land, do runtime detection
Expand Down Expand Up @@ -810,7 +810,7 @@ password=foobar

# RHEL 8/10 have no SHA1 policy, so do not show it.
b.click("#crypto-policy-button")
func = b.wait_not_present if re.match('(centos|rhel)-(8|10).*', m.image) else b.wait_visible
func = b.wait_not_present if re.match(r'(centos|rhel)-(8|10).*', m.image) else b.wait_visible
func(".pf-v5-c-menu__item-main .pf-v5-c-menu__item-text:contains('DEFAULT:SHA1')")
b.click("#crypto-policy-dialog button:contains('Cancel')")
b.wait_not_present("#crypto-policy-dialog")
Expand Down
2 changes: 1 addition & 1 deletion test/verify/check-system-realms
Original file line number Diff line number Diff line change
Expand Up @@ -1054,7 +1054,7 @@ class TestKerberos(testlib.MachineCase):
self.assertIn("HTTP/1.1 200 OK", output)
self.assertIn('"csrf-token"', output)

cookie = re.search("Set-Cookie: cockpit=([^ ;]+)", output).group(1)
cookie = re.search(r"Set-Cookie: cockpit=([^ ;]+)", output).group(1)
b.open("/system/terminal", cookie={"name": "cockpit", "value": cookie, "domain": m.web_address, "path": "/"})
b.wait_visible('#content')

Expand Down
7 changes: 5 additions & 2 deletions test/verify/check-testlib
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,11 @@ class TestRunTestListing(unittest.TestCase):
self.assertIn(b"TestNondestructiveExample.testOne\nTestNondestructiveExample.testTwo", ndtests.stdout)

# nondestructive tests are sorted alphabetically
verify_ndtests = subprocess.run([run_tests, "--test-dir", VERIFY_DIR, "-n", "-l"], check=True, capture_output=True)
self.assertRegex(verify_ndtests.stdout, re.compile(b".*TestAccounts.*TestFirewall.*TestLogin.*TestServices.*TestTerminal.*", re.S))
verify_ndtests = subprocess.run([run_tests, "--test-dir", VERIFY_DIR, "-n", "-l"],
check=True, capture_output=True)
self.assertRegex(
verify_ndtests.stdout,
re.compile(rb".*TestAccounts.*TestFirewall.*TestLogin.*TestServices.*TestTerminal.*", re.S))

def testNonDestructive(self):
self.assertEqual(subprocess.check_output([run_tests, "--test-dir", EXAMPLE_DIR, "--nondestructive", "-l", "TestExample"]).strip().decode(),
Expand Down

0 comments on commit 35192bd

Please sign in to comment.