From f48a4315442c7507c134bd3b1117674209361d5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrg=20Billeter?= Date: Wed, 22 Apr 2020 09:34:07 +0200 Subject: directory.py: Add isfile(), isdir() and islink() methods --- src/buildstream/storage/directory.py | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'src/buildstream') diff --git a/src/buildstream/storage/directory.py b/src/buildstream/storage/directory.py index 5d85cbe46..3bd80dc3e 100644 --- a/src/buildstream/storage/directory.py +++ b/src/buildstream/storage/directory.py @@ -33,6 +33,7 @@ See also: :ref:`sandboxing`. import os +import stat from typing import Callable, Optional, Union, List from .._exceptions import BstError @@ -221,6 +222,54 @@ class Directory: """ raise NotImplementedError() + def isfile(self, *paths: str, follow_symlinks: bool = False) -> bool: + """ Check whether the specified path is an existing regular file. + + Args: + *paths: A list of strings which are all path components. + follow_symlinks: True to follow symlinks. + + Returns: + True if the path is an existing regular file, False otherwise. + """ + try: + st = self.stat(*paths, follow_symlinks=follow_symlinks) + return stat.S_ISREG(st.st_mode) + except (VirtualDirectoryError, FileNotFoundError): + return False + + def isdir(self, *paths: str, follow_symlinks: bool = False) -> bool: + """ Check whether the specified path is an existing directory. + + Args: + *paths: A list of strings which are all path components. + follow_symlinks: True to follow symlinks. + + Returns: + True if the path is an existing directory, False otherwise. + """ + try: + st = self.stat(*paths, follow_symlinks=follow_symlinks) + return stat.S_ISDIR(st.st_mode) + except (VirtualDirectoryError, FileNotFoundError): + return False + + def islink(self, *paths: str, follow_symlinks: bool = False) -> bool: + """ Check whether the specified path is an existing symlink. + + Args: + *paths: A list of strings which are all path components. + follow_symlinks: True to follow symlinks. + + Returns: + True if the path is an existing symlink, False otherwise. + """ + try: + st = self.stat(*paths, follow_symlinks=follow_symlinks) + return stat.S_ISLNK(st.st_mode) + except (VirtualDirectoryError, FileNotFoundError): + return False + def open_file(self, *paths: str, mode: str = "r"): """ Open file and return a corresponding file object. In text mode, UTF-8 is used as encoding. -- cgit v1.2.1