Skip to content

Add JSON output for use command #380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Documentation/SwiftlyDocs.docc/swiftly-cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ Note that listing available snapshots before the latest release (major and minor
Set the in-use or default toolchain. If no toolchain is provided, print the currently in-use toolchain, if any.

```
swiftly use [--print-location] [--global-default] [--assume-yes] [--verbose] [<toolchain>] [--version] [--help]
swiftly use [--print-location] [--global-default] [--format=<format>] [--assume-yes] [--verbose] [<toolchain>] [--version] [--help]
```

**--print-location:**
Expand All @@ -165,6 +165,11 @@ swiftly use [--print-location] [--global-default] [--assume-yes] [--verbose] [<t
*Set the global default toolchain that is used when there are no .swift-version files.*


**--format=\<format\>:**

*Output format (text, json)*


**--assume-yes:**

*Disable confirmation prompts by assuming 'yes'*
Expand Down
57 changes: 57 additions & 0 deletions Sources/Swiftly/OutputSchema.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import Foundation
import SwiftlyCore

struct LocationInfo: OutputData {
let path: String

init(path: String) {
self.path = path
}

var description: String {
self.path
}
}

struct ToolchainInfo: OutputData {
let version: ToolchainVersion
let source: ToolchainSource?

var description: String {
var message = String(describing: self.version)
if let source = source {
message += " (\(source.description))"
}
return message
}
}

struct ToolchainSetInfo: OutputData {
let version: ToolchainVersion
let previousVersion: ToolchainVersion?
let isGlobal: Bool
let versionFile: String?

var description: String {
var message = self.isGlobal ? "The global default toolchain has been set to `\(self.version)`" : "The file `\(self.versionFile ?? ".swift-version")` has been set to `\(self.version)`"
if let previousVersion = previousVersion {
message += " (was \(previousVersion.name))"
}

return message
}
}

enum ToolchainSource: Codable, CustomStringConvertible {
case swiftVersionFile(String)
case globalDefault

var description: String {
switch self {
case let .swiftVersionFile(path):
return path
case .globalDefault:
return "default"
}
}
}
4 changes: 2 additions & 2 deletions Sources/Swiftly/Swiftly.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ public struct Swiftly: SwiftlyCommand {
]
)

public static func createDefaultContext() -> SwiftlyCoreContext {
SwiftlyCoreContext()
public static func createDefaultContext(format: SwiftlyCore.OutputFormat = .text) -> SwiftlyCoreContext {
SwiftlyCoreContext(format: format)
}

/// The list of directories that swiftly needs to exist in order to execute.
Expand Down
48 changes: 26 additions & 22 deletions Sources/Swiftly/Use.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ struct Use: SwiftlyCommand {
@Flag(name: .shortAndLong, help: "Set the global default toolchain that is used when there are no .swift-version files.")
var globalDefault: Bool = false

@Option(name: .long, help: "Output format (text, json)")
var format: SwiftlyCore.OutputFormat = .text

@OptionGroup var root: GlobalOptions

@Argument(help: ArgumentHelp(
Expand Down Expand Up @@ -56,7 +59,7 @@ struct Use: SwiftlyCommand {
var toolchain: String?

mutating func run() async throws {
try await self.run(Swiftly.createDefaultContext())
try await self.run(Swiftly.createDefaultContext(format: self.format))
}

mutating func run(_ ctx: SwiftlyCoreContext) async throws {
Expand Down Expand Up @@ -84,21 +87,20 @@ struct Use: SwiftlyCommand {
}

if self.printLocation {
// Print the toolchain location and exit
await ctx.message("\(Swiftly.currentPlatform.findToolchainLocation(ctx, selectedVersion))")
let location = LocationInfo(path: "\(Swiftly.currentPlatform.findToolchainLocation(ctx, selectedVersion))")
await ctx.output(location)
return
}

var message = "\(selectedVersion)"

switch result {
let source: ToolchainSource? = switch result {
case let .swiftVersionFile(versionFile, _, _):
message += " (\(versionFile))"
.swiftVersionFile("\(versionFile)")
case .globalDefault:
message += " (default)"
.globalDefault
}

await ctx.message(message)
let toolchainInfo = ToolchainInfo(version: selectedVersion, source: source)
await ctx.output(toolchainInfo)

return
}
Expand All @@ -110,8 +112,7 @@ struct Use: SwiftlyCommand {
let selector = try ToolchainSelector(parsing: toolchain)

guard let toolchain = config.listInstalledToolchains(selector: selector).max() else {
await ctx.message("No installed toolchains match \"\(toolchain)\"")
return
throw SwiftlyError(message: "No installed toolchains match \"\(toolchain)\"")
}

try await Self.execute(ctx, toolchain, globalDefault: self.globalDefault, assumeYes: self.root.assumeYes, &config)
Expand All @@ -121,13 +122,14 @@ struct Use: SwiftlyCommand {
static func execute(_ ctx: SwiftlyCoreContext, _ toolchain: ToolchainVersion, globalDefault: Bool, assumeYes: Bool = true, _ config: inout Config) async throws {
let (selectedVersion, result) = try await selectToolchain(ctx, config: &config, globalDefault: globalDefault)

var message: String
let isGlobal: Bool
let configFile: String?

if case let .swiftVersionFile(versionFile, _, _) = result {
// We don't care in this case if there were any problems with the swift version files, just overwrite it with the new value
try toolchain.name.write(to: versionFile, atomically: true)

message = "The file `\(versionFile)` has been set to `\(toolchain)`"
isGlobal = false
configFile = "\(versionFile)"
} else if let newVersionFile = try await findNewVersionFile(ctx), !globalDefault {
if !assumeYes {
await ctx.message("A new file `\(newVersionFile)` will be created to set the new in-use toolchain for this project. Alternatively, you can set your default globally with the `--global-default` flag. Proceed with creating this file?")
Expand All @@ -139,19 +141,21 @@ struct Use: SwiftlyCommand {
}

try toolchain.name.write(to: newVersionFile, atomically: true)

message = "The file `\(newVersionFile)` has been set to `\(toolchain)`"
isGlobal = false
configFile = "\(newVersionFile)"
} else {
config.inUse = toolchain
try config.save(ctx)
message = "The global default toolchain has been set to `\(toolchain)`"
}

if let selectedVersion {
message += " (was \(selectedVersion.name))"
isGlobal = true
configFile = nil
}

await ctx.message(message)
await ctx.output(ToolchainSetInfo(
version: toolchain,
previousVersion: selectedVersion,
isGlobal: isGlobal,
versionFile: configFile
))
}

static func findNewVersionFile(_ ctx: SwiftlyCoreContext) async throws -> FilePath? {
Expand Down
44 changes: 44 additions & 0 deletions Sources/SwiftlyCore/OutputFormatter.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import ArgumentParser
import Foundation

public enum OutputFormat: String, Sendable, CaseIterable, ExpressibleByArgument {
case text
case json

public var description: String {
self.rawValue
}
}

public protocol OutputFormatter {
func format(_ data: OutputData) -> String
}

public protocol OutputData: Codable, CustomStringConvertible {
var description: String { get }
}

public struct TextOutputFormatter: OutputFormatter {
public init() {}

public func format(_ data: OutputData) -> String {
data.description
}
}

public struct JSONOutputFormatter: OutputFormatter {
public init() {}

public func format(_ data: OutputData) -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]

let jsonData = try? encoder.encode(data)

guard let jsonData = jsonData, let result = String(data: jsonData, encoding: .utf8) else {
return "{}"
}

return result
}
}
83 changes: 53 additions & 30 deletions Sources/SwiftlyCore/SwiftlyCore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,68 +37,91 @@ public struct SwiftlyCoreContext: Sendable {
/// The output handler to use, if any.
public var outputHandler: (any OutputHandler)?

/// The input probider to use, if any
/// The output handler for error streams
public var errorOutputHandler: (any OutputHandler)?

/// The input provider to use, if any
public var inputProvider: (any InputProvider)?

public init() {
/// The terminal info provider
public var terminal: any Terminal

/// The format
public var format: OutputFormat = .text

public init(format: SwiftlyCore.OutputFormat = .text) {
self.httpClient = SwiftlyHTTPClient(httpRequestExecutor: HTTPRequestExecutorImpl())
self.currentDirectory = fs.cwd
self.format = format
self.terminal = SystemTerminal()
}

public init(httpClient: SwiftlyHTTPClient) {
self.httpClient = httpClient
self.currentDirectory = fs.cwd
self.terminal = SystemTerminal()
}

/// Pass the provided string to the set output handler if any.
/// If no output handler has been set, just print to stdout.
public func print(_ string: String = "", terminator: String? = nil) async {
public func print(_ string: String = "") async {
guard let handler = self.outputHandler else {
if let terminator {
Swift.print(string, terminator: terminator)
} else {
Swift.print(string)
}
Swift.print(string)
return
}
await handler.handleOutputLine(string + (terminator ?? ""))
await handler.handleOutputLine(string)
}

public func message(_ string: String = "", terminator: String? = nil) async {
// Get terminal size or use default width
let terminalWidth = self.getTerminalWidth()
let wrappedString = string.isEmpty ? string : string.wrapText(to: terminalWidth)
await self.print(wrappedString, terminator: terminator)
let wrappedString = self.wrappedMessage(string) + (terminator ?? "")

if self.format == .json {
await self.printError(wrappedString)
return
} else {
await self.print(wrappedString)
}
}

/// Detects the terminal width in columns
private func getTerminalWidth() -> Int {
#if os(macOS) || os(Linux)
var size = winsize()
#if os(OpenBSD)
// TIOCGWINSZ is a complex macro, so we need the flattened value.
let tiocgwinsz = UInt(0x4008_7468)
let result = ioctl(STDOUT_FILENO, tiocgwinsz, &size)
#else
let result = ioctl(STDOUT_FILENO, UInt(TIOCGWINSZ), &size)
#endif
private func wrappedMessage(_ string: String) -> String {
let terminalWidth = self.terminal.width()
return string.isEmpty ? string : string.wrapText(to: terminalWidth)
}

if result == 0 && Int(size.ws_col) > 0 {
return Int(size.ws_col)
public func printError(_ string: String = "") async {
if let handler = self.errorOutputHandler {
await handler.handleOutputLine(string)
} else {
if let data = (string + "\n").data(using: .utf8) {
try? FileHandle.standardError.write(contentsOf: data)
}
}
#endif
return 80 // Default width if terminal size detection fails
}

public func output(_ data: OutputData) async {
let formattedOutput: String
switch self.format {
case .text:
formattedOutput = TextOutputFormatter().format(data)
case .json:
formattedOutput = JSONOutputFormatter().format(data)
}
await self.print(formattedOutput)
}

public func readLine(prompt: String) async -> String? {
await self.print(prompt, terminator: ": \n")
await self.message(prompt, terminator: ": \n")
guard let provider = self.inputProvider else {
return Swift.readLine(strippingNewline: true)
}
return await provider.readLine()
}

public func promptForConfirmation(defaultBehavior: Bool) async -> Bool {
if self.format == .json {
await self.message("Assuming \(defaultBehavior ? "yes" : "no") due to JSON format")
return defaultBehavior
}
let options: String
if defaultBehavior {
options = "(Y/n)"
Expand All @@ -112,7 +135,7 @@ public struct SwiftlyCoreContext: Sendable {
?? (defaultBehavior ? "y" : "n")).lowercased()

guard ["y", "n", ""].contains(answer) else {
await self.print(
await self.message(
"Please input either \"y\" or \"n\", or press ENTER to use the default.")
continue
}
Expand Down
28 changes: 28 additions & 0 deletions Sources/SwiftlyCore/Terminal.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import Foundation

/// Protocol retrieving terminal properties
public protocol Terminal: Sendable {
/// Detects the terminal width in columns
func width() -> Int
}

public struct SystemTerminal: Terminal {
/// Detects the terminal width in columns
public func width() -> Int {
#if os(macOS) || os(Linux)
var size = winsize()
#if os(OpenBSD)
// TIOCGWINSZ is a complex macro, so we need the flattened value.
let tiocgwinsz = UInt(0x4008_7468)
let result = ioctl(STDOUT_FILENO, tiocgwinsz, &size)
#else
let result = ioctl(STDOUT_FILENO, UInt(TIOCGWINSZ), &size)
#endif

if result == 0 && Int(size.ws_col) > 0 {
return Int(size.ws_col)
}
#endif
return 80 // Default width if terminal size detection fails
}
}
Loading