from typing import Optional


def _apply_umask(mode: int, umask: Optional[int]) -> int:
    """
    Copy the user permission bits to group and all bits and then apply
    the supplied umask. If umask is None just return mode instead.
    """
    if umask is None:
        return mode
    umode = (mode >> 6) & 0o7
    mode &= ~0o777
    mode |= ((umode << 6) | (umode << 3) | umode) & ~umask
    return mode