From c9378046a660511a2a6cfb9161a8441b2a10b06d Mon Sep 17 00:00:00 2001 From: Chris Araman Date: Tue, 11 May 2021 21:45:24 -0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=A6=BE=20Check=20for=20Apple=20Silicon?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Package.swift | 6 ++- .../ExternalCommands/ExternalCommand.swift | 6 +++ .../SysCtlSystemCommand.swift | 40 +++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 Sources/MasKit/ExternalCommands/SysCtlSystemCommand.swift diff --git a/Package.swift b/Package.swift index f730174..99ef526 100644 --- a/Package.swift +++ b/Package.swift @@ -42,7 +42,11 @@ let package = Package( ), .target( name: "MasKit", - dependencies: ["Commandant", "PromiseKit", "Version"], + dependencies: [ + "Commandant", + "PromiseKit", + "Version", + ], swiftSettings: [ .unsafeFlags([ "-I", "Sources/PrivateFrameworks/CommerceKit", diff --git a/Sources/MasKit/ExternalCommands/ExternalCommand.swift b/Sources/MasKit/ExternalCommands/ExternalCommand.swift index caf3ef0..785bc84 100644 --- a/Sources/MasKit/ExternalCommands/ExternalCommand.swift +++ b/Sources/MasKit/ExternalCommands/ExternalCommand.swift @@ -14,6 +14,7 @@ protocol ExternalCommand { var process: Process { get } + var stdout: String { get } var stderr: String { get } var stdoutPipe: Pipe { get } var stderrPipe: Pipe { get } @@ -28,6 +29,11 @@ protocol ExternalCommand { /// Common implementation extension ExternalCommand { + var stdout: String { + let data = stdoutPipe.fileHandleForReading.readDataToEndOfFile() + return String(data: data, encoding: .utf8) ?? "" + } + var stderr: String { let data = stderrPipe.fileHandleForReading.readDataToEndOfFile() return String(data: data, encoding: .utf8) ?? "" diff --git a/Sources/MasKit/ExternalCommands/SysCtlSystemCommand.swift b/Sources/MasKit/ExternalCommands/SysCtlSystemCommand.swift new file mode 100644 index 0000000..3c2a401 --- /dev/null +++ b/Sources/MasKit/ExternalCommands/SysCtlSystemCommand.swift @@ -0,0 +1,40 @@ +// +// SysCtlSystemCommand.swift +// MasKit +// +// Created by Chris Araman on 6/3/21. +// Copyright © 2021 mas-cli. All rights reserved. +// + +import Foundation + +/// Wrapper for the external sysctl system command. +/// https://ss64.com/osx/sysctl.html +struct SysCtlSystemCommand: ExternalCommand { + var binaryPath: String + + let process = Process() + + let stdoutPipe = Pipe() + let stderrPipe = Pipe() + + init(binaryPath: String = "/usr/sbin/sysctl") { + self.binaryPath = binaryPath + } + + static var isAppleSilicon: Bool = { + let sysctl = SysCtlSystemCommand() + do { + // Returns 1 on Apple Silicon even when run in an Intel context in Rosetta. + try sysctl.run(arguments: "-in", "hw.optional.arm64") + } catch { + fatalError("sysctl failed") + } + + guard sysctl.succeeded else { + fatalError("sysctl failed") + } + + return sysctl.stdout.trimmingCharacters(in: .newlines) == "1" + }() +}