import functools


def ensure_exists(*, directory=True):
    """Decorator to ensure the returning path exists.
    """
    def wrapper(f):

        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            path = f(*args, **kwargs)
            if not path.exists():
                if directory:
                    path.mkdir(parents=True)
                else:
                    path.parent.mkdir(parents=True)
                    path.touch()
            return path

        return wrapped

    return wrapper