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.""" 16import os 17 18 19def validate_and_normalize_path( 20 path, 21 check_absolute_path=False, 22 allow_parent_dir=True, 23): 24 """ 25 Validates path and returns its normalized form. 26 27 If path has a valid scheme, treat path as url, otherwise consider path a 28 unix local path. 29 30 Note: 31 File scheme (rfc8089) is currently not supported. 32 33 Args: 34 path (str): Path to be normalized. 35 check_absolute_path (bool): Whether check path scheme is supported. 36 allow_parent_dir (bool): Whether allow parent dir in path. 37 38 Returns: 39 str, normalized path. 40 """ 41 if not path: 42 raise RuntimeError("The path is invalid!") 43 44 path_str = str(path) 45 if not allow_parent_dir: 46 path_components = path_str.split("/") 47 if ".." in path_components: 48 raise RuntimeError("The parent path is not allowed!") 49 50 # path does not have valid schema, treat it as unix local path. 51 if check_absolute_path: 52 if not path_str.startswith("/"): 53 raise RuntimeError("The path is invalid!") 54 try: 55 # most unix systems allow 56 normalized_path = os.path.realpath(path) 57 except ValueError: 58 raise RuntimeError("The path is invalid!") 59 60 return normalized_path 61