diff --git a/salt/utils/__init__.py b/salt/utils/__init__.py index ec018f1ad7..04fcf017e5 100644 --- a/salt/utils/__init__.py +++ b/salt/utils/__init__.py @@ -163,6 +163,37 @@ def is_empty(filename): return False +def safe_filename_leaf(file_basename): + ''' + input the basename of a file, without the directory tree, and returns a safe name to use + i.e. only the required characters are converted by urllib.quote + If the input is a PY2 String, output a PY2 String. If input is Unicode output Unicode. + For consistency all platforms are treated the same. Hard coded to utf8 as its ascii compatible + windows is \ / : * ? " < > | posix is / + ''' + def _replace(re_obj): + return urllib.quote(re_obj.group(0), safe=u'') + if not isinstance(file_basename, six.text_type): + # the following string is not prefixed with u + return re.sub('[\\\/:*?"<>|]', + _replace,six.text_type(file_basename, 'utf8').encode('ascii', 'backslashreplace')) + # the following string is prefixed with u + return re.sub(u'[\\\/:*?"<>|]', _replace, file_basename, flags=re.UNICODE) + + +def safe_filepath(file_path_name): + ''' + input the full path and filename, splits on directory separator and calls safe_filename_leaf for + each part of the path. + ''' + (drive,path) = os.path.splitdrive(file_path_name) + path = os.sep.join([safe_filename_leaf(file_section) for file_section in file_path_name.rsplit(os.sep)]) + if drive: + return os.sep.join([drive, path]) + else: + return path + + def is_hex(value): ''' Returns True if value is a hexidecimal string, otherwise returns False