def create_symlink_strict()

in workstation-config/securedrop-mime-handling.py [0:0]


def create_symlink_strict(source_path_str, target_path_str, overwrite_expected=False):
    """
    Creates a symlink, but warning when idempotence is required and failing if
    link source already exsits.
    """
    source_path = Path(source_path_str)
    target_path = Path(target_path_str)
    target_path.resolve(strict=True)  # raise exception if does not exist

    try:
        source_path.symlink_to(target_path)
    except FileExistsError as e:
        if source_path.is_symlink():
            if source_path.readlink() == target_path:
                if not overwrite_expected:
                    # Harmless situation, yet not ideal (idempotency required)
                    logger.warning(f"'{source_path}' existed already (unexpected)")
            else:
                logger.error(f"'{source_path}' existed already and is linked to the wrong file")
                raise e
        else:
            logger.error(f"'{source_path}' existed already")
            raise e