Add ReadFile class for read_file function

This commit is contained in:
2024-08-19 15:42:13 -05:00
parent b5f71c0e7d
commit 12dbd9505c
+49
View File
@@ -0,0 +1,49 @@
import base64
import requests
import os
import logging
class ReadFile:
def __init__(self, base_url, token, repo, current_branch):
self.base_url = base_url
self.headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json"
}
self.repo = repo
self.current_branch = current_branch
# Set up logging
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
# Create a file handler
file_handler = logging.FileHandler('read_file.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, path):
self.logger.info(f"Reading file: {path} from branch: {self.current_branch}")
url = f"{self.base_url}/repos/{self.repo}/contents/{path}"
response = requests.get(url, headers=self.headers, params={"ref": self.current_branch})
if response.status_code == 200:
content = response.json()["content"]
decoded_content = base64.b64decode(content).decode('utf-8')
self.logger.info(f"Successfully read file: {path}")
return decoded_content
else:
error_message = f"Error reading file: {response.status_code}"
self.logger.error(error_message)
return error_message