import shlex
import pathlib


def _get_pathlib_value(field, value, quote):
    """Get the value for a pathlib.Path type template

    Args:
        field: the path field, e.g. "filename.stem"
        value: the value for the path component
        quote: bool; if true, quotes the returned path for safe execution in the shell
    """
    parts = field.split(".")

    if len(parts) == 1:
        return shlex.quote(value) if quote else value

    if len(parts) > 2:
        raise ValueError(f"Illegal value for path template: {field}")

    path = parts[0]
    attribute = parts[1]
    path = pathlib.Path(value)
    try:
        val = getattr(path, attribute)
        val_str = str(val)
        if quote:
            val_str = shlex.quote(val_str)
        return val_str
    except AttributeError:
        raise ValueError("Illegal value for path template: {attribute}")