util.py 4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
17
"""Common system utilities"""
18 19 20
import os
import tempfile
import shutil
21 22 23 24 25
try:
    import fcntl
except ImportError:
    fcntl = None

26 27

class TempDirectory(object):
28 29 30 31
    """Helper object to manage temp directory during testing.

    Automatically removes the directory when it went out of scope.
    """
32 33 34 35 36 37
    def __init__(self, custom_path=None):
        if custom_path:
            os.mkdir(custom_path)
            self.temp_dir = custom_path
        else:
            self.temp_dir = tempfile.mkdtemp()
Tianqi Chen committed
38
        self._rmtree = shutil.rmtree
39

40 41 42
    def remove(self):
        """Remote the tmp dir"""
        if self.temp_dir:
Hu Shiwen committed
43
            self._rmtree(self.temp_dir, ignore_errors=True)
44 45
            self.temp_dir = None

46
    def __del__(self):
47
        self.remove()
48 49 50 51 52 53 54 55

    def relpath(self, name):
        """Relative path in temp dir

        Parameters
        ----------
        name : str
            The name of the file.
56 57 58 59 60

        Returns
        -------
        path : str
            The concatenated path.
61 62 63
        """
        return os.path.join(self.temp_dir, name)

64
    def listdir(self):
65
        """List contents in the dir.
66 67 68 69 70 71

        Returns
        -------
        names : list
            The content of directory
        """
72
        return os.listdir(self.temp_dir)
73

74

75
def tempdir(custom_path=None):
76
    """Create temp dir which deletes the contents when exit.
77

78 79 80 81 82
    Parameters
    ----------
    custom_path : str, optional
        Manually specify the exact temp dir path

83 84 85 86 87
    Returns
    -------
    temp : TempDirectory
        The temp directory object
    """
88
    return TempDirectory(custom_path)
89 90 91 92 93 94 95 96 97 98 99 100


class FileLock(object):
    """File lock object

    Parameters
    ----------
    path : str
        The path to the lock
    """
    def __init__(self, path):
        self.lock_file = open(path, "w")
101 102
        if fcntl:
            fcntl.lockf(self.lock_file, fcntl.LOCK_EX)
103 104 105 106 107


    def release(self):
        """Release the lock"""
        if self.lock_file:
108 109
            if fcntl:
                fcntl.lockf(self.lock_file, fcntl.LOCK_UN)
110 111 112
            self.lock_file.close()
            self.lock_file = None

113

114 115 116 117 118 119 120 121 122 123 124 125 126
def filelock(path):
    """Create a file lock which locks on path

    Parameters
    ----------
    path : str
        The path to the lock

    Returns
    -------
    lock : File lock object
    """
    return FileLock(path)
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168


def is_source_path(path):
    """Check if path is source code path.

    Parameters
    ----------
    path : str
        A possible path

    Returns
    -------
    valid : bool
        Whether path is a possible source path
    """
    if os.path.exists(path):
        return True
    if path.find("\n") != -1:
        return False
    spath = path.rsplit(".", 1)
    return len(spath) == 2 and spath[1].strip() == spath[1]


def which(exec_name):
    """Try to find full path of exec_name

    Parameters
    ----------
    exec_name : str
        The executable name

    Returns
    -------
    path : str
        The full path of executable if found, otherwise returns None
    """
    base_list = ["", "/bin"] + os.environ.get("PATH", "").split(os.pathsep)
    for path in base_list:
        full_path = os.path.join(path, exec_name)
        if os.path.isfile(full_path) and os.access(full_path, os.X_OK):
            return full_path
    return None