I'm trying to use NSTask
(or Process
since this is Swift) to execute xmllint
to format some XML data. The problem is that the task seems to hang.
I'm using xmllint
rather than XMLDocument.xmlData(withOptions:)
because the output better matches what I need. I'm writing a tool to edit existing files and I want to minimize the impact.
I tried killing the xmllint
process while it was hung, and got the first 84 1/2 lines of the output. The output should be about 10,000 lines for that test case, and most of the content involves elements nested only a couple of levels so it's not a very complex task.
Am I setting up the process and pipes correctly? The documentation is vague and I had a hard time finding directly applicable examples.
The code:
public static func format(xml: XMLDocument) -> Data?
{
let data = xml.xmlData
let task = Process()
let inPipe = Pipe()
let outPipe = Pipe()
task.launchPath = "/usr/bin/xmllint"
task.arguments = ["--format", "-"]
task.standardInput = inPipe
task.standardOutput = outPipe
task.launch()
inPipe.fileHandleForWriting.write(data)
inPipe.fileHandleForWriting.closeFile()
task.waitUntilExit() // Hangs :(
return outPipe.fileHandleForReading.availableData
}