| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
'''String utility functions.''' |
| 5 |
|
| 6 |
import re |
| 7 |
import subprocess |
| 8 |
|
| 9 |
from .errors import CrazyError |
| 10 |
|
| 11 |
|
| 12 |
_VALID_OPTION_STRING_RE = re.compile('-[^\\s,]+') |
| 13 |
_VALID_VARIABLE_RE = re.compile('[a-zA-Z_][a-zA-Z0-9_]*') |
| 14 |
|
| 15 |
|
| 16 |
def contains_space(string): |
| 17 |
'''Check if string contains space type characters.''' |
| 18 |
|
| 19 |
return (' ' in string or '\t' in string or '\n' in string) |
| 20 |
|
| 21 |
|
| 22 |
def is_empty_or_whitespace(string): |
| 23 |
'''Check if string is empty or whitespace.''' |
| 24 |
|
| 25 |
return not string.strip() |
| 26 |
|
| 27 |
|
| 28 |
def is_valid_extended_regex(string): |
| 29 |
'''Check if string is a valid extended regular expression.''' |
| 30 |
|
| 31 |
try: |
| 32 |
r = subprocess.run( |
| 33 |
['grep', '-q', '-E', '--', string], |
| 34 |
input=b"", |
| 35 |
stdout=subprocess.DEVNULL, |
| 36 |
stderr=subprocess.DEVNULL, |
| 37 |
timeout=1, |
| 38 |
check=False) |
| 39 |
|
| 40 |
return r.returncode != 2 |
| 41 |
except (FileNotFoundError, PermissionError, subprocess.TimeoutExpired): |
| 42 |
return True |
| 43 |
|
| 44 |
|
| 45 |
def validate_prog(string): |
| 46 |
'''Validate a program string.''' |
| 47 |
|
| 48 |
if is_empty_or_whitespace(string): |
| 49 |
raise CrazyError('value is empty') |
| 50 |
|
| 51 |
if string.startswith(' '): |
| 52 |
raise CrazyError('begins with space') |
| 53 |
|
| 54 |
if string.endswith(' '): |
| 55 |
raise CrazyError('ends with space') |
| 56 |
|
| 57 |
if '\t' in string: |
| 58 |
raise CrazyError('contains a tabulator') |
| 59 |
|
| 60 |
if '\n' in string: |
| 61 |
raise CrazyError('contains a newline') |
| 62 |
|
| 63 |
if ' ' in string: |
| 64 |
raise CrazyError('contains multiple spaces') |
| 65 |
|
| 66 |
|
| 67 |
def indent(string, num_spaces): |
| 68 |
'''Indents each line in a string by a specified number of spaces, |
| 69 |
preserving empty lines. |
| 70 |
|
| 71 |
Args: |
| 72 |
string (str): The input string to be indented. |
| 73 |
num_spaces (int): The number of spaces to indent each line. |
| 74 |
|
| 75 |
Returns: |
| 76 |
str: The indented string. |
| 77 |
''' |
| 78 |
|
| 79 |
assert isinstance(string, str), \ |
| 80 |
f"indent: string: expected str, got {string!r}" |
| 81 |
|
| 82 |
assert isinstance(num_spaces, int), \ |
| 83 |
f"indent: num_spaces: expected int, got {num_spaces!r}" |
| 84 |
|
| 85 |
spaces = ' ' * num_spaces |
| 86 |
lines = string.split('\n') |
| 87 |
lines = [(spaces + line) if line.strip() else line for line in lines] |
| 88 |
return '\n'.join(lines) |
| 89 |
|
| 90 |
|
| 91 |
def join_with_wrap(primary_sep, secondary_sep, |
| 92 |
max_line_length, items, line_prefix=''): |
| 93 |
''' |
| 94 |
Join a list of strings with a primary separator, automatically wrapping |
| 95 |
to a new line (using the secondary separator) when the current line |
| 96 |
would exceed max_line_length. |
| 97 |
|
| 98 |
Args: |
| 99 |
primary_sep: |
| 100 |
String used to separate items on the same line. |
| 101 |
|
| 102 |
secondary_sep: |
| 103 |
String used to separate wrapped lines. |
| 104 |
|
| 105 |
max_line_length: |
| 106 |
Maximum number of characters per line. |
| 107 |
|
| 108 |
items: |
| 109 |
List of strings to join. |
| 110 |
|
| 111 |
line_prefix: |
| 112 |
Prefix each line with a prefix. |
| 113 |
|
| 114 |
Returns: |
| 115 |
str: Joined string with line wrapping |
| 116 |
''' |
| 117 |
|
| 118 |
lines = [] |
| 119 |
current_items = [] |
| 120 |
current_length = len(line_prefix) |
| 121 |
|
| 122 |
for item in items: |
| 123 |
sep_len = len(primary_sep) if current_items else 0 |
| 124 |
new_length = current_length + sep_len + len(item) |
| 125 |
|
| 126 |
if current_items and new_length > max_line_length: |
| 127 |
# flush current line |
| 128 |
lines.append(line_prefix + primary_sep.join(current_items)) |
| 129 |
current_items = [item] |
| 130 |
current_length = len(line_prefix) + len(item) |
| 131 |
else: |
| 132 |
current_items.append(item) |
| 133 |
current_length = new_length |
| 134 |
|
| 135 |
if current_items: |
| 136 |
lines.append(line_prefix + primary_sep.join(current_items)) |
| 137 |
|
| 138 |
return secondary_sep.join(lines) |
| 139 |
|
| 140 |
|
| 141 |
def is_valid_option_string(option_string): |
| 142 |
'''Check if `option_string` is a valid option string.''' |
| 143 |
|
| 144 |
if not _VALID_OPTION_STRING_RE.fullmatch(option_string): |
| 145 |
return False |
| 146 |
|
| 147 |
if option_string == '--': |
| 148 |
return False |
| 149 |
|
| 150 |
return True |
| 151 |
|
| 152 |
|
| 153 |
def is_valid_variable_name(string): |
| 154 |
'''Check if string is a valid shell variable name.''' |
| 155 |
|
| 156 |
return _VALID_VARIABLE_RE.fullmatch(string) |
| 157 |
|
| 158 |
|
| 159 |
def strip_comments(string): |
| 160 |
'''Strip shell comments from string.''' |
| 161 |
|
| 162 |
lines = [] |
| 163 |
|
| 164 |
for line in string.split('\n'): |
| 165 |
if line.lstrip().startswith('#'): |
| 166 |
continue |
| 167 |
|
| 168 |
lines.append(line) |
| 169 |
|
| 170 |
return '\n'.join(lines) |
| 171 |
|
| 172 |
|
| 173 |
def strip_double_empty_lines(string): |
| 174 |
'''Collapse triple newlines into double newlines.''' |
| 175 |
|
| 176 |
return string.replace('\n\n\n', '\n\n') |
| 177 |
|
| 178 |
|
| 179 |
def replace_many(string, replacements): |
| 180 |
''' |
| 181 |
Replace multiple substrings in `string` according to a list |
| 182 |
of (search, replace) tuples. |
| 183 |
''' |
| 184 |
|
| 185 |
s = string |
| 186 |
|
| 187 |
for search, replace in replacements: |
| 188 |
s = s.replace(search, replace) |
| 189 |
|
| 190 |
return s |