Skip to content

Commit

Permalink
Reduce direct access to .shared singletons (tuist#6381)
Browse files Browse the repository at this point in the history
* Migrate `SwiftPackageManagerController` off singletons

* MIgrate `SimulatorController` and `XcodeBuildController` off singltons (mostly)

* Migrate away from direct calls to DeveloperEnvironment.shared

* Migrate Formatter off `Environment.shared`

* Migrate `GitHandler` off `System.shared`

* Migrate `ManifestLoaderFactory` off `Environment.shared`

* linting

* Move .shared access to default parameter values on `SimulatorController`
  • Loading branch information
waltflanagan authored Jun 28, 2024
1 parent 5140568 commit 242180b
Show file tree
Hide file tree
Showing 15 changed files with 92 additions and 51 deletions.
10 changes: 5 additions & 5 deletions Sources/TuistAutomation/Utilities/Formatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ protocol Formatting {
final class Formatter: Formatting {
private let formatter: XCBeautifier

init() {
init(environment: Environmenting = Environment.shared) {
formatter = XCBeautifier(
colored: Environment.shared.shouldOutputBeColoured,
renderer: Self.renderer(),
colored: environment.shouldOutputBeColoured,
renderer: Self.renderer(for: environment),
preserveUnbeautifiedLines: false,
additionalLines: { nil }
)
Expand All @@ -23,8 +23,8 @@ final class Formatter: Formatting {
formatter.format(line: line)
}

private static func renderer() -> Renderer {
if Environment.shared.isGitHubActions {
private static func renderer(for environment: Environmenting) -> Renderer {
if environment.isGitHubActions {
return .gitHubActions
} else {
return .terminal
Expand Down
18 changes: 11 additions & 7 deletions Sources/TuistAutomation/XcodeBuild/XcodeBuildController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public final class XcodeBuildController: XcodeBuildControlling {

private let formatter: Formatting
private let environment: Environmenting
private let simulatorController: SimulatorController
private let system: Systeming

public convenience init() {
self.init(formatter: Formatter(), environment: Environment.shared)
Expand All @@ -28,6 +30,8 @@ public final class XcodeBuildController: XcodeBuildControlling {
) {
self.formatter = formatter
self.environment = environment
self.simulatorController = SimulatorController()
self.system = System.shared
}

public func build(
Expand Down Expand Up @@ -69,7 +73,7 @@ public final class XcodeBuildController: XcodeBuildControlling {
}
command.append(contentsOf: ["-destination", value.joined(separator: ",")])
case .mac:
command.append(contentsOf: ["-destination", SimulatorController().macOSDestination()])
command.append(contentsOf: ["-destination", simulatorController.macOSDestination()])
case nil:
break
}
Expand Down Expand Up @@ -131,7 +135,7 @@ public final class XcodeBuildController: XcodeBuildControlling {
}
command.append(contentsOf: ["-destination", value.joined(separator: ",")])
case .mac:
command.append(contentsOf: ["-destination", SimulatorController().macOSDestination()])
command.append(contentsOf: ["-destination", simulatorController.macOSDestination()])
}

// Derived data path
Expand Down Expand Up @@ -310,10 +314,10 @@ public final class XcodeBuildController: XcodeBuildControlling {

logger.debug("Running xcodebuild command: \(command.joined(separator: " "))")

try System.shared.run(command,
verbose: false,
environment: System.shared.env,
redirection: .stream(stdout: { bytes in
try system.run(command,
verbose: false,
environment: system.env,
redirection: .stream(stdout: { bytes in
log(bytes)
}, stderr: { bytes in
log(bytes, isError: true)
Expand All @@ -328,7 +332,7 @@ public final class XcodeBuildController: XcodeBuildControlling {
// like that's happening.
return try await Task.retrying(maxRetryCount: 5) {
let systemTask = Task {
return try await System.shared.runAndCollectOutput(command).standardOutput
return try await self.system.runAndCollectOutput(command).standardOutput
}

let timeoutTask = Task {
Expand Down
31 changes: 20 additions & 11 deletions Sources/TuistCore/Simulator/SimulatorController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,22 @@ public final class SimulatorController: SimulatorControlling {
private let jsonDecoder = JSONDecoder()
private let userInputReader: UserInputReading

public init(userInputReader: UserInputReading = UserInputReader()) {
private let system: Systeming
private let devEnvironment: DeveloperEnvironmenting

public init(
userInputReader: UserInputReading = UserInputReader(),
system: Systeming = System.shared,
devEnvironment: DeveloperEnvironmenting = DeveloperEnvironment.shared
) {
self.userInputReader = userInputReader
self.system = system
self.devEnvironment = devEnvironment
}

/// Returns the list of simulator devices that are available in the system.
func devices() async throws -> [SimulatorDevice] {
let output = try await System.shared.runAndCollectOutput(["/usr/bin/xcrun", "simctl", "list", "devices", "--json"])
let output = try await system.runAndCollectOutput(["/usr/bin/xcrun", "simctl", "list", "devices", "--json"])
let data = output.standardOutput.data(using: .utf8)!
let json = try JSONSerialization.jsonObject(with: data, options: [])
guard let dictionary = json as? [String: Any],
Expand All @@ -125,7 +134,7 @@ public final class SimulatorController: SimulatorControlling {

/// Returns the list of simulator runtimes that are available in the system.
func runtimes() async throws -> [SimulatorRuntime] {
let output = try await System.shared.runAndCollectOutput(["/usr/bin/xcrun", "simctl", "list", "runtimes", "--json"])
let output = try await system.runAndCollectOutput(["/usr/bin/xcrun", "simctl", "list", "runtimes", "--json"])
let data = output.standardOutput.data(using: .utf8)!
let json = try JSONSerialization.jsonObject(with: data, options: [])
guard let dictionary = json as? [String: Any],
Expand Down Expand Up @@ -241,15 +250,15 @@ public final class SimulatorController: SimulatorControlling {

public func installApp(at path: AbsolutePath, device: SimulatorDevice) throws {
logger.debug("Installing app at \(path) on simulator device with id \(device.udid)")
let device = try device.booted()
try System.shared.run(["/usr/bin/xcrun", "simctl", "install", device.udid, path.pathString])
let device = try device.booted(using: system)
try system.run(["/usr/bin/xcrun", "simctl", "install", device.udid, path.pathString])
}

public func launchApp(bundleId: String, device: SimulatorDevice, arguments: [String]) throws {
logger.debug("Launching app with bundle id \(bundleId) on simulator device with id \(device.udid)")
let device = try device.booted()
try System.shared.run(["/usr/bin/open", "-a", "Simulator"])
try System.shared.run(["/usr/bin/xcrun", "simctl", "launch", device.udid, bundleId] + arguments)
let device = try device.booted(using: system)
try system.run(["/usr/bin/open", "-a", "Simulator"])
try system.run(["/usr/bin/xcrun", "simctl", "launch", device.udid, bundleId] + arguments)
}

/// https://www.mokacoding.com/blog/xcodebuild-destination-options/
Expand Down Expand Up @@ -280,7 +289,7 @@ public final class SimulatorController: SimulatorControlling {

public func macOSDestination() -> String {
let arch: String
switch DeveloperEnvironment.shared.architecture {
switch devEnvironment.architecture {
case .arm64:
arch = "arm64"
case .x8664:
Expand All @@ -293,9 +302,9 @@ public final class SimulatorController: SimulatorControlling {
extension SimulatorDevice {
/// Attempts to boot the simulator.
/// - returns: The `SimulatorDevice` with updated `isShutdown` field.
fileprivate func booted() throws -> Self {
fileprivate func booted(using system: Systeming) throws -> Self {
guard isShutdown else { return self }
try System.shared.run(["/usr/bin/xcrun", "simctl", "boot", udid])
try system.run(["/usr/bin/xcrun", "simctl", "boot", udid])
return SimulatorDevice(
dataPath: dataPath,
logPath: logPath,
Expand Down
5 changes: 4 additions & 1 deletion Sources/TuistKit/ProjectEditor/ProjectEditorMapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ final class ProjectEditorMapper: ProjectEditorMapping {
private let swiftPackageManagerController: SwiftPackageManagerControlling

init(
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController()
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(
system: System.shared,
fileHandler: FileHandler.shared
)
) {
self.swiftPackageManagerController = swiftPackageManagerController
}
Expand Down
5 changes: 4 additions & 1 deletion Sources/TuistKit/Services/InstallService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ final class InstallService {
init(
pluginService: PluginServicing = PluginService(),
configLoader: ConfigLoading = ConfigLoader(manifestLoader: CachedManifestLoader()),
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(),
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(
system: System.shared,
fileHandler: FileHandler.shared
),
fileHandler: FileHandling = FileHandler.shared,
manifestFilesLocator: ManifestFilesLocating = ManifestFilesLocator()
) {
Expand Down
5 changes: 4 additions & 1 deletion Sources/TuistKit/Services/Plugin/PluginArchiveService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ final class PluginArchiveService {
private let fileArchiverFactory: FileArchivingFactorying

init(
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(),
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(
system: System.shared,
fileHandler: FileHandler.shared
),
manifestLoader: ManifestLoading = ManifestLoader(),
fileArchiverFactory: FileArchivingFactorying = FileArchivingFactory()
) {
Expand Down
2 changes: 1 addition & 1 deletion Sources/TuistLoader/Loaders/ManifestLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public class ManifestLoader: ManifestLoading {
projectDescriptionHelpersBuilderFactory: ProjectDescriptionHelpersBuilderFactory(),
manifestFilesLocator: ManifestFilesLocator(),
xcodeController: XcodeController.shared,
swiftPackageManagerController: SwiftPackageManagerController()
swiftPackageManagerController: SwiftPackageManagerController(system: System.shared, fileHandler: FileHandler.shared)
)
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/TuistLoader/Loaders/ManifestLoaderFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import TuistSupport

public final class ManifestLoaderFactory {
private let useCache: Bool
public convenience init() {
let cacheSetting = Environment.shared.tuistConfigVariables[Constants.EnvironmentVariables.cacheManifests, default: "1"]
public convenience init(environment: Environmenting = Environment.shared) {
let cacheSetting = environment.tuistConfigVariables[Constants.EnvironmentVariables.cacheManifests, default: "1"]
self.init(useCache: cacheSetting == "1")
}

Expand Down
5 changes: 4 additions & 1 deletion Sources/TuistLoader/Loaders/PackageSettingsLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ public final class PackageSettingsLoader: PackageSettingsLoading {

public init(
manifestLoader: ManifestLoading = ManifestLoader(),
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(),
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(
system: System.shared,
fileHandler: FileHandler.shared
),
fileHandler: FileHandling = FileHandler.shared,
manifestFilesLocator: ManifestFilesLocating = ManifestFilesLocator()
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ public final class SwiftPackageManagerGraphLoader: SwiftPackageManagerGraphLoadi
private let fileHandler: FileHandling

public init(
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(),
swiftPackageManagerController: SwiftPackageManagerControlling = SwiftPackageManagerController(
system: System.shared,
fileHandler: FileHandler.shared
),
packageInfoMapper: PackageInfoMapping = PackageInfoMapper(),
manifestLoader: ManifestLoading = ManifestLoader(),
fileHandler: FileHandling = FileHandler.shared
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,45 +45,51 @@ public protocol SwiftPackageManagerControlling {
}

public final class SwiftPackageManagerController: SwiftPackageManagerControlling {
public init() {}
let system: Systeming
let fileHandler: FileHandling

public init(system: Systeming, fileHandler: FileHandling) {
self.system = system
self.fileHandler = fileHandler
}

public func resolve(at path: AbsolutePath, printOutput: Bool) throws {
let command = buildSwiftPackageCommand(packagePath: path, extraArguments: ["resolve"])

printOutput ?
try System.shared.runAndPrint(command) :
try System.shared.run(command)
try system.runAndPrint(command) :
try system.run(command)
}

public func update(at path: AbsolutePath, printOutput: Bool) throws {
let command = buildSwiftPackageCommand(packagePath: path, extraArguments: ["update"])

printOutput ?
try System.shared.runAndPrint(command) :
try System.shared.run(command)
try system.runAndPrint(command) :
try system.run(command)
}

public func setToolsVersion(at path: AbsolutePath, to version: Version) throws {
let extraArguments = ["tools-version", "--set", "\(version.major).\(version.minor)"]

let command = buildSwiftPackageCommand(packagePath: path, extraArguments: extraArguments)

try System.shared.run(command)
try system.run(command)
}

public func getToolsVersion(at path: AbsolutePath) throws -> Version {
let extraArguments = ["tools-version"]

let command = buildSwiftPackageCommand(packagePath: path, extraArguments: extraArguments)

let rawVersion = try System.shared.capture(command).trimmingCharacters(in: .whitespacesAndNewlines)
let rawVersion = try system.capture(command).trimmingCharacters(in: .whitespacesAndNewlines)
return try Version(versionString: rawVersion)
}

public func loadPackageInfo(at path: AbsolutePath) throws -> PackageInfo {
let command = buildSwiftPackageCommand(packagePath: path, extraArguments: ["dump-package"])

let json = try System.shared.capture(command)
let json = try system.capture(command)

let data = Data(json.utf8)
let decoder = JSONDecoder()
Expand All @@ -109,22 +115,22 @@ public final class SwiftPackageManagerController: SwiftPackageManagerControlling

let arm64Target = "arm64-apple-macosx"
let x64Target = "x86_64-apple-macosx"
try System.shared.run(
try system.run(
buildCommand + [
arm64Target,
]
)
try System.shared.run(
try system.run(
buildCommand + [
x64Target,
]
)

if !FileHandler.shared.exists(outputPath) {
try FileHandler.shared.createFolder(outputPath)
if !fileHandler.exists(outputPath) {
try fileHandler.createFolder(outputPath)
}

try System.shared.run([
try system.run([
"lipo", "-create", "-output", outputPath.appending(component: product).pathString,
buildPath.appending(components: arm64Target, "release", product).pathString,
buildPath.appending(components: x64Target, "release", product).pathString,
Expand Down
8 changes: 6 additions & 2 deletions Sources/TuistSupport/Utils/DerivedDataLocator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@ public protocol DerivedDataLocating {
}

public final class DerivedDataLocator: DerivedDataLocating {
public init() {}
private let devEnvironment: DeveloperEnvironmenting

public init(devEnvironment: DeveloperEnvironmenting = DeveloperEnvironment.shared) {
self.devEnvironment = devEnvironment
}

public func locate(
for projectPath: AbsolutePath
) throws -> AbsolutePath {
let hash = try XcodeProjectPathHasher.hashString(for: projectPath.pathString)
return DeveloperEnvironment.shared.derivedDataDirectory
return devEnvironment.derivedDataDirectory
.appending(component: "\(projectPath.basenameWithoutExt)-\(hash)")
}
}
Expand Down
9 changes: 6 additions & 3 deletions Sources/TuistSupport/Utils/GitHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,14 @@ public protocol GitHandling {
/// Uses the system to execute git commands.
public final class GitHandler: GitHandling {
private let system: Systeming
private let environment: Environmenting

public init(
system: Systeming = System.shared
system: Systeming = System.shared,
environment: Environmenting = Environment.shared
) {
self.system = system
self.environment = environment
}

public func clone(url: String, into path: AbsolutePath) throws {
Expand Down Expand Up @@ -75,15 +78,15 @@ public final class GitHandler: GitHandling {
}

private func run(command: String...) throws {
if Environment.shared.isVerbose {
if environment.isVerbose {
try system.runAndPrint(command, verbose: true, environment: System.shared.env)
} else {
try system.run(command)
}
}

private func capture(command: String...) throws -> String {
if Environment.shared.isVerbose {
if environment.isVerbose {
return try system.capture(command, verbose: true, environment: System.shared.env)
} else {
return try system.capture(command)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ final class SimulatorControllerTests: TuistUnitTestCase {

override func setUp() {
super.setUp()
subject = SimulatorController()
subject = SimulatorController(system: system)
}

override func tearDown() {
Expand Down
Loading

0 comments on commit 242180b

Please sign in to comment.