youpdated-scanning 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,245 @@
1
+ """Installed Steam games, from each library's app manifests
2
+
3
+ Steam lists libraries in ``steamapps/libraryfolders.vdf`` under its install directory. Each has an ``appmanifest_<appid>.acf`` per app, with ``appid``, ``name``, ``buildid``, ``installdir``.
4
+ Both are Valve KeyValues text, parsed here rather than with a dependency.
5
+
6
+ Manifests are read rather than ``steamapps/common``.
7
+ Not every manifest is a game: redistributables, Proton, and the Steam Linux Runtime are ignored.
8
+
9
+ On macOS a library on an external drive, or in Desktop, Documents, Downloads, or iCloud Drive, makes macOS confirm before letting the terminal read it.
10
+ A whole-machine scan skips it. ``youpdated scan --only steam`` reads them.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ from pathlib import Path, PurePath
19
+ from typing import Any, ClassVar, Iterable, Iterator, Sequence
20
+
21
+ from .base import Installed
22
+
23
+ # Tools Steam installs alongside games
24
+ TOOL_APPIDS: frozenset[str] = frozenset({
25
+ "228980", # Steamworks Common Redistributables
26
+ "1007", # Steamworks SDK Redist
27
+ })
28
+ TOOL_NAME_RE = re.compile(r"^(?:Proton(?: |$)|Steam Linux Runtime|Steamworks (?:Common Redistributables|SDK Redist))")
29
+
30
+ _TOKEN_RE = re.compile(r'\s+|//[^\n]*|"((?:[^"\\]|\\.)*)"|([{}])|([^\s{}"]+)', re.DOTALL)
31
+ _ESCAPES = {"n": "\n", "t": "\t", "\\": "\\", '"': '"'}
32
+
33
+
34
+ def parse_keyvalues(text: str) -> dict[str, Any]:
35
+ """Valve KeyValues text (``.vdf``/``.acf``) as nested dicts"""
36
+ tokens = _tokens(text)
37
+ root: dict[str, Any] = {}
38
+ stack = [root]
39
+ key: str | None = None
40
+ for token, kind in tokens:
41
+ if kind == "bare" and token.startswith("[") and token.endswith("]"):
42
+ # A platform conditional, `"key" "value" [$WIN32]`
43
+ continue
44
+ if kind == "{":
45
+ if key is None:
46
+ raise ValueError("`{` without a key before it")
47
+ child: dict[str, Any] = {}
48
+ stack[-1][key] = child
49
+ stack.append(child)
50
+ key = None
51
+ elif kind == "}":
52
+ if key is not None or len(stack) == 1:
53
+ raise ValueError("unexpected `}`")
54
+ stack.pop()
55
+ elif key is None:
56
+ key = token
57
+ else:
58
+ stack[-1][key] = token
59
+ key = None
60
+ if key is not None or len(stack) != 1:
61
+ raise ValueError("ended inside a section")
62
+ return root
63
+
64
+
65
+ def _tokens(text: str) -> Iterator[tuple[str, str]]:
66
+ """(text, kind) pairs, kind being ``{``, ``}``, ``quoted``, or ``bare``"""
67
+ position = 0
68
+ while position < len(text):
69
+ match = _TOKEN_RE.match(text, position)
70
+ if match is None:
71
+ raise ValueError(f"unterminated string at character {position}")
72
+ position = match.end()
73
+ quoted, brace, bare = match.groups()
74
+ if brace:
75
+ yield brace, brace
76
+ elif quoted is not None:
77
+ yield re.sub(r"\\(.)", lambda m: _ESCAPES.get(m.group(1), m.group(0)), quoted, flags=re.DOTALL), "quoted"
78
+ elif bare is not None:
79
+ yield bare, "bare"
80
+
81
+
82
+ def _get(section: Any, key: str) -> Any:
83
+ """``section[key]``, ignoring case"""
84
+ if not isinstance(section, dict):
85
+ return None
86
+ if key in section:
87
+ return section[key]
88
+ lower = key.lower()
89
+ return next((value for name, value in section.items() if name.lower() == lower), None)
90
+
91
+
92
+ def _read_keyvalues(path: Path) -> dict[str, Any] | None:
93
+ try:
94
+ return parse_keyvalues(path.read_text(encoding="utf-8", errors="replace"))
95
+ except (OSError, ValueError):
96
+ return None
97
+
98
+
99
+ def steam_roots() -> list[Path]:
100
+ """Where Steam is installed on this OS"""
101
+ home = Path.home()
102
+ if sys.platform == "darwin":
103
+ candidates = [home / "Library" / "Application Support" / "Steam"]
104
+ elif sys.platform == "win32":
105
+ candidates = [*_registry_roots(), Path(os.environ.get("PROGRAMFILES(X86)", r"C:\Program Files (x86)")) / "Steam"]
106
+ else:
107
+ candidates = [
108
+ home / ".steam" / "steam",
109
+ home / ".local" / "share" / "Steam",
110
+ # Flathub's and Snap's Steam
111
+ home / ".var" / "app" / "com.valvesoftware.Steam" / ".local" / "share" / "Steam",
112
+ home / "snap" / "steam" / "common" / ".local" / "share" / "Steam",
113
+ ]
114
+ roots: list[Path] = []
115
+ for path in candidates:
116
+ if _steamapps(path) is not None and path.resolve() not in roots:
117
+ roots.append(path.resolve())
118
+ return roots
119
+
120
+
121
+ def _registry_roots() -> list[Path]:
122
+ """Steam's install directory as it recorded it, for installs off the default drive"""
123
+ try:
124
+ import winreg
125
+ except ImportError:
126
+ return []
127
+ found = []
128
+ for hive, key, value in (
129
+ (winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam", "SteamPath"),
130
+ (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Valve\Steam", "InstallPath"),
131
+ (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Valve\Steam", "InstallPath"),
132
+ ):
133
+ try:
134
+ with winreg.OpenKey(hive, key) as opened:
135
+ path, _ = winreg.QueryValueEx(opened, value)
136
+ except OSError:
137
+ continue
138
+ if isinstance(path, str) and path:
139
+ found.append(Path(path))
140
+ return found
141
+
142
+
143
+ def _steamapps(library: Path) -> Path | None:
144
+ for name in ("steamapps", "SteamApps"):
145
+ if (library / name).is_dir():
146
+ return library / name
147
+ return None
148
+
149
+
150
+ # macOS permissioned folders
151
+ GUARDED_FOLDERS: tuple[tuple[tuple[str, ...], str], ...] = (
152
+ (("Desktop",), "your Desktop folder"),
153
+ (("Documents",), "your Documents folder"),
154
+ (("Downloads",), "your Downloads folder"),
155
+ (("Library", "Mobile Documents"), "iCloud Drive"),
156
+ )
157
+
158
+
159
+ def guarded(path: PurePath, home: PurePath | None = None) -> str | None:
160
+ """What macOS would ask the terminal to read for ``path``, or None. Found from the path"""
161
+ if sys.platform != "darwin":
162
+ return None
163
+ parts = path.parts
164
+ # Steam keeps the path as it was picked. A library on the startup disk is under /Users
165
+ if len(parts) > 2 and parts[:2] == ("/", "Volumes"):
166
+ return f"files on {parts[2]}, which is another drive"
167
+ home_parts = (home or Path.home()).parts
168
+ for folder, name in GUARDED_FOLDERS:
169
+ if parts[: len(home_parts) + len(folder)] == (*home_parts, *folder):
170
+ return name
171
+ return None
172
+
173
+
174
+ def libraries(root: Path) -> list[Path]:
175
+ """``root`` and the libraries its ``libraryfolders.vdf`` lists"""
176
+ found = [root]
177
+ steamapps = _steamapps(root)
178
+ listed = _get(_read_keyvalues(steamapps / "libraryfolders.vdf"), "libraryfolders") if steamapps else None
179
+ for key, value in (listed or {}).items() if isinstance(listed, dict) else ():
180
+ if not key.isdigit():
181
+ # `TimeNextStatsReport`, `ContentStatsID` in the old format
182
+ continue
183
+ # Each library is a section with a `path` now. It used to be the value itself
184
+ path = _get(value, "path") if isinstance(value, dict) else value
185
+ if isinstance(path, str) and path:
186
+ library = Path(path)
187
+ # resolve() would read the guarded place, and macOS would ask
188
+ library = Path(os.path.normpath(library)) if guarded(library) else library.resolve()
189
+ if library not in found:
190
+ found.append(library)
191
+ return found
192
+
193
+
194
+ class SteamScanner:
195
+ name: ClassVar[str] = "steam"
196
+ summary: ClassVar[str] = "Steam games in every library"
197
+ sources: ClassVar[tuple[str, ...]] = ("steam",)
198
+ asks_first: ClassVar[bool] = True
199
+
200
+ def __init__(self, roots: Sequence[Path] | None = None) -> None:
201
+ self.roots = roots
202
+ # Why the last scan skipped a library, for `scan()` to warn with
203
+ self.notes: list[str] = []
204
+
205
+ def available(self) -> bool:
206
+ return bool(steam_roots() if self.roots is None else self.roots)
207
+
208
+ def scan(self, *, guarded_too: bool = False) -> Iterable[Installed]:
209
+ """``guarded_too`` reads the libraries macOS asks about, see the module's docstring"""
210
+ self.notes = []
211
+ seen: set[str] = set()
212
+ libraries_seen: list[Path] = []
213
+ for root in steam_roots() if self.roots is None else self.roots:
214
+ for library in libraries(root):
215
+ if library in libraries_seen:
216
+ continue
217
+ libraries_seen.append(library)
218
+ asks = guarded(library)
219
+ if asks and not guarded_too:
220
+ self.notes.append(
221
+ f"skipped the library at {library}: macOS asks before a terminal reads {asks}. "
222
+ "`youpdated scan --only steam` reads it, once allowed"
223
+ )
224
+ continue
225
+ steamapps = _steamapps(library)
226
+ if steamapps is None:
227
+ continue
228
+ for manifest in sorted(steamapps.glob("appmanifest_*.acf")):
229
+ found = self.read(manifest, steamapps)
230
+ if found is not None and found.entry not in seen:
231
+ seen.add(found.entry)
232
+ yield found
233
+
234
+ def read(self, manifest: Path, steamapps: Path) -> Installed | None:
235
+ app = _get(_read_keyvalues(manifest), "AppState")
236
+ appid, name = _get(app, "appid"), _get(app, "name")
237
+ if not isinstance(appid, str) or not appid.isdigit():
238
+ return None
239
+ name = name.strip() if isinstance(name, str) and name.strip() else None
240
+ if appid in TOOL_APPIDS or (name and TOOL_NAME_RE.match(name)):
241
+ return None
242
+ installdir = _get(app, "installdir")
243
+ where = (steamapps / "common" / installdir).resolve() if isinstance(installdir, str) and installdir else None
244
+ # No version: the manifest's `buildid` is a build number, and Steam's news items have no version to compare it to
245
+ return Installed("steam", appid, name, None, where)
@@ -0,0 +1,68 @@
1
+ """Python tools installed with ``uv tool install``
2
+
3
+ ``uv tool list`` gives each tool's package and version, one ``name v1.2.3`` line each, followed by commands
4
+
5
+ ``UV_OFFLINE`` keeps uv from the network, and Youpdated itself is ignored
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import shutil
12
+ import tomllib
13
+ from pathlib import Path
14
+ from typing import ClassVar, Iterable
15
+
16
+ from .base import Installed, run
17
+ from .pipx import SELF, normalize
18
+
19
+ ENV = {"UV_OFFLINE": "1", "UV_NO_PROGRESS": "1", "UV_PYTHON_DOWNLOADS": "never", "NO_COLOR": "1"}
20
+ TIMEOUT = 60
21
+ _TOOL_RE = re.compile(r"^(?P<name>[A-Za-z0-9][A-Za-z0-9._-]*) v(?P<version>\S+)")
22
+ NOT_PYPI = ("git", "url", "path", "directory", "editable", "index")
23
+
24
+
25
+ def parse_list(text: str) -> list[tuple[str, str]]:
26
+ """``uv tool list`` output as (package, version)"""
27
+ tools = []
28
+ for line in text.splitlines():
29
+ match = _TOOL_RE.match(line.strip())
30
+ if match:
31
+ tools.append((match["name"], match["version"]))
32
+ return tools
33
+
34
+
35
+ def from_pypi(receipt: Path, package: str) -> bool:
36
+ """``package``'s requirement in ``receipt`` is from PyPI. A receipt that can't be read is PyPI"""
37
+ try:
38
+ doc = tomllib.loads(receipt.read_text(encoding="utf-8"))
39
+ except (OSError, ValueError):
40
+ return True
41
+ requirements = doc.get("tool", {}).get("requirements")
42
+ for requirement in requirements if isinstance(requirements, list) else ():
43
+ if isinstance(requirement, dict) and normalize(str(requirement.get("name", ""))) == normalize(package):
44
+ return not any(key in requirement for key in NOT_PYPI)
45
+ return True
46
+
47
+
48
+ class UvScanner:
49
+ name: ClassVar[str] = "uv"
50
+ summary: ClassVar[str] = "Python tools installed with uv"
51
+ sources: ClassVar[tuple[str, ...]] = ("pypi",)
52
+
53
+ def available(self) -> bool:
54
+ return shutil.which("uv") is not None
55
+
56
+ def uv(self, *args: str) -> str:
57
+ return run("uv", *args, timeout=TIMEOUT, env=ENV)
58
+
59
+ def scan(self) -> Iterable[Installed]:
60
+ tools = parse_list(self.uv("tool", "list"))
61
+ if not tools:
62
+ return
63
+ root = Path(self.uv("tool", "dir").strip())
64
+ for package, version in tools:
65
+ # each tool's folder is its normalized name
66
+ if normalize(package) in SELF or not from_pypi(root / normalize(package) / "uv-receipt.toml", package):
67
+ continue
68
+ yield Installed("pypi", package, package, version)
@@ -0,0 +1,318 @@
1
+ """Windows programs winget knows, by package id, matched offline against winget's own index
2
+
3
+ ``winget export`` would work, but it refreshes winget's source index.
4
+
5
+ Reads:
6
+ - The programs in Add or Remove Programs, from the registry's ``Uninstall`` keys (both views of HKLM, and HKCU)
7
+ - The MSIX packages registered for this user, by package family name
8
+ - winget's index of the ``winget`` source, ``Public\\index.db`` in the ``Microsoft.Winget.Source`` package (schema 2)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import shutil
15
+ import sqlite3
16
+ import sys
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import ClassVar, Iterable, Protocol
20
+
21
+ from .base import Installed, ScanError
22
+ from .wingetnames import for_index
23
+
24
+ SOURCE_FAMILY = "Microsoft.Winget.Source_8wekyb3d8bbwe"
25
+ UNINSTALL = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"
26
+ APP_REPOSITORY = r"Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages"
27
+ FRAMEWORK_RE = re.compile(r"^Microsoft\.(?:VCLibs|UI\.Xaml|WindowsAppRuntime|VCRedist|DotNet\.Framework)\.", re.IGNORECASE)
28
+ NO_INDEX = (
29
+ "winget's package index isn't on this machine. Install App Installer from the Microsoft Store, "
30
+ "or run `winget source update`"
31
+ )
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Program:
36
+ """An Add or Remove Programs entry"""
37
+
38
+ key: str
39
+ name: str
40
+ publisher: str = ""
41
+ version: str | None = None
42
+ # InstallLocation, where recorded
43
+ location: str | None = None
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Package:
48
+ """A registered MSIX package"""
49
+
50
+ family: str
51
+ version: str | None = None
52
+
53
+
54
+ def parse_package_full_name(full: str) -> Package | None:
55
+ """``Name_Version_Arch_ResourceId_PublisherId`` as its family name, ``Name_PublisherId``, and version"""
56
+ parts = full.split("_")
57
+ if len(parts) != 5 or not parts[0] or not parts[4]:
58
+ return None
59
+ return Package(f"{parts[0]}_{parts[4]}", parts[1] or None)
60
+
61
+
62
+ def _version_key(version: str) -> tuple[int, ...]:
63
+ return tuple(int(part) for part in re.findall(r"\d+", version))
64
+
65
+
66
+ class Index:
67
+ """winget's ``index.db`` for the ``winget`` source, opened read-only"""
68
+
69
+ def __init__(self, path: Path) -> None:
70
+ self.path = path
71
+ try:
72
+ self.db = sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro&immutable=1", uri=True)
73
+ except sqlite3.Error as exc:
74
+ raise ScanError(f"cannot read winget's index at {path}: {exc}") from None
75
+ meta = dict(self._query("SELECT name, value FROM metadata"))
76
+ if meta.get("majorVersion") != "2":
77
+ self.close()
78
+ raise ScanError(
79
+ f"winget's index at {path} is schema {meta.get('majorVersion', '?')}, expected 2. Update App Installer"
80
+ )
81
+
82
+ def _query(self, sql: str, params: tuple = ()) -> list[tuple]:
83
+ """``sql``'s rows"""
84
+ try:
85
+ return self.db.execute(sql, params).fetchall()
86
+ except sqlite3.Error as exc:
87
+ self.close()
88
+ raise ScanError(f"cannot read winget's index at {self.path}: {exc}") from None
89
+
90
+ def close(self) -> None:
91
+ self.db.close()
92
+
93
+ def package(self, package_id: str) -> tuple[str, str] | None:
94
+ """(id, name) of ``package_id``, matched case-insensitively as winget does"""
95
+ rows = self._query("SELECT id, name FROM packages WHERE id = ? COLLATE NOCASE", (package_id,))
96
+ return (rows[0][0], rows[0][1]) if rows else None
97
+
98
+ def numbers_installs_apart(self, package_id: str) -> bool:
99
+ """If any of ``package_id``'s installers writes a version differently than the package's"""
100
+ rows = self._query("SELECT arp_min_version, arp_max_version FROM packages WHERE id = ?", (package_id,))
101
+ return any(value for row in rows for value in row)
102
+
103
+ def match_program(self, program: Program) -> tuple[str, str] | None:
104
+ """The package ``program`` is, if exactly one is"""
105
+ if program.key.endswith(f"_{SOURCE_FAMILY}"):
106
+ # A portable winget installed, its key the package id and the source
107
+ found = self.package(program.key.removesuffix(f"_{SOURCE_FAMILY}"))
108
+ if found:
109
+ return found
110
+ normalized = for_index(program.name, program.publisher)
111
+ names = [normalized.name_with_architecture()] if normalized.architecture else []
112
+ names.append(normalized.name)
113
+ for name in names:
114
+ rows = self._query(
115
+ """
116
+ SELECT p.rowid, p.id, p.name, p.arp_min_version, p.arp_max_version, 1 FROM productcodes2 c
117
+ JOIN packages p ON p.rowid = c.package WHERE c.productcode = ?
118
+ UNION
119
+ SELECT p.rowid, p.id, p.name, p.arp_min_version, p.arp_max_version, 0 FROM norm_names2 n
120
+ JOIN norm_publishers2 u ON u.package = n.package
121
+ JOIN packages p ON p.rowid = n.package
122
+ WHERE n.norm_name = ? AND u.norm_publisher = ?
123
+ """,
124
+ (program.key.casefold(), name, normalized.publisher),
125
+ )
126
+ if rows:
127
+ return _pick(rows, program.version)
128
+ return None
129
+
130
+ def match_package(self, package: Package) -> tuple[str, str] | None:
131
+ rows = self._query(
132
+ "SELECT p.id, p.name FROM pfns2 f JOIN packages p ON p.rowid = f.package WHERE f.pfn = ?",
133
+ (package.family.casefold(),),
134
+ )
135
+ return (rows[0][0], rows[0][1]) if len(rows) == 1 else None
136
+
137
+
138
+ def _pick(rows: list[tuple], version: str | None) -> tuple[str, str] | None:
139
+ """One of several matches: by product code, then by ``version`` in each one's range of ARP versions"""
140
+ candidates: dict[str, tuple] = {}
141
+ for row in rows:
142
+ # A package matched both ways is a product code match, whichever row UNION gave first
143
+ if row[1] not in candidates or row[5]:
144
+ candidates[row[1]] = row
145
+ if len(candidates) > 1:
146
+ by_code = {pid: row for pid, row in candidates.items() if row[5]}
147
+ candidates = by_code or candidates
148
+ if len(candidates) > 1 and version:
149
+ installed = _version_key(version)
150
+ within = {
151
+ pid: row for pid, row in candidates.items()
152
+ if row[3] and row[4] and _version_key(row[3]) <= installed <= _version_key(row[4])
153
+ }
154
+ same_minor = {
155
+ pid: row for pid, row in candidates.items() if row[3] and _version_key(row[3])[:2] == installed[:2]
156
+ }
157
+ candidates = within or same_minor or candidates
158
+ if len(candidates) != 1:
159
+ return None
160
+ (row,) = candidates.values()
161
+ return row[1], row[2]
162
+
163
+
164
+ def find_index(roots: Iterable[str]) -> Path | None:
165
+ """The newest ``index.db`` among the source package's install folders"""
166
+ found = []
167
+ for root in roots:
168
+ path = Path(root) / "Public" / "index.db"
169
+ if path.is_file():
170
+ found.append(path)
171
+ return found[-1] if found else None
172
+
173
+
174
+ class Registry(Protocol):
175
+ def programs(self) -> list[Program]: ...
176
+ def package_full_names(self) -> list[str]: ...
177
+ def source_roots(self) -> list[str]: ...
178
+
179
+
180
+ class _Registry:
181
+ """What winget reads from this machine's registry. Windows only"""
182
+
183
+ def __init__(self) -> None:
184
+ import winreg
185
+
186
+ self.winreg = winreg
187
+
188
+ def programs(self) -> list[Program]:
189
+ winreg = self.winreg
190
+ programs: dict[tuple[str, str], Program] = {}
191
+ for hive, view in (
192
+ (winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY),
193
+ (winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY),
194
+ (winreg.HKEY_CURRENT_USER, 0),
195
+ ):
196
+ for key, values in self._subkeys(hive, UNINSTALL, view):
197
+ name = _string(values.get("DisplayName"))
198
+ if (
199
+ not name or values.get("SystemComponent") == 1 or _string(values.get("ParentKeyName"))
200
+ or _string(values.get("ReleaseType")) in ("Update", "Hotfix", "Security Update")
201
+ ):
202
+ continue
203
+ program = Program(
204
+ key, name, _string(values.get("Publisher")) or "", _string(values.get("DisplayVersion")) or None,
205
+ _string(values.get("InstallLocation")),
206
+ )
207
+ programs.setdefault((key.casefold(), name), program)
208
+ return list(programs.values())
209
+
210
+ def package_full_names(self) -> list[str]:
211
+ return [key for key, _ in self._subkeys(self.winreg.HKEY_CURRENT_USER, APP_REPOSITORY, 0, values=False)]
212
+
213
+ def source_roots(self) -> list[str]:
214
+ """The source package's install folders, oldest first"""
215
+ roots = []
216
+ for key, values in self._subkeys(self.winreg.HKEY_CURRENT_USER, APP_REPOSITORY, 0, prefix="Microsoft.Winget.Source_"):
217
+ root = _string(values.get("PackageRootFolder"))
218
+ if root:
219
+ roots.append((_version_key(key.split("_")[1]) if key.count("_") >= 4 else (), root))
220
+ return [root for _, root in sorted(roots)]
221
+
222
+ def _subkeys(self, hive, path: str, view: int, values: bool = True, prefix: str = ""):
223
+ winreg = self.winreg
224
+ try:
225
+ parent = winreg.OpenKey(hive, path, 0, winreg.KEY_READ | view)
226
+ except OSError:
227
+ return
228
+ with parent:
229
+ index = 0
230
+ while True:
231
+ try:
232
+ name = winreg.EnumKey(parent, index)
233
+ except OSError:
234
+ break
235
+ index += 1
236
+ if not name.startswith(prefix):
237
+ continue
238
+ if not values:
239
+ yield name, {}
240
+ continue
241
+ try:
242
+ with winreg.OpenKey(parent, name) as child:
243
+ yield name, _values(winreg, child)
244
+ except OSError:
245
+ continue
246
+
247
+
248
+ def _values(winreg, key) -> dict[str, object]:
249
+ found = {}
250
+ index = 0
251
+ while True:
252
+ try:
253
+ name, value, _ = winreg.EnumValue(key, index)
254
+ except OSError:
255
+ return found
256
+ found[name] = value
257
+ index += 1
258
+
259
+
260
+ def install_location(program: Program) -> Path | None:
261
+ """Where ``program`` is installed, so a later scanner reading that folder (electron) leaves it to winget"""
262
+ location = (program.location or "").strip().strip('"').strip()
263
+ if not location or Path(location).parent == Path(location):
264
+ return None
265
+ try:
266
+ return Path(location).resolve()
267
+ except OSError:
268
+ return None
269
+
270
+
271
+ def _string(value: object) -> str | None:
272
+ return value.strip() if isinstance(value, str) and value.strip() else None
273
+
274
+
275
+ class WingetScanner:
276
+ name: ClassVar[str] = "winget"
277
+ summary: ClassVar[str] = "Windows programs winget can identify"
278
+ sources: ClassVar[tuple[str, ...]] = ("winget",)
279
+
280
+ def __init__(self, registry: Registry | None = None) -> None:
281
+ self.registry = registry
282
+
283
+ def available(self) -> bool:
284
+ return sys.platform == "win32" and shutil.which("winget") is not None
285
+
286
+ def scan(self) -> Iterable[Installed]:
287
+ registry = self.registry or _Registry()
288
+ path = find_index(registry.source_roots())
289
+ if path is None:
290
+ raise ScanError(NO_INDEX)
291
+ programs, packages = registry.programs(), registry.package_full_names()
292
+
293
+ index = Index(path)
294
+ seen: set[str] = set()
295
+ try:
296
+ found: list[Installed] = []
297
+
298
+ def version(package_id: str, installed: str | None) -> str | None:
299
+ return None if installed is None or index.numbers_installs_apart(package_id) else installed
300
+
301
+ for program in programs:
302
+ match = index.match_program(program)
303
+ if match:
304
+ found.append(Installed(
305
+ "winget", match[0], match[1], version(match[0], program.version), install_location(program),
306
+ ))
307
+ for full in packages:
308
+ package = parse_package_full_name(full)
309
+ match = index.match_package(package) if package else None
310
+ if match:
311
+ found.append(Installed("winget", match[0], match[1], version(match[0], package.version)))
312
+ finally:
313
+ index.close()
314
+ for item in found:
315
+ if item.entry.casefold() in seen or FRAMEWORK_RE.match(item.entry):
316
+ continue
317
+ seen.add(item.entry.casefold())
318
+ yield item