Search code examples
xcodeswiftmacosxcodebuildxcrun

error while run xcodebuild with xcpretty command in swift


To run xcpretty command in xcodebuild, i use the below code:

import Foundation

class Command{

func command(args: String...) -> Int32 {
    let task = NSTask()
    task.launchPath = "/usr/bin/env"
    task.arguments = args
    task.currentDirectoryPath = "/Users/Desktop/XCode/Test/"
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}


let xcodebuildCommand = Command()
xcodebuildCommand.command("xcodebuild","test","-project","proj.xcodeproj","-scheme","projScheme","-destination","platform=iOS Simulator,name=iPad Air","  | /usr/local/bin/xcpretty --report html --output /Desktop/test_output/report.html")

the error is

xcodebuild: error: Unknown build action ' | /usr/local/bin/xcpretty --report html --output /Desktop/test_output/report.html'.

the below command run properly from terminal:

xcodebuild test -project proj.xcodeproj.xcodeproj -scheme projScheme -destination 'platform=iOS Simulator,name=iPad Air' | xcpretty --repor html --output /pathToReportfolder/report.html

Solution

  • NSTask is not a shell, it will not interpret your shell script for you.

    You'll need to manually set up an NSPipe to connect the standard output of your xcodebuild NSTask to an xcpretty NSTask.

    import Foundation
    
    func runCommand(workingDirectory: String? = nil,
                               stdin: NSPipe? = nil,
                              stdout: NSPipe? = nil,
                              stderr: NSPipe? = nil,
                                args: String...) -> Int32 {
        let task = NSTask()
    
        task.launchPath = "/usr/bin/env"
        task.arguments = args
    
        if let workingDirectory = workingDirectory {
            task.currentDirectoryPath = workingDirectory
        }
    
        if let stdin  = stdin  { task.standardInput  = stdin  }
        if let stdout = stdout { task.standardOutput = stdout }
        if let stderr = stderr { task.standardError  = stderr }
    
        task.launch()
        task.waitUntilExit()
        return (task.terminationStatus)
    }
    
    let pipe = NSPipe()
    
    //omit "workingDirectory:" in Swift 2
    runCommand(workingDirectory: "/Users/Desktop/XCode/Test/",
                         stdout: pipe,
                           args: "xcodebuild","test",
                           "-project","proj.xcodeproj",
                           "-scheme","projScheme",
                           "-destination","platform=iOS Simulator,name=iPad Air")
    
    //omit "workingDirectory:" in Swift 2
    runCommand(workingDirectory: "/Users/Desktop/XCode/Test/",
                          stdin: pipe,
                           args: "/usr/local/bin/xcpretty",
                           "--report html",
                           "--output",
                           "/Desktop/test_output/report.html")