Debian Codegraph @

DisplayCAL/util_os.py

raw
1 """This module provides utility functions for operating system-related tasks."""
2
3 from __future__ import annotations
4
5 import builtins
6 import ctypes
7 import errno
8 import fnmatch
9 import glob
10 import os
11 import pathlib
12 import re
13 import shutil
14 import struct
15 import subprocess as sp
16 import sys
17 import tempfile
18 import time
19 from typing import TYPE_CHECKING, Any, Callable
20
21
22 if TYPE_CHECKING:
23 from collections.abc import Iterator
24
25 if sys.version_info >= (3, 11):
26 from typing import Self
27 else:
28 from typing_extensions import Self
29
30
31 from DisplayCAL.encoding import get_encodings
32
33 if sys.platform == "win32":
34 import msvcrt
35
36 import pywintypes
37 import win32api
38 import win32con
39 import win32file
40 import win32security
41 import winerror
42 from win32.win32file import GetFileAttributes
43 from winioctlcon import FSCTL_GET_REPARSE_POINT
44
45 if sys.platform != "win32":
46 # Linux
47 import fcntl
48 import grp
49 import pwd
50
51
52 # Cache used for safe_shell_filter() function
53 _cache = {}
54 _MAXCACHE = 100
55
56 FILE_ATTRIBUTE_REPARSE_POINT = 1024
57 IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 # Junction
58 IO_REPARSE_TAG_SYMLINK = 0xA000000C
59
60 fs_enc = get_encodings()[1]
61
62 _listdir = os.listdir
63
64
65 def setup_win32_long_paths():
66 """Add support for long paths (> 260 chars) and retry ERROR_SHARING_VIOLATION."""
67
68 def retry_sharing_violation_factory(fn, delay=0.25, maxretries=20):
69 def retry_sharing_violation(*args, **kwargs):
70 retries = 0
71 while True:
72 try:
73 return fn(*args, **kwargs)
74 except OSError as exception:
75 if (
76 exception.winerror == winerror.ERROR_SHARING_VIOLATION
77 and retries < maxretries
78 ):
79 retries += 1
80 time.sleep(delay)
81 continue
82 raise
83
84 return retry_sharing_violation
85
86 def make_win32_compatible_long_path_wrapper(fn):
87 return lambda path, *args, **kwargs: fn(
88 make_win32_compatible_long_path(path), *args, **kwargs
89 )
90
91 def make_win32_compatible_long_path_with_mode_wrapper(fn):
92 return lambda path, mode=0o777, *args, **kwargs: fn(
93 make_win32_compatible_long_path(path, 247), mode, *args, **kwargs
94 )
95
96 def make_win32_compatible_long_path_with_src_dst_wrapper(fn):
97 return lambda src, dst, *args, **kwargs: fn(
98 *[make_win32_compatible_long_path(path) for path in (src, dst)],
99 *args,
100 **kwargs,
101 )
102
103 builtins.open = make_win32_compatible_long_path_wrapper(builtins.open)
104 os.access = make_win32_compatible_long_path_wrapper(os.access)
105 os.path.exists = make_win32_compatible_long_path_wrapper(os.path.exists)
106 os.path.isdir = make_win32_compatible_long_path_wrapper(os.path.isdir)
107 os.path.isfile = make_win32_compatible_long_path_wrapper(os.path.isfile)
108 os.listdir = make_win32_compatible_long_path_wrapper(os.listdir)
109 os.lstat = make_win32_compatible_long_path_wrapper(os.lstat)
110 os.mkdir = make_win32_compatible_long_path_with_mode_wrapper(os.mkdir)
111 os.makedirs = make_win32_compatible_long_path_with_mode_wrapper(os.makedirs)
112 os.remove = retry_sharing_violation_factory(
113 make_win32_compatible_long_path_wrapper(os.remove)
114 )
115 os.rename = retry_sharing_violation_factory(
116 make_win32_compatible_long_path_with_src_dst_wrapper(os.rename)
117 )
118 os.stat = make_win32_compatible_long_path_wrapper(os.stat)
119 os.unlink = retry_sharing_violation_factory(
120 make_win32_compatible_long_path_wrapper(os.unlink)
121 )
122 win32api.GetShortPathName = make_win32_compatible_long_path_wrapper(
123 win32api.GetShortPathName
124 )
125
126
127 if sys.platform == "win32":
128 setup_win32_long_paths()
129 else:
130
131 def listdir(path, *args, **kwargs):
132 """List directory contents.
133
134 This function lists the contents of the specified directory,
135 filtering out undecodable filenames if the path is a string.
136
137 Args:
138 path (str): The path to the directory.
139 *args: Additional positional arguments.
140 **kwargs: Additional keyword arguments.
141
142 Returns:
143 list: A list of filenames in the directory.
144 """
145 paths = _listdir(path, *args, **kwargs)
146 if isinstance(path, str):
147 # Undecodable filenames will still be string objects.
148 # Ignore them.
149 paths = [path for path in paths if isinstance(path, str)]
150 return paths
151
152 os.listdir = listdir
153
154
155 def quote_args(args: list[str]) -> list[str]:
156 """Quote commandline arguments where needed.
157
158 It quotes all arguments that contain spaces or any of the characters
159 ^!$%&()[]{}=;'+,`~
160
161 Args:
162 args: (list[str]): List of commandline arguments to be quoted.
163
164 Returns:
165 list[str]: List of quoted commandline arguments.
166 """
167 args_out = []
168 for arg in args:
169 if arg is None:
170 continue
171 if re.search(r"[\^!$%&()[\]{}=;'+,`~\s]", arg):
172 arg = f'"{arg}"'
173 args_out.append(arg)
174 return args_out
175
176
177 def dlopen(name: str, handle: None | int = None):
178 """Load a shared library.
179
180 Args:
181 name (str): The name of the shared library.
182 handle (None | int): The handle of the shared library. Defaults to None.
183
184 Returns:
185 ctypes.CDLL: The loaded shared library.
186 """
187 try:
188 return ctypes.CDLL(name, handle=handle)
189 except Exception:
190 pass
191
192
193 def find_library(pattern: str, arch: None | str = None) -> str:
194 """Use ldconfig cache to find installed library.
195
196 Can use fnmatch-style pattern matching.
197
198 Args:
199 pattern (str): The pattern to match the library name.
200 arch (None | str): The architecture of the library. Defaults to None.
201
202 Returns:
203 str: The path to the library if found, otherwise None.
204 """
205 try:
206 p = sp.Popen(["/sbin/ldconfig", "-p"], stdout=sp.PIPE)
207 stdout, stderr = p.communicate()
208 except Exception:
209 return None
210
211 if not arch:
212 try:
213 p = sp.Popen(["file", "-L", sys.executable], stdout=sp.PIPE) # noqa: S607
214 file_stdout, file_stderr = p.communicate()
215 file_stdout = file_stdout.decode()
216 file_stderr = file_stderr.decode()
217 except Exception:
218 pass
219 else:
220 # /usr/bin/python3.7: ELF 64-bit LSB shared object, x86-64,
221 # version 1 (SYSV), dynamically linked, interpreter
222 # /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0,
223 # BuildID[sha1]=41a1f0d4da3afee8f22d1947cc13a9f33f59f2b8,
224 # stripped
225 parts = file_stdout.split(",")
226 if len(parts) > 1:
227 arch = parts[1].strip()
228
229 for line in stdout.decode().splitlines():
230 # libxyz.so (libc6,x86_64) => /lib64/libxyz.so.1
231 parts = line.split("=>", 1)
232 candidate = parts[0].split(None, 1)
233 if len(parts) < 2 or len(candidate) < 2:
234 continue
235 info = candidate[1].strip("( )").split(",")
236 if arch and len(info) > 1 and info[1].strip() != arch:
237 # Skip libs for wrong arch
238 continue
239 filename = candidate[0]
240 if fnmatch.fnmatch(filename, pattern):
241 return parts[1].strip()
242 return None
243
244
245 def expanduseru(path: str) -> str:
246 """Unicode version of os.path.expanduser.
247
248 Args:
249 path (str): The path to expand.
250
251 Returns:
252 str: The expanded path.
253 """
254 return str(pathlib.Path(path).expanduser())
255
256
257 def expandvarsu(path: str) -> str:
258 """Unicode version of os.path.expandvars.
259
260 Args:
261 path (str): The path to expand.
262
263 Returns:
264 str: The expanded path.
265 """
266 if sys.platform == "win32":
267 return _expandvarsu_win32(path)
268 return os.path.expandvars(path)
269
270
271 def _expandvarsu_win32(path: str) -> str:
272 """Expand environment variables in a path for Windows.
273
274 Args:
275 path (str): The path to expand.
276
277 Returns:
278 str: The expanded path.
279 """
280 if "$" not in path and "%" not in path:
281 return path
282
283 res = ""
284 index = 0
285 pathlen = len(path)
286
287 while index < pathlen:
288 c = path[index]
289 if c == "'": # no expansion within single quotes
290 path = path[index + 1 :]
291 pathlen = len(path)
292 try:
293 index = path.index("'")
294 res = res + "'" + path[: index + 1]
295 except ValueError:
296 res = res + path
297 index = pathlen - 1
298 elif c == "%": # variable or '%'
299 res = _handle_percent_sign(path, index, res)
300 elif c == "$": # variable or '$$'
301 res = _handle_dollar_sign(path, index, res)
302 else:
303 res = res + c
304 index = index + 1
305
306 return res
307
308
309 def _handle_percent_sign(path, index, res):
310 if path[index + 1 : index + 2] == "%":
311 res = res + "%"
312 index = index + 1
313 else:
314 path = path[index + 1 :]
315 pathlen = len(path)
316 try:
317 index = path.index("%")
318 except ValueError:
319 res = res + "%" + path
320 index = pathlen - 1
321 else:
322 var = path[:index]
323 res = res + getenvu(var) if var in os.environ else f"{res}%{var}%"
324 return res
325
326
327 def _handle_dollar_sign(path, index, res):
328 import string
329
330 varchars = string.ascii_letters + string.digits + "_-"
331
332 if path[index + 1 : index + 2] == "$":
333 res = res + "$"
334 index = index + 1
335 elif path[index + 1 : index + 2] == "{":
336 path = path[index + 2 :]
337 pathlen = len(path)
338 try:
339 index = path.index("}")
340 var = path[:index]
341 res = res + getenvu(var) if var in os.environ else f"{res}${{{var}}}"
342 except ValueError:
343 res = res + "${" + path
344 index = pathlen - 1
345 else:
346 var = ""
347 index = index + 1
348 c = path[index : index + 1]
349 while c != "" and c in varchars:
350 var = var + c
351 index = index + 1
352 c = path[index : index + 1]
353 res = res + getenvu(var) if var in os.environ else f"{res}${var}"
354 if c != "":
355 index = index - 1
356 return res
357
358
359 def fname_ext(path: str) -> tuple[str, str]:
360 """Get filename and extension.
361
362 Args:
363 path (str): The path to the file.
364
365 Returns:
366 tuple[str, str]: A tuple containing the filename and extension.
367 """
368 return os.path.splitext(os.path.basename(path))
369
370
371 def get_program_file(name: str, foldername: str) -> str:
372 """Get path to program file.
373
374 Args:
375 name (str): The name of the program.
376 foldername (str): The folder name.
377
378 Returns:
379 str: The path to the program file.
380 """
381 if sys.platform == "win32":
382 paths = getenvu("PATH", os.defpath).split(os.pathsep)
383 paths += safe_glob(os.path.join(getenvu("PROGRAMFILES", ""), foldername))
384 paths += safe_glob(os.path.join(getenvu("PROGRAMW6432", ""), foldername))
385 exe_ext = ".exe"
386 else:
387 paths = None
388 exe_ext = ""
389 return which(name + exe_ext, paths=paths)
390
391
392 def getenvu(name: str, default: None | str = None) -> str:
393 """Unicode version of os.getenv.
394
395 Args:
396 name (str): The name of the environment variable.
397 default (None | str): The default value if the environment variable
398 is not found. Defaults to None.
399
400 Returns:
401 str: The value of the environment variable.
402 """
403 if sys.platform == "win32":
404 name = str(name)
405 # http://stackoverflow.com/questions/2608200/problems-with-umlauts-in-python-appdata-environvent-variable
406 length = ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0)
407 if length == 0:
408 return default
409 buffer = ctypes.create_unicode_buffer("\0" * length)
410 ctypes.windll.kernel32.GetEnvironmentVariableW(name, buffer, length)
411 return buffer.value
412 var = os.getenv(name, default)
413 return var if isinstance(var, str) else var.encode(fs_enc)
414
415
416 def getgroups(username: None | str = None, names_only: bool = False) -> list[str]:
417 """Return a list of groups that user is member of.
418
419 Or groups of current process if username not given.
420
421 Args:
422 username (None | str): The username. Defaults to None.
423 names_only (bool, optional): Whether to return only the group names.
424 Defaults to False.
425
426 Returns:
427 list[str]: A list of groups.
428 """
429 if sys.platform == "win32":
430 return _getgroups_win32(username, names_only)
431 return _getgroups_unix(username, names_only)
432
433
434 def _getgroups_win32(
435 username: None | str = None, names_only: bool = False
436 ) -> list[str]:
437 """Return a list of groups that user is member of under Windows.
438
439 Or groups of current process if username not given.
440
441 Args:
442 username (None | str): The username. Defaults to None.
443 names_only (bool, optional): Whether to return only the group names.
444 Defaults to False.
445
446 Returns:
447 list[str]: A list of groups.
448 """
449 # TODO: This one doesn't discern groups from group names...
450 if username is None:
451 username = getenvu("USERNAME")
452
453 if not username:
454 return []
455
456 groups = []
457
458 try:
459 sid, domain, type_ = win32security.LookupAccountName("", username)
460 groups_sids = win32security.GetTokenInformation(
461 win32security.OpenProcessToken(
462 win32api.GetCurrentProcess(), win32security.TOKEN_QUERY
463 ),
464 win32security.TokenGroups,
465 )
466 for group_sid in groups_sids:
467 try:
468 group_name, domain, type_ = win32security.LookupAccountSid(
469 "", group_sid.Sid
470 )
471 groups.append(group_name)
472 except pywintypes.error:
473 pass
474 except ImportError:
475 pass
476
477 return groups
478
479
480 def _getgroups_unix(username: None | str = None, names_only: bool = False):
481 """Return a list of groups that user is member of under Unix.
482
483 Or groups of current process if username not given.
484
485 Args:
486 username (None | str): The username. Defaults to None.
487 names_only (bool, optional): Whether to return only the group names.
488 Defaults to False.
489
490 Returns:
491 list[str]: A list of groups.
492 """
493 groups = []
494 if username is None:
495 groups = [grp.getgrgid(g) for g in os.getgroups()]
496 else:
497 groups = [g for g in grp.getgrall() if username in g.gr_mem]
498 gid = pwd.getpwnam(username).pw_gid
499 groups.append(grp.getgrgid(gid))
500 if names_only:
501 groups = [g.gr_name for g in groups]
502 return groups
503
504
505 def islink(path: str) -> bool:
506 """Cross-platform islink implementation.
507
508 Supports Windows NT symbolic links and reparse points.
509
510 Args:
511 path (str): The path to check.
512
513 Returns:
514 bool: True if the path is a symbolic link or reparse point, otherwise False.
515 """
516 if sys.platform != "win32" or sys.getwindowsversion()[0] < 6:
517 return os.path.islink(path)
518 return bool(
519 os.path.exists(path)
520 and GetFileAttributes(path) & FILE_ATTRIBUTE_REPARSE_POINT
521 == FILE_ATTRIBUTE_REPARSE_POINT
522 )
523
524
525 def is_superuser() -> bool:
526 """Check if the current user is a superuser.
527
528 Returns:
529 bool: True if the user is a superuser, otherwise False.
530 """
531 if sys.platform == "win32":
532 if sys.getwindowsversion() >= (5, 1):
533 return bool(ctypes.windll.shell32.IsUserAnAdmin())
534 try:
535 return bool(ctypes.windll.advpack.IsNTAdmin(0, 0))
536 except Exception:
537 return False
538 else:
539 return os.geteuid() == 0
540
541
542 def launch_file(filepath: str) -> None | int:
543 """Open a file with its assigned default app.
544
545 Return tuple(returncode, stdout, stderr) or None if functionality not available.
546
547 Args:
548 filepath (str): The path to the file.
549
550 Returns:
551 None | int: The return code of the launched application.
552 """
553 retcode = None
554 kwargs = {"stdin": sp.PIPE, "stdout": sp.PIPE, "stderr": sp.PIPE}
555 if sys.platform == "darwin":
556 retcode = sp.call(["open", filepath], **kwargs) # noqa: S607
557 elif sys.platform == "win32":
558 # for win32, we could use os.startfile,
559 # but then we'd not be able to return exitcode (does it matter?)
560 startupinfo = sp.STARTUPINFO()
561 startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
562 startupinfo.wShowWindow = sp.SW_HIDE
563 kwargs = {
564 "startupinfo": startupinfo,
565 "shell": True,
566 "close_fds": True,
567 }
568 retcode = sp.call(f'start "" "{filepath}"', **kwargs)
569 elif which("xdg-open"):
570 retcode = sp.call(["xdg-open", filepath], **kwargs) # noqa: S607
571 return retcode
572
573
574 def listdir_re(path, rex: None | str = None) -> list[str]:
575 """Filter directory contents through a regular expression.
576
577 Args:
578 path (str): The path to the directory.
579 rex (None | str): The regular expression pattern. Defaults to None.
580
581 Returns:
582 list[str]: A list of files matching the regular expression.
583 """
584 files = os.listdir(path)
585 if rex:
586 rex = re.compile(rex, re.IGNORECASE)
587 files = list(filter(rex.search, files))
588 return files
589
590
591 def make_win32_compatible_long_path(path: str, maxpath: int = 259) -> str:
592 """Make a path compatible with Windows long path limitations.
593
594 Args:
595 path (str): The path to make compatible.
596 maxpath (int): The maximum path length. Defaults to 259.
597
598 Returns:
599 str: The compatible path.
600 """
601 if (
602 sys.platform == "win32"
603 and len(str(path)) > maxpath
604 and os.path.isabs(path)
605 and not str(path).startswith("\\\\?\\")
606 ):
607 path = "\\\\?\\" + path
608 return path
609
610
611 def mkstemp_bypath(path: str, dirname: None | str = None, text: bool = False):
612 """Wrap mkstemp.
613
614 Uses filename and extension from path as prefix and suffix for the temporary
615 file.
616
617 Args:
618 path (str): The path to use for generating the temporary file name.
619 dirname (None | str): The directory in which to create the temporary
620 file. Defaults to None.
621 text (bool): Whether to open the file in text mode. Defaults to False.
622
623 Returns:
624 tuple[str, str]: A tuple containing the file descriptor and the path of
625 the temporary file.
626 """
627 fname, ext = fname_ext(path)
628 if not dirname:
629 dirname = os.path.dirname(path)
630 return tempfile.mkstemp(ext, f"{fname}-", dirname, text)
631
632
633 def mksfile(filename: str) -> str:
634 """Create a file safely and return abspath.
635
636 If filename already exists, add '(n)' as suffix before extension
637 (will try up to os.TMP_MAX or 10000 for n).
638
639 Args:
640 filename (str): The name of the file to be created.
641
642 Raises:
643 IOError: If no usable temporary file name is found.
644 OSError: If an OS error occurs during file creation.
645
646 Returns:
647 str: A tuple containing the file descriptor and the absolute
648 path of the created file.
649 """
650 flags = tempfile._bin_openflags
651 fname, ext = os.path.splitext(filename)
652 for seq in range(tempfile.TMP_MAX):
653 pth = filename if not seq else f"{fname}({seq:d}){ext}"
654 # not as detailed as the previous implementation but it is dead simple.
655 if os.path.exists(pth):
656 continue
657 return os.path.abspath(pth)
658 raise OSError(errno.EEXIST, "No usable temporary file name found")
659
660
661 def movefile(src: str, dst: str, overwrite: bool = True) -> None:
662 """Move a file to another location.
663
664 dst can be a directory in which case a file with the same basename as src
665 will be created in it.
666
667 Set overwrite to True to make sure existing files are overwritten.
668
669 Args:
670 src (str): The source path.
671 dst (str): The destination path.
672 overwrite (bool): Whether to overwrite existing files. Defaults to
673 True.
674 """
675 if os.path.isdir(dst):
676 dst = os.path.join(dst, os.path.basename(src))
677 if os.path.isfile(dst) and overwrite:
678 os.remove(dst)
679 shutil.move(src, dst)
680
681
682 def putenvu(name: str, value: str) -> None:
683 """Unicode version of os.putenv (also correctly updates os.environ).
684
685 Args:
686 name (str): The name of the environment variable.
687 value (str): The value of the environment variable.
688 """
689 if sys.platform == "win32" and isinstance(value, str):
690 ctypes.windll.kernel32.SetEnvironmentVariableW(str(name), value)
691 else:
692 os.environ[name] = value.encode(fs_enc)
693
694
695 def parse_reparse_buffer(buf):
696 """Implement the below in Python:.
697
698 typedef struct _REPARSE_DATA_BUFFER {
699 ULONG ReparseTag;
700 USHORT ReparseDataLength;
701 USHORT Reserved;
702 union {
703 struct {
704 USHORT SubstituteNameOffset;
705 USHORT SubstituteNameLength;
706 USHORT PrintNameOffset;
707 USHORT PrintNameLength;
708 ULONG Flags;
709 WCHAR PathBuffer[1];
710 } SymbolicLinkReparseBuffer;
711 struct {
712 USHORT SubstituteNameOffset;
713 USHORT SubstituteNameLength;
714 USHORT PrintNameOffset;
715 USHORT PrintNameLength;
716 WCHAR PathBuffer[1];
717 } MountPointReparseBuffer;
718 struct {
719 UCHAR DataBuffer[1];
720 } GenericReparseBuffer;
721 } DUMMYUNIONNAME;
722 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
723
724 Args:
725 buf (bytes): The buffer to parse.
726
727 Returns:
728 dict: A dictionary containing the parsed reparse data.
729 """
730 # See
731 # https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntifs/ns-ntifs-_reparse_data_buffer
732
733 data = {
734 "tag": struct.unpack("<I", buf[:4])[0],
735 "data_length": struct.unpack("<H", buf[4:6])[0],
736 "reserved": struct.unpack("<H", buf[6:8])[0],
737 }
738 buf = buf[8:]
739
740 if data["tag"] in (IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK):
741 keys = [
742 "substitute_name_offset",
743 "substitute_name_length",
744 "print_name_offset",
745 "print_name_length",
746 ]
747 if data["tag"] == IO_REPARSE_TAG_SYMLINK:
748 keys.append("flags")
749
750 # Parsing
751 for k in keys:
752 if k == "flags":
753 fmt, sz = "<I", 4
754 else:
755 fmt, sz = "<H", 2
756 data[k] = struct.unpack(fmt, buf[:sz])[0]
757 buf = buf[sz:]
758
759 # Using the offset and lengths grabbed, we'll set the buffer.
760 data["buffer"] = buf
761
762 return data
763
764
765 def readlink(path: str):
766 """Cross-platform implementation of readlink.
767
768 Supports Windows NT symbolic links and reparse points.
769
770 Args:
771 path (str): The path to the symbolic link or reparse point.
772
773 Raises:
774 OSError: If the path is not a symbolic link or reparse point.
775
776 Returns:
777 str: The target path of the symbolic link or reparse point.
778 """
779 if sys.platform != "win32":
780 return os.readlink(path)
781
782 # This wouldn't return true if the file didn't exist
783 if not islink(path):
784 # Mimic POSIX error
785 raise OSError(22, "Invalid argument", path)
786
787 # Open the file correctly depending on the string type.
788 if isinstance(path, str):
789 createfilefn = win32file.CreateFileW
790 else:
791 createfilefn = win32file.CreateFile
792
793 # Create a PySECURITY_ATTRIBUTES object
794 security_attributes = win32security.SECURITY_ATTRIBUTES()
795
796 # FILE_FLAG_OPEN_REPARSE_POINT alone is not enough if 'path' is a symbolic
797 # link to a directory or a NTFS junction.
798 # We need to set FILE_FLAG_BACKUP_SEMANTICS as well. See
799 # https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea
800 # Now use this security_attributes object in the CreateFileW call
801 handle = createfilefn(
802 path,
803 win32file.GENERIC_READ,
804 0,
805 security_attributes,
806 win32file.OPEN_EXISTING,
807 win32file.FILE_FLAG_BACKUP_SEMANTICS | win32file.FILE_FLAG_OPEN_REPARSE_POINT,
808 0,
809 )
810
811 # Ensure handle is of type int
812 if isinstance(handle, pywintypes.HANDLEType):
813 handle = int(handle)
814 elif isinstance(handle, int):
815 handle = msvcrt.get_osfhandle(handle)
816 else:
817 handle = int(str(handle))
818
819 # MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 = (16 * 1024)
820 buf = win32file.DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, None, 16 * 1024)
821 # Above will return an ugly string (byte array), so we'll need to parse it.
822
823 # But first, we'll close the handle to our file so we're not locking it anymore.
824 win32file.CloseHandle(handle)
825
826 # Minimum possible length (assuming that the length is bigger than 0)
827 if len(buf) < 9:
828 return type(path)()
829 # Parse and return our result.
830 result = parse_reparse_buffer(buf)
831 if result["tag"] in (IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK):
832 offset = result["substitute_name_offset"]
833 ending = offset + result["substitute_name_length"]
834 rpath = result["buffer"][offset:ending].decode("UTF-16-LE")
835 else:
836 rpath = result["buffer"]
837 if len(rpath) > 4 and rpath[0:4] == "\\??\\":
838 rpath = rpath[4:]
839 return rpath
840
841
842 def safe_glob(pathname: str) -> list[str]:
843 """Return a list of paths matching a pathname pattern.
844
845 The pattern may contain simple shell-style wildcards a la fnmatch.
846 However, unlike fnmatch, filenames starting with a dot are special cases
847 that are not matched by '*' and '?' patterns.
848
849 Like fnmatch.glob, but suppresses re.compile errors by escaping
850 uncompilable path components.
851
852 See https://bugs.python.org/issue738361
853
854 Args:
855 pathname (str): The pathname pattern.
856
857 Returns:
858 list[str]: A list of paths matching the pattern.
859 """
860 return list(safe_iglob(pathname))
861
862
863 def safe_iglob(pathname: str) -> Iterator[str]:
864 """Return an iterator which yields the paths matching a pathname pattern.
865
866 The pattern may contain simple shell-style wildcards a la fnmatch.
867 However, unlike fnmatch, filenames starting with a dot are special cases
868 that are not matched by '*' and '?' patterns.
869
870 Like fnmatch.iglob, but suppresses re.compile errors by escaping
871 uncompilable path components.
872
873 See https://bugs.python.org/issue738361
874
875 Args:
876 pathname (str): The pathname pattern.
877
878 Yields:
879 str: The paths matching the pattern.
880 """
881 dirname, basename = os.path.split(pathname)
882 if not glob.has_magic(pathname):
883 if basename:
884 if os.path.lexists(pathname):
885 yield pathname
886 # Patterns ending with a slash should match only directories
887 elif os.path.isdir(dirname):
888 yield pathname
889 return
890 if not dirname:
891 for name in safe_glob1(os.curdir, basename):
892 yield name
893 return
894 # `os.path.split()` returns the argument itself as a dirname if it is a
895 # drive or UNC path.
896 # Prevent an infinite recursion if a drive or UNC path contains magic
897 # characters (i.e. r'\\?\C:').
898 if dirname != pathname and glob.has_magic(dirname):
899 dirs = safe_iglob(dirname)
900 else:
901 dirs = [dirname]
902 glob_in_dir = safe_glob1 if glob.has_magic(basename) else glob.glob0
903 for dirname in dirs:
904 for name in glob_in_dir(dirname, basename):
905 yield os.path.join(dirname, name)
906
907
908 def safe_glob1(dirname, pattern):
909 """Return the subset of the list NAMES that match PAT.
910
911 Args:
912 dirname (str): The directory name.
913 pattern (str): The pattern to match.
914
915 Returns:
916 list: The subset of names that match the pattern.
917 """
918 if not dirname:
919 dirname = os.curdir
920 if isinstance(pattern, str) and not isinstance(dirname, str):
921 dirname = str(dirname, sys.getfilesystemencoding() or sys.getdefaultencoding())
922 try:
923 names = os.listdir(dirname)
924 except OSError:
925 return []
926 if pattern[0] != ".":
927 names = [x for x in names if x[0] != "."]
928 return safe_shell_filter(names, pattern)
929
930
931 def safe_shell_filter(names, pat):
932 """Return the subset of the list NAMES that match PAT.
933
934 Like fnmatch.filter, but suppresses re.compile errors by escaping
935 uncompilable path components.
936
937 See https://bugs.python.org/issue738361
938
939 Args:
940 names (list): The list of names.
941 pat (str): The pattern to match.
942
943 Returns:
944 list: The subset of names that match the pattern.
945 """
946 import posixpath
947
948 result = []
949 pat = os.path.normcase(pat)
950 try:
951 re_pat = _cache[pat]
952 except KeyError:
953 res = safe_translate(pat)
954 if len(_cache) >= _MAXCACHE:
955 _cache.clear()
956 _cache[pat] = re_pat = re.compile(res)
957 match = re_pat.match
958 if os.path is posixpath:
959 # normcase on posix is NOP. Optimize it away from the loop.
960 result = [name for name in names if match(name)]
961 else:
962 result = [name for name in names if match(os.path.normcase(name))]
963 return result
964
965
966 def safe_translate(pat: str) -> str:
967 """Translate a shell PATTERN to a regular expression.
968
969 Like fnmatch.translate, but suppresses re.compile errors by escaping
970 uncompilable path components.
971
972 See https://bugs.python.org/issue738361
973
974 Args:
975 pat (str): The shell pattern.
976
977 Returns:
978 str: The translated regular expression.
979 """
980 if isinstance(getattr(os.path, "altsep", None), str):
981 # Normalize path separators
982 pat = pat.replace(os.path.altsep, os.path.sep)
983 components = pat.split(os.path.sep)
984 for i, component in enumerate(components):
985 translated = fnmatch.translate(component)
986 try:
987 re.compile(translated)
988 except re.error:
989 translated = re.escape(component)
990 components[i] = translated
991 return re.escape(os.path.sep).join(components)
992
993
994 def waccess(path: str, mode: int) -> bool:
995 """Test access to path.
996
997 Args:
998 path (str): The path to test.
999 mode (int): The access mode.
1000
1001 Returns:
1002 bool: True if access is granted, otherwise False.
1003 """
1004 if mode & os.R_OK:
1005 try:
1006 with open(path, "rb"):
1007 pass
1008 except OSError:
1009 return False
1010 if mode & os.W_OK:
1011 directory = path if os.path.isdir(path) else os.path.dirname(path)
1012 try:
1013 if os.path.isfile(path):
1014 with open(path, "ab"):
1015 pass
1016 else:
1017 with tempfile.TemporaryFile(prefix=".", dir=directory):
1018 pass
1019 except OSError:
1020 return False
1021 if mode & os.X_OK:
1022 return os.access(path, mode)
1023 return True
1024
1025
1026 def which(executable: str, paths: None | list[str] = None) -> None | str:
1027 """Return the full path of executable.
1028
1029 Args:
1030 executable (str): The name of the executable.
1031 paths (None | list[str]): The list of paths to search. Defaults to None.
1032
1033 Returns:
1034 None | str: The full path of the executable if found, otherwise None.
1035 """
1036 if not paths:
1037 paths = getenvu("PATH", os.defpath).split(os.pathsep)
1038 for cur_dir in paths:
1039 filename = os.path.join(cur_dir, executable)
1040 if os.path.isfile(filename):
1041 try:
1042 # make sure file is actually executable
1043 if os.access(filename, os.X_OK):
1044 return filename
1045 except Exception:
1046 pass
1047 return None
1048
1049
1050 def whereis(
1051 names: list[str],
1052 search_for_binaries: bool = True,
1053 bin_paths: None | list[str] = None,
1054 man: bool = True,
1055 man_paths: None | list[str] = None,
1056 src: bool = True,
1057 src_paths: None | list[str] = None,
1058 unusual: bool = False,
1059 list_paths: bool = False,
1060 ):
1061 """Wrap whereis.
1062
1063 Args:
1064 names (list[str]): The names to search for.
1065 search_for_binaries (bool): Whether to search for binaries. Defaults to True.
1066 bin_paths (None | list[str]): The list of binary paths. Defaults to None.
1067 man (bool): Whether to search for man pages. Defaults to True.
1068 man_paths (None | list[str]): The list of man paths. Defaults to None.
1069 src (bool): Whether to search for source files. Defaults to True.
1070 src_paths (None | list[str]): The list of source paths. Defaults to None.
1071 unusual (bool): Whether to search for unusual files. Defaults to False.
1072 list_paths (bool): Whether to list paths. Defaults to False.
1073
1074 Returns:
1075 dict: The results of the whereis command.
1076 """
1077 args = build_whereis_args(
1078 search_for_binaries,
1079 bin_paths,
1080 man,
1081 man_paths,
1082 src,
1083 src_paths,
1084 unusual,
1085 list_paths,
1086 )
1087 return execute_whereis(names, args)
1088
1089
1090 def build_whereis_args(
1091 search_for_binaries: bool,
1092 bin_paths: list[str],
1093 man: bool,
1094 man_paths: list[str],
1095 src: bool,
1096 src_paths: list[str],
1097 unusual: bool,
1098 list_paths: list[str],
1099 ) -> list[str]:
1100 """Build arguments for the whereis command.
1101
1102 Args:
1103 search_for_binaries (bool): Whether to search for binaries.
1104 bin_paths (list[str]): The list of binary paths.
1105 man (bool): Whether to search for man pages.
1106 man_paths (list[str]): The list of man paths.
1107 src (bool): Whether to search for source files.
1108 src_paths (list[str]): The list of source paths.
1109 unusual (bool): Whether to search for unusual files.
1110 list_paths (bool): Whether to list paths.
1111
1112 Returns:
1113 list[str]: The list of arguments for the whereis command.
1114 """
1115 args = []
1116 if search_for_binaries:
1117 args.append("-b")
1118 if bin_paths:
1119 args.append("-B")
1120 args.extend(bin_paths)
1121 if man:
1122 args.append("-m")
1123 if man_paths:
1124 args.append("-M")
1125 args.extend(man_paths)
1126 if src:
1127 args.append("-s")
1128 if src_paths:
1129 args.append("-S")
1130 args.extend(src_paths)
1131 if bin_paths or man_paths or src_paths:
1132 args.append("-f")
1133 if unusual:
1134 args.append("-u")
1135 if list_paths:
1136 args.append("-l")
1137 return args
1138
1139
1140 def execute_whereis(names: list[str], args: list[Any]) -> dict:
1141 """Execute the whereis command with the given arguments.
1142
1143 Args:
1144 names (list[str]): The names to search for.
1145 args (list[Any]): The list of arguments for the whereis command.
1146
1147 Returns:
1148 dict: The results of the whereis command.
1149 """
1150 if isinstance(names, str):
1151 names = [names]
1152 p = sp.Popen(["whereis", *args, *names], stdout=sp.PIPE) # noqa: S607
1153 stdout, stderr = p.communicate()
1154 return parse_whereis_output(stdout)
1155
1156
1157 def parse_whereis_output(stdout: bytes) -> dict:
1158 """Parse the output of the whereis command.
1159
1160 Args:
1161 stdout (bytes): The output of the whereis command.
1162
1163 Returns:
1164 dict: The parsed results of the whereis command.
1165 """
1166 result = {}
1167 for line in stdout.decode().strip().splitlines():
1168 match = line.split(":", 1)
1169 if match:
1170 result[match[0]] = match[-1].split()
1171 return result
1172
1173
1174 class FileLock:
1175 """A context manager for file locking.
1176
1177 Args:
1178 file_ (file): The file to lock.
1179 exclusive (bool): Whether to acquire an exclusive lock. Defaults to False.
1180 blocking (bool): Whether to block until the lock is acquired. Defaults to False.
1181 """
1182
1183 if sys.platform == "win32":
1184 _exception_cls = pywintypes.error
1185 else:
1186 _exception_cls = IOError
1187
1188 def __init__(self, file_, exclusive=False, blocking=False):
1189 self._file = file_
1190 self.exclusive = exclusive
1191 self.blocking = blocking
1192 self.lock()
1193
1194 def __enter__(self) -> Self:
1195 """Enter the context manager.
1196
1197 Returns:
1198 FileLock: The FileLock instance.
1199 """
1200 return self
1201
1202 def __exit__(self, exc_type, exc_value, traceback):
1203 """Exit the context manager."""
1204 self.unlock()
1205
1206 def lock(self):
1207 """Acquire the lock."""
1208 if sys.platform == "win32":
1209 mode = 0
1210 if self.exclusive:
1211 mode |= win32con.LOCKFILE_EXCLUSIVE_LOCK
1212 if not self.blocking:
1213 mode |= win32con.LOCKFILE_FAIL_IMMEDIATELY
1214 self._handle = msvcrt.get_osfhandle(self._file.fileno())
1215 self._overlapped = pywintypes.OVERLAPPED()
1216 fn = win32file.LockFileEx
1217 args = (self._handle, mode, 0, -0x10000, self._overlapped)
1218 else:
1219 op = fcntl.LOCK_EX if self.exclusive else fcntl.LOCK_SH
1220 if not self.blocking:
1221 op |= fcntl.LOCK_NB
1222 fn = fcntl.flock
1223 args = (self._file.fileno(), op)
1224 self._call(fn, args, LockingError)
1225
1226 def unlock(self):
1227 """Release the lock."""
1228 if self._file.closed:
1229 return
1230 if sys.platform == "win32":
1231 fn = win32file.UnlockFileEx
1232 args = (self._handle, 0, -0x10000, self._overlapped)
1233 else:
1234 fn = fcntl.flock
1235 args = (self._file.fileno(), fcntl.LOCK_UN)
1236 self._call(fn, args, UnlockingError)
1237
1238 @staticmethod
1239 def _call(fn: Callable, args: tuple[Any], exception_cls: type) -> None:
1240 """Call the function with the given arguments.
1241
1242 Args:
1243 fn (Callable): The function to call.
1244 args (tuple[Any]): The arguments to pass to the function.
1245 exception_cls (Type): The exception class to raise.
1246
1247 Raises:
1248 exception_cls: If the function call fails.
1249 """
1250 try:
1251 fn(*args)
1252 except FileLock._exception_cls as exception:
1253 raise exception_cls(*exception.args) from exception
1254
1255
1256 class Error(Exception):
1257 """Base class for exceptions in this module."""
1258
1259
1260 class LockingError(Error):
1261 """Exception raised for errors in locking."""
1262
1263
1264 class UnlockingError(Error):
1265 """Exception raised for errors in unlocking."""
1266
1267
1268 if sys.platform == "win32" and sys.getwindowsversion() >= (6,):
1269
1270 class win64_disable_file_system_redirection: # noqa: N801
1271 r"""Disable Windows File System Redirection.
1272
1273 When a 32 bit program runs on a 64 bit Windows the paths to C:\Windows\System32
1274 automatically get redirected to the 32 bit version (C:\Windows\SysWow64),
1275 if you really do need to access the contents of System32,
1276 you need to disable the file system redirection first.
1277
1278 # http://code.activestate.com/recipes/578035-disable-file-system-redirector/
1279 """
1280
1281 _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
1282 _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
1283
1284 def __enter__(self):
1285 """Enter the context manager."""
1286 self.old_value = ctypes.c_long()
1287 self.success = self._disable(ctypes.byref(self.old_value))
1288
1289 def __exit__(self, exc_type, exc_value, traceback):
1290 """Exit the context manager."""
1291 if self.success:
1292 self._revert(self.old_value)