Skip to content

string_tools

interpret_as_bool(value)

Interpret a boolean or a string representation of a boolean as a boolean value.

Accepts either a boolean (True or False) or a case-insensitive string representation of a boolean ("true" or "false"). Returns the corresponding boolean value.

Source code in fractal_server/string_tools.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def interpret_as_bool(value: bool | str) -> bool:
    """
    Interpret a boolean or a string representation of a boolean as a boolean
    value.

    Accepts either a boolean (`True` or `False`) or a case-insensitive string
    representation of a boolean ("true" or "false").
    Returns the corresponding boolean value.
    """
    if isinstance(value, bool):
        return value
    elif isinstance(value, str):
        value_lower = value.lower()
        if value_lower == "true":
            return True
        elif value_lower == "false":
            return False
        else:
            raise ValueError("String must be 'true' or 'false'.")
    else:
        raise TypeError(f"Expected bool or str, got {type(value)}: '{value}'.")

sanitize_string(value)

Make string safe to be used in file/folder names and subprocess commands.

Make the string lower-case, and replace any special character with an underscore, where special characters are:

>>> string.punctuation
'!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
' \t\n\r\x0b\x0c'

Parameters:

Name Type Description Default
value str

Input string

required

Returns:

Type Description
str

Sanitized value

Source code in fractal_server/string_tools.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def sanitize_string(value: str) -> str:
    """
    Make string safe to be used in file/folder names and subprocess commands.

    Make the string lower-case, and replace any special character with an
    underscore, where special characters are:


        >>> string.punctuation
        '!"#$%&\'()*+,-./:;<=>?@[\\\\]^_`{|}~'
        >>> string.whitespace
        ' \\t\\n\\r\\x0b\\x0c'

    Args:
        value: Input string

    Returns:
        Sanitized value
    """
    new_value = value.lower()
    for character in __SPECIAL_CHARACTERS__:
        new_value = new_value.replace(character, "_")
    return new_value

validate_cmd(command, *, allow_char=None, attribute_name='Command')

Assert that the provided command does not contain any of the forbidden characters for commands (fractal_server.string_tools.NOT_ALLOWED_FOR_COMMANDS)

Parameters:

Name Type Description Default
command str

command to validate.

required
allow_char str | None

chars to accept among the forbidden ones

None
attribute_name str

Name of the attribute, to be used in error message.

'Command'
Source code in fractal_server/string_tools.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def validate_cmd(
    command: str,
    *,
    allow_char: str | None = None,
    attribute_name: str = "Command",
):
    """
    Assert that the provided `command` does not contain any of the forbidden
    characters for commands
    (fractal_server.string_tools.__NOT_ALLOWED_FOR_COMMANDS__)

    Args:
        command: command to validate.
        allow_char: chars to accept among the forbidden ones
        attribute_name: Name of the attribute, to be used in error message.
    """
    if not isinstance(command, str):
        raise ValueError(f"{command=} is not a string.")
    forbidden = set(__NOT_ALLOWED_FOR_COMMANDS__)
    if allow_char is not None:
        forbidden = forbidden - set(allow_char)
    if not forbidden.isdisjoint(set(command)):
        raise ValueError(
            f"{attribute_name} must not contain any of this characters: "
            f"'{forbidden}'\n"
            f"Provided {attribute_name.lower()}: '{command}'."
        )