1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
|
"""This module provides core functions for handling Unicode and Unix quirks
The @interruptable functions retry when system calls are interrupted,
e.g. when python raises an IOError or OSError with errno == EINTR.
"""
import ctypes
import functools
import itertools
import mimetypes
import os
import platform
import subprocess
import sys
from .decorators import interruptable
from .compat import ustr
from .compat import PY2
from .compat import PY3
from .compat import WIN32
# /usr/include/stdlib.h
# #define EXIT_SUCCESS 0 /* Successful exit status. */
# #define EXIT_FAILURE 1 /* Failing exit status. */
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
# /usr/include/sysexits.h
# #define EX_USAGE 64 /* command line usage error */
# #define EX_NOINPUT 66 /* cannot open input */
# #define EX_UNAVAILABLE 69 /* service unavailable */
EXIT_USAGE = 64
EXIT_NOINPUT = 66
EXIT_UNAVAILABLE = 69
# Default encoding
ENCODING = 'utf-8'
# Some files are not in UTF-8; some other aren't in any codification.
# Remember that GIT doesn't care about encodings (saves binary data)
_encoding_tests = [
ENCODING,
'iso-8859-15',
'windows1252',
'ascii',
# <-- add encodings here
]
class UStr(ustr):
"""Unicode string wrapper that remembers its encoding
UStr wraps Unicode strings to provide the `encoding` attribute.
UStr is used when decoding strings of an unknown encoding.
In order to generate patches that contain the original byte sequences,
we must preserve the original encoding when calling decode()
so that it can later be used when reconstructing the original
byte sequences.
"""
def __new__(cls, string, encoding):
if isinstance(string, UStr):
if encoding != string.encoding:
raise ValueError(f'Encoding conflict: {string.encoding} vs. {encoding}')
string = ustr(string)
obj = ustr.__new__(cls, string)
obj.encoding = encoding
return obj
def decode_maybe(value, encoding, errors='strict'):
"""Decode a value when the "decode" method exists"""
if hasattr(value, 'decode'):
result = value.decode(encoding, errors=errors)
else:
result = value
return result
def decode(value, encoding=None, errors='strict'):
"""decode(encoded_string) returns an un-encoded Unicode string"""
if value is None:
result = None
elif isinstance(value, ustr):
result = UStr(value, ENCODING)
elif encoding == 'bytes':
result = value
else:
result = None
if encoding is None:
encoding_tests = _encoding_tests
else:
encoding_tests = itertools.chain([encoding], _encoding_tests)
for enc in encoding_tests:
try:
decoded = value.decode(enc, errors)
result = UStr(decoded, enc)
break
except ValueError:
pass
if result is None:
decoded = value.decode(ENCODING, errors='ignore')
result = UStr(decoded, ENCODING)
return result
def encode(string, encoding=None):
"""encode(string) returns a byte string encoded to UTF-8"""
if not isinstance(string, ustr):
return string
return string.encode(encoding or ENCODING, 'replace')
def mkpath(path, encoding=None):
# The Windows API requires Unicode strings regardless of python version
if WIN32:
return decode(path, encoding=encoding)
# UNIX prefers bytes
return encode(path, encoding=encoding)
def decode_seq(seq, encoding=None):
"""Decode a sequence of values"""
return [decode(x, encoding=encoding) for x in seq]
def list2cmdline(cmd):
return subprocess.list2cmdline([decode(c) for c in cmd])
def read(filename, size=-1, encoding=None, errors='strict'):
"""Read filename and return contents"""
with xopen(filename, 'rb') as fh:
return xread(fh, size=size, encoding=encoding, errors=errors)
def write(path, contents, encoding=None, append=False):
"""Writes a Unicode string to a file"""
if append:
mode = 'ab'
else:
mode = 'wb'
with xopen(path, mode) as fh:
return xwrite(fh, contents, encoding=encoding)
@interruptable
def xread(fh, size=-1, encoding=None, errors='strict'):
"""Read from a file handle and retry when interrupted"""
return decode(fh.read(size), encoding=encoding, errors=errors)
@interruptable
def xwrite(fh, content, encoding=None):
"""Write to a file handle and retry when interrupted"""
return fh.write(encode(content, encoding=encoding))
@interruptable
def wait(proc):
"""Wait on a subprocess and retry when interrupted"""
return proc.wait()
@interruptable
def readline(fh, encoding=None):
return decode(fh.readline(), encoding=encoding)
@interruptable
def start_command(
cmd,
cwd=None,
add_env=None,
universal_newlines=False,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
no_win32_startupinfo=False,
stderr=subprocess.PIPE,
**extra,
):
"""Start the given command, and return a subprocess object.
This provides a simpler interface to the subprocess module.
"""
env = extra.pop('env', None)
if add_env is not None:
env = os.environ.copy()
env.update(add_env)
# Python3 on windows always goes through list2cmdline() internally inside
# of subprocess.py so we must provide Unicode strings here otherwise
# Python3 breaks when bytes are provided.
#
# Additionally, the preferred usage on Python3 is to pass Unicode
# strings to subprocess. Python will automatically encode into the
# default encoding (UTF-8) when it gets Unicode strings.
shell = extra.get('shell', False)
cmd = prep_for_subprocess(cmd, shell=shell)
if WIN32 and cwd == getcwd():
# Windows cannot deal with passing a cwd that contains Unicode
# but we luckily can pass None when the supplied cwd is the same
# as our current directory and get the same effect.
# Not doing this causes Unicode encoding errors when launching
# the subprocess.
cwd = None
if PY2 and cwd:
cwd = encode(cwd)
if WIN32:
# If git-cola is invoked on Windows using "start pythonw git-cola",
# a console window will briefly flash on the screen each time
# git-cola invokes git, which is very annoying. The code below
# prevents this by ensuring that any window will be hidden.
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
extra['startupinfo'] = startupinfo
if WIN32 and not no_win32_startupinfo:
CREATE_NO_WINDOW = 0x08000000
extra['creationflags'] = CREATE_NO_WINDOW
# Use line buffering when in text/universal_newlines mode,
# otherwise use the system default buffer size.
bufsize = 1 if universal_newlines else -1
return subprocess.Popen(
cmd,
bufsize=bufsize,
stdin=stdin,
stdout=stdout,
stderr=stderr,
cwd=cwd,
env=env,
universal_newlines=universal_newlines,
**extra,
)
def prep_for_subprocess(cmd, shell=False):
"""Decode on Python3, encode on Python2"""
# See the comment in start_command()
if shell:
if PY3:
cmd = decode(cmd)
else:
cmd = encode(cmd)
else:
if PY3:
cmd = [decode(c) for c in cmd]
else:
cmd = [encode(c) for c in cmd]
return cmd
@interruptable
def communicate(proc):
return proc.communicate()
def run_command(cmd, *args, **kwargs):
"""Run the given command to completion, and return its results.
This provides a simpler interface to the subprocess module.
The results are formatted as a 3-tuple: (exit_code, output, errors)
The other arguments are passed on to start_command().
"""
encoding = kwargs.pop('encoding', None)
process = start_command(cmd, *args, **kwargs)
(output, errors) = communicate(process)
output = decode(output, encoding=encoding)
errors = decode(errors, encoding=encoding)
exit_code = process.returncode
return (exit_code, output or UStr('', ENCODING), errors or UStr('', ENCODING))
@interruptable
def _fork_posix(args, cwd=None, shell=False):
"""Launch a process in the background."""
encoded_args = [encode(arg) for arg in args]
return subprocess.Popen(encoded_args, cwd=cwd, shell=shell).pid
def _fork_win32(args, cwd=None, shell=False):
"""Launch a background process using crazy win32 voodoo."""
# This is probably wrong, but it works. Windows.. Wow.
if args[0] == 'git-dag':
# win32 can't exec python scripts
args = [sys.executable] + args
if not shell:
args[0] = _win32_find_exe(args[0])
if PY3:
# see comment in start_command()
argv = [decode(arg) for arg in args]
else:
argv = [encode(arg) for arg in args]
DETACHED_PROCESS = 0x00000008 # Amazing!
return subprocess.Popen(
argv, cwd=cwd, creationflags=DETACHED_PROCESS, shell=shell
).pid
def _win32_find_exe(exe):
"""Find the actual file for a Windows executable.
This function goes through the same process that the Windows shell uses to
locate an executable, taking into account the PATH and PATHEXT environment
variables. This allows us to avoid passing shell=True to subprocess.Popen.
For reference, see:
https://technet.microsoft.com/en-us/library/cc723564.aspx#XSLTsection127121120120
"""
# try the argument itself
candidates = [exe]
# if argument does not have an extension, also try it with each of the
# extensions specified in PATHEXT
if '.' not in exe:
extensions = getenv('PATHEXT', '').split(os.pathsep)
candidates.extend([(exe + ext) for ext in extensions if ext.startswith('.')])
# search the current directory first
for candidate in candidates:
if exists(candidate):
return candidate
# if the argument does not include a path separator, search each of the
# directories on the PATH
if not os.path.dirname(exe):
for path in getenv('PATH').split(os.pathsep):
if path:
for candidate in candidates:
full_path = os.path.join(path, candidate)
if exists(full_path):
return full_path
# not found, punt and return the argument unchanged
return exe
# Portability wrappers
if sys.platform in {'win32', 'cygwin'}:
fork = _fork_win32
else:
fork = _fork_posix
def _decorator_noop(x):
return x
def wrap(action, func, decorator=None):
"""Wrap arguments with `action`, optionally decorate the result"""
if decorator is None:
decorator = _decorator_noop
@functools.wraps(func)
def wrapped(*args, **kwargs):
return decorator(func(action(*args, **kwargs)))
return wrapped
def decorate(decorator, func):
"""Decorate the result of `func` with `action`"""
@functools.wraps(func)
def decorated(*args, **kwargs):
return decorator(func(*args, **kwargs))
return decorated
def getenv(name, default=None):
return decode(os.getenv(name, default))
def guess_mimetype(filename):
"""Robustly guess a filename's mimetype"""
mimetype = None
try:
mimetype = mimetypes.guess_type(filename)[0]
except UnicodeEncodeError:
mimetype = mimetypes.guess_type(encode(filename))[0]
except (TypeError, ValueError):
mimetype = mimetypes.guess_type(decode(filename))[0]
return mimetype
def xopen(path, mode='r', encoding=None):
"""Open a file with the specified mode and encoding
The path is decoded into Unicode on Windows and encoded into bytes on Unix.
"""
return open(mkpath(path, encoding=encoding), mode)
def open_append(path, encoding=None):
"""Open a file for appending in UTF-8 text mode"""
return open(mkpath(path, encoding=encoding), 'a', encoding='utf-8')
def open_read(path, encoding=None):
"""Open a file for reading in UTF-8 text mode"""
return open(mkpath(path, encoding=encoding), encoding='utf-8')
def open_write(path, encoding=None):
"""Open a file for writing in UTF-8 text mode"""
return open(mkpath(path, encoding=encoding), 'w', encoding='utf-8')
def print_stdout(msg, linesep='\n'):
msg = msg + linesep
if PY2:
msg = encode(msg, encoding=ENCODING)
sys.stdout.write(msg)
def print_stderr(msg, linesep='\n'):
msg = msg + linesep
if PY2:
msg = encode(msg, encoding=ENCODING)
sys.stderr.write(msg)
def error(msg, status=EXIT_FAILURE, linesep='\n'):
print_stderr(msg, linesep=linesep)
sys.exit(status)
@interruptable
def node():
return platform.node()
abspath = wrap(mkpath, os.path.abspath, decorator=decode)
chdir = wrap(mkpath, os.chdir)
exists = wrap(mkpath, os.path.exists)
expanduser = wrap(encode, os.path.expanduser, decorator=decode)
if PY2:
if hasattr(os, 'getcwdu'):
getcwd = os.getcwdu
else:
getcwd = decorate(decode, os.getcwd)
else:
getcwd = os.getcwd
# NOTE: find_executable() is originally from the stdlib, but starting with
# python3.7 the stdlib no longer bundles distutils.
def _find_executable(executable, path=None):
"""Tries to find 'executable' in the directories listed in 'path'.
A string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']. Returns the complete filename or None if not found.
"""
if path is None:
path = os.environ['PATH']
paths = path.split(os.pathsep)
_, ext = os.path.splitext(executable)
if (sys.platform == 'win32') and (ext != '.exe'):
executable = executable + '.exe'
if not os.path.isfile(executable):
for dirname in paths:
filename = os.path.join(dirname, executable)
if os.path.isfile(filename):
# the file exists, we have a shot at spawn working
return filename
return None
return executable
def _fdatasync(fd):
"""fdatasync the file descriptor. Returns True on success"""
try:
os.fdatasync(fd)
except OSError:
pass
def _fsync(fd):
"""fsync the file descriptor. Returns True on success"""
try:
os.fsync(fd)
except OSError:
pass
def fsync(fd):
"""Flush contents to disk using fdatasync() / fsync()"""
has_libc_fdatasync = False
has_libc_fsync = False
has_os_fdatasync = hasattr(os, 'fdatasync')
has_os_fsync = hasattr(os, 'fsync')
if not has_os_fdatasync and not has_os_fsync:
try:
libc = ctypes.CDLL('libc.so.6')
except OSError:
libc = None
has_libc_fdatasync = libc and hasattr(libc, 'fdatasync')
has_libc_fsync = libc and hasattr(libc, 'fsync')
if has_os_fdatasync:
_fdatasync(fd)
elif has_os_fsync:
_fsync(fd)
elif has_libc_fdatasync:
libc.fdatasync(fd)
elif has_libc_fsync:
libc.fsync(fd)
def rename(old, new):
"""Rename a path. Transform arguments to handle non-ASCII file paths"""
os.rename(mkpath(old), mkpath(new))
if PY2:
find_executable = wrap(mkpath, _find_executable, decorator=decode)
else:
find_executable = wrap(decode, _find_executable, decorator=decode)
isdir = wrap(mkpath, os.path.isdir)
isfile = wrap(mkpath, os.path.isfile)
islink = wrap(mkpath, os.path.islink)
listdir = wrap(mkpath, os.listdir, decorator=decode_seq)
makedirs = wrap(mkpath, os.makedirs)
try:
readlink = wrap(mkpath, os.readlink, decorator=decode)
except AttributeError:
def _readlink_noop(p):
return p
readlink = _readlink_noop
realpath = wrap(mkpath, os.path.realpath, decorator=decode)
relpath = wrap(mkpath, os.path.relpath, decorator=decode)
remove = wrap(mkpath, os.remove)
stat = wrap(mkpath, os.stat)
unlink = wrap(mkpath, os.unlink)
if PY2:
walk = wrap(mkpath, os.walk)
else:
walk = os.walk
|