def workspace_from_dir(directory, recurse=True):
    """
    Construct a workspace object from a directory name.  If recurse=True, this
    function will search down the directory tree and return the first workspace
    it finds.  If recurse=False, an exception will be raised if the given
    directory is not a workspace.  Workspace identification requires a file
    called 'workspace.pkl' to be present in each workspace directory, which can
    unfortunately be a little fragile.
    """
    directory = os.path.abspath(directory)
    pickle_path = os.path.join(directory, 'workspace.pkl')

    # Make sure the given directory contains a 'workspace' file.  This file is
    # needed to instantiate the right kind of workspace.

    if not os.path.exists(pickle_path):
        if recurse:
            parent_dir = os.path.dirname(directory)

            # Keep looking for a workspace as long as we haven't hit the root
            # of the file system.  If an exception is raised, that means no
            # workspace was found.  Catch and re-raise the exception so that
            # the name of the directory reported in the exception is meaningful
            # to the user.

            try:
                return workspace_from_dir(parent_dir, parent_dir != '/')
            except WorkspaceNotFound:
                raise WorkspaceNotFound(directory)
        else:
            raise WorkspaceNotFound(directory)

    # Load the 'workspace' file and create a workspace.

    with open(pickle_path) as file:
        workspace_class = pickle.load(file)

    return workspace_class.from_directory(directory)
Construct a workspace object from a directory name.  If recurse=True, this
    function will search down the directory tree and return the first workspace
    it finds.  If recurse=False, an exception will be raised if the given
    directory is not a workspace.  Workspace identification requires a file
    called 'workspace.pkl' to be present in each workspace directory, which can
    unfortunately be a little fragile.