capellambse.filehandler package

class capellambse.filehandler.FileHandler

Bases: object

Abstract super class for file handler implementations.

Parameters:
  • path (str | PathLike) – The location of the remote. The exact accepted forms are determined by the specific file handler implementation, for example the LocalFileHandler accepts only local paths, and the GitFileHandler accepts everything that Git accepts.

  • subdir (str | PurePosixPath) – Consider all paths relative to this subdirectory, instead of the root of the file handler’s hierarchy.

__init__(path, *, subdir='/', **kw)
Parameters:
Return type:

None

get_model_info()
Return type:

HandlerInfo

is_dir(path, /)
Parameters:

path (str | PurePosixPath)

is_file(path, /)
Parameters:

path (str | PurePosixPath)

iterdir(path='.', /)

Iterate over the contents of a directory.

This method is equivalent to calling fh.rootdir.joinpath(path).iterdir().

Parameters:

path (str | PurePosixPath) – The directory to list. If not given, lists the contents of the root directory (i.e. the one specified by path and subdir).

Return type:

Iterator[FilePath[Self]]

abstract open(filename, mode='rb')

Open the model file for reading or writing.

A “file” in this context does not necessarily refer to a physical file on disk; it may just as well be streamed in via network or other means. Due to this, the file-like returned by this method is not required to support random access.

Parameters:
  • filename (str | PurePosixPath) – The name of the file, relative to the path that was given to the constructor.

  • mode (Literal['r', 'rb', 'w', 'wb']) – The mode to open the file in. Either "r" or "rb" for reading, or "w" or "wb" for writing a new file. Be aware that this method may refuse to open a file for writing unless a transaction was started with write_transaction() first.

Return type:

IO[bytes]

path: str | PathLike
read_file(path, /)

Read a file.

This method is a convenience wrapper around open().

Return type:

bytes

Parameters:

path (str | PurePosixPath)

property rootdir: FilePath[Self]

The root directory of the file handler.

write_file(path, content, /)

Write a file.

This method is a convenience wrapper around open().

Return type:

None

Parameters:
write_transaction(**kw)

Start a transaction for writing new model files.

During a transaction, writable objects returned by open() buffer their contents in a temporary location, and once the transaction ends, all updated files are committed to their destinations at once. If the transaction is aborted, for example because an exception was raised, then all changes must be rolled back to the state immediately before the transaction. If, during a transaction, any relevant file is touched without the file handler knowing about it, the behavior is undefined.

Note that open() may refuse to open a file as writable if no transaction is currently open. This depends on the needs of the underlying abstract file system.

Return type:

ContextManager[Mapping[str, Any]]

Parameters:

kw (Any)

Transaction arguments

A concrete file handler implementation may accept arbitrary additional arguments to this method. The implementation should however always support the case of no arguments given, in which case it should start a transaction with sensible defaults, and it should also accept and ignore any arguments it does not understand. All additional arguments must be passed in via keywords. Positional arguments are not supported.

The return value of the context manager’s __enter__() method is expected to be a mapping of all the keyword arguments that were not understood. Client code may use this to react properly (e.g. by aborting the transaction early) if a required keyword argument is found to be not supported by the underlying file handler. If a subclass wishes to call its super class’ write_transaction() method, it should remove all the keyword arguments that it handles itself and pass on the others unchanged.

Well-known arguments

The following arguments are considered well-known, and their meaning is expected to be the same for all file handlers that support them.

  • dry_run (bool): If set to True, changes made during the transaction should be rolled back instead of being committed, just as if an exception had been raised.

  • author_name (str): The name of the author of the changes.

  • author_email (str): The e-mail address to record alongside the author_name.

  • commit_msg (str): A message describing the changes, which will be recorded in the version control system.

  • remote_branch (str): If the model came from a remote version control system, changes are normally pushed back to the same branch on that remote. This argument specifies an alternative branch name to push to (which may not yet exist on the remote).

exception capellambse.filehandler.TransactionClosedError

Bases: RuntimeError

Raised when a transaction must be opened first to write files.

capellambse.filehandler.get_filehandler(path, **kwargs)
Return type:

FileHandler

Parameters:

Submodules

capellambse.filehandler.abc module

The abstract FileHandler superclass and utilities.

capellambse.filehandler.abc.AbstractFilePath

alias of FilePath

class capellambse.filehandler.abc.FileHandler

Bases: object

Abstract super class for file handler implementations.

Parameters:
  • path (str | PathLike) – The location of the remote. The exact accepted forms are determined by the specific file handler implementation, for example the LocalFileHandler accepts only local paths, and the GitFileHandler accepts everything that Git accepts.

  • subdir (str | PurePosixPath) – Consider all paths relative to this subdirectory, instead of the root of the file handler’s hierarchy.

__init__(path, *, subdir='/', **kw)
Parameters:
Return type:

None

get_model_info()
Return type:

HandlerInfo

is_dir(path, /)
Parameters:

path (str | PurePosixPath)

is_file(path, /)
Parameters:

path (str | PurePosixPath)

iterdir(path='.', /)

Iterate over the contents of a directory.

This method is equivalent to calling fh.rootdir.joinpath(path).iterdir().

Parameters:

path (str | PurePosixPath) – The directory to list. If not given, lists the contents of the root directory (i.e. the one specified by path and subdir).

Return type:

Iterator[FilePath[Self]]

abstract open(filename, mode='rb')

Open the model file for reading or writing.

A “file” in this context does not necessarily refer to a physical file on disk; it may just as well be streamed in via network or other means. Due to this, the file-like returned by this method is not required to support random access.

Parameters:
  • filename (str | PurePosixPath) – The name of the file, relative to the path that was given to the constructor.

  • mode (Literal['r', 'rb', 'w', 'wb']) – The mode to open the file in. Either "r" or "rb" for reading, or "w" or "wb" for writing a new file. Be aware that this method may refuse to open a file for writing unless a transaction was started with write_transaction() first.

Return type:

IO[bytes]

path: str | PathLike
read_file(path, /)

Read a file.

This method is a convenience wrapper around open().

Return type:

bytes

Parameters:

path (str | PurePosixPath)

property rootdir: FilePath[Self]

The root directory of the file handler.

write_file(path, content, /)

Write a file.

This method is a convenience wrapper around open().

Return type:

None

Parameters:
write_transaction(**kw)

Start a transaction for writing new model files.

During a transaction, writable objects returned by open() buffer their contents in a temporary location, and once the transaction ends, all updated files are committed to their destinations at once. If the transaction is aborted, for example because an exception was raised, then all changes must be rolled back to the state immediately before the transaction. If, during a transaction, any relevant file is touched without the file handler knowing about it, the behavior is undefined.

Note that open() may refuse to open a file as writable if no transaction is currently open. This depends on the needs of the underlying abstract file system.

Return type:

ContextManager[Mapping[str, Any]]

Parameters:

kw (Any)

Transaction arguments

A concrete file handler implementation may accept arbitrary additional arguments to this method. The implementation should however always support the case of no arguments given, in which case it should start a transaction with sensible defaults, and it should also accept and ignore any arguments it does not understand. All additional arguments must be passed in via keywords. Positional arguments are not supported.

The return value of the context manager’s __enter__() method is expected to be a mapping of all the keyword arguments that were not understood. Client code may use this to react properly (e.g. by aborting the transaction early) if a required keyword argument is found to be not supported by the underlying file handler. If a subclass wishes to call its super class’ write_transaction() method, it should remove all the keyword arguments that it handles itself and pass on the others unchanged.

Well-known arguments

The following arguments are considered well-known, and their meaning is expected to be the same for all file handlers that support them.

  • dry_run (bool): If set to True, changes made during the transaction should be rolled back instead of being committed, just as if an exception had been raised.

  • author_name (str): The name of the author of the changes.

  • author_email (str): The e-mail address to record alongside the author_name.

  • commit_msg (str): A message describing the changes, which will be recorded in the version control system.

  • remote_branch (str): If the model came from a remote version control system, changes are normally pushed back to the same branch on that remote. This argument specifies an alternative branch name to push to (which may not yet exist on the remote).

class capellambse.filehandler.abc.FilePath

Bases: PathLike[str], Traversable, Generic[_F]

A path to a file in a file handler.

This is an abstract class with FileHandler-agnostic implementations of some of Traversable’s methods. It is not meant to be instantiated directly, but rather to be used as a base class for concrete file path implementations.

Note that some of these implementations may be inefficient, and subclasses are encouraged to override them with more efficient implementations if possible.

__init__(parent, path)
Parameters:
is_dir()

Return True if self is a directory

Return type:

bool

is_file()

Return True if self is a file

Return type:

bool

iterdir(path='.')

Yield Traversable objects in self

Return type:

Iterator[Self]

Parameters:

path (str | PurePosixPath)

joinpath(path)

Return Traversable resolved with any descendants applied.

Each descendant should be a path segment relative to self and each may contain multiple levels separated by posixpath.sep (/).

Return type:

Self

Parameters:

path (str | PurePosixPath)

property name: str

The base name of this object without any parent references.

open(mode='rb', buffering=-1, encoding=None, errors=None, newline=None)

mode may be ‘r’ or ‘rb’ to open as text or binary. Return a handle suitable for reading (same as pathlib.Path.open).

When opening as text, accepts encoding parameters such as those accepted by io.TextIOWrapper.

Return type:

IO[bytes]

Parameters:
  • mode (Literal['r', 'rb', 'w', 'wb'])

  • buffering (int)

  • encoding (str | None)

  • errors (str | None)

  • newline (str | None)

property parent: Self
read_bytes()

Read contents of self as bytes

Return type:

bytes

read_text(encoding=None)

Read contents of self as text

Return type:

str

Parameters:

encoding (str | None)

rglob(pattern)
Return type:

Iterator[Self]

Parameters:

pattern (str)

property stem: str
property suffix: str
class capellambse.filehandler.abc.HandlerInfo

Bases: object

HandlerInfo(url: ‘str’)

__init__(url)
Parameters:

url (str)

Return type:

None

url: str
exception capellambse.filehandler.abc.TransactionClosedError

Bases: RuntimeError

Raised when a transaction must be opened first to write files.

capellambse.filehandler.git module

class capellambse.filehandler.git.GitFileHandler

Bases: FileHandler

File handler for git:// and related protocols.

Parameters:
  • revision (str) – The Git revision to check out. Either a branch or tag name, a full ref name, or the object name (i.e. hash) of a commit-ish.

  • username (str) – The user name for authentication with the Git remote.

  • password (str) – The password for authentication with the Git remote.

  • identity_file (str) – Authenticate against the remote with the private key in this file. Defaults to using SSH’s algorithm for determining a suitable key. (SSH only, ignored otherwise)

  • known_hosts_file (str) – An OpenSSH-style known_hosts file containing the public key of the remote server. (SSH only, ignored otherwise)

  • disable_cache (bool) – Wipe the local cache and create a fresh, new clone.

  • update_cache (bool) – Contact the remote and make sure that the local cache is up to date. Note that setting this to False does not necessarily inhibit all attempts to contact the remote; it just disables the initial “fetch” operation. Later operations may still require to access the server, for example to download Git-LFS files.

See also

capellambse.filehandler.abc.FileHandler

Documentation of common parameters.

__init__(path, revision='HEAD', username='', password='', identity_file='', known_hosts_file='', disable_cache=False, update_cache=True, *, subdir='/')
Parameters:
Return type:

None

cache_dir: Path

Path to the temporary work tree created by this file handler.

get_model_info()
Return type:

HandlerInfo

identity_file: str
iterdir(path='.')

Iterate over the files in the given directory.

Parameters:

path (str | PurePosixPath) – The path to the directory to iterate over.

Return type:

Iterator[GitPath]

known_hosts_file: str
open(filename, mode='rb')

Open the model file for reading or writing.

A “file” in this context does not necessarily refer to a physical file on disk; it may just as well be streamed in via network or other means. Due to this, the file-like returned by this method is not required to support random access.

Parameters:
  • filename (str | PurePosixPath) – The name of the file, relative to the path that was given to the constructor.

  • mode (Literal['r', 'rb', 'w', 'wb']) – The mode to open the file in. Either "r" or "rb" for reading, or "w" or "wb" for writing a new file. Be aware that this method may refuse to open a file for writing unless a transaction was started with write_transaction() first.

Return type:

BinaryIO

password: str
property rootdir: GitPath

The root directory of the repository.

shallow: Final = False
username: str
write_transaction(dry_run=False, author_name=None, author_email=None, commit_msg='Changes made with python-capellambse', ignore_empty=True, remote_branch=None, push=True, push_options=(), **kw)

Create a transaction that records all changes as a new commit.

Parameters:
  • author_name (str | None) – The name of the commit author.

  • author_email (str | None) – The e-mail address of the commit author.

  • commit_msg (str) – The commit message.

  • dry_run (bool) – If True, stop before updating the revision pointer. The commit will be created, but will not be part of any branch or tag.

  • ignore_empty (bool) –

    If True and the transaction did not actually change any files (i.e. the new commit would be tree-same with its parent), do not actually make a new commit.

    Changed in version 0.5.67: Previous versions would create empty commits if no files changed. If you relied on that behavior (e.g. to trigger subsequent CI actions), use this option.

  • remote_branch (str | None) –

    An alternative branch name to push to on the remote, instead of pushing back to the same branch. This is required if push is True and the revision that was passed to the constructor does not refer to a branch (or looks like a git object).

    Note: For convenience, refs/heads/ will be prepended automatically to this name if it isn’t already present. This also means that it is not possible to create tags or other types of refs; passing in something like refs/tags/v2.4 would result in the full ref name refs/heads/refs/tags/v2.4.

  • push (bool) – Set to False to inhibit pushing the changes back.

  • push_options (Sequence[str]) – Additional git push options. See --push-option in git-push(1). Ignored if push is False.

  • **kw (Any) – Additional arguments are ignored.

Raises:

ValueError

  • If a commit hash was used during loading, and no remote_branch was given - If the given remote_branch (or the final part of the originally given revision) looks like a git object

Return type:

ContextManager[Mapping[str, Any]]

class capellambse.filehandler.git.GitHandlerInfo

Bases: HandlerInfo

GitHandlerInfo(url: ‘str’, branch: ‘str | None’, revision: ‘str’, rev_hash: ‘str’)

__init__(url, branch, revision, rev_hash)
Parameters:
  • url (str)

  • branch (str | None)

  • revision (str)

  • rev_hash (str)

Return type:

None

branch: str | None
rev_hash: str
revision: str
class capellambse.filehandler.git.GitPath

Bases: FilePath[GitFileHandler]

is_dir()

Return True if self is a directory

Return type:

bool

is_file()

Return True if self is a file

Return type:

bool

capellambse.filehandler.git_askpass module

capellambse.filehandler.gitlab_artifacts module

class capellambse.filehandler.gitlab_artifacts.GitlabArtifactsFiles

Bases: FileHandler

Download files from Gitlab’s artifacts hosting service.

This file handler is roughly equivalent to an HTTPFileHandler with appropriate headers and the following URL:

https://<path>/api/v4/projects/<project>/jobs/artifacts/<branch>/raw/<subdir>/%s?job_name=<job>

One important difference is that this file handler will always use the latest successful job, regardless of the overall pipeline status, while an HTTPFileHandler with the above URL would only consider jobs from successful pipelines.

This file handler uses several of the Gitlab CI/CD pre-defined environment variables. Refer to the documentation for their exact meaning and behavior during CI runs, and see below for how they are used.

Parameters:
  • path (str) –

    The URL to fetch artifacts from, in one of the following formats:

    • The literal string glart: (or glart://), which uses the URL from $CI_SERVER_FQDN or - if that is not set - the public Gitlab instance at https://gitlab.com.

    • The base URL of the Gitlab server, using glart:, glart+http: or glart+https: as the protocol. glart: uses the protocol specified by $CI_SERVER_PROTOCOL, or falls back to HTTPS.

    • A URL that combines the above with some of the required parameters described below, using the format:

      glart://gitlab.mycompany.com/group/subgroup/project#branch=<branch>&job=<jobname>
      

      Note that this format does not support numeric IDs for the project and job, thus requiring to pass a branch name. Any of the parts of this combined URL may instead be passed explicitly via keyword arguments.

      Keyword arguments have precedence over the combined URL.

  • token (str | None) –

    A personal or project access token with read_api permission on the specified project. The following ways are supported for passing the token, which are checked in order:

    1. Directly via this argument.

    2. If the argument starts with a dollar sign ($), it is treated as the name of an environment variable that points to a file containing the token. This is compatible with variables of type “File” in Gitlab CI/CD.

    3. A file called gitlab_artifacts_token in the $CREDENTIALS_DIRECTORY.

    4. The CI_JOB_TOKEN environment variable. This is intended for use in Gitlab pipelines, in order to avoid having to create explicit tokens. Note that your instance might be set up with restrictive default permissions for the job token.

  • project (str | int | None) – The path (e.g. group/subgroup/project) or numeric ID of the project to pull the artifacts from. Defaults to the $CI_PROJECT_ID environment variable, which Gitlab sets to the project currently executing a pipeline.

  • branch (str | None) – The branch to pull artifacts from. Defaults to the value of the CI_DEFAULT_BRANCH environment variable, or main if that is unset. Ignored if a numeric ID is given for job.

  • job (str | int | None) –

    Name of the job to pull artifacts from. May also be a numeric job ID. Defaults to “update_capella_diagram_cache”.

    If a job name was given, the Gitlab API is queried for the most recent successful job on the given branch that has attached artifacts. Note that jobs whose artifacts have been deleted (for example, because their retention period expired) are ignored.

    By default, at most 1000 jobs will be checked. This includes all successful jobs in the repo, regardless of their name or the branch they ran on. This number can be changed using the CAPELLAMBSE_GLART_MAX_JOBS environment variable.

  • subdir (str | PurePosixPath) – An optional path prefix inside the artifacts archive to prepend to all file names.

  • disable_cache (bool) – Clear the local cache and discard any previously cached data.

See also

capellambse.filehandler.http.HTTPFileHandler

A general-purpose HTTP file handler.

__init__(path, *, subdir='/', token=None, project=None, branch=None, job=None, disable_cache=False)
Parameters:
Return type:

None

open(filename, mode='rb')

Open the model file for reading or writing.

A “file” in this context does not necessarily refer to a physical file on disk; it may just as well be streamed in via network or other means. Due to this, the file-like returned by this method is not required to support random access.

Parameters:
  • filename (str | PurePosixPath) – The name of the file, relative to the path that was given to the constructor.

  • mode (Literal['r', 'rb', 'w', 'wb']) – The mode to open the file in. Either "r" or "rb" for reading, or "w" or "wb" for writing a new file. Be aware that this method may refuse to open a file for writing unless a transaction was started with write_transaction() first.

Return type:

BinaryIO

capellambse.filehandler.http module

class capellambse.filehandler.http.DownloadStream

Bases: BinaryIO

__init__(session, url, chunk_size=1048576)
Parameters:
Return type:

None

close()
Return type:

None

read(n=-1)
Return type:

bytes

Parameters:

n (int)

readable()
Return type:

bool

writable()
Return type:

bool

write(s)
Return type:

int

Parameters:

s (bytes | bytearray)

class capellambse.filehandler.http.HTTPFileHandler

Bases: FileHandler

A remote file handler that fetches files using HTTP GET.

__init__(path, username=None, password=None, *, headers=None, subdir='/')

Connect to a remote server through HTTP or HTTPS.

This file handler supports two ways of specifying a URL:

  1. If a plain URL is passed, the requested file name is appended after a forward slash /.

  2. The URL may contain one or more of the following escape sequences to provide more fine-grained control over how and where the file name is inserted into the URL:

    • %s: The path to the file, with everything except forward slashes percent-escaped

    • %q: The path to the file, with forward slashes percent escaped as well

    • %d: The directory name, without trailing slash, like %s

    • %n: The file name without extension

    • %e: The file extension without leading dot

    • %%: A literal percent sign

Examples: When requesting the file name demo/my model.aird, …

  • https://example.com/~user as path results in the URL https://example.com/~user/demo/my%20model.aird

  • https://example.com/~user/%s results in https://example.com/~user/demo/my%20model.aird

  • https://example.com/?file=%q results in https://example.com/?file=demo%2Fmy%20model.aird

Note that the file name that is inserted into the URL will never start with a forward slash. This means that a URL like https://example.com%s will not work; you need to hard-code the slash at the appropriate place.

This also applies to the %q escape. If the server expects the file name argument to start with a slash, hard-code a percent-escaped slash in the URL. For example, instead of ...?file=%q use ...?file=%2F%q.

Parameters:
  • path (str | PathLike) – The base URL to fetch files from. Must start with http:// or https://. See above for how to specify complex URLs.

  • username (str | None) – The username for HTTP Basic Auth.

  • password (str | None) – The password for HTTP Basic Auth.

  • headers (Mapping[str, str] | None) – Additional HTTP headers to send to the server.

  • subdir (str | PurePosixPath) – Prepend this path to all requested files. It is subject to the same file name escaping rules explained above.

Return type:

None

iterdir(path='.', /)

Iterate over the contents of a directory.

This method is equivalent to calling fh.rootdir.joinpath(path).iterdir().

Parameters:

path (str | PurePosixPath) – The directory to list. If not given, lists the contents of the root directory (i.e. the one specified by path and subdir).

Return type:

Iterator[FilePath[Self]]

open(filename, mode='rb')

Open the model file for reading or writing.

A “file” in this context does not necessarily refer to a physical file on disk; it may just as well be streamed in via network or other means. Due to this, the file-like returned by this method is not required to support random access.

Parameters:
  • filename (str | PurePosixPath) – The name of the file, relative to the path that was given to the constructor.

  • mode (Literal['r', 'rb', 'w', 'wb']) – The mode to open the file in. Either "r" or "rb" for reading, or "w" or "wb" for writing a new file. Be aware that this method may refuse to open a file for writing unless a transaction was started with write_transaction() first.

Return type:

BinaryIO

write_transaction(**kw)

Start a transaction for writing new model files.

During a transaction, writable objects returned by open() buffer their contents in a temporary location, and once the transaction ends, all updated files are committed to their destinations at once. If the transaction is aborted, for example because an exception was raised, then all changes must be rolled back to the state immediately before the transaction. If, during a transaction, any relevant file is touched without the file handler knowing about it, the behavior is undefined.

Note that open() may refuse to open a file as writable if no transaction is currently open. This depends on the needs of the underlying abstract file system.

Return type:

NoReturn

Parameters:

kw (Any)

Transaction arguments

A concrete file handler implementation may accept arbitrary additional arguments to this method. The implementation should however always support the case of no arguments given, in which case it should start a transaction with sensible defaults, and it should also accept and ignore any arguments it does not understand. All additional arguments must be passed in via keywords. Positional arguments are not supported.

The return value of the context manager’s __enter__() method is expected to be a mapping of all the keyword arguments that were not understood. Client code may use this to react properly (e.g. by aborting the transaction early) if a required keyword argument is found to be not supported by the underlying file handler. If a subclass wishes to call its super class’ write_transaction() method, it should remove all the keyword arguments that it handles itself and pass on the others unchanged.

Well-known arguments

The following arguments are considered well-known, and their meaning is expected to be the same for all file handlers that support them.

  • dry_run (bool): If set to True, changes made during the transaction should be rolled back instead of being committed, just as if an exception had been raised.

  • author_name (str): The name of the author of the changes.

  • author_email (str): The e-mail address to record alongside the author_name.

  • commit_msg (str): A message describing the changes, which will be recorded in the version control system.

  • remote_branch (str): If the model came from a remote version control system, changes are normally pushed back to the same branch on that remote. This argument specifies an alternative branch name to push to (which may not yet exist on the remote).

capellambse.filehandler.local module

class capellambse.filehandler.local.LocalFileHandler

Bases: FileHandler

__init__(path, *, subdir='/')
Parameters:
Return type:

None

iterdir(subdir='.')

Iterate over the contents of a directory.

This method is equivalent to calling fh.rootdir.joinpath(path).iterdir().

Parameters:
  • path – The directory to list. If not given, lists the contents of the root directory (i.e. the one specified by path and subdir).

  • subdir (str | PurePosixPath)

Return type:

Iterator[LocalFilePath]

open(filename, mode='rb')

Open the model file for reading or writing.

A “file” in this context does not necessarily refer to a physical file on disk; it may just as well be streamed in via network or other means. Due to this, the file-like returned by this method is not required to support random access.

Parameters:
  • filename (str | PurePosixPath) – The name of the file, relative to the path that was given to the constructor.

  • mode (Literal['r', 'rb', 'w', 'wb']) – The mode to open the file in. Either "r" or "rb" for reading, or "w" or "wb" for writing a new file. Be aware that this method may refuse to open a file for writing unless a transaction was started with write_transaction() first.

Return type:

BinaryIO

property rootdir: LocalFilePath

The root directory of the file handler.

write_transaction(*, dry_run=False, **kw)

Start a write transaction.

During the transaction, file writes are redirected to temporary files next to the target files, and if the transaction ends successfully they are moved to their destinations all at once.

Parameters:
  • dry_run (bool) – Discard the temporary files after a successful transaction instead of committing them to their destinations.

  • **kw (Any) – Additional arguments are ignored.

Return type:

Generator[Mapping[str, Any], None, None]

class capellambse.filehandler.local.LocalFilePath

Bases: FilePath[LocalFileHandler]

is_dir()

Return True if self is a directory

Return type:

bool

is_file()

Return True if self is a file

Return type:

bool

capellambse.filehandler.memory module

class capellambse.filehandler.memory.MemoryFile

Bases: BinaryIO

__init__(data, mode)
Parameters:
Return type:

None

read(n=-1)
Return type:

bytes

Parameters:

n (int)

write(s)
Return type:

int

Parameters:

s (bytes | bytearray)

class capellambse.filehandler.memory.MemoryFileHandler

Bases: FileHandler

A file handler that stores data in memory.

__init__(path='memory:', *, subdir='/')

Initialize a new memory file handler.

Parameters:
  • path (str | PathLike) – An optional path to a directory to use as fallback. Opened files’ contents will be prepopulated with the contents of files from this directory.

  • subdir (str | PurePosixPath) – An optional path to prepend to all opened (physical) files.

Return type:

None

iterdir(path='/', /)

Iterate over the contents of a directory.

This method is equivalent to calling fh.rootdir.joinpath(path).iterdir().

Parameters:

path (str | PurePosixPath) – The directory to list. If not given, lists the contents of the root directory (i.e. the one specified by path and subdir).

Return type:

Iterator[MemoryFilePath]

open(filename, mode='rb')

Open the model file for reading or writing.

A “file” in this context does not necessarily refer to a physical file on disk; it may just as well be streamed in via network or other means. Due to this, the file-like returned by this method is not required to support random access.

Parameters:
  • filename (str | PurePosixPath) – The name of the file, relative to the path that was given to the constructor.

  • mode (Literal['r', 'rb', 'w', 'wb']) – The mode to open the file in. Either "r" or "rb" for reading, or "w" or "wb" for writing a new file. Be aware that this method may refuse to open a file for writing unless a transaction was started with write_transaction() first.

Return type:

BinaryIO

property rootdir: MemoryFilePath

The root directory of the file handler.

class capellambse.filehandler.memory.MemoryFilePath

Bases: FilePath[MemoryFileHandler]

is_dir()

Return True if self is a directory

Return type:

bool

is_file()

Return True if self is a file

Return type:

bool

capellambse.filehandler.zip module

class capellambse.filehandler.zip.ZipFileHandler

Bases: FileHandler

File handler that can read from zip files.

Parameters:
  • path (str | PathLike) –

    Location of the zip file. May contain a nested path, like zip+https://host.name/%s, which will be resolved using an appropriate file handler.

    If zipname is not passed or is None, the path may include the zip file name as well, using either ! or / as separator. For example, the following calls are equivalent:

    ZipFileHandler("zip+https://host.name/path/to/file.zip")
    ZipFileHandler("zip+https://host.name/path/to!file.zip")
    ZipFileHandler("zip+https://host.name/path/to/%s!file.zip")
    

    Note

    The %s replacement shown in this example is done by the underlying HTTPFileHandler, which is used to fetch the nested https:// URL. Other nested protocols may require different syntax.)

    Note

    It is currently not possible to pass down arbitrary arguments to the underlying FileHandler other than the path.

  • zipname (str | PurePosixPath | None) – Name of the zip file in the above path.

  • subdir (str | PurePosixPath | None) –

    A subdirectory inside the zip file to use as base directory.

    If the zip file contains only a single directory entry and no other files at the root, this directory is used as default. Pass subdir="." explicitly to override this behaviour.

__init__(path, zipname=None, subdir=None)
Parameters:
Return type:

None

is_dir(path, /)
Return type:

bool

Parameters:

path (str | PurePosixPath)

is_file(path, /)
Return type:

bool

Parameters:

path (str | PurePosixPath)

iterdir(path='.', /)

Iterate over the contents of a directory.

This method is equivalent to calling fh.rootdir.joinpath(path).iterdir().

Parameters:

path (str | PurePosixPath) – The directory to list. If not given, lists the contents of the root directory (i.e. the one specified by path and subdir).

Return type:

Iterator[FilePath[ZipFileHandler]]

open(filename, mode='rb')

Open the model file for reading or writing.

A “file” in this context does not necessarily refer to a physical file on disk; it may just as well be streamed in via network or other means. Due to this, the file-like returned by this method is not required to support random access.

Parameters:
  • filename (str | PurePosixPath) – The name of the file, relative to the path that was given to the constructor.

  • mode (Literal['r', 'rb', 'w', 'wb']) – The mode to open the file in. Either "r" or "rb" for reading, or "w" or "wb" for writing a new file. Be aware that this method may refuse to open a file for writing unless a transaction was started with write_transaction() first.

Return type:

IO[bytes]

property rootdir: FilePath[ZipFileHandler]

The root directory of the file handler.