pathops

pathlib-like interface for local and ops.Container filesystem paths.

The pathops charm library provides:

  • PathProtocol: defines the interface of methods common to both local and container paths. Use this to type annotate code designed to work on both Kubernetes and machine charms.

  • ContainerPath: the concrete implementation of the interface for remote paths in the workload container of Kubernetes charms. Operations are implemented using the Pebble file API.

  • LocalPath: the concrete implementation of the interface for local paths, which includes both machine charms and the charm container of Kubernetes charms.

  • Top-level helper functions such as ensure_contents, which operate on both container and local paths.

ContainerPath methods that interact with the remote filesystem will raise a PebbleConnectionError if the workload container isn’t reachable. Methods designed to work with both local and container paths may handle this error internally, or they may leave handling connection errors to the caller, documenting this if so.

class ContainerPath(*parts: str | os.PathLike[str], container: ops.Container)

Bases: object

Implementation of PathProtocol for Pebble-based workload containers.

The following examples are all equivalent:

container = self.unit.get_container('c')
ContainerPath('/foo', container=container)
ContainerPath('/', 'foo', container=container)
ContainerPath(pathlib.PurePath('/foo'), container=container)
ContainerPath(pathlib.PurePath('/'), 'foo', container=container)

str follows the pathlib convention and returns the string representation of the path. ContainerPath return the string representation of the path in the remote filesystem. The string representation is suitable for use with system calls (on the correct local or remote system) and Pebble layers.

Comparison methods compare by path. A ContainerPath is only comparable to another object if it is also a ContainerPath on the same ops.Container. If this is not the case, then equality is False and other comparisons are NotImplemented.

Parameters:
  • *parts – components of the path, like pathlib.Path constructor.

  • container – used to communicate with the workload container. Required. Must be provided as a keyword argument.

Raises:

RelativePathError – If instantiated with a relative path.

as_posix() str

Return the string representation of the path in the container.

__truediv__(key: str | os.PathLike[str]) Self

Return a new ContainerPath with the same container and the joined path.

The joined path is equivalent to str(self) / pathlib.PurePath(key).

Warning

__rtruediv__ is not supported, as ContainerPath only supports absolute paths. You likely wouldn’t want to provide an absolute path as the right-hand operand, because the absolute path would completely replace the left-hand path.

is_absolute() bool

Return whether the path is absolute (has a root), which is always the case.

Always True, since initialising a ContainerPath with a non-absolute path will result in a RelativePathError.

match(path_pattern: str) bool

Return whether this path matches the given pattern.

If the pattern is relative, matching is done from the right; otherwise, the entire path is matched. The recursive wildcard '**' is not supported by this method. Matching is always case-sensitive. Only the path is matched against, the container is not considered.

with_name(name: str) Self

Return a new ContainerPath, with the same container, but with the path name replaced.

The name is the last component of the path, including any suffixes.

container = self.unit.get_container('c')
path = ContainerPath('/', 'foo', 'bar.txt', container=container)
repr(path.with_name('baz.bin'))
# ContainerPath('/foo/baz.bin', container=<ops.Container 'c'>)"
with_suffix(suffix: str) Self

Return a new ContainerPath with the same container and the suffix changed.

Parameters:

suffix – Must start with a '.', unless it is an empty string, in which case any existing suffix will be removed entirely.

Returns:

A new instance of the same type, updated as follows. If it contains no '.', or ends with a '.', the suffix argument is appended to its name. Otherwise, the last '.' and any trailing content is replaced with the suffix argument.

joinpath(*other: str | os.PathLike[str]) Self

Return a new ContainerPath with the same container and the new args joined to its path.

Parameters:

other – Any number of str or os.PathLike objects. If zero are provided, an effective copy of this ContainerPath object is returned. *other is joined to this object’s path as with os.path.join. This means that if any member of other is an absolute path, all the previous components, including this object’s path, are dropped entirely.

Returns:

A new ContainerPath with the same ops.Container object, with its path updated with *other as follows. For each item in other, if it is a relative path, it is appended to the current path. If it is an absolute path, it replaces the current path.

Warning

ContainerPath is not os.PathLike. A ContainerPath instance is not a valid value for other, and will result in an error.

property parents: tuple[Self, ...]

A sequence of this path’s logical parents. Each parent is a ContainerPath.

property parent: Self

The logical parent of this path, as a ContainerPath.

property parts: tuple[str, ...]

A sequence of the components in the filesystem path. The components are strings.

property name: str

The final path component, or an empty string if this is the root path.

property suffix: str

The path name’s last suffix (if it has any) including the leading '.'.

If the path name doesn’t have a suffix, the result is an empty string.

property suffixes: list[str]

A list of the path name’s suffixes.

Each suffix includes the leading '.'.

If the path name doesn’t have any suffixes, the result is an empty list.

property stem: str

The path name, minus its last suffix.

Where name == stem + suffix

read_text(*, newline: str | None = None) str

Read a remote file as text and return the contents as a string.

Compared to pathlib.Path.read_text, this method drops the encoding and errors args. The encoding is assumed to be UTF-8, and any errors encountered will be raised.

Parameters:

newline – if None (default), all newlines ('\r\n', '\r', '\n') are replaced with '\n'. Otherwise the file contents are returned unmodified.

Returns:

The contents of the the path as a string.

Raises:
  • FileNotFoundError – if the parent directory does not exist.

  • IsADirectoryError – if the target is a directory.

  • PermissionError – if the Pebble user does not have permissions for the operation.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.

read_bytes() bytes

Read a remote file as bytes and return the contents.

Returns:

The contents of the the path as byes.

Raises:
  • FileNotFoundError – if the parent directory does not exist.

  • IsADirectoryError – if the target is a directory.

  • PermissionError – if the Pebble user does not have permissions for the operation.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.

iterdir() Generator[Self]

Yield ContainerPath objects corresponding to the directory’s contents.

There are no guarantees about the order of the children. The special entries '.' and '..' are not included.

NotADirectoryError is raised (if appropriate) when iterdir() is called. This follows the behaviour of pathlib.Path.iterdir in Python 3.13+. Previous versions deferred the error until the generator was consumed.

Raises:
  • FileNotFoundError – If this path does not exist.

  • NotADirectoryError – If this path is not a directory.

  • PermissionError – If the local or remote user does not have appropriate permissions.

  • PebbleConnectionError – If the remote container cannot be reached.

glob(pattern: str | os.PathLike[str]) Generator[Self]

Iterate over this directory and yield all paths matching the provided pattern.

For example, path.glob('*.txt'), path.glob('*/foo.txt').

Warning

Recursive matching using the '**' pattern is not supported.

Parameters:

pattern – The pattern must be relative, meaning it cannot begin with '/'. Matching is case-sensitive.

Returns:

A generator yielding ContainerPath objects, corresponding to those of its children which match the pattern. If this path is not a directory, there will be no matches.

Raises:
  • FileNotFoundError – If this path does not exist.

  • NotImplementedError – If pattern is an absolute path or it uses the '**' pattern.

  • PermissionError – If the remote user does not have appropriate permissions.

  • ValueError – If the pattern is invalid.

  • PebbleConnectionError – If the remote container cannot be reached.

owner() str

Return the user name of the file owner.

Raises:
  • FileNotFoundError – If the path does not exist.

  • PebbleConnectionError – If the remote container cannot be reached.

group() str

Return the group name of the file.

Raises:
  • FileNotFoundError – If the path does not exist.

  • PebbleConnectionError – If the remote container cannot be reached.

exists() bool

Whether this path exists.

Will follow symlinks to determine if the symlink target exists. This means that this method will return False for a broken symlink.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

is_dir() bool

Whether this path exists and is a directory.

Will follow symlinks to determine if the symlink target exists and is a directory.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

is_file() bool

Whether this path exists and is a regular file.

Will follow symlinks to determine if the symlink target exists and is a regular file.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

is_fifo() bool

Whether this path exists and is a named pipe (also called a FIFO).

Will follow symlinks to determine if the symlink target exists and is a named pipe.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

is_socket() bool

Whether this path exists and is a socket.

Will follow symlinks to determine if the symlink target exists and is a socket.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

write_bytes(
data: bytes | bytearray | memoryview,
*,
mode: int | None = None,
user: str | None = None,
group: str | None = None,
) int

Write the provided data to the corresponding path in the remote container.

Compared to pathlib.Path.write_bytes, this method adds mode, user and group args. These are forwarded to Pebble, which sets these on file creation.

Parameters:
  • data – The bytes to write. If data is a bytearray or memoryview, it will be converted to bytes in memory first.

  • mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, unless mode is None (default).

  • user – The name of the user to set for the file. If group isn’t provided, the user’s default group is used. If the file already exists, its user and group will be changed, unless user is None (default).

  • group – The name of the group to set for the directory. It is an error to provide group if user isn’t provided. If the file already exists, its group will be changed, unless user and group are None (default).

Returns: The number of bytes written.

Raises:
  • FileNotFoundError – if the parent directory does not exist.

  • LookupError – if the user or group is unknown, or a group is provided without a user.

  • NotADirectoryError – if the parent exists as a non-directory file.

  • PermissionError – if the Pebble user does not have permissions for the operation.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.

write_text(
data: str,
*,
mode: int | None = None,
user: str | None = None,
group: str | None = None,
) int

Write the provided string to the corresponding path in the remote container.

Compared to pathlib.Path.write_text, this method drops the encoding and errors args to simplify the API. The args mode, user and group are added, and are forwarded to Pebble, which sets these on file creation.

Parameters:
  • data – The string to write. Will be encoded to bytes in memory as UTF-8, raising any errors. Newlines are not modified on writing.

  • mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, unless mode is None (default).

  • user – The name of the user to set for the file. If group isn’t provided, the user’s default group is used. If the file already exists, its user and group will be changed, unless user is None (default).

  • group – The name of the group to set for the directory. It is an error to provide group if user isn’t provided. If the file already exists, its group will be changed, unless user and group are None (default).

Returns: The number of bytes written.

Raises:
  • FileNotFoundError – if the parent directory does not exist.

  • LookupError – if the user or group is unknown, or a group is provided without a user.

  • NotADirectoryError – if the parent exists as a non-directory file.

  • PermissionError – if the Pebble user does not have permissions for the operation.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.

mkdir(
mode: int = 493,
parents: bool = False,
exist_ok: bool = False,
*,
user: str | None = None,
group: str | None = None,
) None

Create a new directory at the corresponding path in the remote container.

Compared to pathlib.Path.mkdir, this method adds user and group args. These are used to set the ownership of the created directory. Any created parents will not have their ownership set.

Parameters:
  • mode – The permissions to set on the created directory. Any parents created will have their permissions set to the default value of 0o755 (drwxr-xr-x). The permissions are not changed if the directory already exists.

  • parents – Whether to create any missing parent directories as well. If False (default) and a parent directory does not exist, a FileNotFound error will be raised.

  • exist_ok – Whether to raise an error if the directory already exists. If False (default) and the directory already exists, a FileExistsError will be raised.

  • user – The name of the user to set for the directory. If group isn’t provided, the user’s default group is used. The user and group are not changed if the directory already exists.

  • group – The name of the group to set for the directory. It is an error to provide group if user isn’t provided. The user and group are not changed if the directory already exists.

Raises:
  • FileExistsError – if the directory already exists and exist_ok is False.

  • FileNotFoundError – if the parent directory does not exist and parents is False.

  • LookupError – if the user or group is unknown, or a group is provided without a user.

  • NotADirectoryError – if the parent exists as a non-directory file.

  • PermissionError – if the remote user does not have permissions for the operation.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.

with_segments(*pathsegments: str | os.PathLike[str]) Self

Construct a new ContainerPath (with the same container) from path-like objects.

You can think of this like a copy of the current ContainerPath, with its path replaced by pathlib.Path(*pathsegments).

This method is used internally by all ContainerPath methods that return new ContainerPath instances, including parent and parents. Therefore, subclasses can customise the behaviour of all such methods by overriding only this method. The same is true of pathlib.Path in Python 3.12+.

class LocalPath(*args, **kwargs)

Bases: PosixPath

pathlib.PosixPath subclass with extended file-creation method arguments.

Note

The write_bytes, write_text, and mkdir methods are extended with file permission and ownership arguments, for compatibility with PathProtocol.

Parameters:

*partsstr or os.PathLike. LocalPath takes no keyword arguments.

LocalPath(pathlib.Path('/foo'))
LocalPath('/', 'foo')
write_bytes(
data: Buffer,
*,
mode: int | None = None,
user: str | None = None,
group: str | None = None,
) int

Write the provided data to the corresponding local filesystem path.

Compared to pathlib.Path.write_bytes, this method adds mode, user and group args. These are used to set the permissions and ownership of the file.

Parameters:
  • data – The bytes to write, typically a bytes object, but may also be a bytearray or memoryview.

  • mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, using pathlib.PosixPath.chmod, unless mode is None (default).

  • user – The name of the user to set for the file using shutil.chown. Validated to be an existing user before writing. If the file already exists, its user and group will be changed, unless user is None (default).

  • group – The name of the group to set for the file using shutil.chown. Validated to be an existing group before writing. If the file already exists, its group will be changed, unless user and group are None (default).

Returns:

The number of bytes written.

Raises:
write_text(
data: str,
encoding: str | None = None,
errors: str | None = None,
newline: str | None = None,
*,
mode: int | None = None,
user: str | None = None,
group: str | None = None,
) int

Write the provided string to the corresponding local filesystem path.

Compared to pathlib.Path.write_bytes, this method adds mode, user and group args. These are used to set the permissions and ownership of the file.

Warning

ContainerPath and PathProtocol do not support the encoding, errors, and newline arguments of pathlib.Path.write_text. For ContainerPath compatible code, do not use these arguments. They are provided to allow LocalPath to be used as a drop-in replacement for pathlib.Path if needed.

Parameters:
  • data – The string to write. Newlines are not modified on writing.

  • encoding – The encoding to use when writing the data, defaults to ‘UTF-8’.

  • errors – ‘strict’ to raise any encoding errors, ‘ignore’ to ignore them. Defaults to ‘strict’.

  • newline – If None, '', or '\n', then ‘n’ will be written as is. This is the default behaviour. If newline is '\r' or '\r\n', then '\n' will be replaced with newline in memory before writing.

  • mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, using pathlib.PosixPath.chmod, unless mode is None (default).

  • user – The name of the user to set for the file using shutil.chown. Validated to be an existing user before writing. If the file already exists, its user and group will be changed, unless user is None (default).

  • group – The name of the group to set for the file using shutil.chown. Validated to be an existing group before writing. If the file already exists, its group will be changed, unless user and group are None (default).

Returns:

The number of bytes written.

Raises:
mkdir(
mode: int = 493,
parents: bool = False,
exist_ok: bool = False,
*,
user: str | None = None,
group: str | None = None,
) None

Create a new directory at the corresponding local filesystem path.

Compared to pathlib.Path.mkdir, this method adds user and group args. These are used to set the ownership of the created directory. Any created parents will not have their ownership set.

Parameters:
  • mode – The permissions to set on the created directory. Any parents created will have their permissions set to the default value of 0o755 (drwxr-xr-x). The permissions are not changed if the directory already exists.

  • parents – Whether to create any missing parent directories as well. If False (default) and a parent directory does not exist, a FileNotFound error will be raised.

  • exist_ok – Whether to raise an error if the directory already exists. If False (default) and the directory already exists, a FileExistsError will be raised.

  • user – The name of the user to set for the directory using shutil.chown. Validated to be an existing user before writing. The user and group are not changed if the directory already exists.

  • group – The name of the group to set for the directory using shutil.chown. Validated to be an existing group before writing. The user and group are not changed if the directory already exists.

Raises:
class PathProtocol(*args, **kwargs)

Bases: Protocol

The protocol implemented by ContainerPath and LocalPath.

Use this class in type annotations where either ContainerPath or LocalPath is acceptable. This will result in both correct type checking and useful autocompletions.

While using a union type will also give correct type checking results, it provides less useful autocompletions, as most editors will autocomplete methods and attributes that any of the union members have, rather than only those that all of the union members have.

str follows the pathlib convention and returns the string representation of the path. ContainerPath return the string representation of the path in the remote filesystem. The string representation is suitable for use with system calls (on the correct local or remote system) and Pebble layers.

Comparison methods compare by path. A ContainerPath is only comparable to another object if it is also a ContainerPath on the same ops.Container. If this is not the case, then equality is False and other comparisons are NotImplemented.

Protocol implementers are hashable.

__truediv__(key: str | os.PathLike[str]) Self

Return a new instance of the same type, with the other operand appended to its path.

Used as protocol_implementor / str_or_pathlike.

Note

__rtruediv__ is currently not part of this protocol, as ContainerPath objects only support absolute paths.

as_posix() str

Return the string representation of the path.

Exactly like pathlib.Path for local paths. Following this convention, remote filesystem paths such as ContainerPath return the string representation of the path in the remote filesystem. The string representation is suitable for use with system calls (on the correct local or remote system) and Pebble layers.

Identical to str, since we only support posix systems.

is_absolute() bool

Return whether the path is absolute (has a root).

Note

Currently always True for ContainerPath.

match(path_pattern: str) bool

Return whether this path matches the given pattern.

If the pattern is relative, matching is done from the right; otherwise, the entire path is matched. The recursive wildcard '**' is not supported by this method. Matching is always case-sensitive.

with_name(name: str) Self

Return a new instance of the same type, with the path name replaced.

The name is the last component of the path, including any suffixes.

with_suffix(suffix: str) Self

Return a new instance of the same type, with the path suffix replaced.

Parameters:

suffix – Must start with a '.', unless it is an empty string, in which case any existing suffix will be removed entirely.

Returns:

A new instance of the same type, updated as follows. If it contains no '.', or ends with a '.', the suffix argument is appended to its name. Otherwise, the last '.' and any trailing content is replaced with the suffix argument.

joinpath(*other: str | os.PathLike[str]) Self

Return a new instance of the same type, with its path joined with the arguments.

Parameters:

other – Any number of str or os.PathLike objects.

Returns:

A new instance of the same type, updated as follows. For each item in other, if it is a relative path, it is appended to the current path. If it is an absolute path, it replaces the current path.

Warning

ContainerPath is not os.PathLike. A ContainerPath instance is not a valid value for other, and will result in an error.

property parents: Sequence[Self]

A sequence of this path’s logical parents. Each parent is an instance of this type.

property parent: Self

The logical parent of this path. An instance of this type.

property parts: tuple[str, ...]

A sequence of the components in the filesystem path.

property name: str

The final path component, or an empty string if this is the root path.

property suffix: str

The path name’s last suffix (if it has any) including the leading '.'.

If the path name doesn’t have a suffix, the result is an empty string.

property suffixes: list[str]

A list of the path name’s suffixes.

Each suffix includes the leading '.'.

If the path name doesn’t have any suffixes, the result is an empty list.

property stem: str

The path name, minus its last suffix.

Where name == stem + suffix

read_text() str

Read the corresponding local or remote filesystem path and return the string contents.

Compared to pathlib.Path.read_text, this method drops the encoding and errors args to simplify the API.

Returns:

The UTF-8 decoded contents of the file as a str.

Raises:
  • FileNotFoundError – If this path does not exist.

  • PermissionError – If the local or remote user does not have read permissions.

  • UnicodeError – If the file’s contents are not valid UTF-8.

  • PebbleConnectionError – If the remote container cannot be reached.

read_bytes() bytes

Read the corresponding local or remote filesystem path and return the binary contents.

Returns:

The file’s raw contents as bytes.

Raises:
  • FileNotFoundError – If this path does not exist.

  • PermissionError – If the local or remote user does not have read permissions.

  • PebbleConnectionError – If the remote container cannot be reached.

iterdir() Generator[Self]

Yield objects of the same type corresponding to the directory’s contents.

There are no guarantees about the order of the children. The special entries '.' and '..' are not included.

Raises:
  • FileNotFoundError – If this path does not exist.

  • NotADirectoryError – If this path is not a directory.

  • PermissionError – If the local or remote user does not have appropriate permissions.

  • PebbleConnectionError – If the remote container cannot be reached.

glob(pattern: str) Generator[Self]

Iterate over this directory and yield all paths matching the provided pattern.

For example, path.glob('*.txt'), path.glob('*/foo.txt').

Warning

Recursive matching, using the '**' pattern, is not supported by ContainerPath.glob.

Parameters:

pattern – Must be relative, meaning it cannot begin with '/'. Matching is case-sensitive.

Returns:

A generator yielding objects of the same type as this path, corresponding to those of its children which match the pattern. If this path is not a directory, there will be no matches.

Raises:
owner() str

Return the user name of the file owner.

Raises:
  • FileNotFoundError – If the path does not exist.

  • PebbleConnectionError – If the remote container cannot be reached.

group() str

Return the group name of the file.

Raises:
  • FileNotFoundError – If the path does not exist.

  • PebbleConnectionError – If the remote container cannot be reached.

exists() bool

Whether this path exists.

Will follow symlinks to determine if the symlink target exists. This means that this method will return False for a broken symlink.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

is_dir() bool

Whether this path exists and is a directory.

Will follow symlinks to determine if the symlink target exists and is a directory.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

is_file() bool

Whether this path exists and is a regular file.

Will follow symlinks to determine if the symlink target exists and is a regular file.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

is_fifo() bool

Whether this path exists and is a named pipe (also called a FIFO).

Will follow symlinks to determine if the symlink target exists and is a named pipe.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

is_socket() bool

Whether this path exists and is a socket.

Will follow symlinks to determine if the symlink target exists and is a socket.

Raises:

PebbleConnectionError – If the remote container cannot be reached.

write_bytes(
data: bytes,
*,
mode: int | None = None,
user: str | None = None,
group: str | None = None,
) int

Write the provided data to the corresponding path.

Compared to pathlib.Path.write_bytes, this method adds mode, user and group args, which are set on file creation.

Parameters:
  • data – The bytes to write, typically a bytes object, but may also be a bytearray or memoryview.

  • mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, unless mode is None (default).

  • user – The name of the user to set for the directory. If group isn’t provided, the user’s default group is used. If the file already exists, its user and group will be changed, unless user is None (default).

  • group – The name of the group to set for the directory. For ContainerPath, it is an error to provide group if user isn’t provided. If the file already exists, its group will be changed, unless user and group are None (default).

Returns:

The number of bytes written.

Raises:
  • FileNotFoundError – if the parent directory does not exist.

  • LookupError – if the user or group is unknown, or a group is provided without a user.

  • NotADirectoryError – if the parent exists as a non-directory file.

  • PermissionError – if the user does not have permissions for the operation.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.

write_text(
data: str,
*,
mode: int | None = None,
user: str | None = None,
group: str | None = None,
) int

Write the provided string to the corresponding path.

Compared to pathlib.Path.write_text, this method drops the encoding and errors args to simplify the API. This method adds mode, user and group args, which are set on file creation.

Parameters:
  • data – The string to write. Newlines are not modified on writing.

  • mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, unless mode is None (default).

  • user – The name of the user to set for the directory. If group isn’t provided, the user’s default group is used. If the file already exists, its user and group will be changed, unless user is None (default).

  • group – The name of the group to set for the directory. For ContainerPath, it is an error to provide group if user isn’t provided. If the file already exists, its group will be changed, unless user and group are None (default).

Returns:

The number of bytes written.

Raises:
  • FileNotFoundError – if the parent directory does not exist.

  • LookupError – if the user or group is unknown, or a group is provided without a user.

  • NotADirectoryError – if the parent exists as a non-directory file.

  • PermissionError – if the user does not have permissions for the operation.

  • UnicodeError – if the provided data is not valid UTF-8.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.

mkdir(
mode: int = 493,
parents: bool = False,
exist_ok: bool = False,
*,
user: str | None = None,
group: str | None = None,
) None

Create a new directory at the corresponding path.

Compared to pathlib.Path.mkdir, this method adds user and group args. These are used to set the ownership of the created directory. Any created parents will not have their ownership set.

Parameters:
  • mode – The permissions to set on the created directory. Any parents created will have their permissions set to the default value of 0o755 (drwxr-xr-x). The permissions are not changed if the directory already exists.

  • parents – Whether to create any missing parent directories as well. If False (default) and a parent directory does not exist, a FileNotFound error will be raised.

  • exist_ok – Whether to raise an error if the directory already exists. If False (default) and the directory already exists, a FileExistsError will be raised.

  • user – The name of the user to set for the directory. If group isn’t provided, the user’s default group is used. The user and group are not changed if the directory already exists.

  • group – The name of the group to set for the directory. For ContainerPath, it is an error to provide group if user isn’t provided. The user and group are not changed if the directory already exists.

Raises:
  • FileExistsError – if the directory already exists and exist_ok is False.

  • FileNotFoundError – if the parent directory does not exist and parents is False.

  • LookupError – if the user or group is unknown, or a group is provided without a user.

  • NotADirectoryError – if the parent exists as a non-directory file.

  • PermissionError – if the local user does not have permissions for the operation.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.

PebbleConnectionError

alias of ConnectionError

exception RelativePathError

Bases: ValueError

ContainerPath only supports absolute paths.

This is because Pebble only works with absolute paths. Relative path support will likely remain unavailable at least until Pebble supports relative paths. In the meantime, use absolute paths.

ensure_contents(
path: str | os.PathLike[str] | PathProtocol,
source: bytes | str | BinaryIO | TextIO,
*,
mode: int = 420,
user: str | None = None,
group: str | None = None,
) bool

Ensure source can be read from path. Return True if any changes were made.

Ensure that path exists, contains source, has the correct permissions (mode), and has the correct file ownership (user and group).

Parameters:
  • path – A local or remote filesystem path.

  • source – The desired contents in str or bytes form, or an object with a .read() method which returns a str or bytes object.

  • mode – The desired file permissions.

  • user – The desired file owner, or None to not change the owner.

  • group – The desired group, or None to not change the group.

Returns:

True if any changes were made, including permissions or ownership, otherwise False.

Raises:
  • LookupError – if the user or group is unknown.

  • NotADirectoryError – if the parent exists as a non-directory file.

  • PermissionError – if the user does not have permissions for the operation.

  • PebbleConnectionError – if the remote Pebble client cannot be reached.