swift 脚本

1.需求更改xcode build id

PlistBuddy 为操作plist文件的命令行工具
swift 通过process 执行shell脚本, pipe输入执行结果

2.编写swfit脚本

func shell 为固定写法, 作用为执行shell脚本



import Cocoa


// 执行更改, 此处使用时间戳更改 build id

excute(infoPlist: "/Users/ext.guyuxi1/Desktop/未命名文件夹/Info.plist")

// 打印更改后的值
print(shell(path:"/usr/libexec/PlistBuddy", commands:"-c","Print :CFBundleVersion","/Users/ext.guyuxi1/Desktop/未命名文件夹/Info.plist").results)




@discardableResult
func excute(infoPlist path: String)-> String{
    let format = DateFormatter()
        format.dateFormat = "yyyyMMddHHmmss"
// 设置info 中key 为CFBundleVersion 的值
// 此处使用时间戳
// 此处path 为PlistBuddy(操作info.plist的终端)的路径
// commands 为所需要的传参
    return shell(path:"/usr/libexec/PlistBuddy", commands:"-c","Set :CFBundleVersion \(format.string(from: Date()))",path).results
}


/// 执行 Shell 命令 (会等待执行完成)
/// - Parameters:
///   - command: 命令
///   - path: 路径 默认为 "/bind/bash",即 shell 脚本
/// - Returns: 运行结果和命令执行标准输出
@discardableResult
func shell (path: String = "/bin/bash", commands: String...) -> (status: Int, results:String) {
        
    let task = Process();
    task.executableURL = URL(fileURLWithPath:path)
    var environment = ProcessInfo.processInfo.environment
    environment["PATH"] = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    task.environment = environment
    task.arguments = commands
    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = String(data: data, encoding: String.Encoding.utf8)!
    task.waitUntilExit()
    pipe.fileHandleForReading.closeFile()
    return (Int(task.terminationStatus),output)
}

3.xcode中使用

/usr/bin/env xcrun --sdk macosx swift

  1. 添加脚本, 上面代码复制到shell下面, path 路径为当前工程info.list路径
  2. 注意: 其他项目path路径需要修改


    执行脚本.png
  3. 查看脚本执行结果, 此处可以查看print 打印


    脚本执行结果.png
  4. 执行结果


    image.png

4.xcode创建命令行工程, 开发swfit脚本

image.png

5.参考文章

https://mp.weixin.qq.com/s/tX8LPjmGLEV9IT1_smMQBw
https://www.journaldev.com/19593/swift-script-command-line-arguments
https://www.codenong.com/js1f52583cc943/
https://www.jianshu.com/p/ab8e31bd68cf

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容