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 thepathlib
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 aContainerPath
on the sameops.Container
. If this is not the case, then equality isFalse
and other comparisons areNotImplemented
.- 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.
- __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, asContainerPath
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 aContainerPath
with a non-absolute path will result in aRelativePathError
.
- 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'.'
, thesuffix
argument is appended to its name. Otherwise, the last'.'
and any trailing content is replaced with thesuffix
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
oros.PathLike
objects. If zero are provided, an effective copy of thisContainerPath
object is returned. *other is joined to this object’s path as withos.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 sameops.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 notos.PathLike
. AContainerPath
instance is not a valid value forother
, 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 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.
- 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) wheniterdir()
is called. This follows the behaviour ofpathlib.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,
Write the provided data to the corresponding path in the remote container.
Compared to
pathlib.Path.write_bytes
, this method addsmode
,user
andgroup
args. These are forwarded to Pebble, which sets these on file creation.- Parameters:
data – The bytes to write. If data is a
bytearray
ormemoryview
, it will be converted tobytes
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
isNone
(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, unlessuser
isNone
(default).group – The name of the group to set for the directory. It is an error to provide
group
ifuser
isn’t provided. If the file already exists, its group will be changed, unlessuser
andgroup
areNone
(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( ) int ¶
Write the provided string to the corresponding path in the remote container.
Compared to
pathlib.Path.write_text
, this method drops theencoding
anderrors
args to simplify the API. The argsmode
,user
andgroup
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
isNone
(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, unlessuser
isNone
(default).group – The name of the group to set for the directory. It is an error to provide
group
ifuser
isn’t provided. If the file already exists, its group will be changed, unlessuser
andgroup
areNone
(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,
Create a new directory at the corresponding path in the remote container.
Compared to
pathlib.Path.mkdir
, this method addsuser
andgroup
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, aFileNotFound
error will be raised.exist_ok – Whether to raise an error if the directory already exists. If
False
(default) and the directory already exists, aFileExistsError
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
ifuser
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
isFalse
.FileNotFoundError – if the parent directory does not exist and
parents
isFalse
.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 bypathlib.Path(*pathsegments)
.This method is used internally by all
ContainerPath
methods that return newContainerPath
instances, includingparent
andparents
. Therefore, subclasses can customise the behaviour of all such methods by overriding only this method. The same is true ofpathlib.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
, andmkdir
methods are extended with file permission and ownership arguments, for compatibility withPathProtocol
.- Parameters:
*parts –
str
oros.PathLike
.LocalPath
takes no keyword arguments.
LocalPath(pathlib.Path('/foo')) LocalPath('/', 'foo')
- write_bytes( ) int ¶
Write the provided data to the corresponding local filesystem path.
Compared to
pathlib.Path.write_bytes
, this method addsmode
,user
andgroup
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 abytearray
ormemoryview
.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
, unlessmode
isNone
(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, unlessuser
isNone
(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, unlessuser
andgroup
areNone
(default).
- Returns:
The number of bytes written.
- Raises:
FileNotFoundError – if the parent directory does not exist.
LookupError – if the user or group is unknown.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the local user does not have permissions for the operation.
- 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,
Write the provided string to the corresponding local filesystem path.
Compared to
pathlib.Path.write_bytes
, this method addsmode
,user
andgroup
args. These are used to set the permissions and ownership of the file.Warning
ContainerPath
andPathProtocol
do not support theencoding
,errors
, andnewline
arguments ofpathlib.Path.write_text
. ForContainerPath
compatible code, do not use these arguments. They are provided to allowLocalPath
to be used as a drop-in replacement forpathlib.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. Ifnewline
is'\r'
or'\r\n'
, then'\n'
will be replaced withnewline
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
, unlessmode
isNone
(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, unlessuser
isNone
(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, unlessuser
andgroup
areNone
(default).
- Returns:
The number of bytes written.
- Raises:
FileNotFoundError – if the parent directory does not exist.
LookupError – if the user or group is unknown.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the local user does not have permissions for the operation.
ValueError – if
newline
is any value other than those documented above.
- mkdir(
- mode: int = 493,
- parents: bool = False,
- exist_ok: bool = False,
- *,
- user: str | None = None,
- group: str | None = None,
Create a new directory at the corresponding local filesystem path.
Compared to
pathlib.Path.mkdir
, this method addsuser
andgroup
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, aFileNotFound
error will be raised.exist_ok – Whether to raise an error if the directory already exists. If
False
(default) and the directory already exists, aFileExistsError
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:
FileExistsError – if the directory already exists and
exist_ok
isFalse
.FileNotFoundError – if the parent directory does not exist and
parents
isFalse
.LookupError – if the user or group is unknown.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the local user does not have permissions for the operation.
- class PathProtocol(*args, **kwargs)¶
Bases:
Protocol
The protocol implemented by
ContainerPath
andLocalPath
.Use this class in type annotations where either
ContainerPath
orLocalPath
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 thepathlib
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 aContainerPath
on the sameops.Container
. If this is not the case, then equality isFalse
and other comparisons areNotImplemented
.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, asContainerPath
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 asContainerPath
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
forContainerPath
.
- 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'.'
, thesuffix
argument is appended to its name. Otherwise, the last'.'
and any trailing content is replaced with thesuffix
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
oros.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 notos.PathLike
. AContainerPath
instance is not a valid value forother
, 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 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.
- 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 theencoding
anderrors
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 byContainerPath.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:
FileNotFoundError – If this path does not exist.
NotImplementedError – If pattern is an absolute path, or (in the case of
ContainerPath
) if it uses the'**'
pattern.PermissionError – If the local or 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( ) int ¶
Write the provided data to the corresponding path.
Compared to
pathlib.Path.write_bytes
, this method addsmode
,user
andgroup
args, which are set on file creation.- Parameters:
data – The bytes to write, typically a
bytes
object, but may also be abytearray
ormemoryview
.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
isNone
(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, unlessuser
isNone
(default).group – The name of the group to set for the directory. For
ContainerPath
, it is an error to providegroup
ifuser
isn’t provided. If the file already exists, its group will be changed, unlessuser
andgroup
areNone
(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( ) int ¶
Write the provided string to the corresponding path.
Compared to
pathlib.Path.write_text
, this method drops theencoding
anderrors
args to simplify the API. This method addsmode
,user
andgroup
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
isNone
(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, unlessuser
isNone
(default).group – The name of the group to set for the directory. For
ContainerPath
, it is an error to providegroup
ifuser
isn’t provided. If the file already exists, its group will be changed, unlessuser
andgroup
areNone
(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,
Create a new directory at the corresponding path.
Compared to
pathlib.Path.mkdir
, this method addsuser
andgroup
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, aFileNotFound
error will be raised.exist_ok – Whether to raise an error if the directory already exists. If
False
(default) and the directory already exists, aFileExistsError
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 providegroup
ifuser
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
isFalse
.FileNotFoundError – if the parent directory does not exist and
parents
isFalse
.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,
Ensure
source
can be read frompath
. Return True if any changes were made.Ensure that
path
exists, containssource
, has the correct permissions (mode
), and has the correct file ownership (user
andgroup
).- Parameters:
path – A local or remote filesystem path.
source – The desired contents in
str
orbytes
form, or an object with a.read()
method which returns astr
orbytes
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, otherwiseFalse
.- 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.