升级到运行在MacOS Catalina上的Xcode 11.1之后,运行一些命令例如"git status"会导致Xcode提示必须同意许可。显然,我们可以运行"git status"和"grep"命令来获取一些输出,但这似乎不是最佳方法。
有没有一种程序化方式(例如使用“xcodebuild”)来检查是否需要接受Xcode许可证?
有没有一种程序化方式(例如使用“xcodebuild”)来检查是否需要接受Xcode许可证?
评估已同意的许可证
运行中
defaults read /Library/Preferences/com.apple.dt.Xcode
{
IDELastGMLicenseAgreedTo = EA1647;
IDEXcodeVersionForAgreedToGMLicense = "11.3.1";
}
这也可以通过编程进行评估。
有几种方法可以实现这一点,其中之一是使用 shell 脚本。例如,您可以将其命名为 XcodeLicenseAccepted.sh,如果当前安装的 Xcode 版本的许可已经被接受,则它将返回 0。
Xcode 版本
要获取当前安装的 Xcode 的版本号,您可以查看以下输出:
xcodebuild -version
Xcode 11.3.1
Build version 11C505
XcodeLicenseAccepted.sh
#!/bin/sh
XCODE_VERSION=`xcodebuild -version | grep '^Xcode\s' | sed -E 's/^Xcode[[:space:]]+([0-9\.]+)/\1/'`
ACCEPTED_LICENSE_VERSION=`defaults read /Library/Preferences/com.apple.dt.Xcode 2> /dev/null | grep IDEXcodeVersionForAgreedToGMLicense | cut -d '"' -f 2`
if [ "$XCODE_VERSION" = "$ACCEPTED_LICENSE_VERSION" ]
then
exit 0 #success
else
exit 1
fi
Swift程序
另一个可能的解决方案是使用一个小的Swift程序,例如:
import Foundation
private var acceptedXcodeVersion: String {
var acceptedXcodeVersion = ""
let licensePlistPath = "/Library/Preferences/com.apple.dt.Xcode.plist"
if FileManager.default.fileExists(atPath: licensePlistPath) {
if let licenseInfo = NSDictionary(contentsOfFile: licensePlistPath) {
if let version = licenseInfo["IDEXcodeVersionForAgreedToGMLicense"] as? String {
acceptedXcodeVersion = version
}
}
}
return acceptedXcodeVersion
}
private var installedXcodeVersion: String {
let process = Process()
process.launchPath = "/bin/sh"
process.arguments = ["-c", "xcodebuild -version"]
let stdoutPipe = Pipe()
process.standardOutput = stdoutPipe
process.launch()
var version = ""
let output = stdoutPipe.fileHandleForReading.readDataToEndOfFile()
if let versionInfo = String(data: output, encoding: .utf8) {
let lines = versionInfo.split { $0.isNewline }
for line in lines {
let parts = line.split { $0 == " " }
if parts.count > 1 && parts[0] == "Xcode" {
version = String(parts[1])
}
}
}
process.waitUntilExit()
return version
}
exit(acceptedXcodeVersion == installedXcodeVersion ? 0 : 1)
测试
为了演示XcodeLicenseAccepted.sh的功能,也可以使用一个简短的shell脚本:
#!/bin/sh
./XcodeLicenseAccepted.sh
if [ $? -eq 0 ]
then
echo "xcode license already accepted"
else
echo "xcode license still needs to be accepted"
fi
使用Swift程序测试备选方案,替换对XcodeLicenseAccepted.sh
的调用。
最后附上接受Xcode许可证之前和之后结果的屏幕截图: