63 lines
2.3 KiB
Python
63 lines
2.3 KiB
Python
import requests
|
|
import logging
|
|
|
|
class ListFiles:
|
|
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('list_files.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"Listing files in: {path} on 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:
|
|
files = [item["name"] for item in response.json() if item["type"] == "file"]
|
|
directories = [item["name"] for item in response.json() if item["type"] == "dir"]
|
|
self.logger.info(f"Successfully listed files and directories in {path}")
|
|
return {"files": files, "directories": directories}
|
|
else:
|
|
error_message = f"Error listing files: {response.status_code}"
|
|
self.logger.error(error_message)
|
|
return error_message
|
|
|
|
# JSON definition for the list_files function
|
|
list_files_definition = {
|
|
"name": "list_files",
|
|
"description": "List files in a directory of the repository",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"path": {
|
|
"type": "string",
|
|
"description": "Path to the directory in the repository"
|
|
}
|
|
},
|
|
"required": ["path"]
|
|
}
|
|
} |