如果你在推特上關注了我們(@iachievedit)你就知道我們不僅做了很多 Swift 開源項目,還有做了一些操作系統和架構。我們決定做這個項目沒有特別的原因,但是看著各個版本的 git 倉庫最終整合一個工具感覺真是太棒了。
我們很高興最終 Swift 能夠取代 Linux 上的其他腳本語言(比如名字讀起來像 Bython 和 Buby 的兩門語言),對我們來說是時候寫腳本了(用 Swift)。
這里有一些注意事項:
- 我們使用了一個
String
的subscript
擴展,由于某些原因它可能不會是核心語言的一部分。 - 我們的版本里的 exec 在其他腳本語言里是反引號(
output = `ls`
),我們需要執行命令并讀取輸出。 - 當然還可以做更多優化和精簡。
掌握了這些之后,下面就是 swiftrevs.swift
:
import Glibc
extension String {
subscript (r: CountableClosedRange<Int>) -> String {
get {
let startIndex = self.characters.index(self.characters.startIndex, offsetBy:r.lowerBound)
let endIndex = self.characters.index(self.characters.startIndex, offsetBy:r.upperBound)
return self[startIndex..<endIndex]
}
}
}
func exec(_ command:String) -> String {
let BUFSIZE = 128
let pipe = popen(command, "r")
var buf = [CChar](repeating:CChar(0), count:BUFSIZE)
var output:String = ""
while fgets(&buf, Int32(BUFSIZE), pipe) != nil {
output = String(cString:buf)
}
return output
}
func gitRevision() -> String {
return exec("/usr/bin/git rev-parse HEAD")[0...9]
}
func gitFetchURL() -> String {
return exec("/usr/bin/git remote show origin -n|grep Fetch| echo -n `cut --characters=14-`")
}
func gitBranch() -> String {
return exec("/usr/bin/git branch | echo -n `cut --characters=2-`")
}
let dirs = ["swift", "llvm", "clang", "lldb", "compiler-rt", "cmark", "llbuild", "swiftpm", "swift-corelibs-xctest", "swift-corelibs-foundation", "swift-integration-tests", "swift-corelibs-libdispatch"]
for dir in dirs {
let cwd = String(cString:getcwd(nil, 0))
let rc = chdir(dir) // pushd
guard rc == 0 else {
continue
}
let fetch = gitFetchURL()
let rev = gitRevision()
let branch = gitBranch()
print("\(dir),\(fetch),\(branch),\(rev)")
chdir(cwd) // popd
}
我們按照如下方法來使用:
bash
# swift swiftrevs.swift
swift,https://github.com/apple/swift.git,master,cf3fdff04
llvm,https://github.com/apple/swift-llvm.git,stable,8d0086ac3
clang,https://github.com/apple/swift-clang.git,stable,460d629e8
lldb,https://github.com/apple/swift-lldb.git,master,da120cf91
compiler-rt,https://github.com/apple/swift-compiler-rt.git,stable,9daa1b32c
cmark,https://github.com/apple/swift-cmark.git,master,5af77f3c1
llbuild,https://github.com/apple/swift-llbuild.git,master,7aadcf936
swiftpm,https://github.com/apple/swift-package-manager.git,master,423c2a1c8
swift-corelibs-xctest,https://github.com/apple/swift-corelibs-xctest.git,master,03905f564
swift-corelibs-foundation,https://github.com/apple/swift-corelibs-foundation.git,master,4c15543f8
swift-integration-tests,https://github.com/apple/swift-integration-tests.git,master,4eda8055a
swift-corelibs-libdispatch,https://github.com/apple/swift-corelibs-libdispatch.git,master,e922531c2
當然,這都是在滿足構建 Swift 的倉庫目錄下運行的,如果你有興趣學習為 X86 或者 ARM 設備構建 Swift ,請查閱我們的 package-swift 倉庫。其中不僅包含 swiftrevs.swift
,還有幾個能無痛構建 Swift(和 REPL、Foundation、Swift 包管理器)的腳本。
本文由 SwiftGG 翻譯組翻譯,已經獲得作者翻譯授權,最新文章請訪問 http://swift.gg。