Mike Frysinger | f601376 | 2019-06-13 02:30:51 -0400 | [diff] [blame] | 1 | # -*- coding:utf-8 -*- |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 2 | # |
| 3 | # Copyright (C) 2016 The Android Open Source Project |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
| 16 | |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 17 | import errno |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 18 | import os |
| 19 | import platform |
| 20 | import select |
Renaud Paquay | a65adf7 | 2016-11-03 10:37:53 -0700 | [diff] [blame] | 21 | import shutil |
| 22 | import stat |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 23 | |
Dylan Deng | e469a0c | 2018-06-23 15:02:26 +0800 | [diff] [blame] | 24 | from pyversion import is_python3 |
| 25 | if is_python3(): |
| 26 | from queue import Queue |
| 27 | else: |
| 28 | from Queue import Queue |
| 29 | |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 30 | from threading import Thread |
| 31 | |
| 32 | |
| 33 | def isWindows(): |
| 34 | """ Returns True when running with the native port of Python for Windows, |
| 35 | False when running on any other platform (including the Cygwin port of |
| 36 | Python). |
| 37 | """ |
| 38 | # Note: The cygwin port of Python returns "CYGWIN_NT_xxx" |
| 39 | return platform.system() == "Windows" |
| 40 | |
| 41 | |
| 42 | class FileDescriptorStreams(object): |
| 43 | """ Platform agnostic abstraction enabling non-blocking I/O over a |
| 44 | collection of file descriptors. This abstraction is required because |
| 45 | fctnl(os.O_NONBLOCK) is not supported on Windows. |
| 46 | """ |
| 47 | @classmethod |
| 48 | def create(cls): |
| 49 | """ Factory method: instantiates the concrete class according to the |
| 50 | current platform. |
| 51 | """ |
| 52 | if isWindows(): |
| 53 | return _FileDescriptorStreamsThreads() |
| 54 | else: |
| 55 | return _FileDescriptorStreamsNonBlocking() |
| 56 | |
| 57 | def __init__(self): |
| 58 | self.streams = [] |
| 59 | |
| 60 | def add(self, fd, dest, std_name): |
| 61 | """ Wraps an existing file descriptor as a stream. |
| 62 | """ |
| 63 | self.streams.append(self._create_stream(fd, dest, std_name)) |
| 64 | |
| 65 | def remove(self, stream): |
| 66 | """ Removes a stream, when done with it. |
| 67 | """ |
| 68 | self.streams.remove(stream) |
| 69 | |
| 70 | @property |
| 71 | def is_done(self): |
| 72 | """ Returns True when all streams have been processed. |
| 73 | """ |
| 74 | return len(self.streams) == 0 |
| 75 | |
| 76 | def select(self): |
| 77 | """ Returns the set of streams that have data available to read. |
| 78 | The returned streams each expose a read() and a close() method. |
| 79 | When done with a stream, call the remove(stream) method. |
| 80 | """ |
| 81 | raise NotImplementedError |
| 82 | |
| 83 | def _create_stream(fd, dest, std_name): |
| 84 | """ Creates a new stream wrapping an existing file descriptor. |
| 85 | """ |
| 86 | raise NotImplementedError |
| 87 | |
| 88 | |
| 89 | class _FileDescriptorStreamsNonBlocking(FileDescriptorStreams): |
| 90 | """ Implementation of FileDescriptorStreams for platforms that support |
| 91 | non blocking I/O. |
| 92 | """ |
Theodore Dubois | 1e01a74 | 2019-12-17 17:51:29 -0800 | [diff] [blame] | 93 | def __init__(self): |
| 94 | super(_FileDescriptorStreamsNonBlocking, self).__init__() |
| 95 | self._poll = select.poll() |
| 96 | self._fd_to_stream = {} |
| 97 | |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 98 | class Stream(object): |
| 99 | """ Encapsulates a file descriptor """ |
| 100 | def __init__(self, fd, dest, std_name): |
| 101 | self.fd = fd |
| 102 | self.dest = dest |
| 103 | self.std_name = std_name |
| 104 | self.set_non_blocking() |
| 105 | |
| 106 | def set_non_blocking(self): |
| 107 | import fcntl |
| 108 | flags = fcntl.fcntl(self.fd, fcntl.F_GETFL) |
| 109 | fcntl.fcntl(self.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) |
| 110 | |
| 111 | def fileno(self): |
| 112 | return self.fd.fileno() |
| 113 | |
| 114 | def read(self): |
| 115 | return self.fd.read(4096) |
| 116 | |
| 117 | def close(self): |
| 118 | self.fd.close() |
| 119 | |
| 120 | def _create_stream(self, fd, dest, std_name): |
Theodore Dubois | 1e01a74 | 2019-12-17 17:51:29 -0800 | [diff] [blame] | 121 | stream = self.Stream(fd, dest, std_name) |
| 122 | self._fd_to_stream[stream.fileno()] = stream |
| 123 | self._poll.register(stream, select.POLLIN) |
| 124 | return stream |
| 125 | |
| 126 | def remove(self, stream): |
| 127 | self._poll.unregister(stream) |
| 128 | del self._fd_to_stream[stream.fileno()] |
| 129 | super(_FileDescriptorStreamsNonBlocking, self).remove(stream) |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 130 | |
| 131 | def select(self): |
Theodore Dubois | 1e01a74 | 2019-12-17 17:51:29 -0800 | [diff] [blame] | 132 | return [self._fd_to_stream[fd] for fd, _ in self._poll.poll()] |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 133 | |
| 134 | |
| 135 | class _FileDescriptorStreamsThreads(FileDescriptorStreams): |
| 136 | """ Implementation of FileDescriptorStreams for platforms that don't support |
| 137 | non blocking I/O. This implementation requires creating threads issuing |
| 138 | blocking read operations on file descriptors. |
| 139 | """ |
| 140 | def __init__(self): |
| 141 | super(_FileDescriptorStreamsThreads, self).__init__() |
| 142 | # The queue is shared accross all threads so we can simulate the |
| 143 | # behavior of the select() function |
| 144 | self.queue = Queue(10) # Limit incoming data from streams |
| 145 | |
| 146 | def _create_stream(self, fd, dest, std_name): |
| 147 | return self.Stream(fd, dest, std_name, self.queue) |
| 148 | |
| 149 | def select(self): |
| 150 | # Return only one stream at a time, as it is the most straighforward |
| 151 | # thing to do and it is compatible with the select() function. |
| 152 | item = self.queue.get() |
| 153 | stream = item.stream |
| 154 | stream.data = item.data |
| 155 | return [stream] |
| 156 | |
| 157 | class QueueItem(object): |
| 158 | """ Item put in the shared queue """ |
| 159 | def __init__(self, stream, data): |
| 160 | self.stream = stream |
| 161 | self.data = data |
| 162 | |
| 163 | class Stream(object): |
| 164 | """ Encapsulates a file descriptor """ |
| 165 | def __init__(self, fd, dest, std_name, queue): |
| 166 | self.fd = fd |
| 167 | self.dest = dest |
| 168 | self.std_name = std_name |
| 169 | self.queue = queue |
| 170 | self.data = None |
| 171 | self.thread = Thread(target=self.read_to_queue) |
| 172 | self.thread.daemon = True |
| 173 | self.thread.start() |
| 174 | |
| 175 | def close(self): |
| 176 | self.fd.close() |
| 177 | |
| 178 | def read(self): |
| 179 | data = self.data |
| 180 | self.data = None |
| 181 | return data |
| 182 | |
| 183 | def read_to_queue(self): |
| 184 | """ The thread function: reads everything from the file descriptor into |
| 185 | the shared queue and terminates when reaching EOF. |
| 186 | """ |
| 187 | for line in iter(self.fd.readline, b''): |
| 188 | self.queue.put(_FileDescriptorStreamsThreads.QueueItem(self, line)) |
| 189 | self.fd.close() |
| 190 | self.queue.put(_FileDescriptorStreamsThreads.QueueItem(self, None)) |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 191 | |
| 192 | |
| 193 | def symlink(source, link_name): |
| 194 | """Creates a symbolic link pointing to source named link_name. |
| 195 | Note: On Windows, source must exist on disk, as the implementation needs |
| 196 | to know whether to create a "File" or a "Directory" symbolic link. |
| 197 | """ |
| 198 | if isWindows(): |
| 199 | import platform_utils_win32 |
| 200 | source = _validate_winpath(source) |
| 201 | link_name = _validate_winpath(link_name) |
| 202 | target = os.path.join(os.path.dirname(link_name), source) |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 203 | if isdir(target): |
| 204 | platform_utils_win32.create_dirsymlink(_makelongpath(source), link_name) |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 205 | else: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 206 | platform_utils_win32.create_filesymlink(_makelongpath(source), link_name) |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 207 | else: |
| 208 | return os.symlink(source, link_name) |
| 209 | |
| 210 | |
| 211 | def _validate_winpath(path): |
| 212 | path = os.path.normpath(path) |
| 213 | if _winpath_is_valid(path): |
| 214 | return path |
| 215 | raise ValueError("Path \"%s\" must be a relative path or an absolute " |
| 216 | "path starting with a drive letter".format(path)) |
| 217 | |
| 218 | |
| 219 | def _winpath_is_valid(path): |
| 220 | """Windows only: returns True if path is relative (e.g. ".\\foo") or is |
| 221 | absolute including a drive letter (e.g. "c:\\foo"). Returns False if path |
| 222 | is ambiguous (e.g. "x:foo" or "\\foo"). |
| 223 | """ |
| 224 | assert isWindows() |
| 225 | path = os.path.normpath(path) |
| 226 | drive, tail = os.path.splitdrive(path) |
| 227 | if tail: |
| 228 | if not drive: |
| 229 | return tail[0] != os.sep # "\\foo" is invalid |
| 230 | else: |
| 231 | return tail[0] == os.sep # "x:foo" is invalid |
| 232 | else: |
| 233 | return not drive # "x:" is invalid |
Renaud Paquay | a65adf7 | 2016-11-03 10:37:53 -0700 | [diff] [blame] | 234 | |
| 235 | |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 236 | def _makelongpath(path): |
| 237 | """Return the input path normalized to support the Windows long path syntax |
| 238 | ("\\\\?\\" prefix) if needed, i.e. if the input path is longer than the |
| 239 | MAX_PATH limit. |
| 240 | """ |
Renaud Paquay | a65adf7 | 2016-11-03 10:37:53 -0700 | [diff] [blame] | 241 | if isWindows(): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 242 | # Note: MAX_PATH is 260, but, for directories, the maximum value is actually 246. |
| 243 | if len(path) < 246: |
| 244 | return path |
| 245 | if path.startswith(u"\\\\?\\"): |
| 246 | return path |
| 247 | if not os.path.isabs(path): |
| 248 | return path |
| 249 | # Append prefix and ensure unicode so that the special longpath syntax |
| 250 | # is supported by underlying Win32 API calls |
| 251 | return u"\\\\?\\" + os.path.normpath(path) |
| 252 | else: |
| 253 | return path |
| 254 | |
| 255 | |
Mike Frysinger | f454512 | 2019-11-11 04:34:16 -0500 | [diff] [blame] | 256 | def rmtree(path, ignore_errors=False): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 257 | """shutil.rmtree(path) wrapper with support for long paths on Windows. |
| 258 | |
| 259 | Availability: Unix, Windows.""" |
Mike Frysinger | f454512 | 2019-11-11 04:34:16 -0500 | [diff] [blame] | 260 | onerror = None |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 261 | if isWindows(): |
Mike Frysinger | f454512 | 2019-11-11 04:34:16 -0500 | [diff] [blame] | 262 | path = _makelongpath(path) |
| 263 | onerror = handle_rmtree_error |
| 264 | shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror) |
Renaud Paquay | a65adf7 | 2016-11-03 10:37:53 -0700 | [diff] [blame] | 265 | |
| 266 | |
| 267 | def handle_rmtree_error(function, path, excinfo): |
| 268 | # Allow deleting read-only files |
| 269 | os.chmod(path, stat.S_IWRITE) |
| 270 | function(path) |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 271 | |
| 272 | |
| 273 | def rename(src, dst): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 274 | """os.rename(src, dst) wrapper with support for long paths on Windows. |
| 275 | |
| 276 | Availability: Unix, Windows.""" |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 277 | if isWindows(): |
| 278 | # On Windows, rename fails if destination exists, see |
| 279 | # https://docs.python.org/2/library/os.html#os.rename |
| 280 | try: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 281 | os.rename(_makelongpath(src), _makelongpath(dst)) |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 282 | except OSError as e: |
| 283 | if e.errno == errno.EEXIST: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 284 | os.remove(_makelongpath(dst)) |
| 285 | os.rename(_makelongpath(src), _makelongpath(dst)) |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 286 | else: |
| 287 | raise |
| 288 | else: |
| 289 | os.rename(src, dst) |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 290 | |
| 291 | |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 292 | def remove(path): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 293 | """Remove (delete) the file path. This is a replacement for os.remove that |
| 294 | allows deleting read-only files on Windows, with support for long paths and |
| 295 | for deleting directory symbolic links. |
| 296 | |
| 297 | Availability: Unix, Windows.""" |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 298 | if isWindows(): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 299 | longpath = _makelongpath(path) |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 300 | try: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 301 | os.remove(longpath) |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 302 | except OSError as e: |
| 303 | if e.errno == errno.EACCES: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 304 | os.chmod(longpath, stat.S_IWRITE) |
| 305 | # Directory symbolic links must be deleted with 'rmdir'. |
| 306 | if islink(longpath) and isdir(longpath): |
| 307 | os.rmdir(longpath) |
| 308 | else: |
| 309 | os.remove(longpath) |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 310 | else: |
| 311 | raise |
| 312 | else: |
| 313 | os.remove(path) |
| 314 | |
| 315 | |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 316 | def walk(top, topdown=True, onerror=None, followlinks=False): |
| 317 | """os.walk(path) wrapper with support for long paths on Windows. |
| 318 | |
| 319 | Availability: Windows, Unix. |
| 320 | """ |
| 321 | if isWindows(): |
| 322 | return _walk_windows_impl(top, topdown, onerror, followlinks) |
| 323 | else: |
| 324 | return os.walk(top, topdown, onerror, followlinks) |
| 325 | |
| 326 | |
| 327 | def _walk_windows_impl(top, topdown, onerror, followlinks): |
| 328 | try: |
| 329 | names = listdir(top) |
David Pursehouse | d26146d | 2018-11-01 11:54:10 +0900 | [diff] [blame] | 330 | except Exception as err: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 331 | if onerror is not None: |
| 332 | onerror(err) |
| 333 | return |
| 334 | |
| 335 | dirs, nondirs = [], [] |
| 336 | for name in names: |
| 337 | if isdir(os.path.join(top, name)): |
| 338 | dirs.append(name) |
| 339 | else: |
| 340 | nondirs.append(name) |
| 341 | |
| 342 | if topdown: |
| 343 | yield top, dirs, nondirs |
| 344 | for name in dirs: |
| 345 | new_path = os.path.join(top, name) |
| 346 | if followlinks or not islink(new_path): |
| 347 | for x in _walk_windows_impl(new_path, topdown, onerror, followlinks): |
| 348 | yield x |
| 349 | if not topdown: |
| 350 | yield top, dirs, nondirs |
| 351 | |
| 352 | |
| 353 | def listdir(path): |
| 354 | """os.listdir(path) wrapper with support for long paths on Windows. |
| 355 | |
| 356 | Availability: Windows, Unix. |
| 357 | """ |
| 358 | return os.listdir(_makelongpath(path)) |
| 359 | |
| 360 | |
| 361 | def rmdir(path): |
| 362 | """os.rmdir(path) wrapper with support for long paths on Windows. |
| 363 | |
| 364 | Availability: Windows, Unix. |
| 365 | """ |
| 366 | os.rmdir(_makelongpath(path)) |
| 367 | |
| 368 | |
| 369 | def isdir(path): |
| 370 | """os.path.isdir(path) wrapper with support for long paths on Windows. |
| 371 | |
| 372 | Availability: Windows, Unix. |
| 373 | """ |
| 374 | return os.path.isdir(_makelongpath(path)) |
| 375 | |
| 376 | |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 377 | def islink(path): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 378 | """os.path.islink(path) wrapper with support for long paths on Windows. |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 379 | |
| 380 | Availability: Windows, Unix. |
| 381 | """ |
| 382 | if isWindows(): |
| 383 | import platform_utils_win32 |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 384 | return platform_utils_win32.islink(_makelongpath(path)) |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 385 | else: |
| 386 | return os.path.islink(path) |
| 387 | |
| 388 | |
| 389 | def readlink(path): |
| 390 | """Return a string representing the path to which the symbolic link |
| 391 | points. The result may be either an absolute or relative pathname; |
| 392 | if it is relative, it may be converted to an absolute pathname using |
| 393 | os.path.join(os.path.dirname(path), result). |
| 394 | |
| 395 | Availability: Windows, Unix. |
| 396 | """ |
| 397 | if isWindows(): |
| 398 | import platform_utils_win32 |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 399 | return platform_utils_win32.readlink(_makelongpath(path)) |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 400 | else: |
| 401 | return os.readlink(path) |
| 402 | |
| 403 | |
| 404 | def realpath(path): |
| 405 | """Return the canonical path of the specified filename, eliminating |
| 406 | any symbolic links encountered in the path. |
| 407 | |
| 408 | Availability: Windows, Unix. |
| 409 | """ |
| 410 | if isWindows(): |
| 411 | current_path = os.path.abspath(path) |
| 412 | path_tail = [] |
| 413 | for c in range(0, 100): # Avoid cycles |
| 414 | if islink(current_path): |
| 415 | target = readlink(current_path) |
| 416 | current_path = os.path.join(os.path.dirname(current_path), target) |
| 417 | else: |
| 418 | basename = os.path.basename(current_path) |
| 419 | if basename == '': |
| 420 | path_tail.append(current_path) |
| 421 | break |
| 422 | path_tail.append(basename) |
| 423 | current_path = os.path.dirname(current_path) |
| 424 | path_tail.reverse() |
| 425 | result = os.path.normpath(os.path.join(*path_tail)) |
| 426 | return result |
| 427 | else: |
| 428 | return os.path.realpath(path) |