From eb3506ed782b94311161d7ec3d5450607edee789 Mon Sep 17 00:00:00 2001 From: bucolucas Date: Mon, 19 Aug 2024 15:47:14 -0500 Subject: [PATCH] Add GetFileAtCommit class for get_file_at_commit function with JSON definition --- .../get_file_at_commit.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 tools/github_tool_functions/get_file_at_commit.py diff --git a/tools/github_tool_functions/get_file_at_commit.py b/tools/github_tool_functions/get_file_at_commit.py new file mode 100644 index 0000000..0234d74 --- /dev/null +++ b/tools/github_tool_functions/get_file_at_commit.py @@ -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"] + } +} \ No newline at end of file