Skip to content
Snippets Groups Projects
Commit 3e6f4fdb authored by Raphaël Gomès's avatar Raphaël Gomès
Browse files

utils: create module with new string escaping functions

parent da96b3d2
No related branches found
No related tags found
1 merge request!37general improvements
......@@ -20,6 +20,7 @@
RETURN_CODE_SETUP_ISSUE,
RETURN_CODE_SUCCESS,
)
from poulpe.utils import escape_string, split_unescape
def generate_tasks(
......@@ -137,52 +138,6 @@
yield kv
def escape_string(s: str, chars: str, escape: chr = "\\") -> str:
"""Escape all unescaped characters in `chars` with `escape`"""
for delim in chars:
s = re.sub(rf"([^{delim}]){delim}", rf"\g<1>{escape}{delim}", s)
return s
def split_unescape(s: str, delim: chr, escape: chr = "\\") -> str:
"""Split a string along `delim`, only if not escaped by `escape`
>>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo$,ba$r', ',', '$')
['foo,ba$r']
>>> split_unescape('foo$$,bar', ',', '$')
['foo$', 'bar']
>>> split_unescape('foo$', ',', '$')
['foo$']
"""
ret = []
current = []
itr = iter(s)
for ch in itr:
if ch == escape:
try:
# skip the next character; it has been escaped!
next_char = next(itr)
if next_char == delim:
current.append(next_char)
else:
current.append(escape)
current.append(next_char)
except StopIteration:
current.append(escape)
elif ch == delim:
# split! (add current to the list and reset it)
ret.append("".join(current))
current = []
else:
current.append(ch)
ret.append("".join(current))
return ret
class BinEnvSpec:
@classmethod
def from_piece(cls, piece: str):
......
# Useful common code
import re
def escape_string(s: str, chars: str, escape: chr = "\\") -> str:
"""Escape all unescaped characters in `chars` with `escape`"""
for delim in chars:
s = re.sub(rf"([^{delim}]){delim}", rf"\g<1>{escape}{delim}", s)
return s
def split_unescape(s: str, delim: chr, escape: chr = "\\") -> str:
"""Split a string along `delim`, only if not escaped by `escape`
>>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo$,ba$r', ',', '$')
['foo,ba$r']
>>> split_unescape('foo$$,bar', ',', '$')
['foo$', 'bar']
>>> split_unescape('foo$', ',', '$')
['foo$']
"""
ret = []
current = []
itr = iter(s)
for ch in itr:
if ch == escape:
try:
# skip the next character; it has been escaped!
next_char = next(itr)
if next_char == delim:
current.append(next_char)
else:
current.append(escape)
current.append(next_char)
except StopIteration:
current.append(escape)
elif ch == delim:
# split! (add current to the list and reset it)
ret.append("".join(current))
current = []
else:
current.append(ch)
ret.append("".join(current))
return ret
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment