# -*- 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 Tuple
import os
import sys
import subprocess
import shutil
import tempfile
import stat
from Muscat.Helpers.IO.Which import Which
[docs]class TemporaryDirectory():
"""Class to generate and to destroy a temporary directory
"""
path: str = None
prefix: str = "Muscat_Test_Directory_"
createdOnRam = False
[docs] @classmethod
def GetTempPath(cls, onRam: bool = False) -> str:
"""Get and Create (if needed) a temporary directory
Parameters
----------
onRam : bool, optional, default False
if true an on ram directory is created (only on linux ), by default None, on disk
Returns
-------
str
Path to the temporary directory
"""
if cls.path is not None and (onRam == cls.createdOnRam):
return cls.path
if onRam and not sys.platform.startswith('linux'): # pragma: no cover
raise Exception("ERROR! can create a temporary directory on ran only on linux.")
if onRam: # only posix coverage
cls.path: str = tempfile.mkdtemp(prefix=cls.prefix, suffix="_safe_to_delete", dir="/dev/shm/") + os.sep
cls.createdOnRam = True
else:
cls.path = tempfile.mkdtemp(prefix=cls.prefix, suffix="_safe_to_delete") + os.sep
cls.createdOnRam = False
cls.__saveTempPath()
return cls.path
# we cant test this function, because the temp path will be delete
[docs] @classmethod
def DeleteTempPath(cls) -> None:
"""Delete the temporary directory and all its content
"""
if cls.path is not None:
shutil.rmtree(cls.path)
cls.path = None
[docs] @classmethod
def OpenTempFolder(cls) -> None: # pragma: no cover
"""Open a file explorer on the temporary directory
"""
if os.sys.platform == "win32":
subprocess.Popen(f'explorer "{cls.GetTempPath()}"')
elif os.platform == "darwin":
subprocess.Popen(f'open "{cls.GetTempPath()}"')
elif Which("nautilus"):
subprocess.Popen(['nautilus', cls.GetTempPath()])
[docs] @classmethod
def SetTempPath(cls, path: str) -> None:
"""Set the temporary path from the given path
Parameters
----------
path : str
temporary path to be created, no error is raised if the directory already exists.
"""
cls.path = os.path.abspath(path+os.sep) + os.sep
if not os.path.exists(cls.path):
os.makedirs(cls.path)
cls.__saveTempPath()
@classmethod
def __saveTempPath(cls) -> None:
"""Save the temporary path to the user home directory
This very useful in combination of a alias:
alias cdtmp='source ~/.MuscatToolsTempPath'
"""
home: str = os.path.expanduser("~")
with open(home + os.sep+".MuscatToolsTempPath", "w") as f:
f.write("cd " + cls.path.replace("\\", "/") + "\n")
os.chmod(home + os.sep+".MuscatToolsTempPath", stat.S_IWUSR | stat.S_IRUSR | stat.S_IXUSR)
[docs] @classmethod
def GetFullFilenameOnTempDirectory(cls, filename: str) -> str:
"""Return an absolute path to filename in the temporary directory
if pathname is an absolute path then this function return path
Parameters
----------
filename : str
relative (to the temp path) or absolute filename
Returns
-------
str
full filename (with path) in the temporary directory
"""
if os.path.isabs(filename):
return filename
else:
return os.path.abspath(cls.GetTempPath() + filename)
[docs]def CheckIntegrity(GUI:bool=False):
from Muscat.Helpers.IO.TemporaryDirectory import TemporaryDirectory
saveTempPath = TemporaryDirectory.path
try:
TemporaryDirectory.path = None
path = TemporaryDirectory.GetTempPath()
path2 = TemporaryDirectory.GetTempPath()
assert (path == path2)
TemporaryDirectory.DeleteTempPath()
TemporaryDirectory.SetTempPath(path)
TemporaryDirectory.DeleteTempPath()
path = TemporaryDirectory.GetTempPath(onRam=False)
path2 = TemporaryDirectory.GetTempPath(onRam=False)
assert (path == path2)
path = TemporaryDirectory.GetFullFilenameOnTempDirectory("toto")
path = TemporaryDirectory.GetFullFilenameOnTempDirectory("/toto")
TemporaryDirectory.path = None
if sys.platform.startswith("linux"): # only posix coverage
print(f"{TemporaryDirectory.GetTempPath(onRam=True)=}")
if GUI: # pragma no coverage
TemporaryDirectory.OpenTempFolder()
except: # pragma no coverage
TemporaryDirectory.path = saveTempPath
raise
return "ok"