Created
May 15, 2024 16:54
-
-
Save Frank-Buss/9eea494be56b4a0b04c4ac7d5a6e1292 to your computer and use it in GitHub Desktop.
pin github workflow dependencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# automatically pins all your workflows, see | |
# https://github.com/fmtlib/fmt/issues/3449 | |
# for details | |
import sys | |
import requests | |
import os | |
def get_github_token(): | |
# get your github token here, like from env variable | |
return None | |
def get_commit_hash(repo, reference, github_token=None): | |
headers = {} | |
if github_token: | |
headers['Authorization'] = f'token {github_token}' | |
# First, try to get the commit hash for the tag | |
tag_url = f"https://api.github.com/repos/{repo}/git/ref/tags/{reference}" | |
tag_response = requests.get(tag_url, headers=headers) | |
if tag_response.status_code == 200: | |
return tag_response.json()['object']['sha'] | |
else: | |
# If tag is not found, try to get the commit hash for the branch | |
branch_url = f"https://api.github.com/repos/{repo}/git/ref/heads/{reference}" | |
branch_response = requests.get(branch_url, headers=headers) | |
if branch_response.status_code == 200: | |
return branch_response.json()['object']['sha'] | |
else: | |
print(f"Error fetching commit hash for {repo}@{reference}: {branch_response.status_code}") | |
return None | |
def replace_tags_with_hashes(file_path, github_token=None): | |
with open(file_path) as file: | |
lines = file.readlines() | |
updated_lines = [] | |
for line in lines: | |
line = line | |
if 'uses: ' in line: | |
parts = line.split('uses: ')[1].split('@') | |
if len(parts) == 2: | |
repo, tag = parts | |
if '/' in repo: | |
tag = tag.strip().split(' ')[0] | |
if len(tag) < 40: | |
commit_hash = get_commit_hash(repo, tag, github_token) | |
if commit_hash: | |
line2 = line.replace(f"{repo}@{tag}", f"{repo}@{commit_hash} # {tag}") | |
print(f"org: {line.strip()}") | |
print(f"replaced: {line2.strip()}") | |
line = line2 | |
updated_lines.append(line) | |
with open(file_path, "w") as file: | |
file.writelines(updated_lines) | |
def main(): | |
if len(sys.argv) < 2: | |
print("Usage: python3 script.py <path_to_yaml_file_1> <path_to_yaml_file_2> ...") | |
sys.exit(1) | |
github_token = get_github_token() # Get GitHub token from gradle.properties | |
for file_path in sys.argv[1:]: | |
print(f"Processing {file_path}...") | |
replace_tags_with_hashes(file_path, github_token) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment