Skip to content

Instantly share code, notes, and snippets.

@CraigSiemens
Last active April 25, 2023 16:41
Show Gist options
  • Save CraigSiemens/1557c62cc81f1a70ee4849315862731a to your computer and use it in GitHub Desktop.
Save CraigSiemens/1557c62cc81f1a70ee4849315862731a to your computer and use it in GitHub Desktop.
Takes a string from the default implementation of `String(describing:)` and reformats it to be on multiple lines with indented properties. Useful when looking at logs or crash reports that generates strings from types using `String(describing:)`.
#!/usr/bin/swift
import Darwin
import Foundation
var inputString = CommandLine.arguments.dropFirst().joined(separator: " ")
if inputString.isEmpty {
while let line = readLine(strippingNewline: false) {
inputString += line
}
}
let scanner = Scanner(string: inputString)
scanner.charactersToBeSkipped = nil
let symbols = CharacterSet(charactersIn: "()<>[],")
var indentLevel = 0
var genericLevel = 0
var outputString = ""
func addNewline() {
_ = scanner.scanCharacters(from: .whitespaces)
outputString += "\n" + String(repeating: " ", count: indentLevel * 4)
}
while !scanner.isAtEnd {
outputString += scanner.scanUpToCharacters(from: symbols) ?? ""
guard let symbol = scanner.scanCharacter() else { continue }
switch symbol {
case "(", "[":
indentLevel += 1
outputString += String(symbol)
addNewline()
case ")", "]":
indentLevel -= 1
addNewline()
outputString += String(symbol)
case "<":
genericLevel += 1
outputString += String(symbol)
case ">":
genericLevel -= 1
outputString += String(symbol)
case ",":
outputString += String(symbol)
if genericLevel == 0 {
addNewline()
}
default:
break
}
}
print(outputString)
@CraigSiemens
Copy link
Author

CraigSiemens commented Apr 25, 2023

Example

Input

User<G1<G2>, G3>(name: "Craig", address: __lldb_expr_43.Address(city: "Calgary", province: "AB"))

Output

User<G1<G2>, G3>(
    name: "Craig",
    address: __lldb_expr_39.Address(
        city: "Calgary",
        province: "AB"
    )
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment