1#
2# Copyright (C) 2017 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import logging
18import os
19import shutil
20import tempfile
21
22
23def FindFile(directory, filename):
24    '''Find a file under directory given the filename.
25
26    Args:
27        directory: string, directory path
28        filename: string, file name to find
29
30    Returns:
31        String, path to the file found. None if not found.
32    '''
33    for (dirpath, dirnames, filenames) in os.walk(
34            directory, followlinks=False):
35        for fn in filenames:
36            if fn == filename:
37                return os.path.join(dirpath, filename)
38
39    return None
40
41
42def Rmdirs(path, ignore_errors=False):
43    '''Remove the given directory and its contents recursively.
44
45    Args:
46        path: string, directory to delete
47        ignore_errors: bool, whether to ignore errors. Defaults to False
48
49    Returns:
50        bool, True if directory is deleted.
51              False if errors occur or directory does not exist.
52    '''
53    return_value = False
54    if os.path.exists(path):
55        try:
56            shutil.rmtree(path, ignore_errors=ignore_errors)
57            return_value = True
58        except OSError as e:
59            logging.exception(e)
60    return return_value
61
62
63def Mkdir(path, skip_if_exists=True):
64    """Make a leaf directory.
65
66    This method only makes the leaf directory. This means if the parent directory
67    doesn't exist, the method will catch an OSError and return False.
68
69    Args:
70        path: string, directory to make
71        skip_if_exists: bool, True for ignoring exisitng dir. False for throwing
72                        error from os.mkdir. Defaults to True
73
74    Returns:
75        bool, True if directory is created or directory already exists
76              (with skip_if_exists being True).
77              False if errors occur or directory already exists (with skip_if_exists being False).
78    """
79    if skip_if_exists and os.path.exists(path):
80        return True
81
82    try:
83        os.mkdir(path)
84        return True
85    except OSError as e:
86        logging.exception(e)
87        return False
88
89
90def Makedirs(path, skip_if_exists=True):
91    '''Make directories lead to the given path.
92
93    This method makes all parent directories if they don't exist.
94
95    Args:
96        path: string, directory to make
97        skip_if_exists: bool, True for ignoring exisitng dir. False for throwing
98                        error from os.makedirs. Defaults to True
99
100    Returns:
101        bool, True if directory is created or directory already exists
102              (with skip_if_exists being True).
103              False if errors occur or directory already exists (with skip_if_exists being False).
104    '''
105    if skip_if_exists and os.path.exists(path):
106        return True
107
108    try:
109        os.makedirs(path)
110        return True
111    except OSError as e:
112        logging.exception(e)
113        return False
114
115
116def MakeTempDir(base_dir):
117    """Make a temp directory based on the given path and return its path.
118
119    Args:
120        base_dir: string, base directory to make temp directory.
121
122    Returns:
123        string, relative path to created temp directory
124    """
125    Makedirs(base_dir)
126    return tempfile.mkdtemp(dir=base_dir)