Add GetFileAtCommit class for get_file_at_commit function with JSON definition

This commit is contained in:
2024-08-19 15:47:14 -05:00
parent 9aa00dd302
commit eb3506ed78
@@ -0,0 +1,67 @@
import base64
import requests
import logging
class GetFileAtCommit:
def __init__(self, base_url, token, repo):
self.base_url = base_url
self.headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json"
}
self.repo = repo
# Set up logging
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
# Create a file handler
file_handler = logging.FileHandler('get_file_at_commit.log')
file_handler.setLevel(logging.INFO)
# Create a console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
# Create a formatting for the logs
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Add the handlers to the logger
self.logger.addHandler(file_handler)
self.logger.addHandler(console_handler)
def __call__(self, file_path, commit_sha):
self.logger.info(f"Getting file: {file_path} at commit: {commit_sha}")
url = f"{self.base_url}/repos/{self.repo}/contents/{file_path}"
response = requests.get(url, headers=self.headers, params={"ref": commit_sha})
if response.status_code == 200:
content = response.json()["content"]
decoded_content = base64.b64decode(content).decode('utf-8')
self.logger.info(f"Successfully retrieved file at commit")
return decoded_content
else:
error_message = f"Error reading file at commit: {response.status_code}"
self.logger.error(error_message)
return error_message
# JSON definition for the get_file_at_commit function
get_file_at_commit_definition = {
"name": "get_file_at_commit",
"description": "Get the contents of a file at a specific commit",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the file in the repository"
},
"commit_sha": {
"type": "string",
"description": "SHA of the commit to retrieve the file from"
}
},
"required": ["file_path", "commit_sha"]
}
}