SPPAS 4.22

https://sppas.org/

Module sppas.src.wkps

Class sppasWkps

Description

Manage the set of workspaces.

A workspace is made of:

  • a file in which data are saved and loaded when needed;
  • a name, matching the filename without path nor extension.

Constructor

Create a sppasWkps instance.

Load the list of existing wjson file names of the workspaces folder of the software.

View Source
def __init__(self):
    """Create a sppasWkps instance.

    Load the list of existing wjson file names of the workspaces folder
    of the software.

    """
    wkp_dir = paths.wkps
    if os.path.exists(wkp_dir) is False:
        os.mkdir(wkp_dir)
    self.__wkps = list()
    self.__wkps.append('Blank')
    self.ext = '.' + sppasWkpRW.default_extension()
    self.set_workspaces()

Public functions

set_workspaces

Fix the list of existing workspaces in the software.

Reset the current list of workspaces.

View Source
def set_workspaces(self):
    """Fix the list of existing workspaces in the software.

        Reset the current list of workspaces.

        """
    for fn in os.listdir(paths.wkps):
        fn_observed, ext_observed = os.path.splitext(fn)
        if ext_observed.lower() == self.ext:
            wkp_name = os.path.basename(fn_observed)
            self.__wkps.append(wkp_name)
            logging.info('Workspace added: {:s}'.format(wkp_name))

import_from_file

Import and append an external workspace.

Parameters
  • filename: (str)
Returns
  • The real name used to save the workspace
View Source
def import_from_file(self, filename):
    """Import and append an external workspace.

        :param filename: (str)
        :returns: The real name used to save the workspace

        """
    if os.path.exists(filename) is False:
        raise FileTypeError(filename)
    name, ext = os.path.splitext(os.path.basename(filename))
    ext = ext[1:]
    if ext.lower() not in sppasWkpRW.extensions():
        raise WkpExtensionError(ext)
    u_name = self.__raises_existing(name)
    try:
        dest = os.path.join(paths.wkps, u_name + self.ext)
        shutil.copyfile(filename, dest)
    except:
        raise
    try:
        w = sppasWkpRW(filename).read()
    except:
        os.remove(dest)
        raise
    self.__wkps.append(u_name)
    return u_name

new

Create and append a new empty workspace.

Parameters
  • name: (str) Name of the workspace to create.
Returns
  • The real name used to save the workspace
Raises

IOError, ValueError

View Source
def new(self, name):
    """Create and append a new empty workspace.

        :param name: (str) Name of the workspace to create.
        :returns: The real name used to save the workspace
        :raises: IOError, ValueError

        """
    u_name = self.__raises_existing(name)
    fn = os.path.join(paths.wkps, u_name) + self.ext
    self.__wkps.append(u_name)
    wkp = sppasWorkspace(u_name)
    sppasWkpRW(fn).write(wkp)
    return u_name

export_to_file

Save an existing workspace into an external file.

Override filename if the file already exists.

Parameters
  • index: (int) Index of the workspace to save data in
  • filename: (str)
Raises

IOError

View Source
def export_to_file(self, index, filename):
    """Save an existing workspace into an external file.

        Override filename if the file already exists.

        :param index: (int) Index of the workspace to save data in
        :param filename: (str)
        :raises: IOError

        """
    if index == 0:
        raise WkpExportBlankError
    u_name = self[index]
    fn = os.path.join(paths.wkps, u_name) + self.ext
    if fn == filename:
        raise WkpExportValueError(filename)
    shutil.copyfile(fn, filename)

delete

Delete the workspace with the given index.

Parameters
  • index: (int) Index of the workspace
Raises

IndexError

View Source
def delete(self, index):
    """Delete the workspace with the given index.

        :param index: (int) Index of the workspace
        :raises: IndexError

        """
    if index == 0:
        raise WkpDeleteBlankError
    try:
        fn = self.check_filename(index)
        os.remove(fn)
    except OSError:
        pass
    self.__wkps.pop(index)

index

Return the index of the workspace with the given name.

Parameters
  • name: (str)
Returns
  • (int)
Raises

ValueError

View Source
def index(self, name):
    """Return the index of the workspace with the given name.

        :param name: (str)
        :returns: (int)
        :raises: ValueError

        """
    u_name = self.__raises_not_existing(name)
    i = 0
    while self.__wkps[i] != u_name:
        i += 1
    return i

rename

Set a new name to the workspace at the given index.

Parameters
  • index: (int) Index of the workspace
  • new_name: (str) New name of the workspace
Returns
  • (str)
Raises

IndexError, OSError

View Source
def rename(self, index, new_name):
    """Set a new name to the workspace at the given index.

        :param index: (int) Index of the workspace
        :param new_name: (str) New name of the workspace
        :returns: (str)
        :raises: IndexError, OSError

        """
    if index == 0:
        raise WkpRenameBlankError
    u_name = self.__raises_existing(new_name)
    cur_name = self[index]
    if cur_name == new_name:
        return
    src = self.check_filename(index)
    dest = os.path.join(paths.wkps, u_name) + self.ext
    shutil.move(src, dest)
    self.__wkps[index] = u_name
    return u_name

check_filename

Get the filename of the workspace at the given index.

Parameters
  • index: (int) Index of the workspace
Returns
  • (str) name of the file
Raises

IndexError, OSError

View Source
def check_filename(self, index):
    """Get the filename of the workspace at the given index.

        :param index: (int) Index of the workspace
        :returns: (str) name of the file
        :raises: IndexError, OSError


        """
    fn = os.path.join(paths.wkps, self[index]) + self.ext
    if os.path.exists(fn) is False:
        raise WkpFileError(fn[:-4])
    return fn

load_data

Return the data of the workspace at the given index.

Parameters
  • index: (int) Index of the workspace
Returns
  • (str) sppasWorkspace()
Raises

IndexError

View Source
def load_data(self, index):
    """Return the data of the workspace at the given index.

        :param index: (int) Index of the workspace
        :returns: (str) sppasWorkspace()
        :raises: IndexError

        """
    if index == 0:
        return sppasWorkspace()
    try:
        filename = self.check_filename(index)
    except OSError as e:
        logging.error("Workspace can't be loaded: {}".format(str(e)))
        return sppasWorkspace()
    return sppasWkpRW(filename).read()

save_data

Save data into a workspace.

The data can already match an existing workspace or a new workspace is created. Raises indexerror if is attempted to save the 'Blank' workspace.

Parameters
  • data: (sppasWorkspace) Data of a workspace to save
  • index: (int) Index of the workspace to save data in
Returns
  • The real name used to save the workspace
Raises

IOError, IndexError

View Source
def save_data(self, data, index=-1):
    """Save data into a workspace.

        The data can already match an existing workspace or a new workspace
        is created. Raises indexerror if is attempted to save the 'Blank'
        workspace.

        :param data: (sppasWorkspace) Data of a workspace to save
        :param index: (int) Index of the workspace to save data in
        :returns: The real name used to save the workspace
        :raises: IOError, IndexError

        """
    if index == 0:
        raise WkpSaveBlankError
    if index == -1:
        u_name = self.new('New workspace')
    else:
        u_name = self[index]
    filename = os.path.join(paths.wkps, u_name) + self.ext
    parser = sppasWkpRW(filename)
    parser.write(data)
    return u_name

Protected functions

__raises_not_existing

Raises WkpNameError if name is not already in self.

Parameters
  • name
View Source
def __raises_not_existing(self, name):
    """Raises WkpNameError if name is not already in self."""
    sp = sppasUnicode(name)
    u_name = sp.to_strip()
    contains = False
    for a in self.__wkps:
        if a.lower() == u_name.lower():
            contains = True
            break
    if contains is False:
        raise WkpNameError(u_name)
    return u_name

__raises_existing

Raises WkpIdValueError if name is already in self.

Parameters
  • name
View Source
def __raises_existing(self, name):
    """Raises WkpIdValueError if name is already in self."""
    sp = sppasUnicode(name)
    u_name = sp.to_strip()
    contains = False
    for a in self.__wkps:
        if a.lower() == u_name.lower():
            contains = True
            break
    if contains is True:
        raise WkpIdValueError(u_name)
    return u_name

Overloads

__len__

Return the number of workspaces.

View Source
def __len__(self):
    """Return the number of workspaces."""
    return len(self.__wkps)

__iter__

View Source
def __iter__(self):
    for a in self.__wkps:
        yield a

__getitem__

View Source
def __getitem__(self, i):
    try:
        item = self.__wkps[i]
    except IndexError:
        raise sppasIndexError(i)
    return item

__contains__

View Source
def __contains__(self, name):
    sp = sppasUnicode(name)
    u_name = sp.to_strip()
    for a in self.__wkps:
        if a.lower() == u_name.lower():
            return True
    return False