From a50ae72f2d7aa89bd8e6441d0646c5b7b956c615 Mon Sep 17 00:00:00 2001 From: Ranga Ngwerume Date: Mon, 18 Aug 2025 11:15:59 +0200 Subject: [PATCH 1/4] Add bulk repository add tool - Add codacy_bulk_add.py with comprehensive bulk add functionality - Uses Codacy org endpoint to discover repositories automatically - Includes integration settings configuration (all disabled by default) - Supports dry-run mode, selective repository processing, and rate limiting - Handles existing repositories gracefully with detailed error reporting - Update README.md to document both tools with usage examples - Maintain backward compatibility with existing codacy_follow.py --- .gitignore | 4 + README.md | 152 ++++++++++++++++++++++----- codacy_bulk_add.py | 249 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 380 insertions(+), 25 deletions(-) create mode 100644 codacy_bulk_add.py diff --git a/.gitignore b/.gitignore index 82f9275..99b2146 100644 --- a/.gitignore +++ b/.gitignore @@ -160,3 +160,7 @@ cython_debug/ # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ + + +#Ignore vscode AI rules +.github/copilot-instructions.md diff --git a/README.md b/README.md index 0e80ba6..9e88764 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,18 @@ -# Codacy Repository Auto-Follow Script +# Codacy Repository Tools -A Python script that automates the process of following repositories in Codacy. It can follow all repositories in an organization or specific ones you select, with comprehensive error handling and logging capabilities. +A collection of Python scripts for managing repositories in Codacy. This toolkit includes tools for both following repositories and bulk adding repositories to your Codacy organization. + +## Tools Included + +### 1. Repository Auto-Follow (`codacy_follow.py`) +Automates the process of following repositories in Codacy. It can follow all repositories in an organization or specific ones you select. + +### 2. Bulk Repository Add (`codacy_bulk_add.py`) +Bulk adds repositories from your organization to Codacy and configures integration settings. Uses Codacy's organization endpoint to discover repositories automatically - no CSV file required. ## Features +### Repository Auto-Follow (`codacy_follow.py`) - Follow all repositories in an organization or select specific ones - Automatic pagination handling for large organizations - Detailed logging with debug mode option @@ -12,6 +21,16 @@ A Python script that automates the process of following repositories in Codacy. - Validates repository names before attempting to follow - Comprehensive error handling and reporting +### Bulk Repository Add (`codacy_bulk_add.py`) +- Automatically discovers repositories using Codacy's organization endpoint +- Bulk adds repositories to Codacy with a single command +- Configures integration settings (disables all integrations by default) +- Handles repositories that already exist gracefully +- Dry-run mode to preview changes before execution +- Rate limiting to avoid API throttling +- Comprehensive error handling and detailed logging +- Selective repository processing with `--reponames` option + ## Prerequisites - Python 3.x @@ -29,26 +48,24 @@ A Python script that automates the process of following repositories in Codacy. ## Usage -### Basic Usage +### Repository Auto-Follow (`codacy_follow.py`) +#### Basic Usage ```bash python codacy_follow.py --token YOUR_API_TOKEN --provider PROVIDER --organization ORG_NAME ``` -### Follow Specific Repositories - +#### Follow Specific Repositories ```bash python codacy_follow.py --token YOUR_API_TOKEN --provider PROVIDER --organization ORG_NAME --reponames "repo1,repo2,repo3" ``` -### Enable Debug Mode - +#### Enable Debug Mode ```bash python codacy_follow.py --token YOUR_API_TOKEN --provider PROVIDER --organization ORG_NAME --debug ``` -### Command Line Arguments - +#### Command Line Arguments - `--token`: (Required) Your Codacy API token - `--provider`: (Required) Git provider code (e.g., 'gh' for GitHub, 'gl' for GitLab) - `--organization`: (Required) Your organization name @@ -56,16 +73,47 @@ python codacy_follow.py --token YOUR_API_TOKEN --provider PROVIDER --organizatio - `--reponames`: (Optional) Comma-separated list of specific repositories to follow - `--debug`: (Optional) Enable debug logging +### Bulk Repository Add (`codacy_bulk_add.py`) + +#### Basic Usage (with defaults) +```bash +python codacy_bulk_add.py --token YOUR_API_TOKEN --organization ORG_NAME +``` + +#### Full Usage Example +```bash +python codacy_bulk_add.py --token YOUR_API_TOKEN --provider gh --organization ORG_NAME --baseurl https://app.codacy.com --debug +``` + +#### Dry Run Mode (Preview Changes) +```bash +python codacy_bulk_add.py --token YOUR_API_TOKEN --organization ORG_NAME --dry-run +``` + +#### Add Specific Repositories Only +```bash +python codacy_bulk_add.py --token YOUR_API_TOKEN --organization ORG_NAME --reponames "repo1,repo2,repo3" +``` + +#### Command Line Arguments +- `--token`: (Required) Your Codacy API token +- `--organization`: (Required) Your organization name +- `--provider`: (Optional) Git provider code - default: 'gh' (GitHub) +- `--baseurl`: (Optional) Codacy server address - default: 'https://app.codacy.com' +- `--reponames`: (Optional) Comma-separated list of specific repositories to add +- `--dry-run`: (Optional) Preview what would be added without making actual changes +- `--debug`: (Optional) Enable debug logging + ## Output -The script provides: +Both scripts provide: - Progress updates for each repository - Success/failure status for each operation - Summary of total successes and failures - Execution time - Detailed logs in debug mode -### Example Output +### Example Output - Repository Follow ``` 2024-01-12 10:00:01 - INFO - Starting script with provider: gh, organization: myorg @@ -76,18 +124,51 @@ The script provides: 2024-01-12 10:00:04 - INFO - Successfully followed 2 repositories ``` +### Example Output - Bulk Repository Add + +``` +2024-01-12 10:00:01 - INFO - Starting bulk add with provider: gh, organization: myorg +2024-01-12 10:00:02 - INFO - Total repositories found: 25 +2024-01-12 10:00:02 - INFO - Processing all repositories +2024-01-12 10:00:03 - INFO - Processing repository 1/25: repo1 +2024-01-12 10:00:03 - INFO - Successfully added repo1 +2024-01-12 10:00:04 - INFO - Successfully updated integration settings for repo1 +2024-01-12 10:00:06 - INFO - Processing repository 2/25: repo2 +2024-01-12 10:00:06 - WARNING - Repository repo2 already exists +2024-01-12 10:00:07 - INFO - ================================================== +2024-01-12 10:00:07 - INFO - Script completed in 45.67 seconds +2024-01-12 10:00:07 - INFO - Successfully added 24 repositories +2024-01-12 10:00:07 - INFO - Skipped 1 repositories (already exist) +2024-01-12 10:00:07 - INFO - ================================================== +``` + ## Error Handling -The script handles various error scenarios: +Both scripts handle various error scenarios: - Invalid API tokens - Network connectivity issues - Rate limiting - Invalid repository names - Malformed API responses - Permission issues +- Repositories that already exist (bulk add tool) +- Integration settings update failures (bulk add tool) All errors are logged with appropriate detail level based on the debug setting. +## Integration Settings + +The bulk add tool (`codacy_bulk_add.py`) automatically configures integration settings for each added repository. By default, all integrations are disabled: + +- **Commit Status**: Disabled +- **Pull Request Comments**: Disabled +- **Pull Request Summary**: Disabled +- **Coverage Summary**: Disabled +- **Suggestions**: Disabled +- **AI Enhanced Comments**: Disabled + +This ensures a clean setup where you can selectively enable integrations as needed. + ## Exit Codes - 0: All operations completed successfully @@ -95,10 +176,12 @@ All errors are logged with appropriate detail level based on the debug setting. ## Best Practices -1. Use environment variables for sensitive information like API tokens -2. Enable debug mode when troubleshooting -3. Test with a small set of repositories first -4. Monitor rate limits when dealing with large organizations +1. **Security**: Use environment variables for sensitive information like API tokens +2. **Testing**: Enable debug mode when troubleshooting +3. **Gradual Rollout**: Test with a small set of repositories first using `--reponames` +4. **Rate Limiting**: Monitor rate limits when dealing with large organizations +5. **Dry Run**: Use `--dry-run` mode with the bulk add tool to preview changes +6. **Backup**: Consider backing up your current Codacy configuration before bulk operations ## Security Considerations @@ -111,21 +194,32 @@ All errors are logged with appropriate detail level based on the debug setting. Common issues and solutions: -1. Rate Limiting - - Reduce concurrent requests - - Check API quotas - - Implement retry mechanism +1. **Rate Limiting** + - The bulk add tool includes automatic 2-second delays between requests + - Check API quotas in your Codacy account + - Consider processing repositories in smaller batches using `--reponames` -2. Permission Errors +2. **Permission Errors** - Verify API token permissions - Check organization access - Verify repository visibility + - Ensure token has repository management permissions for bulk add operations -3. Connection Issues +3. **Connection Issues** - Check network connectivity - - Verify base URL + - Verify base URL (default: https://app.codacy.com) - Check proxy settings +4. **Repository Already Exists (Bulk Add)** + - This is normal behavior - the tool will skip existing repositories + - Use `--dry-run` to see which repositories would be processed + - Check the summary report for details on skipped repositories + +5. **Integration Settings Failures** + - Repository may be added successfully but integration settings update may fail + - Check the logs for specific error messages + - You can manually configure integration settings in the Codacy UI if needed + ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. @@ -138,9 +232,17 @@ For issues with: ## Changelog +### v2.0.0 +- Added bulk repository add tool (`codacy_bulk_add.py`) +- Automatic repository discovery using Codacy's organization endpoint +- Integration settings configuration with sensible defaults +- Dry-run mode for safe testing +- Enhanced error handling for bulk operations +- Rate limiting to prevent API throttling + ### v1.0.0 -- Initial release with merged functionality +- Initial release with repository auto-follow functionality - Added support for specific repository selection - Implemented comprehensive error handling - Added debug mode -- Added success/failure tracking \ No newline at end of file +- Added success/failure tracking diff --git a/codacy_bulk_add.py b/codacy_bulk_add.py new file mode 100644 index 0000000..893fb67 --- /dev/null +++ b/codacy_bulk_add.py @@ -0,0 +1,249 @@ +import argparse +import requests +import json +import time +import logging +from urllib.parse import quote + +# Set up logging +logging.basicConfig( + level=logging.DEBUG, + format='%(asctime)s - %(levelname)s - %(message)s' +) +logger = logging.getLogger(__name__) + +def listRepositories(baseurl, provider, organization, token): + """List all repositories in the organization with pagination support.""" + repositories = [] + headers = { + 'Accept': 'application/json', + 'api-token': token + } + + url = f'{baseurl}/api/v3/organizations/{provider}/{organization}/repositories' + cursor = None + + while True: + current_url = f'{url}?limit=100' + (f'&cursor={quote(cursor)}' if cursor else '') + logger.debug(f"Making request to: {current_url}") + + try: + response = requests.get(current_url, headers=headers) + response.raise_for_status() + data = response.json() + + logger.info(f"Retrieved {len(data.get('data', []))} repositories") + logger.debug(f"Response: {json.dumps(data, indent=2)}") + + repositories.extend([repo['name'] for repo in data['data']]) + + if 'pagination' in data and 'cursor' in data['pagination']: + cursor = data['pagination']['cursor'] + logger.debug(f"Next page cursor: {cursor}") + else: + break + + except requests.exceptions.RequestException as e: + logger.error(f"Error making request: {str(e)}") + if response is not None: + logger.error(f"Response status: {response.status_code}") + logger.error(f"Response body: {response.text}") + raise + except json.JSONDecodeError as e: + logger.error(f"Error decoding JSON response: {str(e)}") + raise + except KeyError as e: + logger.error(f"Unexpected response structure: {str(e)}") + raise + + logger.info(f"Total repositories found: {len(repositories)}") + return repositories + +def addRepository(baseurl, provider, organization, repo, token): + """Add a repository to Codacy.""" + headers = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'api-token': token, + 'caller': 'codacy-integration-helper' + } + data = { + "provider": provider, + "repositoryFullPath": f'{organization}/{repo}' + } + url = f'{baseurl}/api/v3/repositories' + + try: + logger.debug(f"Adding repository {repo} to Codacy...") + logger.debug(f"Making request to: {url}") + logger.debug(f"Request data: {json.dumps(data, indent=2)}") + + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + + logger.info(f"Successfully added {repo}") + logger.debug(f"Response: {response.text}") + return True, f"Successfully added {repo}: {response.status_code}" + + except requests.exceptions.RequestException as e: + if hasattr(e, 'response') and e.response is not None: + if e.response.status_code == 409: + logger.warning(f"Repository {repo} already exists") + return False, f"Repository {repo} already exists: {e.response.status_code}" + else: + logger.error(f"Failed to add {repo}: {e.response.status_code}, Response: {e.response.text}") + return False, f"Failed to add {repo}: {e.response.status_code}, Response: {e.response.text}" + else: + logger.error(f"Failed to add {repo}: {str(e)}") + return False, f"Failed to add {repo}: {str(e)}" + +def updateRepositoryIntegrationsSettings(baseurl, provider, organization, repo, token): + """Update repository integration settings to disable all integrations.""" + headers = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'api-token': token, + 'caller': 'codacy-integration-helper' + } + data = { + "commitStatus": False, + "pullRequestComment": False, + "pullRequestSummary": False, + "coverageSummary": False, + "suggestions": False, + "aiEnhancedComments": False + } + url = f'{baseurl}/api/v3/organizations/{provider}/{organization}/repositories/{repo}/integrations/providerSettings' + + try: + logger.debug(f"Updating integration settings for {repo}...") + logger.debug(f"Making request to: {url}") + logger.debug(f"Request data: {json.dumps(data, indent=2)}") + + response = requests.patch(url, headers=headers, json=data) + response.raise_for_status() + + logger.info(f"Successfully updated integration settings for {repo}") + logger.debug(f"Response: {response.text}") + return True, f"Successfully updated integration settings {repo}: {response.status_code}" + + except requests.exceptions.RequestException as e: + if hasattr(e, 'response') and e.response is not None: + logger.error(f"Failed to update integration settings {repo}: {e.response.status_code}, Response: {e.response.text}") + return False, f"Failed to update integration settings {repo}: {e.response.status_code}, Response: {e.response.text}" + else: + logger.error(f"Failed to update integration settings {repo}: {str(e)}") + return False, f"Failed to update integration settings {repo}: {str(e)}" + +def processAllRepositories(baseurl, provider, organization, token, reponames=None, dry_run=False): + """Process all repositories or specific ones if provided.""" + repositories = listRepositories(baseurl, provider, organization, token) + + if reponames: + target_repos = [repo.strip() for repo in reponames.split(',')] + logger.info(f"Processing specific repositories: {target_repos}") + invalid_repos = set(target_repos) - set(repositories) + if invalid_repos: + logger.warning(f"These repositories were not found: {invalid_repos}") + repositories = [repo for repo in repositories if repo in target_repos] + else: + logger.info("Processing all repositories") + + if dry_run: + logger.info("DRY RUN MODE - No actual changes will be made") + logger.info(f"Would process {len(repositories)} repositories:") + for repo in repositories: + logger.info(f" - {repo}") + return len(repositories), 0, 0 + + success_count = 0 + fail_count = 0 + already_exists_count = 0 + + for i, repo in enumerate(repositories, 1): + logger.info(f"Processing repository {i}/{len(repositories)}: {repo}") + + # Add repository + add_success, add_message = addRepository(baseurl, provider, organization, repo, token) + + if add_success: + success_count += 1 + # Update integration settings + settings_success, settings_message = updateRepositoryIntegrationsSettings( + baseurl, provider, organization, repo, token + ) + if not settings_success: + logger.warning(f"Repository added but failed to update settings: {settings_message}") + else: + if "already exists" in add_message.lower(): + already_exists_count += 1 + logger.info(f"Repository {repo} already exists, skipping...") + else: + fail_count += 1 + logger.error(add_message) + + # Rate limiting - wait between requests + if i < len(repositories): # Don't wait after the last repository + logger.debug("Waiting 2 seconds to avoid rate limiting...") + time.sleep(2) + + return success_count, fail_count, already_exists_count + +def main(): + print('\nWelcome to Codacy Bulk Repository Add Tool\n') + + parser = argparse.ArgumentParser(description='Codacy Bulk Repository Add Tool') + parser.add_argument('--token', required=True, help='The API token to be used on the REST API') + parser.add_argument('--provider', default='gh', help='Git provider (gh for GitHub, gl for GitLab, etc.) - default: gh') + parser.add_argument('--organization', required=True, help='Organization name') + parser.add_argument('--baseurl', default='https://app.codacy.com', help='Codacy server address - default: https://app.codacy.com') + parser.add_argument('--reponames', help='Comma separated list of repositories to add (optional - if not provided, all repos will be processed)') + parser.add_argument('--dry-run', action='store_true', help='Preview what would be added without making actual changes') + parser.add_argument('--debug', action='store_true', help='Enable debug logging') + + args = parser.parse_args() + + if not args.debug: + logging.getLogger().setLevel(logging.INFO) + + logger.info(f"Starting bulk add with provider: {args.provider}, organization: {args.organization}") + logger.debug(f"Base URL: {args.baseurl}") + logger.debug(f"Dry run mode: {args.dry_run}") + + start_time = time.time() + + try: + success_count, fail_count, already_exists_count = processAllRepositories( + args.baseurl, + args.provider, + args.organization, + args.token, + args.reponames, + args.dry_run + ) + + end_time = time.time() + execution_time = round(end_time - start_time, 2) + + logger.info(f"\n{'='*50}") + logger.info(f"Script completed in {execution_time} seconds") + + if args.dry_run: + logger.info(f"DRY RUN: Would have processed {success_count} repositories") + else: + logger.info(f"Successfully added {success_count} repositories") + if already_exists_count > 0: + logger.info(f"Skipped {already_exists_count} repositories (already exist)") + if fail_count > 0: + logger.warning(f"Failed to add {fail_count} repositories") + + logger.info(f"{'='*50}") + + return 0 if fail_count == 0 else 1 + + except Exception as e: + logger.error(f"Script failed: {str(e)}") + return 1 + +if __name__ == "__main__": + exit(main()) From 73896a4ef4308e446d0a6cfde674de0f84df1155 Mon Sep 17 00:00:00 2001 From: Ranga Ngwerume Date: Mon, 18 Aug 2025 11:47:37 +0200 Subject: [PATCH 2/4] final --- codacy_bulk_add.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/codacy_bulk_add.py b/codacy_bulk_add.py index 893fb67..059ca70 100644 --- a/codacy_bulk_add.py +++ b/codacy_bulk_add.py @@ -90,6 +90,17 @@ def addRepository(baseurl, provider, organization, repo, token): if e.response.status_code == 409: logger.warning(f"Repository {repo} already exists") return False, f"Repository {repo} already exists: {e.response.status_code}" + elif e.response.status_code == 401: + # Check if the error message indicates the repository is already being followed + try: + error_response = e.response.json() + if "permission" in error_response.get("message", "").lower(): + logger.warning(f"Repository {repo} already exists (following state)") + return False, f"Repository {repo} already exists: {e.response.status_code}" + except: + pass + logger.error(f"Failed to add {repo}: {e.response.status_code}, Response: {e.response.text}") + return False, f"Failed to add {repo}: {e.response.status_code}, Response: {e.response.text}" else: logger.error(f"Failed to add {repo}: {e.response.status_code}, Response: {e.response.text}") return False, f"Failed to add {repo}: {e.response.status_code}, Response: {e.response.text}" From a471937ae0e89dd2377fb4be560a8575ab4525d3 Mon Sep 17 00:00:00 2001 From: Ranga Ngwerume Date: Mon, 18 Aug 2025 12:12:52 +0200 Subject: [PATCH 3/4] add filter --- codacy_bulk_add.py | 2 +- test_list_repos.py | 89 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 test_list_repos.py diff --git a/codacy_bulk_add.py b/codacy_bulk_add.py index 059ca70..8bac91a 100644 --- a/codacy_bulk_add.py +++ b/codacy_bulk_add.py @@ -24,7 +24,7 @@ def listRepositories(baseurl, provider, organization, token): cursor = None while True: - current_url = f'{url}?limit=100' + (f'&cursor={quote(cursor)}' if cursor else '') + current_url = f'{url}?limit=100&filter=NotSynced' + (f'&cursor={quote(cursor)}' if cursor else '') logger.debug(f"Making request to: {current_url}") try: diff --git a/test_list_repos.py b/test_list_repos.py new file mode 100644 index 0000000..1391614 --- /dev/null +++ b/test_list_repos.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +import requests +import json +import argparse + +def test_list_repositories(baseurl, provider, organization, token): + """Test different API endpoints to list repositories.""" + + headers = { + 'Accept': 'application/json', + 'api-token': token + } + + # Test the current endpoint (only shows added repos) + print("=== Testing current endpoint (added repos only) ===") + url1 = f'{baseurl}/api/v3/organizations/{provider}/{organization}/repositories' + print(f"URL: {url1}") + + try: + response = requests.get(url1, headers=headers) + print(f"Status: {response.status_code}") + if response.status_code == 200: + data = response.json() + repos = [repo['name'] for repo in data.get('data', [])] + print(f"Found {len(repos)} repositories:") + for repo in repos[:10]: # Show first 10 + print(f" - {repo}") + if len(repos) > 10: + print(f" ... and {len(repos) - 10} more") + else: + print(f"Error: {response.text}") + except Exception as e: + print(f"Error: {e}") + + print("\n" + "="*60 + "\n") + + # Test potential alternative endpoints + test_endpoints = [ + f'{baseurl}/api/v3/organizations/{provider}/{organization}/repositories/available', + f'{baseurl}/api/v3/organizations/{provider}/{organization}/repositories?include=available', + f'{baseurl}/api/v3/organizations/{provider}/{organization}/repositories?source=provider', + f'{baseurl}/api/v3/organizations/{provider}/{organization}/repositories?status=all', + f'{baseurl}/api/v3/providers/{provider}/organizations/{organization}/repositories', + f'{baseurl}/api/v3/{provider}/{organization}/repositories', + ] + + for url in test_endpoints: + print(f"=== Testing: {url} ===") + try: + response = requests.get(url, headers=headers) + print(f"Status: {response.status_code}") + if response.status_code == 200: + data = response.json() + if isinstance(data, dict) and 'data' in data: + repos = [repo.get('name', 'Unknown') for repo in data.get('data', [])] + print(f"Found {len(repos)} repositories") + for repo in repos[:5]: # Show first 5 + print(f" - {repo}") + elif isinstance(data, list): + print(f"Found {len(data)} items") + for item in data[:5]: # Show first 5 + if isinstance(item, dict): + name = item.get('name', item.get('repositoryName', 'Unknown')) + print(f" - {name}") + else: + print(f"Response structure: {type(data)}") + else: + print(f"Error: {response.text[:200]}...") + except Exception as e: + print(f"Error: {e}") + print() + +def main(): + parser = argparse.ArgumentParser(description='Test Codacy API endpoints for listing repositories') + parser.add_argument('--token', required=True, help='Codacy API token') + parser.add_argument('--provider', default='gh', help='Git provider (gh, gl, etc.)') + parser.add_argument('--organization', required=True, help='Organization name') + parser.add_argument('--baseurl', default='https://app.codacy.com', help='Codacy base URL') + + args = parser.parse_args() + + print(f"Testing repository listing for {args.provider}/{args.organization}") + print(f"Base URL: {args.baseurl}") + print("="*60) + + test_list_repositories(args.baseurl, args.provider, args.organization, args.token) + +if __name__ == "__main__": + main() From d3f1c39a1801697fd7c00557a0c61dc867341b15 Mon Sep 17 00:00:00 2001 From: Ranga Ngwerume Date: Mon, 18 Aug 2025 14:42:01 +0200 Subject: [PATCH 4/4] fixes --- codacy_bulk_add.py | 43 ------------------------------------------- 1 file changed, 43 deletions(-) diff --git a/codacy_bulk_add.py b/codacy_bulk_add.py index 8bac91a..b60eb00 100644 --- a/codacy_bulk_add.py +++ b/codacy_bulk_add.py @@ -108,43 +108,6 @@ def addRepository(baseurl, provider, organization, repo, token): logger.error(f"Failed to add {repo}: {str(e)}") return False, f"Failed to add {repo}: {str(e)}" -def updateRepositoryIntegrationsSettings(baseurl, provider, organization, repo, token): - """Update repository integration settings to disable all integrations.""" - headers = { - 'Content-Type': 'application/json', - 'Accept': 'application/json', - 'api-token': token, - 'caller': 'codacy-integration-helper' - } - data = { - "commitStatus": False, - "pullRequestComment": False, - "pullRequestSummary": False, - "coverageSummary": False, - "suggestions": False, - "aiEnhancedComments": False - } - url = f'{baseurl}/api/v3/organizations/{provider}/{organization}/repositories/{repo}/integrations/providerSettings' - - try: - logger.debug(f"Updating integration settings for {repo}...") - logger.debug(f"Making request to: {url}") - logger.debug(f"Request data: {json.dumps(data, indent=2)}") - - response = requests.patch(url, headers=headers, json=data) - response.raise_for_status() - - logger.info(f"Successfully updated integration settings for {repo}") - logger.debug(f"Response: {response.text}") - return True, f"Successfully updated integration settings {repo}: {response.status_code}" - - except requests.exceptions.RequestException as e: - if hasattr(e, 'response') and e.response is not None: - logger.error(f"Failed to update integration settings {repo}: {e.response.status_code}, Response: {e.response.text}") - return False, f"Failed to update integration settings {repo}: {e.response.status_code}, Response: {e.response.text}" - else: - logger.error(f"Failed to update integration settings {repo}: {str(e)}") - return False, f"Failed to update integration settings {repo}: {str(e)}" def processAllRepositories(baseurl, provider, organization, token, reponames=None, dry_run=False): """Process all repositories or specific ones if provided.""" @@ -179,12 +142,6 @@ def processAllRepositories(baseurl, provider, organization, token, reponames=Non if add_success: success_count += 1 - # Update integration settings - settings_success, settings_message = updateRepositoryIntegrationsSettings( - baseurl, provider, organization, repo, token - ) - if not settings_success: - logger.warning(f"Repository added but failed to update settings: {settings_message}") else: if "already exists" in add_message.lower(): already_exists_count += 1