Normalize a path.

    This function simplifies a path by collapsing back-references
    and removing duplicated separators.

    Arguments:
        path (str): Path to normalize.

    Returns:
        str: A valid FS path.

    Example:
        >>> normpath("/foo//bar/frob/../baz")
        '/foo/bar/baz'
        >>> normpath("foo/../../bar")
        Traceback (most recent call last)
            ...
        IllegalBackReference: path 'foo/../../bar' contains back-references outside of filesystem"

def normpath(path):
    # type: (Text) -> Text
    """Normalize a path.

    This function simplifies a path by collapsing back-references
    and removing duplicated separators.

    Arguments:
        path (str): Path to normalize.

    Returns:
        str: A valid FS path.

    Example:
        >>> normpath("/foo//bar/frob/../baz")
        '/foo/bar/baz'
        >>> normpath("foo/../../bar")
        Traceback (most recent call last)
            ...
        IllegalBackReference: path 'foo/../../bar' contains back-references outside of filesystem"

    """
    if path in "/":
        return path

    # An early out if there is no need to normalize this path
    if not _requires_normalization(path):
        return path.rstrip("/")

    prefix = "/" if path.startswith("/") else ""
    components = []  # type: List[Text]
    try:
        for component in path.split("/"):
            if component in "..":  # True for '..', '.', and ''
                if component == "..":
                    components.pop()
            else:
                components.append(component)
    except IndexError:
        raise IllegalBackReference(path)
    return prefix + "/".join(components)