diff --git a/src/caosadvancedtools/utils.py b/src/caosadvancedtools/utils.py index 4e85c9dffedbf1076f8406777ed51d6c7313dda5..2d273edcef195369122fcb9c440da5d10f6f331b 100644 --- a/src/caosadvancedtools/utils.py +++ b/src/caosadvancedtools/utils.py @@ -24,9 +24,12 @@ import logging import os +import pathlib import caosdb as db +logger = logging.getLogger(__name__) + def set_log_level(level): logger = logging.getLogger(__name__) @@ -110,6 +113,50 @@ def assure_absolute_path_in_glob(glob, prefix): return glob +def check_win_path(path, filename=None): + """ + check whether '/' are in the path but no '\'. + + If that is the case, it is likely, that the path is not a Windows path. + + Parameters: + path: path to be checked + filename: if the path is located in a file, this parameter can be used to + direct the user to the file where the path is located. + """ + + if r"\\" not in path and "/" in path: + if filename: + msg = "In file\n{}\nthe ".format(filename) + else: + msg = "The " + msg += ("path\n{}\ndoes not look like " + "a Windows path.".format(path)) + logger.warning(msg, extra={'identifier': str(path), + 'category': "inconsistency"}) + + return False + + return True + + +def treat_win_path(path, relative_to, filename=None): + """ + check win path and convert it to posix and make it absolute. + Parameters: + path: windows path as string + relative_to: unix path as string + filename: if the path is located in a file, this parameter can be used to + direct the user to the file where the path is located. + """ + check_win_path(path, filename=filename) + path = pathlib.PureWindowsPath(path) + path = path.as_posix() + path = assure_absolute_path_in_glob(str(path), prefix=relative_to) + + return path + + def return_field_or_property(value, prop=None): """ returns value itself of a property. diff --git a/unittests/test_utils.py b/unittests/test_utils.py index 24082d47dd574d16a5432b7138a8b89d67654c5b..46ca537e2d5ff63f3f0a40943066dc5c03f864b9 100644 --- a/unittests/test_utils.py +++ b/unittests/test_utils.py @@ -23,7 +23,8 @@ import unittest from caosadvancedtools.utils import (assure_absolute_path_in_glob, - string_to_person) + check_win_path, string_to_person, + treat_win_path) class Assure_absoluteTest(unittest.TestCase): @@ -55,3 +56,12 @@ class PersonParserTest(unittest.TestCase): assert is_dhornung(rec) rec = string_to_person("Henrik tom Wörden (MPI)") assert not is_dhornung(rec) + + +class PathTest(unittest.TestCase): + def test_win(self): + assert check_win_path(r"C:\hallo") + assert check_win_path(r"\hallo") + assert not check_win_path("/hallo") + self.assertEqual(treat_win_path(r"tag\hallo", "/lol"), + "/lol/tag/hallo")