Skip to content

Commit

Permalink
Scope logger to test cases (tuist#7194)
Browse files Browse the repository at this point in the history
* Add apple-service-context dependency

* Rename TuistApp to TuistCLI

* Use the service context to pass the logger instance

* Adjust TuistSupport to use the logger from the context service

* Adjust TuistCore to use the logger from the service context

* Adjust TuistServer to read the logger from the ServiceContext in the task local

* Adjust TuistPlugin to use the logger from the ServiceContext in the task local

* Update TuistHasher to use the logger from the ServiceContext instance in the task local

* Update TuistGenerator to get the logger from the ServiceContext instance in the task local

* Update TuistAutomation to use the logger from the ServiceContext in the task local

* Update TuistMigration to get the logger from the ServiceContext instance in the taxk actor

* Update TuistLoader to read the ServiceContext from the task local

* Update TuistDependencies to use ServiceContext from the task local

* Update TuistAsyncQueue to use the logger from the ServiceContext in the task local

* Update TuistKit to use the logger from the ServiceContext in the task local

* Create an interface to dependency-inject the testing logger

* Fix tests

* Make implicit dependency explicit

* Add missing dependency to the Package.swift

* Some lint fixes
  • Loading branch information
pepicrft authored Jan 3, 2025
1 parent 8b61360 commit 2867c7b
Show file tree
Hide file tree
Showing 174 changed files with 4,180 additions and 3,716 deletions.
20 changes: 19 additions & 1 deletion Package.resolved
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"originHash" : "bf0667dacb79660d6272837f5c8857de0bc8cebff357be450933f9d91e77965e",
"originHash" : "a5463ecc4f8a522ac814a97c426e0720fabee269b69720a02aeea1507736824f",
"pins" : [
{
"identity" : "aexml",
Expand Down Expand Up @@ -235,6 +235,15 @@
"version" : "1.6.1"
}
},
{
"identity" : "swift-log-oslog",
"kind" : "remoteSourceControl",
"location" : "https://github.com/chrisaljoudi/swift-log-oslog.git",
"state" : {
"revision" : "176d41d46429e79c806333025b226e0c50a0c602",
"version" : "0.2.2"
}
},
{
"identity" : "swift-nio",
"kind" : "remoteSourceControl",
Expand Down Expand Up @@ -262,6 +271,15 @@
"version" : "1.0.2"
}
},
{
"identity" : "swift-service-context",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-service-context",
"state" : {
"revision" : "0c62c5b4601d6c125050b5c3a97f20cce881d32b",
"version" : "1.1.0"
}
},
{
"identity" : "swift-syntax",
"kind" : "remoteSourceControl",
Expand Down
3 changes: 3 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ let targets: [Target] = [
"Mockable",
"FileSystem",
"Command",
.product(name: "ServiceContextModule", package: "swift-service-context"),
],
swiftSettings: [
.define("MOCKING", .when(configuration: .debug)),
Expand Down Expand Up @@ -517,6 +518,8 @@ let package = Package(
.package(url: "https://github.com/tuist/Command.git", exact: "0.8.0"),
.package(url: "https://github.com/sparkle-project/Sparkle.git", from: "2.6.4"),
.package(url: "https://github.com/apple/swift-collections", .upToNextMajor(from: "1.1.4")),
.package(url: "https://github.com/apple/swift-service-context", .upToNextMajor(from: "1.0.0")),
.package(url: "https://github.com/chrisaljoudi/swift-log-oslog.git", .upToNextMajor(from: "0.2.2")),
],
targets: targets
)
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ open class ServerAcceptanceTestCase: TuistAcceptanceTestCase {
try await run(ProjectDeleteCommand.self, fullHandle)
try await run(OrganizationDeleteCommand.self, organizationHandle)
try await run(LogoutCommand.self)
TestingLogHandler.reset()
try await super.tearDown()
}
}
4 changes: 0 additions & 4 deletions Sources/TuistAcceptanceTesting/TuistAcceptanceTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,6 @@ open class TuistAcceptanceTestCase: XCTestCase {

fileSystem = FileSystem()

DispatchQueue.once(token: "io.tuist.test.logging") {
LoggingSystem.bootstrap { AcceptanceTestCaseLogHandler(label: $0) }
}

derivedDataDirectory = try TemporaryDirectory(removeTreeOnDeinit: true)
fixtureTemporaryDirectory = try TemporaryDirectory(removeTreeOnDeinit: true)

Expand Down

This file was deleted.

3 changes: 0 additions & 3 deletions Sources/TuistAnalytics/Log/Logger.swift

This file was deleted.

18 changes: 12 additions & 6 deletions Sources/TuistAsyncQueue/AsyncQueue.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Foundation
import Mockable
import Queuer
import ServiceContextModule
import TuistCore
import TuistSupport

Expand Down Expand Up @@ -73,7 +74,8 @@ public class AsyncQueue: AsyncQueuing {

public func dispatch(event: some AsyncQueueEvent) throws {
guard let dispatcher = dispatchers[event.dispatcherId] else {
logger.debug("Couldn't find dispatcher with id: \(event.dispatcherId), skipping dispatching \(event.id)")
ServiceContext.current?.logger?
.debug("Couldn't find dispatcher with id: \(event.dispatcherId), skipping dispatching \(event.id)")
return
}

Expand All @@ -89,7 +91,8 @@ public class AsyncQueue: AsyncQueuing {

private func liveDispatchOperation(event: some AsyncQueueEvent, dispatcher: AsyncQueueDispatching) -> Operation {
AsyncConcurrentOperation(name: event.id.uuidString) { operation in
logger.debug("Dispatching event with ID '\(event.id.uuidString)' to '\(dispatcher.identifier)'")
ServiceContext.current?.logger?
.debug("Dispatching event with ID '\(event.id.uuidString)' to '\(dispatcher.identifier)'")
do {
try dispatcher.dispatch(event: event) {
try await self.persistor.delete(event: event)
Expand All @@ -108,7 +111,8 @@ public class AsyncQueue: AsyncQueuing {
private func dispatchPersisted(eventTuple: AsyncQueueEventTuple) async throws {
guard let dispatcher = dispatchers.first(where: { $0.key == eventTuple.dispatcherId })?.value else {
try await deletePersistedEvent(filename: eventTuple.filename)
logger.error("Couldn't find dispatcher for persisted event with id: \(eventTuple.dispatcherId)")
ServiceContext.current?.logger?
.error("Couldn't find dispatcher for persisted event with id: \(eventTuple.dispatcherId)")
return
}

Expand All @@ -122,12 +126,14 @@ public class AsyncQueue: AsyncQueuing {
) -> Operation {
ConcurrentOperation(name: event.id.uuidString) { _ in
do {
logger.debug("Dispatching persisted event with ID '\(event.id.uuidString)' to '\(dispatcher.identifier)'")
ServiceContext.current?.logger?
.debug("Dispatching persisted event with ID '\(event.id.uuidString)' to '\(dispatcher.identifier)'")
try dispatcher.dispatchPersisted(data: event.data) {
try await self.deletePersistedEvent(filename: event.filename)
}
} catch {
logger.debug("Failed to dispatch persisted event with ID '\(event.id.uuidString)' to '\(dispatcher.identifier)'")
ServiceContext.current?.logger?
.debug("Failed to dispatch persisted event with ID '\(event.id.uuidString)' to '\(dispatcher.identifier)'")
}
}
}
Expand All @@ -139,7 +145,7 @@ public class AsyncQueue: AsyncQueuing {
try await dispatchPersisted(eventTuple: event)
}
} catch {
logger.debug("Error loading persisted events: \(error)")
ServiceContext.current?.logger?.debug("Error loading persisted events: \(error)")
}
}

Expand Down
3 changes: 0 additions & 3 deletions Sources/TuistAsyncQueue/Log/Logger.swift

This file was deleted.

6 changes: 4 additions & 2 deletions Sources/TuistAutomation/Device/DeviceController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import FileSystem
import Foundation
import Mockable
import Path
import ServiceContextModule
import TuistSupport
import XcodeGraph

Expand Down Expand Up @@ -84,7 +85,7 @@ public final class DeviceController: DeviceControlling {
at path: AbsolutePath,
device: PhysicalDevice
) async throws {
logger.debug("Installing app at \(path) on simulator device with id \(device.id)")
ServiceContext.current?.logger?.debug("Installing app at \(path) on simulator device with id \(device.id)")
do {
_ = try await commandRunner.run(
arguments: [
Expand All @@ -108,7 +109,8 @@ public final class DeviceController: DeviceControlling {
bundleId: String,
device: PhysicalDevice
) async throws {
logger.debug("Launching app with bundle id \(bundleId) on a physical device with id \(device.id)")
ServiceContext.current?.logger?
.debug("Launching app with bundle id \(bundleId) on a physical device with id \(device.id)")
_ = try await commandRunner.run(
arguments: [
"/usr/bin/xcrun", "devicectl",
Expand Down
3 changes: 0 additions & 3 deletions Sources/TuistAutomation/Log/Logger.swift

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import Foundation
import Path
import ServiceContextModule
import TuistCore
import XcodeGraph

public final class SkipUITestsProjectMapper: ProjectMapping {
public init() {}

public func map(project: Project) throws -> (Project, [SideEffectDescriptor]) {
logger.debug("Transforming project \(project.name): Pruning UI tests targets")
ServiceContext.current?.logger?.debug("Transforming project \(project.name): Pruning UI tests targets")

var project = project
project.targets = project.targets.mapValues { target in
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Foundation
import Path
import ServiceContextModule
import TuistCore
import XcodeGraph

Expand All @@ -12,7 +13,7 @@ public final class SourceRootPathProjectMapper: ProjectMapping {
public init() {}

public func map(project: Project) throws -> (Project, [SideEffectDescriptor]) {
logger.debug("Transforming project \(project.name): Setting $SRCROOT to \(project.name)")
ServiceContext.current?.logger?.debug("Transforming project \(project.name): Setting $SRCROOT to \(project.name)")

var project = project
var base = project.settings.base
Expand Down
5 changes: 3 additions & 2 deletions Sources/TuistAutomation/Utilities/AppRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import FileSystem
import Foundation
import Mockable
import Path
import ServiceContextModule
import struct TSCUtility.Version
import TuistCore
import TuistSupport
Expand Down Expand Up @@ -171,11 +172,11 @@ public final class AppRunner: AppRunning {
})
else { throw AppRunnerError.selectedPlatformNotFound(simulatorPlatform.caseValue) }

logger.notice("Installing and launching \(appBundle.infoPlist.name) on \(simulator.device.name)")
ServiceContext.current?.logger?.notice("Installing and launching \(appBundle.infoPlist.name) on \(simulator.device.name)")
let device = try simulatorController.booted(device: simulator.device)
try simulatorController.installApp(at: appBundle.path, device: device)
try await simulatorController.launchApp(bundleId: appBundle.infoPlist.bundleId, device: device, arguments: [])
logger.notice("\(appBundle.infoPlist.name) was successfully launched 📲", metadata: .success)
ServiceContext.current?.logger?.notice("\(appBundle.infoPlist.name) was successfully launched 📲", metadata: .success)
}
}

Expand Down
3 changes: 2 additions & 1 deletion Sources/TuistAutomation/Utilities/BuildGraphInspector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import FileSystem
import Foundation
import Mockable
import Path
import ServiceContextModule
import TuistCore
import TuistSupport
import XcodeGraph
Expand Down Expand Up @@ -93,7 +94,7 @@ public final class BuildGraphInspector: BuildGraphInspecting {
if configurations.contains(where: { $0.key.name == configuration }) {
arguments.append(.configuration(configuration))
} else {
logger
ServiceContext.current?.logger?
.warning(
"The scheme's targets don't have the given configuration \(configuration). Defaulting to the scheme's default."
)
Expand Down
9 changes: 7 additions & 2 deletions Sources/TuistAutomation/Utilities/TargetBuilder.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import FileSystem
import Path
import ServiceContextModule
import TSCUtility
import TuistCore
import TuistSupport
Expand Down Expand Up @@ -95,7 +96,7 @@ public final class TargetBuilder: TargetBuilding {
graphTraverser: GraphTraversing,
passthroughXcodeBuildArguments: [String]
) async throws {
logger.log(level: .notice, "Building scheme \(scheme.name)", metadata: .section)
ServiceContext.current?.logger?.log(level: .notice, "Building scheme \(scheme.name)", metadata: .section)

let buildArguments = buildGraphInspector.buildArguments(
project: target.project,
Expand Down Expand Up @@ -160,7 +161,11 @@ public final class TargetBuilder: TargetBuilding {
if try await !fileSystem.exists(buildOutputPath) {
try FileHandler.shared.createFolder(buildOutputPath)
}
logger.log(level: .notice, "Copying build products to \(buildOutputPath.pathString)", metadata: .subsection)
ServiceContext.current?.logger?.log(
level: .notice,
"Copying build products to \(buildOutputPath.pathString)",
metadata: .subsection
)

for product in try FileHandler.shared.contentsOfDirectory(xcodeSchemeBuildPath) {
let productOutputPath = buildOutputPath.appending(component: product.basename)
Expand Down
10 changes: 6 additions & 4 deletions Sources/TuistAutomation/Utilities/TargetRunner.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import FileSystem
import Path
import ServiceContextModule
import struct TSCUtility.Version
import TuistCore
import TuistSupport
Expand Down Expand Up @@ -137,8 +138,8 @@ public final class TargetRunner: TargetRunning {
}

private func runExecutable(_ executablePath: AbsolutePath, arguments: [String]) throws {
logger.notice("Running executable \(executablePath.basename)", metadata: .section)
logger.debug("Forwarding arguments: \(arguments.joined(separator: ", "))")
ServiceContext.current?.logger?.notice("Running executable \(executablePath.basename)", metadata: .section)
ServiceContext.current?.logger?.debug("Forwarding arguments: \(arguments.joined(separator: ", "))")
try System.shared.runAndPrint([executablePath.pathString] + arguments)
}

Expand All @@ -164,8 +165,9 @@ public final class TargetRunner: TargetRunning {
deviceName: deviceName
)

logger.debug("Running app \(appPath.pathString) with arguments [\(arguments.joined(separator: ", "))]")
logger.notice("Running app \(bundleId) on \(simulator.device.name)", metadata: .section)
ServiceContext.current?.logger?
.debug("Running app \(appPath.pathString) with arguments [\(arguments.joined(separator: ", "))]")
ServiceContext.current?.logger?.notice("Running app \(bundleId) on \(simulator.device.name)", metadata: .section)
try simulatorController.installApp(at: appPath, device: simulator.device)
try await simulatorController.launchApp(bundleId: bundleId, device: simulator.device, arguments: arguments)
}
Expand Down
7 changes: 4 additions & 3 deletions Sources/TuistAutomation/XcodeBuild/XcodeBuildController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Foundation
import Path
import TuistCore
import TuistSupport
import ServiceContextModule

public final class XcodeBuildController: XcodeBuildControlling {
// MARK: - Attributes
Expand Down Expand Up @@ -311,14 +312,14 @@ public final class XcodeBuildController: XcodeBuildControlling {
let lines = format(bytes).split(separator: "\n")
for line in lines where !line.isEmpty {
if isError {
logger.error("\(line)")
ServiceContext.current?.logger?.error("\(line)")
} else {
logger.info("\(line)")
ServiceContext.current?.logger?.info("\(line)")
}
}
}

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

try system.run(command,
verbose: false,
Expand Down
3 changes: 0 additions & 3 deletions Sources/TuistCore/Log/Logger.swift

This file was deleted.

Loading

0 comments on commit 2867c7b

Please sign in to comment.