Source code for tbot.machine.linux.path

# tbot, Embedded Automation Tool
# Copyright (C) 2019  Harald Seiler
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <>.

import os
import errno
import typing
import pathlib
from .. import linux  # noqa: F401

H = typing.TypeVar("H", bound="linux.LinuxShell")

[docs]class Path(pathlib.PurePosixPath, typing.Generic[H]): """ A path that is associated with a tbot machine. A path can only be used with its associated host. Using it with any other host will raise an exception and will be detected by a static typechecker. Apart from that, ``Path`` behaves like a :class:`pathlib.Path`:: from tbot.machine import linux p = linux.Path(mach, "/foo/bar") p2 = p / "bar" / "baz" if not p2.exists(): mach.exec0("mkdir", "-p", p2.parent) mach.exec0("touch", p2) elif not p2.is_file(): raise Exception(f"{p2} must be a normal file!") """ __slots__ = ("_host",) def __new__(cls, host: H, *args: typing.Any) -> "Path": """ Create a new path instance. :param linux.LinuxShell host: Host this path should be associated with :param args: :py:class:`pathlib.PurePosixPath` constructor arguments :rtype: Path :returns: A path associated with host """ return super().__new__(cls, *args) def __init__(self, host: H, *args: typing.Any) -> None: """ Create a new path. :param linux.LinuxShell host: Host this path should be associated with :param args: :py:class:`pathlib.PurePosixPath` constructor arguments """ self._host = host @property def host(self) -> H: """Host associated with this path.""" return self._host
[docs] def stat(self) -> os.stat_result: """ Return the result of ``stat`` on this path. Tries to imitate the results of :meth:`pathlib.Path.stat`, returns a :class:`os.stat_result`. """ ec, stat_str ="stat", "-t", self) if ec != 0: raise OSError(errno.ENOENT, f"Can't stat {self}") stat_res = stat_str[len(self._local_str()) + 1 :].split(" ") return os.stat_result( ( int(stat_res[2], 16), int(stat_res[6]), 0, int(stat_res[7]), int(stat_res[3]), int(stat_res[4]), int(stat_res[0]), int(stat_res[10]), int(stat_res[11]), int(stat_res[12]), ) )
[docs] def exists(self) -> bool: """Whether this path exists.""" return"test", "-e", self)
[docs] def is_dir(self) -> bool: """Whether this path points to a directory.""" return"test", "-d", self)
[docs] def is_file(self) -> bool: """Whether this path points to a normal file.""" return"test", "-f", self)
[docs] def is_block_device(self) -> bool: """Whether this path points to a block device.""" return"test", "-b", self)
[docs] def is_char_device(self) -> bool: """Whether this path points to a character device.""" return"test", "-c", self)
[docs] def is_fifo(self) -> bool: """Whether this path points to a pipe(fifo).""" return"test", "-p", self)
[docs] def is_socket(self) -> bool: """Whether this path points to a unix domain-socket.""" return"test", "-S", self)
@property def parent(self) -> "Path[H]": """Parent of this path.""" return Path(self._host, super().parent)
[docs] def glob(self, pattern: str) -> "typing.Iterator[Path[H]]": """ Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern. **Example**: .. code-block:: python ubootdir = lh.workdir / "u-boot" # .glob() returns a list which can be iterated. for f in ubootdir.glob("common/*.c"): tbot.log.message(f"Found {f}.") # To use the globs in another commandline (note the `*`!): lh.exec0("ls", "-l", *ubootdir.glob("common/*.c")) .. warning:: The glob pattern **must not contain spaces or other special characters**! """ fullpath = + "/" + pattern output ="printf", "%s\\n", linux.Raw(fullpath)) for line in output[:-1].split("\n"): yield Path(self._host, line)
def __truediv__(self, key: typing.Any) -> "Path[H]": return Path(self._host, super().__truediv__(key)) def _local_str(self) -> str: return super().__str__() def __str__(self) -> str: return f"{}:{super().__str__()}" def __repr__(self) -> str: return f"{self.__class__.__name__}({self._host!r}, {super().__str__()!r})" def __fspath__(self) -> str: raise NotImplementedError("__fspath__ does not exist for tbot paths!")