agent: |
WUbZAB1XhI6xzYww1FYxCreate a new branch for a repo.
Create a new branch for a repo.
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
This script creates a new branch specified in branch_name for the specified GitHub repository.
inputs
outputs
import requests
import json
# Function to check if the GitHub token is valid
def check_github_token_validity():
token = getEnvVar('GITHUB_TOKEN')
url = 'https://api.github.com/user'
headers = {
'Authorization': f'token {token}'
}
response = requests.get(url, headers=headers)
return response.status_code == 200
# Function to get the latest commit SHA of the default branch
def get_latest_commit_sha(owner, repo_name):
token = getEnvVar('GITHUB_TOKEN')
url = f'https://api.github.com/repos/{owner}/{repo_name}/branches/main'
headers = {
'Authorization': f'token {token}',
'Accept': 'application/vnd.github.v3+json'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
branch_info = response.json()
return branch_info['commit']['sha']
else:
print(f'Error: {response.status_code} - {response.text}')
return None
# Function to create a new branch
def create_branch(owner, repo_name, branch_name, sha):
token = getEnvVar('GITHUB_TOKEN')
url = f'https://api.github.com/repos/{owner}/{repo_name}/git/refs'
headers = {
'Authorization': f'token {token}',
'Accept': 'application/vnd.github.v3+json'
}
data = {
'ref': f'refs/heads/{branch_name}',
'sha': sha
}
response = requests.post(url, headers=headers, data=json.dumps(data))
return response
# Input
print(f'Input owner: {owner}')
print(f'Input repo_name: {repo_name}')
print(f'Input branch_name: {branch_name}')
# Check token validity
is_valid = check_github_token_validity()
if is_valid:
# Get the latest commit SHA of the default branch
sha = get_latest_commit_sha(owner, repo_name)
if sha:
# Create a new branch
response = create_branch(owner, repo_name, branch_name, sha)
if response.status_code == 201:
explanation = f'Branch {branch_name} created successfully.'
else:
explanation = f'Error: {response.status_code} - {response.text}'
else:
explanation = 'Failed to get the latest commit SHA.'
else:
explanation = 'The GitHub token is not valid.'
# Output
print('Output explanation:')
print(explanation)
copied