From 6f58c23944dae4c15358aa671492f93e0572fa47 Mon Sep 17 00:00:00 2001 From: Helmut Grohne Date: Sun, 24 Mar 2024 08:23:18 +0100 Subject: AtLocation.mkdir: support optional arguments from pathlib --- linuxnamespaces/atlocation.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/linuxnamespaces/atlocation.py b/linuxnamespaces/atlocation.py index be9d17c..6b28ec3 100644 --- a/linuxnamespaces/atlocation.py +++ b/linuxnamespaces/atlocation.py @@ -341,14 +341,33 @@ class AtLocation: ), ) - def mkdir(self, mode: int = 0o777) -> None: - """Wrapper for os.mkdir supplying path and dir_fd.""" + def mkdir( + self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False + ) -> None: + """Wrapper for os.mkdir supplying path and dir_fd. It also supports + the parents and exist_ok arguments from pathlib.Path.mkdir. + """ if self.flags != AtFlags.NONE: raise NotImplementedError( "mkdir is not supported for an AtLocation with flags" ) assert self.location - os.mkdir(self.location, mode, dir_fd=self.fd_or_none) + try: + os.mkdir(self.location, mode, dir_fd=self.fd_or_none) + except FileNotFoundError: + if not parents: + raise + parentlocation = os.path.dirname(self.location) + if not parentlocation: + raise + AtLocation(self.fd, parentlocation, self.flags).mkdir( + parents=True, exist_ok=True + ) + self.mkdir(mode, False, exist_ok) + except OSError: + # Like pathlib, avoid checking EEXISTS as there may be more reasons + if not exist_ok or not self.is_dir(): + raise def mknod(self, mode: int = 0o600, device: int = 0) -> None: """Wrapper for os.mknod supplying path and dir_fd.""" -- cgit v1.2.3