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 | |
Rostislav Krasny | ec0ba27 | 2020-01-25 14:32:37 +0200 | [diff] [blame] | 83 | def _create_stream(self, fd, dest, std_name): |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 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 | """ |
| 93 | class Stream(object): |
| 94 | """ Encapsulates a file descriptor """ |
David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 95 | |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 96 | def __init__(self, fd, dest, std_name): |
| 97 | self.fd = fd |
| 98 | self.dest = dest |
| 99 | self.std_name = std_name |
| 100 | self.set_non_blocking() |
| 101 | |
| 102 | def set_non_blocking(self): |
| 103 | import fcntl |
| 104 | flags = fcntl.fcntl(self.fd, fcntl.F_GETFL) |
| 105 | fcntl.fcntl(self.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) |
| 106 | |
| 107 | def fileno(self): |
| 108 | return self.fd.fileno() |
| 109 | |
| 110 | def read(self): |
| 111 | return self.fd.read(4096) |
| 112 | |
| 113 | def close(self): |
| 114 | self.fd.close() |
| 115 | |
| 116 | def _create_stream(self, fd, dest, std_name): |
Mike Frysinger | 91d9587 | 2020-02-03 22:11:19 +0000 | [diff] [blame] | 117 | return self.Stream(fd, dest, std_name) |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 118 | |
| 119 | def select(self): |
Mike Frysinger | 91d9587 | 2020-02-03 22:11:19 +0000 | [diff] [blame] | 120 | ready_streams, _, _ = select.select(self.streams, [], []) |
| 121 | return ready_streams |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 122 | |
| 123 | |
| 124 | class _FileDescriptorStreamsThreads(FileDescriptorStreams): |
| 125 | """ Implementation of FileDescriptorStreams for platforms that don't support |
| 126 | non blocking I/O. This implementation requires creating threads issuing |
| 127 | blocking read operations on file descriptors. |
| 128 | """ |
David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 129 | |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 130 | def __init__(self): |
| 131 | super(_FileDescriptorStreamsThreads, self).__init__() |
| 132 | # The queue is shared accross all threads so we can simulate the |
| 133 | # behavior of the select() function |
| 134 | self.queue = Queue(10) # Limit incoming data from streams |
| 135 | |
| 136 | def _create_stream(self, fd, dest, std_name): |
| 137 | return self.Stream(fd, dest, std_name, self.queue) |
| 138 | |
| 139 | def select(self): |
| 140 | # Return only one stream at a time, as it is the most straighforward |
| 141 | # thing to do and it is compatible with the select() function. |
| 142 | item = self.queue.get() |
| 143 | stream = item.stream |
| 144 | stream.data = item.data |
| 145 | return [stream] |
| 146 | |
| 147 | class QueueItem(object): |
| 148 | """ Item put in the shared queue """ |
David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 149 | |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 150 | def __init__(self, stream, data): |
| 151 | self.stream = stream |
| 152 | self.data = data |
| 153 | |
| 154 | class Stream(object): |
| 155 | """ Encapsulates a file descriptor """ |
David Pursehouse | 819827a | 2020-02-12 15:20:19 +0900 | [diff] [blame] | 156 | |
Renaud Paquay | 2e70291 | 2016-11-01 11:23:38 -0700 | [diff] [blame] | 157 | def __init__(self, fd, dest, std_name, queue): |
| 158 | self.fd = fd |
| 159 | self.dest = dest |
| 160 | self.std_name = std_name |
| 161 | self.queue = queue |
| 162 | self.data = None |
| 163 | self.thread = Thread(target=self.read_to_queue) |
| 164 | self.thread.daemon = True |
| 165 | self.thread.start() |
| 166 | |
| 167 | def close(self): |
| 168 | self.fd.close() |
| 169 | |
| 170 | def read(self): |
| 171 | data = self.data |
| 172 | self.data = None |
| 173 | return data |
| 174 | |
| 175 | def read_to_queue(self): |
| 176 | """ The thread function: reads everything from the file descriptor into |
| 177 | the shared queue and terminates when reaching EOF. |
| 178 | """ |
| 179 | for line in iter(self.fd.readline, b''): |
| 180 | self.queue.put(_FileDescriptorStreamsThreads.QueueItem(self, line)) |
| 181 | self.fd.close() |
| 182 | self.queue.put(_FileDescriptorStreamsThreads.QueueItem(self, None)) |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 183 | |
| 184 | |
| 185 | def symlink(source, link_name): |
| 186 | """Creates a symbolic link pointing to source named link_name. |
| 187 | Note: On Windows, source must exist on disk, as the implementation needs |
| 188 | to know whether to create a "File" or a "Directory" symbolic link. |
| 189 | """ |
| 190 | if isWindows(): |
| 191 | import platform_utils_win32 |
| 192 | source = _validate_winpath(source) |
| 193 | link_name = _validate_winpath(link_name) |
| 194 | target = os.path.join(os.path.dirname(link_name), source) |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 195 | if isdir(target): |
| 196 | platform_utils_win32.create_dirsymlink(_makelongpath(source), link_name) |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 197 | else: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 198 | platform_utils_win32.create_filesymlink(_makelongpath(source), link_name) |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 199 | else: |
| 200 | return os.symlink(source, link_name) |
| 201 | |
| 202 | |
| 203 | def _validate_winpath(path): |
| 204 | path = os.path.normpath(path) |
| 205 | if _winpath_is_valid(path): |
| 206 | return path |
| 207 | raise ValueError("Path \"%s\" must be a relative path or an absolute " |
| 208 | "path starting with a drive letter".format(path)) |
| 209 | |
| 210 | |
| 211 | def _winpath_is_valid(path): |
| 212 | """Windows only: returns True if path is relative (e.g. ".\\foo") or is |
| 213 | absolute including a drive letter (e.g. "c:\\foo"). Returns False if path |
| 214 | is ambiguous (e.g. "x:foo" or "\\foo"). |
| 215 | """ |
| 216 | assert isWindows() |
| 217 | path = os.path.normpath(path) |
| 218 | drive, tail = os.path.splitdrive(path) |
| 219 | if tail: |
| 220 | if not drive: |
| 221 | return tail[0] != os.sep # "\\foo" is invalid |
| 222 | else: |
| 223 | return tail[0] == os.sep # "x:foo" is invalid |
| 224 | else: |
| 225 | return not drive # "x:" is invalid |
Renaud Paquay | a65adf7 | 2016-11-03 10:37:53 -0700 | [diff] [blame] | 226 | |
| 227 | |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 228 | def _makelongpath(path): |
| 229 | """Return the input path normalized to support the Windows long path syntax |
| 230 | ("\\\\?\\" prefix) if needed, i.e. if the input path is longer than the |
| 231 | MAX_PATH limit. |
| 232 | """ |
Renaud Paquay | a65adf7 | 2016-11-03 10:37:53 -0700 | [diff] [blame] | 233 | if isWindows(): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 234 | # Note: MAX_PATH is 260, but, for directories, the maximum value is actually 246. |
| 235 | if len(path) < 246: |
| 236 | return path |
| 237 | if path.startswith(u"\\\\?\\"): |
| 238 | return path |
| 239 | if not os.path.isabs(path): |
| 240 | return path |
| 241 | # Append prefix and ensure unicode so that the special longpath syntax |
| 242 | # is supported by underlying Win32 API calls |
| 243 | return u"\\\\?\\" + os.path.normpath(path) |
| 244 | else: |
| 245 | return path |
| 246 | |
| 247 | |
Mike Frysinger | f454512 | 2019-11-11 04:34:16 -0500 | [diff] [blame] | 248 | def rmtree(path, ignore_errors=False): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 249 | """shutil.rmtree(path) wrapper with support for long paths on Windows. |
| 250 | |
| 251 | Availability: Unix, Windows.""" |
Mike Frysinger | f454512 | 2019-11-11 04:34:16 -0500 | [diff] [blame] | 252 | onerror = None |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 253 | if isWindows(): |
Mike Frysinger | f454512 | 2019-11-11 04:34:16 -0500 | [diff] [blame] | 254 | path = _makelongpath(path) |
| 255 | onerror = handle_rmtree_error |
| 256 | shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror) |
Renaud Paquay | a65adf7 | 2016-11-03 10:37:53 -0700 | [diff] [blame] | 257 | |
| 258 | |
| 259 | def handle_rmtree_error(function, path, excinfo): |
| 260 | # Allow deleting read-only files |
| 261 | os.chmod(path, stat.S_IWRITE) |
| 262 | function(path) |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 263 | |
| 264 | |
| 265 | def rename(src, dst): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 266 | """os.rename(src, dst) wrapper with support for long paths on Windows. |
| 267 | |
| 268 | Availability: Unix, Windows.""" |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 269 | if isWindows(): |
| 270 | # On Windows, rename fails if destination exists, see |
| 271 | # https://docs.python.org/2/library/os.html#os.rename |
| 272 | try: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 273 | os.rename(_makelongpath(src), _makelongpath(dst)) |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 274 | except OSError as e: |
| 275 | if e.errno == errno.EEXIST: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 276 | os.remove(_makelongpath(dst)) |
| 277 | os.rename(_makelongpath(src), _makelongpath(dst)) |
Renaud Paquay | ad1abcb | 2016-11-01 11:34:55 -0700 | [diff] [blame] | 278 | else: |
| 279 | raise |
| 280 | else: |
| 281 | os.rename(src, dst) |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 282 | |
| 283 | |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 284 | def remove(path): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 285 | """Remove (delete) the file path. This is a replacement for os.remove that |
| 286 | allows deleting read-only files on Windows, with support for long paths and |
| 287 | for deleting directory symbolic links. |
| 288 | |
| 289 | Availability: Unix, Windows.""" |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 290 | if isWindows(): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 291 | longpath = _makelongpath(path) |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 292 | try: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 293 | os.remove(longpath) |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 294 | except OSError as e: |
| 295 | if e.errno == errno.EACCES: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 296 | os.chmod(longpath, stat.S_IWRITE) |
| 297 | # Directory symbolic links must be deleted with 'rmdir'. |
| 298 | if islink(longpath) and isdir(longpath): |
| 299 | os.rmdir(longpath) |
| 300 | else: |
| 301 | os.remove(longpath) |
Renaud Paquay | 010fed7 | 2016-11-11 14:25:29 -0800 | [diff] [blame] | 302 | else: |
| 303 | raise |
| 304 | else: |
| 305 | os.remove(path) |
| 306 | |
| 307 | |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 308 | def walk(top, topdown=True, onerror=None, followlinks=False): |
| 309 | """os.walk(path) wrapper with support for long paths on Windows. |
| 310 | |
| 311 | Availability: Windows, Unix. |
| 312 | """ |
| 313 | if isWindows(): |
| 314 | return _walk_windows_impl(top, topdown, onerror, followlinks) |
| 315 | else: |
| 316 | return os.walk(top, topdown, onerror, followlinks) |
| 317 | |
| 318 | |
| 319 | def _walk_windows_impl(top, topdown, onerror, followlinks): |
| 320 | try: |
| 321 | names = listdir(top) |
David Pursehouse | d26146d | 2018-11-01 11:54:10 +0900 | [diff] [blame] | 322 | except Exception as err: |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 323 | if onerror is not None: |
| 324 | onerror(err) |
| 325 | return |
| 326 | |
| 327 | dirs, nondirs = [], [] |
| 328 | for name in names: |
| 329 | if isdir(os.path.join(top, name)): |
| 330 | dirs.append(name) |
| 331 | else: |
| 332 | nondirs.append(name) |
| 333 | |
| 334 | if topdown: |
| 335 | yield top, dirs, nondirs |
| 336 | for name in dirs: |
| 337 | new_path = os.path.join(top, name) |
| 338 | if followlinks or not islink(new_path): |
| 339 | for x in _walk_windows_impl(new_path, topdown, onerror, followlinks): |
| 340 | yield x |
| 341 | if not topdown: |
| 342 | yield top, dirs, nondirs |
| 343 | |
| 344 | |
| 345 | def listdir(path): |
| 346 | """os.listdir(path) wrapper with support for long paths on Windows. |
| 347 | |
| 348 | Availability: Windows, Unix. |
| 349 | """ |
| 350 | return os.listdir(_makelongpath(path)) |
| 351 | |
| 352 | |
| 353 | def rmdir(path): |
| 354 | """os.rmdir(path) wrapper with support for long paths on Windows. |
| 355 | |
| 356 | Availability: Windows, Unix. |
| 357 | """ |
| 358 | os.rmdir(_makelongpath(path)) |
| 359 | |
| 360 | |
| 361 | def isdir(path): |
| 362 | """os.path.isdir(path) wrapper with support for long paths on Windows. |
| 363 | |
| 364 | Availability: Windows, Unix. |
| 365 | """ |
| 366 | return os.path.isdir(_makelongpath(path)) |
| 367 | |
| 368 | |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 369 | def islink(path): |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 370 | """os.path.islink(path) wrapper with support for long paths on Windows. |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 371 | |
| 372 | Availability: Windows, Unix. |
| 373 | """ |
| 374 | if isWindows(): |
| 375 | import platform_utils_win32 |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 376 | return platform_utils_win32.islink(_makelongpath(path)) |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 377 | else: |
| 378 | return os.path.islink(path) |
| 379 | |
| 380 | |
| 381 | def readlink(path): |
| 382 | """Return a string representing the path to which the symbolic link |
| 383 | points. The result may be either an absolute or relative pathname; |
| 384 | if it is relative, it may be converted to an absolute pathname using |
| 385 | os.path.join(os.path.dirname(path), result). |
| 386 | |
| 387 | Availability: Windows, Unix. |
| 388 | """ |
| 389 | if isWindows(): |
| 390 | import platform_utils_win32 |
Renaud Paquay | bed8b62 | 2018-09-27 10:46:58 -0700 | [diff] [blame] | 391 | return platform_utils_win32.readlink(_makelongpath(path)) |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 392 | else: |
| 393 | return os.readlink(path) |
| 394 | |
| 395 | |
| 396 | def realpath(path): |
| 397 | """Return the canonical path of the specified filename, eliminating |
| 398 | any symbolic links encountered in the path. |
| 399 | |
| 400 | Availability: Windows, Unix. |
| 401 | """ |
| 402 | if isWindows(): |
| 403 | current_path = os.path.abspath(path) |
| 404 | path_tail = [] |
| 405 | for c in range(0, 100): # Avoid cycles |
| 406 | if islink(current_path): |
| 407 | target = readlink(current_path) |
| 408 | current_path = os.path.join(os.path.dirname(current_path), target) |
| 409 | else: |
| 410 | basename = os.path.basename(current_path) |
| 411 | if basename == '': |
| 412 | path_tail.append(current_path) |
| 413 | break |
| 414 | path_tail.append(basename) |
| 415 | current_path = os.path.dirname(current_path) |
| 416 | path_tail.reverse() |
| 417 | result = os.path.normpath(os.path.join(*path_tail)) |
| 418 | return result |
| 419 | else: |
| 420 | return os.path.realpath(path) |