本文介绍一种简单的swift脚本实现方案和执行方法。脚本可以读取文件内容,需要读者自行实现内容转换,然后脚本将结果输出到指定输出文件。
脚本模版
其中getResult函数需要读者按照自己需要实现。
swift
import Foundation
final class TestOnlySwift {
//入参为输入文案,返回为输出文案,改这个函数实现就行了
func getResult(str:String)->String {
return str + "1"
}
//下面的可以不改
func run(jsonFile: String, outputFile: String) {
let pwd = shell("pwd")
print("Working in \(pwd)")
do {
let jsonUrl = URL(fileURLWithPath: pwd).appendingPathComponent(jsonFile)
guard FileManager.default.fileExists(atPath: jsonUrl.path) else {
print("JSON file \(jsonUrl.path) does not exists!")
exit(0)
}
let inputStr = try String(contentsOfFile: jsonUrl.path)
let outputStr = getResult(str: inputStr)
try outputStr.write(to: URL(fileURLWithPath: pwd).appendingPathComponent(outputFile), atomically: true, encoding: .utf8)
print("Success")
} catch {
print("\(error)")
}
}
@discardableResult
func shell(_ command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/zsh"
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output.trimmingCharacters(in: .newlines)
}
}
let namedArguments = UserDefaults.standard
guard let jsonFile = namedArguments.string(forKey: "i") else {
print("Provide json crash file name with -i flag")
exit(0)
}
guard let outputFile = namedArguments.string(forKey: "o") else {
print("Provide output file name with -o flag")
exit(0)
}
TestOnlySwift().run(jsonFile: jsonFile, outputFile: outputFile)
使用方式
把上面代码写到TestOnlySwift.swift文件中,跟输入文件放(inputFile)到一个目录,在终端如下执行命令,结果会放在outputFile。
swift TestOnlySwift.swift -i inputFile -o outputFile