运行 在 swift 中使用 xcpretty 命令构建 xcode 时出错

error while run xcodebuild with xcpretty command in swift

为了运行 xcodebuild中的xcpretty命令,我使用下面的代码:

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")

错误是

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

以下命令 运行 正确地来自终端:

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

NSTask 不是 shell,它不会为您解释您的 shell 脚本。

您需要手动设置 NSPipe 以将 xcodebuild NSTask 的标准输出连接到 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")