Last active
April 25, 2023 16:41
-
-
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:)`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Input
Output