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