Source code for Muscat.Helpers.IO.PathController

# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
#

from typing import Optional, Type
from types import TracebackType
import os


from Muscat.Helpers.IO.TemporaryDirectory import TemporaryDirectory


[docs] class TemporalChdir(): """ class to change directory for a local context. This function use os.chdir to change the current path. The user is responsible of ensuring the path exists and il has the correct permissions At exit the install will restore the path at the creation of the instance. with TemporalChdir("c:/my/local/working/path") : #do something """ def __init__(self, targetPath: str) -> None: super().__init__() self.originalPath = os.getcwd()+os.sep self.targetPath = targetPath def __enter__(self) -> None: """Context manager enter function """ os.chdir(self.targetPath) def __exit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[TracebackType]) -> None: """Context manager exit function Parameters ---------- exc_type : Optional[Type[BaseException]] _description_ exc : Optional[BaseException] _description_ traceback : Optional[TracebackType] _description_ """ os.chdir(self.originalPath)
[docs] class PathController(): """ Class to do operation on path and filename. The idea is to store 2 path (for an application). This are class attributes (not instance attributes). the currentDirectory, defined initially with value of os.getcwd()+os.sep. intended to store the path from where the user execute the application the workingDirectory, defined initially with value of os.getcwd()+os.sep. intended to store the path of the treated file, The user can set the currentDirectory with SetCurrentDirectory or SetCurrentDirectoryUsingFile The user can set the workingDirectory with SetWorkingDirectory or SetWorkingDirectoryUsingFile Then different function are available to recover path, and full path filename on current/working directories. .. note:: This class DOES NOT change the working directory of python( value returned by os.getcwd()), this class is intender only for path manipulation. """ currentDirectory: str = os.getcwd()+os.sep workingDirectory: str = os.getcwd()+os.sep
[docs] @staticmethod def SetCurrentDirectory(folder: str) -> None: """Set the current directory using a path. Parameters ---------- folder : str path to a folder """ PathController.currentDirectory = os.path.abspath(os.path.expanduser(folder))+os.sep
[docs] @staticmethod def SetCurrentDirectoryUsingFile(folder: str) -> None: """set the current directory using a file os.path Parameters ---------- folder : str path to a file """ PathController.currentDirectory = os.path.dirname(os.path.abspath(os.path.expanduser(folder)))+os.sep
[docs] @staticmethod def SetWorkingDirectory(folder: str) -> None: """Set the working directory using a path. Parameters ---------- folder : str path to a folder """ PathController.workingDirectory = os.path.abspath(os.path.expanduser(folder))+os.sep
[docs] @staticmethod def SetWorkingDirectoryUsingFile(file) -> None: """set the working directory using a file path Parameters ---------- folder : str path to a file """ PathController.workingDirectory = os.path.abspath(os.path.dirname(os.path.expanduser(file)))+os.sep
[docs] @staticmethod def GetCurrentDirectory() -> str: """Return the current directory""" return PathController.currentDirectory
[docs] @staticmethod def GetWorkingDirectory() -> str: """Return the working directory""" return PathController.workingDirectory
[docs] @staticmethod def GetFullFilenameCurrentDirectory(filename: str) -> str: """Return a absolution path of a filename in the currentDirectory Parameters ---------- filename : str Path to a file relative to Current Directory Returns ------- str the absolute path of filename """ if os.path.isabs(filename): return filename else: return os.path.abspath(PathController.currentDirectory + filename)
[docs] @staticmethod def GetFullFilenameWorkingDirectory(filename: str) -> str: """Return a absolution path of a filename in the workingDirectory Parameters ---------- filename : str Path to a file relative to Working Directory Returns ------- str the absolute path of filename """ if os.path.isabs(filename): return filename else: return os.path.abspath(PathController.workingDirectory + filename)
[docs] @staticmethod def GetFullPathCurrentDirectoryUsingFile(filename: str) -> str: """Return the absolute path of a filename relative to the current directory If current directory is "/my/current/directory", and filename is "./test1/output.toto" then: GetFullPathInCurrentDirectoryUsingFile(filename) -> "/my/current/directory/test1" if filename is an absolute path then this function return path Parameters ---------- filename : str filename with a relative or absolute path Returns ------- str an absolute path """ file = PathController.GetFullFilenameCurrentDirectory(filename) return os.path.abspath(os.path.dirname(os.path.expanduser(file)))+os.sep
[docs] @staticmethod def GetFullPathWorkingDirectory(pathname: str) -> str: """Return the absolute path of a path relative to the working directory if pathname is an absolute path then this function return path Parameters ---------- pathname : str relative (to working directory) or absolute path Returns ------- str an absolute path """ if os.path.isabs(pathname): return pathname else: return os.path.abspath(PathController.workingDirectory + pathname)+os.sep
[docs] def CheckIntegrity(GUI:bool=False): print("C: " + PathController.currentDirectory) print("W: " + PathController.workingDirectory) PathController.SetCurrentDirectoryUsingFile(PathController.currentDirectory+"toto.dox") PathController.SetWorkingDirectoryUsingFile(PathController.workingDirectory+"toto.dox") print("C: " + PathController.GetFullFilenameCurrentDirectory("tata")) print("W: " + PathController.GetFullFilenameWorkingDirectory("toto")) print("*************") PathController.SetCurrentDirectory("~") PathController.SetWorkingDirectory("/tmp") print("C: " + PathController.GetFullFilenameCurrentDirectory("tata")) print("C: " + PathController.GetFullFilenameCurrentDirectory("/tata")) print("W: " + PathController.GetFullFilenameWorkingDirectory("toto")) print("W: " + PathController.GetFullFilenameWorkingDirectory("/toto")) print("*************") print("W: " + PathController.GetFullPathCurrentDirectoryUsingFile("tata")) print("W: " + PathController.GetFullPathWorkingDirectory(".")) print("W: " + PathController.GetFullPathWorkingDirectory("/.")) PathController.SetCurrentDirectory("..") PathController.SetWorkingDirectory("/tmp/") print("C: " + PathController.GetFullFilenameCurrentDirectory("tata")) print("W: " + PathController.GetFullFilenameWorkingDirectory("../toto")) print(PathController.GetCurrentDirectory()) print(PathController.GetWorkingDirectory()) with TemporalChdir(".."): print("hello") return ("ok")
if __name__ == '__main__': print(CheckIntegrity(False)) # pragma: no cover