Add ListBranches class for list_branches function with JSON definition
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
import requests
|
||||
import logging
|
||||
|
||||
class ListBranches:
|
||||
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('list_branches.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, per_page=100, all_pages=True):
|
||||
self.logger.info(f"Listing branches. Per page: {per_page}, All pages: {all_pages}")
|
||||
url = f"{self.base_url}/repos/{self.repo}/branches"
|
||||
params = {"per_page": min(per_page, 100)} # GitHub API max is 100 per page
|
||||
all_branches = []
|
||||
|
||||
while url:
|
||||
self.logger.info(f"Fetching branches from: {url}")
|
||||
response = requests.get(url, headers=self.headers, params=params)
|
||||
if response.status_code != 200:
|
||||
error_message = f"Error listing branches: {response.status_code}"
|
||||
self.logger.error(error_message)
|
||||
return error_message
|
||||
|
||||
branches = [branch["name"] for branch in response.json()]
|
||||
all_branches.extend(branches)
|
||||
self.logger.info(f"Fetched {len(branches)} branches")
|
||||
|
||||
if not all_pages:
|
||||
break
|
||||
|
||||
# Check if there's a next page
|
||||
url = response.links.get('next', {}).get('url')
|
||||
if url:
|
||||
params = {} # Remove per_page for subsequent requests
|
||||
|
||||
self.logger.info(f"Successfully listed all branches. Total: {len(all_branches)}")
|
||||
return all_branches
|
||||
|
||||
# JSON definition for the list_branches function
|
||||
list_branches_definition = {
|
||||
"name": "list_branches",
|
||||
"description": "List all branches in the repository",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"per_page": {
|
||||
"type": "integer",
|
||||
"description": "Number of branches to return per page (max 100)",
|
||||
"default": 100
|
||||
},
|
||||
"all_pages": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to fetch all pages of results",
|
||||
"default": True
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user