如何在Process()中包含命令修饰符?

时间:2019-04-14 19:50:38

标签: swift macos tar

目标:我正在尝试通过快捷脚本压缩文件。

我想通过如下所示的Swift脚本(在提示符下)压缩文件夹:

$~/workarea:ls
MyStuff/
$~/workarea:tar -cf MyStuff.zip MyStuff
$~/workarea:ls
MyStuff/    MyStuff.zip
$~/workarea:

这是Swift脚本:

import Foundation

let workArea = "/Users/Ric/workarea"

extension Process {
    private static let tarExecURL = URL(fileURLWithPath: "/usr/bin/tar")

    public func zip(source: String, archivedOutput: String) throws {
        executableURL = Process.tarExecURL
        arguments = ["-cf", archivedOutput, source]
        // emulate this: $~/workarea:tar -cf MyStuff.zip MyStuff
        try run()
    }

}

// ============================================================================================

func zipFolder() {
   // let sourceURL = URL(string:workArea+"MyStuff")
    let source = workArea+"/"+"MyStuff"
    let output = workArea+"/"+"MyStuff.zip"
    try! Process().zip(source: source, archivedOutput: output)
    print("Finished Archive")
}

// ============================================================================================

zipFolder()

print("Done")

我使用了成员文件的绝对路径:

(lldb) po source
"/Users/Ric/workarea/MyStuff"

(lldb) po output
"/Users/Ric/workarea/MyStuff.zip"

但是tar抱怨'/'。

我在控制台中收到以下错误:

Finished Archive
Done
tar: Removing leading '/' from member names
Program ended with exit code: 0

解决方案?

1 个答案:

答案 0 :(得分:1)

您要两次包含tar,一次是作为命令,另一次是作为参数。应该是:

arguments = ["-cf", archivedOutput, source]

一旦删除了多余的tar,您应该会得到输出:

Finished Archive
Done

编辑:“ workArea”路径应包含尾随正斜杠:

let workArea = "/Users/Ric/workarea/"

否则,您最终将获得如下所示的路径:

/Users/Ric/workareaMyStuff.zip