Files
cyclop/tools/github_tool_functions/commit_file.py
T

94 lines
3.3 KiB
Python

import base64
import requests
import logging
class CommitFile:
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('commit_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, file_path, content, commit_message):
self.logger.info(f"Committing file: {file_path} to branch: {self.current_branch}")
if self.current_branch == "main":
error_message = "Cannot commit directly to main branch"
self.logger.error(error_message)
return error_message
url = f"{self.base_url}/repos/{self.repo}/contents/{file_path}"
self.logger.info("Checking if file already exists")
response = requests.get(url, headers=self.headers, params={"ref": self.current_branch})
data = {
"message": commit_message,
"content": base64.b64encode(content.encode()).decode(),
"branch": self.current_branch
}
if response.status_code == 200:
self.logger.info("File exists, updating")
file_sha = response.json()["sha"]
data["sha"] = file_sha
else:
self.logger.info("File does not exist, creating new file")
response = requests.put(url, headers=self.headers, json=data)
if response.status_code in [200, 201]:
success_message = f"File committed successfully to branch '{self.current_branch}'"
self.logger.info(success_message)
return success_message
else:
error_message = f"Error committing file: {response.status_code}\nResponse: {response.text}"
self.logger.error(error_message)
return error_message
# JSON definition for the commit_file function
commit_file_definition = {
"name": "commit_file",
"description": "Commit a file to a branch (not main)",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the file in the repository"
},
"commit_message": {
"type": "string",
"description": "Commit message"
},
"content": {
"type": "string",
"description": "Content of the file"
}
},
"required": ["file_path", "commit_message", "content"]
}
}