import typing


def _remove_arg(
    source: typing.List[str],
    flag: str,
    has_value: bool,
) -> typing.List[str]:
    """
    Search for and remove the specified flag within the source arguments.

    This function removes it and its optional value if has_value is specified,
    returning a copy of the source list with those elements removed. If the flag is not
    found an unaltered copy of the source list is returned instead. This is used in the
    CLI command to prevent certain flags from being used in both the host and container
    invocation contexts.
    """
    try:
        index = source.index(flag)
        offset = 1 if has_value else 0
        next_index = index + 1 + offset
        return source[:index] + source[next_index:]
    except ValueError:
        pass

    if not flag.startswith("--"):
        return source.copy()

    try:
        finder = (i for i, x in enumerate(source) if x.startswith(f"{flag}="))
        index = next(finder)
        next_index = index + 1
        return source[:index] + source[next_index:]
    except StopIteration:
        pass

    return source.copy()