You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

validate_path.py 2.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Validate the input path."""
  16. import os
  17. def validate_and_normalize_path(
  18. path,
  19. check_absolute_path=False,
  20. allow_parent_dir=True,
  21. ):
  22. """
  23. Validates path and returns its normalized form.
  24. If path has a valid scheme, treat path as url, otherwise consider path a
  25. unix local path.
  26. Note:
  27. File scheme (rfc8089) is currently not supported.
  28. Args:
  29. path (str): Path to be normalized.
  30. check_absolute_path (bool): Whether check path scheme is supported.
  31. allow_parent_dir (bool): Whether allow parent dir in path.
  32. Returns:
  33. str, normalized path.
  34. """
  35. if not path:
  36. raise RuntimeError("The path is invalid!")
  37. path_str = str(path)
  38. if not allow_parent_dir:
  39. path_components = path_str.split("/")
  40. if ".." in path_components:
  41. raise RuntimeError("The parent path is not allowed!")
  42. # path does not have valid schema, treat it as unix local path.
  43. if check_absolute_path:
  44. if not path_str.startswith("/"):
  45. raise RuntimeError("The path is invalid!")
  46. try:
  47. # most unix systems allow
  48. normalized_path = os.path.realpath(path)
  49. except ValueError:
  50. raise RuntimeError("The path is invalid!")
  51. return normalized_path