← Back to Pull requests

[Windows] Build swiftly on Windows and list toolchains from Windows Installer #619

Open
AbdAlRahmanGad opened this pull request with 684 lines diff across 20 files
View on GitHub
AbdAlRahmanGad AbdAlRahmanGad commented on Nov 09, 2026 05:38 UTC
Author

The beginning of bringing Swiftly to Windows. See the Swift Forums proposal.

swiftly now builds and runs on Windows. The OpenAPI clients use openapi-winhttp-transport there (swift-nio-ssl doesn't compile against the Windows SDK), and installed toolchains come from Windows Installer's records of the swift.org MSIs; Linux and macOS are unchanged.

Works on Windows


  • swift build build Swiftly

  • swiftly init --skip-install: sets up swiftly's home directory; skips the shell profile, which Windows doesn't have

  • swiftly --version, swiftly --help

  • swiftly list: shows toolchains installed with the swift.org installer

  • swiftly list-available: fetches the release list from swift.org over WinHTTP

  • swiftly use, swiftly use <version>, swiftly use --print-location: shows or picks the in-use toolchain

  • - Couldn't test picking different valid toolchain since windows doesn't support having multiple toolchains installed at once

    in progress


  • swiftly run minimal working verision
  • Diff: 684 lines (+670 / -14) across 20 files Reviewer: compnerd Review duration: 35293m
    All Vouch review confidence checks passed
    Residual risk 0.10 = Change Risk (0.71) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.71 · 684 lines diff across 20 files
    0.71
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 5 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    86%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.391
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    16 items
    compnerd compnerd commented on code on Nov 09, 2026 18:09 UTC
    Code Review
    Sources/CMsi/include/CMsi.h:1
    @@ -0,0 +1,40 @@
    +#pragma once

    Why do we need this? Can we not use WinSDK to get the appropriate header pulled in?

    AbdAlRahmanGad AbdAlRahmanGad commented on Nov 17, 2026 22:44 UTC
    Author

    Just used swift format using swiftly \:)

    compnerd compnerd commented on code on Nov 26, 2026 01:01 UTC
    Code Review
    Sources/Swiftly/Proxy.swift:1
    @@ -10,9 +10,19 @@ public enum Proxy {
     
             do {
                 let zero = CommandLine.arguments[0]
    +#if os(Windows)
    +            // argv[0] can use either slash and usually ends in .exe.
    +            guard var binName = zero.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) else {

    Please avoid this pattern. Use win32 APIs directly to get the base name or use URL APIs. Treating the file path as a formatted string is non-portable and error prone.

    compnerd compnerd commented on code on Nov 26, 2026 01:18 UTC
    Code Review
    Sources/SwiftlyCore/Platform+Process.swift:1
    @@ -44,5 +44,54 @@ extension Platform {
             return environment
         }
     
    +#elseif os(Windows)
    +    public func proxyEnvironment(_ ctx: SwiftlyCoreContext, env: Environment, toolchain: ToolchainVersion) async throws -> Environment {
    +        var environment = env
    +
    +        let tcPath = try await self.findToolchainBinDir(ctx, toolchain)
    +        guard try await fs.exists(atPath: tcPath) else {
    +            throw SwiftlyError(
    +                message:
    +                "Toolchain \(toolchain) could not be located in \(tcPath). You can try `swiftly uninstall \(toolchain)` to uninstall it and then `swiftly install \(toolchain)` to install it again."
    +            )
    +        }
    +
    +        // TODO: Handle Git Bash and other shells, which pass the variable as PATH rather than Path.
    +        let path = ProcessInfo.processInfo.environment["Path"] ?? ""

    If possible, I prefer that we pull in swift-tools-support-core for the environment. There was a wrapper that I introduced to deal with the case sensitivity. Windows environment is case insensitive, and duplication is fatal.

    compnerd compnerd commented on code on Nov 27, 2026 05:38 UTC
    Code Review
    Sources/SwiftlyCore/Platform+Process.swift:1
    @@ -44,5 +47,41 @@ extension Platform {
             return environment
         }
     
    +#elseif os(Windows)
    +    public func proxyEnvironment(_ ctx: SwiftlyCoreContext, env: Environment, toolchain: ToolchainVersion) async throws -> Environment {
    +        var environment = env
    +
    +        let tcPath = try await self.findToolchainBinDir(ctx, toolchain)
    +        guard try await fs.exists(atPath: tcPath) else {
    +            throw SwiftlyError(
    +                message:
    +                "Toolchain \(toolchain) could not be located in \(tcPath). You can try `swiftly uninstall \(toolchain)` to uninstall it and then `swiftly install \(toolchain)` to install it again."
    +            )
    +        }
    +
    +        // ProcessEnv's keys ignore case on Windows, so this finds the variable whether the parent
    +        // passed it as Path or, like Git Bash, as PATH.
    +        let path = ProcessEnv.block["Path"] ?? ""
    +        var pathComponents = path.split(separator: ";").map { String($0) }
    +
    +        // The toolchain goes to the beginning of the Path. Entries compare as FilePath, which treats
    +        // forward and backward slashes alike and drops a trailing one.
    +        pathComponents.removeAll(where: { FilePath($0) == tcPath })
    +        // TODO: add runtimes path too after toolchain path. Can compute or maybe add it from other places later

    Is this for clients or the toolchain? The latter doesn’t need it IMO. We should be now using the SxS bound version which should be loaded by the loader without Path alterations I believe.

    compnerd compnerd commented on code on Nov 27, 2026 05:39 UTC
    Code Review
    Sources/SwiftlyCore/Platform+Process.swift:1
    @@ -44,5 +47,41 @@ extension Platform {
             return environment
         }
     
    +#elseif os(Windows)
    +    public func proxyEnvironment(_ ctx: SwiftlyCoreContext, env: Environment, toolchain: ToolchainVersion) async throws -> Environment {
    +        var environment = env
    +
    +        let tcPath = try await self.findToolchainBinDir(ctx, toolchain)
    +        guard try await fs.exists(atPath: tcPath) else {
    +            throw SwiftlyError(
    +                message:
    +                "Toolchain \(toolchain) could not be located in \(tcPath). You can try `swiftly uninstall \(toolchain)` to uninstall it and then `swiftly install \(toolchain)` to install it again."
    +            )
    +        }
    +
    +        // ProcessEnv's keys ignore case on Windows, so this finds the variable whether the parent
    +        // passed it as Path or, like Git Bash, as PATH.
    +        let path = ProcessEnv.block["Path"] ?? ""
    +        var pathComponents = path.split(separator: ";").map { String($0) }
    +
    +        // The toolchain goes to the beginning of the Path. Entries compare as FilePath, which treats
    +        // forward and backward slashes alike and drops a trailing one.
    +        pathComponents.removeAll(where: { FilePath($0) == tcPath })
    +        // TODO: add runtimes path too after toolchain path. Can compute or maybe add it from other places later
    +        pathComponents = [tcPath.string] + pathComponents
    +
    +        // Remove swiftly bin directory from the Path entirely
    +        let swiftlyBinDir = self.swiftlyBinDir(ctx)
    +        pathComponents.removeAll(where: { FilePath($0) == swiftlyBinDir })
    +
    +        environment = environment.updating(["Path": String(pathComponents.joined(separator: ";"))])
    +        // TEMP: show the Path the toolchain command gets

    Maybe wrap in #if DEBUG.

    compnerd compnerd commented on code on Nov 27, 2026 05:41 UTC
    Code Review
    Sources/WindowsPlatform/MsiEnumeration.swift:1
    @@ -0,0 +1,307 @@
    +import CMsi
    +import Foundation
    +import SystemPackage
    +import WinSDK
    +
    +/// A Swift version the official Windows installer registered, with where each of its pieces lives.
    +struct InstalledSwift: Equatable {
    +    /// The products' `VersionString`, such as "6.4.1".
    +    var version: String
    +    /// The toolchain root, the folder that holds `usr\bin\swift.exe`.
    +    var toolchain: FilePath?
    +    /// SDK folders, such as `...\Windows.platform\Developer\SDKs\Windows.sdk`.
    +    var sdks: [FilePath]
    +    /// The runtime's `usr\bin`, which holds `swiftCore.dll`.
    +    var runtime: FilePath?
    +}
    +
    +/// Finds installed Swift toolchains, SDKs and runtimes using only what Windows Installer has
    +/// registered: no cached .msi files and no hard-coded component GUIDs.
    +///
    +/// Windows Installer has no "components of this product" call, so this lists the swift.org
    +/// products, walks the components registered in the install contexts those products use, and
    +/// asks which products use each one. The key file of a component identifies the piece.
    +///
    +/// The walk takes seconds, so its result is saved to a file and reused while the set of swift.org
    +/// products stays the same. A product code always installs the same thing, so installing,
    +/// upgrading or removing Swift changes the set and leads to a new walk.
    +enum MsiEnumeration {
    +    /// The installed Swift versions, read from `cacheFile` when it was saved for the swift.org
    +    /// products installed now, or found by walking Windows Installer and then saved there.
    +    static func installed(cacheFile: FilePath) -> [InstalledSwift] {

    I would say that installed(cache: FilePath?) reads more naturally. That also allows bypassing the cache if desired/needed.

    compnerd compnerd commented on code on Nov 27, 2026 05:45 UTC
    Code Review
    Sources/WindowsPlatform/MsiEnumeration.swift:1
    @@ -0,0 +1,307 @@
    +import CMsi
    +import Foundation
    +import SystemPackage
    +import WinSDK
    +
    +/// A Swift version the official Windows installer registered, with where each of its pieces lives.
    +struct InstalledSwift: Equatable {
    +    /// The products' `VersionString`, such as "6.4.1".
    +    var version: String
    +    /// The toolchain root, the folder that holds `usr\bin\swift.exe`.
    +    var toolchain: FilePath?
    +    /// SDK folders, such as `...\Windows.platform\Developer\SDKs\Windows.sdk`.
    +    var sdks: [FilePath]
    +    /// The runtime's `usr\bin`, which holds `swiftCore.dll`.
    +    var runtime: FilePath?
    +}
    +
    +/// Finds installed Swift toolchains, SDKs and runtimes using only what Windows Installer has
    +/// registered: no cached .msi files and no hard-coded component GUIDs.
    +///
    +/// Windows Installer has no "components of this product" call, so this lists the swift.org
    +/// products, walks the components registered in the install contexts those products use, and
    +/// asks which products use each one. The key file of a component identifies the piece.
    +///
    +/// The walk takes seconds, so its result is saved to a file and reused while the set of swift.org
    +/// products stays the same. A product code always installs the same thing, so installing,
    +/// upgrading or removing Swift changes the set and leads to a new walk.
    +enum MsiEnumeration {
    +    /// The installed Swift versions, read from `cacheFile` when it was saved for the swift.org
    +    /// products installed now, or found by walking Windows Installer and then saved there.
    +    static func installed(cacheFile: FilePath) -> [InstalledSwift] {
    +        var complete = true
    +        let products = Self.swiftProducts(complete: &complete)
    +        let codes = products.keys.sorted()
    +        if complete, let cache = Cache.read(from: cacheFile), cache.products == codes, cache.pathsExist {
    +            return cache.installed
    +        }
    +
    +        let installed = Self.findInstalledSwift(products, complete: &complete)
    +        // A walk cut short by an error would otherwise leave toolchains out until Swift is next
    +        // installed or removed.
    +        if complete {
    +            Cache(products: codes, installed: installed).write(to: cacheFile)
    +        }
    +        return installed
    +    }
    +
    +    /// The swift.org products visible to the current user, by product code.
    +    private static func swiftProducts(complete: inout Bool) -> [String: Product] {

    Why not generalize? Something like func products(vendor:complete:) -> [String:Product].

    compnerd compnerd commented on code on Nov 27, 2026 05:49 UTC
    Code Review
    Sources/WindowsPlatform/MsiEnumeration.swift:1
    @@ -0,0 +1,307 @@
    +import CMsi
    +import Foundation
    +import SystemPackage
    +import WinSDK
    +
    +/// A Swift version the official Windows installer registered, with where each of its pieces lives.
    +struct InstalledSwift: Equatable {
    +    /// The products' `VersionString`, such as "6.4.1".
    +    var version: String
    +    /// The toolchain root, the folder that holds `usr\bin\swift.exe`.
    +    var toolchain: FilePath?
    +    /// SDK folders, such as `...\Windows.platform\Developer\SDKs\Windows.sdk`.
    +    var sdks: [FilePath]
    +    /// The runtime's `usr\bin`, which holds `swiftCore.dll`.
    +    var runtime: FilePath?
    +}
    +
    +/// Finds installed Swift toolchains, SDKs and runtimes using only what Windows Installer has
    +/// registered: no cached .msi files and no hard-coded component GUIDs.
    +///
    +/// Windows Installer has no "components of this product" call, so this lists the swift.org
    +/// products, walks the components registered in the install contexts those products use, and
    +/// asks which products use each one. The key file of a component identifies the piece.
    +///
    +/// The walk takes seconds, so its result is saved to a file and reused while the set of swift.org
    +/// products stays the same. A product code always installs the same thing, so installing,
    +/// upgrading or removing Swift changes the set and leads to a new walk.
    +enum MsiEnumeration {
    +    /// The installed Swift versions, read from `cacheFile` when it was saved for the swift.org
    +    /// products installed now, or found by walking Windows Installer and then saved there.
    +    static func installed(cacheFile: FilePath) -> [InstalledSwift] {
    +        var complete = true
    +        let products = Self.swiftProducts(complete: &complete)
    +        let codes = products.keys.sorted()
    +        if complete, let cache = Cache.read(from: cacheFile), cache.products == codes, cache.pathsExist {
    +            return cache.installed
    +        }
    +
    +        let installed = Self.findInstalledSwift(products, complete: &complete)
    +        // A walk cut short by an error would otherwise leave toolchains out until Swift is next
    +        // installed or removed.
    +        if complete {
    +            Cache(products: codes, installed: installed).write(to: cacheFile)
    +        }
    +        return installed
    +    }
    +
    +    /// The swift.org products visible to the current user, by product code.
    +    private static func swiftProducts(complete: inout Bool) -> [String: Product] {
    +        Dictionary(
    +            Self.installedProducts(complete: &complete).filter { $0.publisher == "swift.org" }.map { ($0.code, $0) },
    +            uniquingKeysWith: { first, _ in first }
    +        )
    +    }
    +
    +    /// Walks the components of `products`. Sets `complete` to false if a Windows Installer call
    +    /// failed partway, and returns what was found before that.
    +    private static func findInstalledSwift(_ products: [String: Product], complete: inout Bool) -> [InstalledSwift] {
    +        let paths = Self.installedPaths(of: products, complete: &complete)

    Why not make installedPaths a property of Product? What benefit does the static version have?

    compnerd compnerd commented on code on Nov 27, 2026 05:50 UTC
    Code Review
    Sources/WindowsPlatform/MsiEnumeration.swift:1
    @@ -0,0 +1,307 @@
    +import CMsi
    +import Foundation
    +import SystemPackage
    +import WinSDK
    +
    +/// A Swift version the official Windows installer registered, with where each of its pieces lives.
    +struct InstalledSwift: Equatable {
    +    /// The products' `VersionString`, such as "6.4.1".
    +    var version: String
    +    /// The toolchain root, the folder that holds `usr\bin\swift.exe`.
    +    var toolchain: FilePath?
    +    /// SDK folders, such as `...\Windows.platform\Developer\SDKs\Windows.sdk`.
    +    var sdks: [FilePath]
    +    /// The runtime's `usr\bin`, which holds `swiftCore.dll`.
    +    var runtime: FilePath?
    +}
    +
    +/// Finds installed Swift toolchains, SDKs and runtimes using only what Windows Installer has
    +/// registered: no cached .msi files and no hard-coded component GUIDs.
    +///
    +/// Windows Installer has no "components of this product" call, so this lists the swift.org
    +/// products, walks the components registered in the install contexts those products use, and
    +/// asks which products use each one. The key file of a component identifies the piece.
    +///
    +/// The walk takes seconds, so its result is saved to a file and reused while the set of swift.org
    +/// products stays the same. A product code always installs the same thing, so installing,
    +/// upgrading or removing Swift changes the set and leads to a new walk.
    +enum MsiEnumeration {
    +    /// The installed Swift versions, read from `cacheFile` when it was saved for the swift.org
    +    /// products installed now, or found by walking Windows Installer and then saved there.
    +    static func installed(cacheFile: FilePath) -> [InstalledSwift] {
    +        var complete = true
    +        let products = Self.swiftProducts(complete: &complete)
    +        let codes = products.keys.sorted()
    +        if complete, let cache = Cache.read(from: cacheFile), cache.products == codes, cache.pathsExist {
    +            return cache.installed
    +        }
    +
    +        let installed = Self.findInstalledSwift(products, complete: &complete)
    +        // A walk cut short by an error would otherwise leave toolchains out until Swift is next
    +        // installed or removed.
    +        if complete {
    +            Cache(products: codes, installed: installed).write(to: cacheFile)
    +        }
    +        return installed
    +    }
    +
    +    /// The swift.org products visible to the current user, by product code.
    +    private static func swiftProducts(complete: inout Bool) -> [String: Product] {
    +        Dictionary(
    +            Self.installedProducts(complete: &complete).filter { $0.publisher == "swift.org" }.map { ($0.code, $0) },
    +            uniquingKeysWith: { first, _ in first }
    +        )
    +    }
    +
    +    /// Walks the components of `products`. Sets `complete` to false if a Windows Installer call
    +    /// failed partway, and returns what was found before that.
    +    private static func findInstalledSwift(_ products: [String: Product], complete: inout Bool) -> [InstalledSwift] {
    +        let paths = Self.installedPaths(of: products, complete: &complete)
    +
    +        var byVersion: [String: InstalledSwift] = [:]
    +        for product in products.values {
    +            let version = product.version
    +            var entry = byVersion[version] ?? InstalledSwift(version: version, toolchain: nil, sdks: [], runtime: nil)
    +            for path in paths[product.code] ?? [] {
    +                switch Self.piece(forKeyFile: path) {
    +                case let .toolchain(root):
    +                    // Pick deterministically if two variants of one version are installed.
    +                    if entry.toolchain == nil || root.string < entry.toolchain!.string {
    +                        entry.toolchain = root
    +                    }
    +                case let .sdk(folder):
    +                    entry.sdks.append(folder)
    +                case let .runtime(bin):
    +                    entry.runtime = bin
    +                case nil:
    +                    continue
    +                }
    +            }
    +            byVersion[version] = entry
    +        }

    Can this be done as a dictionary initializer?

    compnerd compnerd commented on code on Nov 27, 2026 05:51 UTC
    Code Review
    Sources/WindowsPlatform/MsiEnumeration.swift:1
    @@ -0,0 +1,307 @@
    +import CMsi
    +import Foundation
    +import SystemPackage
    +import WinSDK
    +
    +/// A Swift version the official Windows installer registered, with where each of its pieces lives.
    +struct InstalledSwift: Equatable {
    +    /// The products' `VersionString`, such as "6.4.1".
    +    var version: String
    +    /// The toolchain root, the folder that holds `usr\bin\swift.exe`.
    +    var toolchain: FilePath?
    +    /// SDK folders, such as `...\Windows.platform\Developer\SDKs\Windows.sdk`.
    +    var sdks: [FilePath]
    +    /// The runtime's `usr\bin`, which holds `swiftCore.dll`.
    +    var runtime: FilePath?
    +}
    +
    +/// Finds installed Swift toolchains, SDKs and runtimes using only what Windows Installer has
    +/// registered: no cached .msi files and no hard-coded component GUIDs.
    +///
    +/// Windows Installer has no "components of this product" call, so this lists the swift.org
    +/// products, walks the components registered in the install contexts those products use, and
    +/// asks which products use each one. The key file of a component identifies the piece.
    +///
    +/// The walk takes seconds, so its result is saved to a file and reused while the set of swift.org
    +/// products stays the same. A product code always installs the same thing, so installing,
    +/// upgrading or removing Swift changes the set and leads to a new walk.
    +enum MsiEnumeration {
    +    /// The installed Swift versions, read from `cacheFile` when it was saved for the swift.org
    +    /// products installed now, or found by walking Windows Installer and then saved there.
    +    static func installed(cacheFile: FilePath) -> [InstalledSwift] {
    +        var complete = true
    +        let products = Self.swiftProducts(complete: &complete)
    +        let codes = products.keys.sorted()
    +        if complete, let cache = Cache.read(from: cacheFile), cache.products == codes, cache.pathsExist {
    +            return cache.installed
    +        }
    +
    +        let installed = Self.findInstalledSwift(products, complete: &complete)
    +        // A walk cut short by an error would otherwise leave toolchains out until Swift is next
    +        // installed or removed.
    +        if complete {
    +            Cache(products: codes, installed: installed).write(to: cacheFile)
    +        }
    +        return installed
    +    }
    +
    +    /// The swift.org products visible to the current user, by product code.
    +    private static func swiftProducts(complete: inout Bool) -> [String: Product] {
    +        Dictionary(
    +            Self.installedProducts(complete: &complete).filter { $0.publisher == "swift.org" }.map { ($0.code, $0) },
    +            uniquingKeysWith: { first, _ in first }
    +        )
    +    }
    +
    +    /// Walks the components of `products`. Sets `complete` to false if a Windows Installer call
    +    /// failed partway, and returns what was found before that.
    +    private static func findInstalledSwift(_ products: [String: Product], complete: inout Bool) -> [InstalledSwift] {
    +        let paths = Self.installedPaths(of: products, complete: &complete)
    +
    +        var byVersion: [String: InstalledSwift] = [:]
    +        for product in products.values {
    +            let version = product.version
    +            var entry = byVersion[version] ?? InstalledSwift(version: version, toolchain: nil, sdks: [], runtime: nil)
    +            for path in paths[product.code] ?? [] {
    +                switch Self.piece(forKeyFile: path) {
    +                case let .toolchain(root):
    +                    // Pick deterministically if two variants of one version are installed.
    +                    if entry.toolchain == nil || root.string < entry.toolchain!.string {
    +                        entry.toolchain = root
    +                    }
    +                case let .sdk(folder):
    +                    entry.sdks.append(folder)
    +                case let .runtime(bin):
    +                    entry.runtime = bin
    +                case nil:
    +                    continue
    +                }
    +            }
    +            byVersion[version] = entry
    +        }
    +
    +        return byVersion.values
    +            .map { var e = $0
    +                e.sdks.sort { $0.string < $1.string }
    +                return e
    +            }
    +            .sorted { $0.version < $1.version }
    +    }
    +
    +    /// A walk's result, with the swift.org product codes it was found for.
    +    private struct Cache: Codable {
    +        struct Entry: Codable {
    +            var version: String
    +            var toolchain: String?
    +            var sdks: [String]
    +            var runtime: String?
    +        }
    +
    +        var products: [String]
    +        var entries: [Entry]
    +
    +        init(products: [String], installed: [InstalledSwift]) {
    +            self.products = products
    +            self.entries = installed.map {
    +                Entry(version: $0.version, toolchain: $0.toolchain?.string, sdks: $0.sdks.map(\.string), runtime: $0.runtime?.string)
    +            }
    +        }
    +
    +        var installed: [InstalledSwift] {
    +            self.entries.map {
    +                InstalledSwift(
    +                    version: $0.version,
    +                    toolchain: $0.toolchain.map { FilePath($0) },
    +                    sdks: $0.sdks.map { FilePath($0) },
    +                    runtime: $0.runtime.map { FilePath($0) }
    +                )
    +            }
    +        }
    +
    +        /// Whether every folder is still there. Deleting one outside Windows Installer leaves the
    +        /// product codes as they were.
    +        var pathsExist: Bool {
    +            self.entries.allSatisfy { entry in
    +                ([entry.toolchain, entry.runtime].compactMap { $0 } + entry.sdks).allSatisfy {
    +                    FileManager.default.fileExists(atPath: $0)
    +                }
    +            }
    +        }
    +
    +        static func read(from file: FilePath) -> Cache? {
    +            guard let data = FileManager.default.contents(atPath: file.string) else {
    +                return nil
    +            }
    +            return try? JSONDecoder().decode(Cache.self, from: data)
    +        }
    +
    +        /// Best effort: if the file can't be written, the next run walks again.
    +        func write(to file: FilePath) {
    +            let encoder = JSONEncoder()
    +            encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
    +            guard let data = try? encoder.encode(self) else {
    +                return
    +            }
    +            try? data.write(to: URL(fileURLWithPath: file.string), options: .atomic)
    +        }
    +    }
    +
    +    enum Piece: Equatable {

    Component might be better than piece

    compnerd compnerd commented on code on Nov 27, 2026 05:55 UTC
    Code Review
    Sources/WindowsPlatform/MsiEnumeration.swift:1
    @@ -0,0 +1,307 @@
    +import CMsi
    +import Foundation
    +import SystemPackage
    +import WinSDK
    +
    +/// A Swift version the official Windows installer registered, with where each of its pieces lives.
    +struct InstalledSwift: Equatable {
    +    /// The products' `VersionString`, such as "6.4.1".
    +    var version: String
    +    /// The toolchain root, the folder that holds `usr\bin\swift.exe`.
    +    var toolchain: FilePath?
    +    /// SDK folders, such as `...\Windows.platform\Developer\SDKs\Windows.sdk`.
    +    var sdks: [FilePath]
    +    /// The runtime's `usr\bin`, which holds `swiftCore.dll`.
    +    var runtime: FilePath?
    +}
    +
    +/// Finds installed Swift toolchains, SDKs and runtimes using only what Windows Installer has
    +/// registered: no cached .msi files and no hard-coded component GUIDs.
    +///
    +/// Windows Installer has no "components of this product" call, so this lists the swift.org
    +/// products, walks the components registered in the install contexts those products use, and
    +/// asks which products use each one. The key file of a component identifies the piece.
    +///
    +/// The walk takes seconds, so its result is saved to a file and reused while the set of swift.org
    +/// products stays the same. A product code always installs the same thing, so installing,
    +/// upgrading or removing Swift changes the set and leads to a new walk.
    +enum MsiEnumeration {
    +    /// The installed Swift versions, read from `cacheFile` when it was saved for the swift.org
    +    /// products installed now, or found by walking Windows Installer and then saved there.
    +    static func installed(cacheFile: FilePath) -> [InstalledSwift] {
    +        var complete = true
    +        let products = Self.swiftProducts(complete: &complete)
    +        let codes = products.keys.sorted()
    +        if complete, let cache = Cache.read(from: cacheFile), cache.products == codes, cache.pathsExist {
    +            return cache.installed
    +        }
    +
    +        let installed = Self.findInstalledSwift(products, complete: &complete)
    +        // A walk cut short by an error would otherwise leave toolchains out until Swift is next
    +        // installed or removed.
    +        if complete {
    +            Cache(products: codes, installed: installed).write(to: cacheFile)
    +        }
    +        return installed
    +    }
    +
    +    /// The swift.org products visible to the current user, by product code.
    +    private static func swiftProducts(complete: inout Bool) -> [String: Product] {
    +        Dictionary(
    +            Self.installedProducts(complete: &complete).filter { $0.publisher == "swift.org" }.map { ($0.code, $0) },
    +            uniquingKeysWith: { first, _ in first }
    +        )
    +    }
    +
    +    /// Walks the components of `products`. Sets `complete` to false if a Windows Installer call
    +    /// failed partway, and returns what was found before that.
    +    private static func findInstalledSwift(_ products: [String: Product], complete: inout Bool) -> [InstalledSwift] {
    +        let paths = Self.installedPaths(of: products, complete: &complete)
    +
    +        var byVersion: [String: InstalledSwift] = [:]
    +        for product in products.values {
    +            let version = product.version
    +            var entry = byVersion[version] ?? InstalledSwift(version: version, toolchain: nil, sdks: [], runtime: nil)
    +            for path in paths[product.code] ?? [] {
    +                switch Self.piece(forKeyFile: path) {
    +                case let .toolchain(root):
    +                    // Pick deterministically if two variants of one version are installed.
    +                    if entry.toolchain == nil || root.string < entry.toolchain!.string {
    +                        entry.toolchain = root
    +                    }
    +                case let .sdk(folder):
    +                    entry.sdks.append(folder)
    +                case let .runtime(bin):
    +                    entry.runtime = bin
    +                case nil:
    +                    continue
    +                }
    +            }
    +            byVersion[version] = entry
    +        }
    +
    +        return byVersion.values
    +            .map { var e = $0
    +                e.sdks.sort { $0.string < $1.string }
    +                return e
    +            }
    +            .sorted { $0.version < $1.version }
    +    }
    +
    +    /// A walk's result, with the swift.org product codes it was found for.
    +    private struct Cache: Codable {
    +        struct Entry: Codable {
    +            var version: String
    +            var toolchain: String?
    +            var sdks: [String]
    +            var runtime: String?
    +        }
    +
    +        var products: [String]
    +        var entries: [Entry]
    +
    +        init(products: [String], installed: [InstalledSwift]) {
    +            self.products = products
    +            self.entries = installed.map {
    +                Entry(version: $0.version, toolchain: $0.toolchain?.string, sdks: $0.sdks.map(\.string), runtime: $0.runtime?.string)
    +            }
    +        }
    +
    +        var installed: [InstalledSwift] {
    +            self.entries.map {
    +                InstalledSwift(
    +                    version: $0.version,
    +                    toolchain: $0.toolchain.map { FilePath($0) },
    +                    sdks: $0.sdks.map { FilePath($0) },
    +                    runtime: $0.runtime.map { FilePath($0) }
    +                )
    +            }
    +        }
    +
    +        /// Whether every folder is still there. Deleting one outside Windows Installer leaves the
    +        /// product codes as they were.
    +        var pathsExist: Bool {
    +            self.entries.allSatisfy { entry in
    +                ([entry.toolchain, entry.runtime].compactMap { $0 } + entry.sdks).allSatisfy {
    +                    FileManager.default.fileExists(atPath: $0)
    +                }
    +            }
    +        }
    +
    +        static func read(from file: FilePath) -> Cache? {
    +            guard let data = FileManager.default.contents(atPath: file.string) else {
    +                return nil
    +            }
    +            return try? JSONDecoder().decode(Cache.self, from: data)
    +        }
    +
    +        /// Best effort: if the file can't be written, the next run walks again.
    +        func write(to file: FilePath) {
    +            let encoder = JSONEncoder()
    +            encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
    +            guard let data = try? encoder.encode(self) else {
    +                return
    +            }
    +            try? data.write(to: URL(fileURLWithPath: file.string), options: .atomic)
    +        }
    +    }
    +
    +    enum Piece: Equatable {
    +        case toolchain(FilePath)
    +        case sdk(FilePath)
    +        case runtime(FilePath)
    +    }
    +
    +    /// Which piece a component's key file identifies, and the folder that piece lives in.
    +    static func piece(forKeyFile path: String) -> Piece? {
    +        let file = FilePath(path)
    +        switch file.lastComponent?.string.lowercased() {
    +        case "swift.exe":
    +            // <root>\usr\bin\swift.exe
    +            return .toolchain(file.removingLastComponent().removingLastComponent().removingLastComponent())
    +        case "sdksettings.json":
    +            // <sdk>\SDKSettings.json
    +            return .sdk(file.removingLastComponent())
    +        case "swiftcore.dll":
    +            // Runtimes\<version>\usr\bin\swiftCore.dll
    +            return .runtime(file.removingLastComponent())
    +        default:
    +            return nil
    +        }
    +    }
    +
    +    // MARK: - Windows Installer calls
    +
    +    private struct Product {
    +        let code: String
    +        let context: MSIINSTALLCONTEXT
    +        let sid: String?
    +
    +        func info(_ property: String) -> String? {
    +            MsiEnumeration.readString { buffer, length in
    +                withWide(self.code) { code in
    +                    withWide(self.sid) { sid in
    +                        withWide(property) { property in
    +                            MsiGetProductInfoExW(code, sid, self.context, property, buffer, length)
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        var version: String { self.info("VersionString") ?? "" }
    +        var publisher: String { self.info("Publisher") ?? "" }
    +
    +        /// Full path of the key file of `componentCode`, if it's installed locally.
    +        func componentPath(_ componentCode: String) -> String? {
    +            var capacity: UInt32 = 512
    +            while true {
    +                var buffer = [WCHAR](repeating: 0, count: Int(capacity))
    +                var length = capacity
    +                let state = withWide(self.code) { code in
    +                    withWide(componentCode) { component in
    +                        withWide(self.sid) { sid in
    +                            MsiGetComponentPathExW(code, component, sid, self.context, &buffer, &length)
    +                        }
    +                    }
    +                }
    +                if state == INSTALLSTATE_MOREDATA {
    +                    capacity = length + 1
    +                    continue
    +                }
    +                return state == INSTALLSTATE_LOCAL ? string(from: buffer) : nil
    +            }
    +        }
    +    }
    +
    +    /// Every product visible to the current user: their per-user installs plus per-machine ones.
    +    private static func installedProducts(complete: inout Bool) -> [Product] {
    +        Self.enumerate(complete: &complete) { index, code, context, sid, sidLength in
    +            MsiEnumProductsExW(nil, nil, UInt32(MSIINSTALLCONTEXT_ALL.rawValue), index, code, context, sid, sidLength)
    +        }.map { Product(code: $0.code, context: $0.context, sid: $0.sid) }
    +    }
    +
    +    /// Key-file paths of every locally installed component that belongs to one of `products`,
    +    /// walking only the install contexts those products live in.
    +    private static func installedPaths(of products: [String: Product], complete: inout Bool) -> [String: [String]] {
    +        var paths: [String: [String]] = [:]
    +        let contexts = products.values.reduce(UInt32(0)) { $0 | UInt32($1.context.rawValue) }
    +        guard contexts != 0 else {
    +            return paths
    +        }
    +
    +        let components = Self.enumerate(complete: &complete) { index, code, context, sid, sidLength in
    +            MsiEnumComponentsExW(nil, contexts, index, code, context, sid, sidLength)
    +        }
    +        for component in components {
    +            let clients = withWide(component.code) { componentCode in
    +                Self.enumerate(complete: &complete) { index, code, context, sid, sidLength in
    +                    MsiEnumClientsExW(componentCode, nil, UInt32(MSIINSTALLCONTEXT_ALL.rawValue), index, code, context, sid, sidLength)
    +                }
    +            }
    +            for client in clients {
    +                guard let product = products[client.code], let path = product.componentPath(component.code) else {
    +                    continue
    +                }
    +                paths[client.code, default: []].append(path)
    +            }
    +        }
    +        return paths
    +    }
    +
    +    /// Calls an MSI "fill this buffer" function, growing the buffer on ERROR_MORE_DATA.
    +    fileprivate static func readString(
    +        _ call: (UnsafeMutablePointer<WCHAR>, UnsafeMutablePointer<UInt32>) -> UInt32
    +    ) -> String? {
    +        var capacity: UInt32 = 256
    +        while true {
    +            var buffer = [WCHAR](repeating: 0, count: Int(capacity))
    +            var length = capacity
    +            let result = call(&buffer, &length)
    +            if result == ERROR_MORE_DATA {
    +                capacity = length + 1
    +                continue
    +            }
    +            return result == ERROR_SUCCESS ? string(from: buffer) : nil
    +        }
    +    }
    +
    +    /// Drives one of the MsiEnum*ExW functions, which each return a GUID, a context and a SID per index.
    +    /// Stops at the first error, which leaves the items found so far. An error other than the end of
    +    /// the list sets `complete` to false.
    +    private static func enumerate(
    +        complete: inout Bool,
    +        _ call: (UInt32, UnsafeMutablePointer<WCHAR>, UnsafeMutablePointer<MSIINSTALLCONTEXT>, UnsafeMutablePointer<WCHAR>, UnsafeMutablePointer<UInt32>) -> UInt32
    +    ) -> [(code: String, context: MSIINSTALLCONTEXT, sid: String?)] {
    +        var items: [(code: String, context: MSIINSTALLCONTEXT, sid: String?)] = []
    +        var index: UInt32 = 0
    +        while true {
    +            var code = [WCHAR](repeating: 0, count: 39)
    +            var context = MSIINSTALLCONTEXT_NONE
    +            var sid = [WCHAR](repeating: 0, count: 256)
    +            var sidLength: UInt32 = 256
    +            let result = call(index, &code, &context, &sid, &sidLength)
    +            if result != ERROR_SUCCESS {
    +                if result != UInt32(ERROR_NO_MORE_ITEMS) {
    +                    complete = false
    +                }
    +                break
    +            }
    +            let sidString = string(from: sid)
    +            items.append((string(from: code), context, sidString.isEmpty ? nil : sidString))
    +            index += 1
    +        }
    +        return items
    +    }
    +}
    +
    +private func withWide<R>(_ s: String?, _ body: (UnsafePointer<WCHAR>?) -> R) -> R {

    Perhaps withUTF16Representation is better. I wonder if this should just be a private extension on String?.

    compnerd compnerd commented on code on Nov 27, 2026 05:57 UTC
    Code Review
    Sources/WindowsPlatform/MsiEnumeration.swift:1
    @@ -0,0 +1,307 @@
    +import CMsi
    +import Foundation
    +import SystemPackage
    +import WinSDK
    +
    +/// A Swift version the official Windows installer registered, with where each of its pieces lives.
    +struct InstalledSwift: Equatable {
    +    /// The products' `VersionString`, such as "6.4.1".
    +    var version: String
    +    /// The toolchain root, the folder that holds `usr\bin\swift.exe`.
    +    var toolchain: FilePath?
    +    /// SDK folders, such as `...\Windows.platform\Developer\SDKs\Windows.sdk`.
    +    var sdks: [FilePath]
    +    /// The runtime's `usr\bin`, which holds `swiftCore.dll`.
    +    var runtime: FilePath?
    +}
    +
    +/// Finds installed Swift toolchains, SDKs and runtimes using only what Windows Installer has
    +/// registered: no cached .msi files and no hard-coded component GUIDs.
    +///
    +/// Windows Installer has no "components of this product" call, so this lists the swift.org
    +/// products, walks the components registered in the install contexts those products use, and
    +/// asks which products use each one. The key file of a component identifies the piece.
    +///
    +/// The walk takes seconds, so its result is saved to a file and reused while the set of swift.org
    +/// products stays the same. A product code always installs the same thing, so installing,
    +/// upgrading or removing Swift changes the set and leads to a new walk.
    +enum MsiEnumeration {
    +    /// The installed Swift versions, read from `cacheFile` when it was saved for the swift.org
    +    /// products installed now, or found by walking Windows Installer and then saved there.
    +    static func installed(cacheFile: FilePath) -> [InstalledSwift] {
    +        var complete = true
    +        let products = Self.swiftProducts(complete: &complete)
    +        let codes = products.keys.sorted()
    +        if complete, let cache = Cache.read(from: cacheFile), cache.products == codes, cache.pathsExist {
    +            return cache.installed
    +        }
    +
    +        let installed = Self.findInstalledSwift(products, complete: &complete)
    +        // A walk cut short by an error would otherwise leave toolchains out until Swift is next
    +        // installed or removed.
    +        if complete {
    +            Cache(products: codes, installed: installed).write(to: cacheFile)
    +        }
    +        return installed
    +    }
    +
    +    /// The swift.org products visible to the current user, by product code.
    +    private static func swiftProducts(complete: inout Bool) -> [String: Product] {
    +        Dictionary(
    +            Self.installedProducts(complete: &complete).filter { $0.publisher == "swift.org" }.map { ($0.code, $0) },
    +            uniquingKeysWith: { first, _ in first }
    +        )
    +    }
    +
    +    /// Walks the components of `products`. Sets `complete` to false if a Windows Installer call
    +    /// failed partway, and returns what was found before that.
    +    private static func findInstalledSwift(_ products: [String: Product], complete: inout Bool) -> [InstalledSwift] {
    +        let paths = Self.installedPaths(of: products, complete: &complete)
    +
    +        var byVersion: [String: InstalledSwift] = [:]
    +        for product in products.values {
    +            let version = product.version
    +            var entry = byVersion[version] ?? InstalledSwift(version: version, toolchain: nil, sdks: [], runtime: nil)
    +            for path in paths[product.code] ?? [] {
    +                switch Self.piece(forKeyFile: path) {
    +                case let .toolchain(root):
    +                    // Pick deterministically if two variants of one version are installed.
    +                    if entry.toolchain == nil || root.string < entry.toolchain!.string {
    +                        entry.toolchain = root
    +                    }
    +                case let .sdk(folder):
    +                    entry.sdks.append(folder)
    +                case let .runtime(bin):
    +                    entry.runtime = bin
    +                case nil:
    +                    continue
    +                }
    +            }
    +            byVersion[version] = entry
    +        }
    +
    +        return byVersion.values
    +            .map { var e = $0
    +                e.sdks.sort { $0.string < $1.string }
    +                return e
    +            }
    +            .sorted { $0.version < $1.version }
    +    }
    +
    +    /// A walk's result, with the swift.org product codes it was found for.
    +    private struct Cache: Codable {
    +        struct Entry: Codable {
    +            var version: String
    +            var toolchain: String?
    +            var sdks: [String]
    +            var runtime: String?
    +        }
    +
    +        var products: [String]
    +        var entries: [Entry]
    +
    +        init(products: [String], installed: [InstalledSwift]) {
    +            self.products = products
    +            self.entries = installed.map {
    +                Entry(version: $0.version, toolchain: $0.toolchain?.string, sdks: $0.sdks.map(\.string), runtime: $0.runtime?.string)
    +            }
    +        }
    +
    +        var installed: [InstalledSwift] {
    +            self.entries.map {
    +                InstalledSwift(
    +                    version: $0.version,
    +                    toolchain: $0.toolchain.map { FilePath($0) },
    +                    sdks: $0.sdks.map { FilePath($0) },
    +                    runtime: $0.runtime.map { FilePath($0) }
    +                )
    +            }
    +        }
    +
    +        /// Whether every folder is still there. Deleting one outside Windows Installer leaves the
    +        /// product codes as they were.
    +        var pathsExist: Bool {
    +            self.entries.allSatisfy { entry in
    +                ([entry.toolchain, entry.runtime].compactMap { $0 } + entry.sdks).allSatisfy {
    +                    FileManager.default.fileExists(atPath: $0)
    +                }
    +            }
    +        }
    +
    +        static func read(from file: FilePath) -> Cache? {
    +            guard let data = FileManager.default.contents(atPath: file.string) else {
    +                return nil
    +            }
    +            return try? JSONDecoder().decode(Cache.self, from: data)
    +        }
    +
    +        /// Best effort: if the file can't be written, the next run walks again.
    +        func write(to file: FilePath) {
    +            let encoder = JSONEncoder()
    +            encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
    +            guard let data = try? encoder.encode(self) else {
    +                return
    +            }
    +            try? data.write(to: URL(fileURLWithPath: file.string), options: .atomic)
    +        }
    +    }
    +
    +    enum Piece: Equatable {
    +        case toolchain(FilePath)
    +        case sdk(FilePath)
    +        case runtime(FilePath)
    +    }
    +
    +    /// Which piece a component's key file identifies, and the folder that piece lives in.
    +    static func piece(forKeyFile path: String) -> Piece? {
    +        let file = FilePath(path)
    +        switch file.lastComponent?.string.lowercased() {
    +        case "swift.exe":
    +            // <root>\usr\bin\swift.exe
    +            return .toolchain(file.removingLastComponent().removingLastComponent().removingLastComponent())
    +        case "sdksettings.json":
    +            // <sdk>\SDKSettings.json
    +            return .sdk(file.removingLastComponent())
    +        case "swiftcore.dll":
    +            // Runtimes\<version>\usr\bin\swiftCore.dll
    +            return .runtime(file.removingLastComponent())
    +        default:
    +            return nil
    +        }
    +    }
    +
    +    // MARK: - Windows Installer calls
    +
    +    private struct Product {
    +        let code: String
    +        let context: MSIINSTALLCONTEXT
    +        let sid: String?
    +
    +        func info(_ property: String) -> String? {
    +            MsiEnumeration.readString { buffer, length in
    +                withWide(self.code) { code in
    +                    withWide(self.sid) { sid in
    +                        withWide(property) { property in
    +                            MsiGetProductInfoExW(code, sid, self.context, property, buffer, length)
    +                        }
    +                    }
    +                }
    +            }
    +        }
    +
    +        var version: String { self.info("VersionString") ?? "" }
    +        var publisher: String { self.info("Publisher") ?? "" }
    +
    +        /// Full path of the key file of `componentCode`, if it's installed locally.
    +        func componentPath(_ componentCode: String) -> String? {
    +            var capacity: UInt32 = 512
    +            while true {
    +                var buffer = [WCHAR](repeating: 0, count: Int(capacity))
    +                var length = capacity
    +                let state = withWide(self.code) { code in
    +                    withWide(componentCode) { component in
    +                        withWide(self.sid) { sid in
    +                            MsiGetComponentPathExW(code, component, sid, self.context, &buffer, &length)
    +                        }
    +                    }
    +                }
    +                if state == INSTALLSTATE_MOREDATA {
    +                    capacity = length + 1
    +                    continue
    +                }
    +                return state == INSTALLSTATE_LOCAL ? string(from: buffer) : nil
    +            }
    +        }
    +    }
    +
    +    /// Every product visible to the current user: their per-user installs plus per-machine ones.
    +    private static func installedProducts(complete: inout Bool) -> [Product] {
    +        Self.enumerate(complete: &complete) { index, code, context, sid, sidLength in
    +            MsiEnumProductsExW(nil, nil, UInt32(MSIINSTALLCONTEXT_ALL.rawValue), index, code, context, sid, sidLength)
    +        }.map { Product(code: $0.code, context: $0.context, sid: $0.sid) }
    +    }
    +
    +    /// Key-file paths of every locally installed component that belongs to one of `products`,
    +    /// walking only the install contexts those products live in.
    +    private static func installedPaths(of products: [String: Product], complete: inout Bool) -> [String: [String]] {
    +        var paths: [String: [String]] = [:]
    +        let contexts = products.values.reduce(UInt32(0)) { $0 | UInt32($1.context.rawValue) }
    +        guard contexts != 0 else {
    +            return paths
    +        }
    +
    +        let components = Self.enumerate(complete: &complete) { index, code, context, sid, sidLength in
    +            MsiEnumComponentsExW(nil, contexts, index, code, context, sid, sidLength)
    +        }
    +        for component in components {
    +            let clients = withWide(component.code) { componentCode in
    +                Self.enumerate(complete: &complete) { index, code, context, sid, sidLength in
    +                    MsiEnumClientsExW(componentCode, nil, UInt32(MSIINSTALLCONTEXT_ALL.rawValue), index, code, context, sid, sidLength)
    +                }
    +            }
    +            for client in clients {
    +                guard let product = products[client.code], let path = product.componentPath(component.code) else {
    +                    continue
    +                }
    +                paths[client.code, default: []].append(path)
    +            }
    +        }
    +        return paths
    +    }
    +
    +    /// Calls an MSI "fill this buffer" function, growing the buffer on ERROR_MORE_DATA.
    +    fileprivate static func readString(
    +        _ call: (UnsafeMutablePointer<WCHAR>, UnsafeMutablePointer<UInt32>) -> UInt32
    +    ) -> String? {
    +        var capacity: UInt32 = 256
    +        while true {
    +            var buffer = [WCHAR](repeating: 0, count: Int(capacity))
    +            var length = capacity
    +            let result = call(&buffer, &length)
    +            if result == ERROR_MORE_DATA {
    +                capacity = length + 1
    +                continue
    +            }
    +            return result == ERROR_SUCCESS ? string(from: buffer) : nil
    +        }
    +    }
    +
    +    /// Drives one of the MsiEnum*ExW functions, which each return a GUID, a context and a SID per index.
    +    /// Stops at the first error, which leaves the items found so far. An error other than the end of
    +    /// the list sets `complete` to false.
    +    private static func enumerate(
    +        complete: inout Bool,
    +        _ call: (UInt32, UnsafeMutablePointer<WCHAR>, UnsafeMutablePointer<MSIINSTALLCONTEXT>, UnsafeMutablePointer<WCHAR>, UnsafeMutablePointer<UInt32>) -> UInt32
    +    ) -> [(code: String, context: MSIINSTALLCONTEXT, sid: String?)] {
    +        var items: [(code: String, context: MSIINSTALLCONTEXT, sid: String?)] = []
    +        var index: UInt32 = 0
    +        while true {
    +            var code = [WCHAR](repeating: 0, count: 39)
    +            var context = MSIINSTALLCONTEXT_NONE
    +            var sid = [WCHAR](repeating: 0, count: 256)
    +            var sidLength: UInt32 = 256
    +            let result = call(index, &code, &context, &sid, &sidLength)
    +            if result != ERROR_SUCCESS {
    +                if result != UInt32(ERROR_NO_MORE_ITEMS) {
    +                    complete = false
    +                }
    +                break
    +            }
    +            let sidString = string(from: sid)
    +            items.append((string(from: code), context, sidString.isEmpty ? nil : sidString))
    +            index += 1
    +        }
    +        return items
    +    }
    +}
    +
    +private func withWide<R>(_ s: String?, _ body: (UnsafePointer<WCHAR>?) -> R) -> R {
    +    guard let s else {
    +        return body(nil)
    +    }
    +    return s.withCString(encodedAs: UTF16.self) { body($0) }
    +}
    +
    +private func string(from buffer: [WCHAR]) -> String {

    Why is this needed? Why not just String(decoding: buffer, as: UTF16.self)? That is why do you need to do the prefix call?

    compnerd compnerd commented on code on Nov 27, 2026 05:58 UTC
    Code Review
    Sources/WindowsPlatform/Windows.swift:1
    @@ -0,0 +1,138 @@
    +import Foundation
    +import Subprocess
    +import SwiftlyCore
    +import SystemPackage
    +
    +typealias fs = SwiftlyCore.FileSystem
    +
    +/// `Platform` implementation for Windows systems.
    +public struct Windows: Platform {
    +    public init() {}
    +
    +    public var defaultSwiftlyHomeDir: FilePath {
    +        // Foundation's application support directory on Windows is the Local AppData folder,
    +        // the one %LOCALAPPDATA% normally points to.
    +        let localAppData = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
    +            .first.map { FilePath($0.path) } ?? fs.home / "AppData" / "Local"

    Please use the Windows API rather than hardcoding this.

    compnerd compnerd commented on code on Nov 27, 2026 05:59 UTC
    Code Review
    Sources/WindowsPlatform/Windows.swift:1
    @@ -0,0 +1,138 @@
    +import Foundation
    +import Subprocess
    +import SwiftlyCore
    +import SystemPackage
    +
    +typealias fs = SwiftlyCore.FileSystem
    +
    +/// `Platform` implementation for Windows systems.
    +public struct Windows: Platform {
    +    public init() {}
    +
    +    public var defaultSwiftlyHomeDir: FilePath {
    +        // Foundation's application support directory on Windows is the Local AppData folder,
    +        // the one %LOCALAPPDATA% normally points to.
    +        let localAppData = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
    +            .first.map { FilePath($0.path) } ?? fs.home / "AppData" / "Local"
    +        return localAppData / "swiftly"
    +    }
    +
    +    public func swiftlyBinDir(_ ctx: SwiftlyCoreContext) -> FilePath {
    +        ctx.mockedHomeDir.map { $0 / "bin" }
    +            ?? ProcessInfo.processInfo.environment["SWIFTLY_BIN_DIR"].map { FilePath($0) }
    +            ?? self.defaultSwiftlyHomeDir / "bin"
    +    }
    +
    +    public func swiftlyToolchainsDir(_ ctx: SwiftlyCoreContext) -> FilePath {
    +        ctx.mockedHomeDir.map { $0 / "toolchains" }
    +            ?? ProcessInfo.processInfo.environment["SWIFTLY_TOOLCHAINS_DIR"].map { FilePath($0) }
    +            ?? self.defaultSwiftlyHomeDir / "toolchains"
    +    }
    +
    +    public func escapePathForShell(_ path: FilePath) -> String {
    +        // Double quotes work for both cmd and PowerShell, and neither allows them inside a path.
    +        "\"\(path.string)\""
    +    }
    +
    +    public var toolchainFileExtension: String {
    +        "exe"
    +    }
    +
    +    public func install(
    +        _: SwiftlyCoreContext, from _: FilePath, version _: ToolchainVersion, verbose _: Bool
    +    ) async throws {
    +        throw Self.notSupportedYet("Installing toolchains")
    +    }
    +
    +    public func extractSwiftlyAndInstall(_: SwiftlyCoreContext, from _: FilePath) async throws {
    +        throw Self.notSupportedYet("Installing swiftly")
    +    }
    +
    +    public func uninstall(_: SwiftlyCoreContext, _: ToolchainVersion, verbose _: Bool) async throws {
    +        throw Self.notSupportedYet("Uninstalling toolchains")
    +    }
    +
    +    public func getExecutableName() -> String {
    +        "swiftly-\(cpuArch)-unknown-windows-msvc.exe"
    +    }
    +
    +    public func verifySwiftlySystemPrerequisites() async throws {
    +        // Nothing beyond Windows itself is needed to run swiftly.
    +    }
    +
    +    public func verifySystemPrerequisitesForInstall(
    +        _: SwiftlyCoreContext, platformName _: String, version _: ToolchainVersion,
    +        requireSignatureValidation _: Bool
    +    ) async throws -> String? {
    +        throw Self.notSupportedYet("Installing toolchains")
    +    }
    +
    +    public func verifyToolchainSignature(
    +        _: SwiftlyCoreContext, toolchainFile _: ToolchainFile, archive _: FilePath, verbose _: Bool
    +    ) async throws {
    +        throw Self.notSupportedYet("Verifying toolchain signatures")
    +    }
    +
    +    public func verifySwiftlySignature(
    +        _: SwiftlyCoreContext, archiveDownloadURL _: URL, archive _: FilePath, verbose _: Bool
    +    ) async throws {
    +        throw Self.notSupportedYet("Verifying swiftly signatures")
    +    }
    +
    +    public func detectPlatform(
    +        _: SwiftlyCoreContext, disableConfirmation _: Bool, platform _: String?
    +    ) async throws -> PlatformDefinition {
    +        PlatformDefinition(name: "win10", nameFull: "windows10", namePretty: "Windows 10")
    +    }
    +
    +    public func getShell() async throws -> String {
    +        ProcessInfo.processInfo.environment["ComSpec"] ?? "cmd.exe"

    This seems sketchy.

    Reviewers
    Assignees
    AbdAlRahmanGad AbdAlRahmanGad
    Labels
    risk: low confidence: 86.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 70.6% (HIGH) · Higher = larger blast radius
    70.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 86.1% · Lower = rushed or shallow review
    86.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.8% · Safe to merge
    9.8%