Skip to content

Instantly share code, notes, and snippets.

@zhihuitang
Last active December 25, 2022 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhihuitang/8c0214d467d00368941494b4a74528a5 to your computer and use it in GitHub Desktop.
Save zhihuitang/8c0214d467d00368941494b4a74528a5 to your computer and use it in GitHub Desktop.
This script is a workaround to resolve SPM versions.
#!/opt/homebrew/bin/python3
# Sometimes Xcode cannot resolve SPM(File -> Packages -> Resolve Package versions) if the dependency url is ssh
# This script is a workaround to resolve package versions.
# Usage:
# python spmResolve.py
# or
# python3 spmResolve.py
import os.path
import subprocess
import glob
import json
def main():
package_file = "xcshareddata/swiftpm/Package.resolved"
xcodeproj = glob.glob('*.xcodeproj')
xcworkspace = glob.glob('*.xcworkspace')
spmproj = glob.glob('Package.resolved')
package_resolved = ""
if xcodeproj:
package_resolved = xcodeproj[0] + f"/project.xcworkspace/{package_file}"
elif xcworkspace:
package_resolved = xcworkspace[0] + f"/{package_file}"
elif spmproj:
package_resolved = spmproj[0]
else:
print(f"😱 Cannot find *.xcodeproj, *.xcworkspace or Package.resolved file")
exit(-1)
update_package_resolved(package_resolved)
def update_package_resolved(package_resolved):
if not os.path.exists(package_resolved):
print(f"😱 Package.resolved file doesn't exit: {package_resolved}")
exit(-1)
print(f"Found: {package_resolved}")
f = open(package_resolved)
content = json.load(f)
f.close()
for pin in content["pins"]:
url = pin["location"]
if "branch" in pin["state"]:
branch = pin["state"]["branch"]
commit_hash = get_git_revision_hash(url, branch)
print(f"{url}, {branch}, {commit_hash}")
pin["state"]["revision"] = commit_hash
elif "version" in pin["state"]:
version = pin["state"]["version"]
commit_hash = get_git_revision_by_tag(url, version)
print(f"{url}, {version}, {commit_hash}")
pin["state"]["revision"] = commit_hash
with open(package_resolved, "w") as output:
json.dump(content, output, indent=4)
# resolve SPM
subprocess.run(['xcodebuild', '-resolvePackageDependencies'])
print('🎉 Well done')
def get_git_revision_hash(url, branch) -> str:
command = f'git ls-remote {url} refs/heads/{branch} | cut -f 1'
return get_git_command_output(command)
def get_git_revision_by_tag(url, version) -> str:
command = f'git ls-remote {url} -t {version} | cut -f 1'
return get_git_command_output(command)
def get_git_command_output(command) -> str:
return subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True).decode('ascii').rstrip()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment