|
| 1 | +import fnmatch |
| 2 | +import json |
| 3 | +from typing import Dict, List, Any, AsyncGenerator |
| 4 | +from loguru import logger |
| 5 | +import yaml |
| 6 | +from integration import BitbucketFilePattern |
| 7 | +from port_ocean.utils.async_iterators import stream_async_iterators_tasks |
| 8 | +from initialize_client import init_client |
| 9 | + |
| 10 | + |
| 11 | +JSON_FILE_SUFFIX = ".json" |
| 12 | +YAML_FILE_SUFFIX = (".yaml", ".yml") |
| 13 | + |
| 14 | + |
| 15 | +def build_search_terms( |
| 16 | + filename: str, repos: List[str] | None, path: str, extension: str |
| 17 | +) -> str: |
| 18 | + """ |
| 19 | + This function builds search terms for Bitbucket's search API. |
| 20 | + The entire workspace is searched for the filename if repos is not provided. |
| 21 | + If repos are provided, only the repos specified are searched. |
| 22 | + The path and extension are required to tailor the search so results |
| 23 | + are relevant to the file kind. |
| 24 | +
|
| 25 | + Args: |
| 26 | + filename (str): The filename to search for. |
| 27 | + repos (List[str] | None): The repositories to search in. |
| 28 | + path (str): The path to search in. |
| 29 | + extension (str): The extension to search for. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + str: The search terms for Bitbucket's search API. |
| 33 | + """ |
| 34 | + search_terms = [f'"{filename}"'] |
| 35 | + if repos: |
| 36 | + repo_filters = " ".join(f"repo:{repo}" for repo in repos) |
| 37 | + search_terms.append(f"{repo_filters}") |
| 38 | + |
| 39 | + search_terms.append(f"path:{path}") |
| 40 | + |
| 41 | + if extension: |
| 42 | + search_terms.append(f"ext:{extension}") |
| 43 | + |
| 44 | + return " ".join(search_terms) |
| 45 | + |
| 46 | + |
| 47 | +async def process_file_patterns( |
| 48 | + file_pattern: BitbucketFilePattern, |
| 49 | +) -> AsyncGenerator[List[Dict[str, Any]], None]: |
| 50 | + """Process file patterns and retrieve matching files using Bitbucket's search API.""" |
| 51 | + logger.info( |
| 52 | + f"Searching for files in {len(file_pattern.repos) if file_pattern.repos else 'all'} repositories with pattern: {file_pattern.path}" |
| 53 | + ) |
| 54 | + |
| 55 | + if not file_pattern.repos: |
| 56 | + logger.warning("No repositories provided, searching entire workspace") |
| 57 | + if not file_pattern.path: |
| 58 | + logger.info("Path is required, skipping file search") |
| 59 | + return |
| 60 | + if not file_pattern.filenames: |
| 61 | + logger.info("No filenames provided, skipping file search") |
| 62 | + return |
| 63 | + |
| 64 | + for filename in file_pattern.filenames: |
| 65 | + search_query = build_search_terms( |
| 66 | + filename=filename, |
| 67 | + repos=file_pattern.repos, |
| 68 | + path=file_pattern.path, |
| 69 | + extension=filename.split(".")[-1], |
| 70 | + ) |
| 71 | + logger.debug(f"Constructed search query: {search_query}") |
| 72 | + bitbucket_client = init_client() |
| 73 | + async for search_results in bitbucket_client.search_files(search_query): |
| 74 | + tasks = [] |
| 75 | + for result in search_results: |
| 76 | + if len(result["path_matches"]) >= 1: |
| 77 | + file_info = result["file"] |
| 78 | + file_path = file_info["path"] |
| 79 | + |
| 80 | + if not validate_file_match(file_path, filename, file_pattern.path): |
| 81 | + logger.debug( |
| 82 | + f"Skipping file {file_path} as it doesn't match expected patterns" |
| 83 | + ) |
| 84 | + continue |
| 85 | + |
| 86 | + tasks.append(retrieve_file_content(file_info)) |
| 87 | + |
| 88 | + async for file_results in stream_async_iterators_tasks(*tasks): |
| 89 | + if not file_pattern.skip_parsing: |
| 90 | + file_results = parse_file(file_results) |
| 91 | + yield [file_results] |
| 92 | + |
| 93 | + |
| 94 | +async def retrieve_file_content( |
| 95 | + file_info: Dict[str, Any], |
| 96 | +) -> AsyncGenerator[Dict[str, Any], None]: |
| 97 | + """ |
| 98 | + Retrieve the content of a single file from Bitbucket. |
| 99 | +
|
| 100 | + Args: |
| 101 | + file_info (Dict[str, Any]): Information about the file to retrieve |
| 102 | +
|
| 103 | + Yields: |
| 104 | + Dict[str, Any]: Dictionary containing the file content and metadata |
| 105 | + """ |
| 106 | + file_path = file_info.get("path", "") |
| 107 | + repo_info = file_info["commit"]["repository"] |
| 108 | + repo_slug = repo_info["name"] |
| 109 | + branch = repo_info["mainbranch"]["name"] |
| 110 | + |
| 111 | + logger.info(f"Retrieving contents for file: {file_path}") |
| 112 | + bitbucket_client = init_client() |
| 113 | + file_content = await bitbucket_client.get_repository_files( |
| 114 | + repo_slug, branch, file_path |
| 115 | + ) |
| 116 | + |
| 117 | + yield { |
| 118 | + "content": file_content, |
| 119 | + "repo": repo_info, |
| 120 | + "branch": branch, |
| 121 | + "metadata": file_info, |
| 122 | + } |
| 123 | + |
| 124 | + |
| 125 | +def parse_file(file: Dict[str, Any]) -> Dict[str, Any]: |
| 126 | + """Parse a file based on its extension.""" |
| 127 | + try: |
| 128 | + file_path = file.get("metadata", {}).get("path", "") |
| 129 | + file_content = file.get("content", "") |
| 130 | + if file_path.endswith(JSON_FILE_SUFFIX): |
| 131 | + loaded_file = json.loads(file_content) |
| 132 | + file["content"] = loaded_file |
| 133 | + elif file_path.endswith(YAML_FILE_SUFFIX): |
| 134 | + loaded_file = yaml.safe_load(file_content) |
| 135 | + file["content"] = loaded_file |
| 136 | + return file |
| 137 | + except Exception as e: |
| 138 | + logger.error(f"Error parsing file: {e}") |
| 139 | + return file |
| 140 | + |
| 141 | + |
| 142 | +def validate_file_match(file_path: str, filename: str, expected_path: str) -> bool: |
| 143 | + """Validate if the file path and filename match the expected patterns.""" |
| 144 | + if not file_path.endswith(filename): |
| 145 | + return False |
| 146 | + |
| 147 | + if (not expected_path or expected_path == "/") and file_path == filename: |
| 148 | + return True |
| 149 | + |
| 150 | + dir_path = file_path[: -len(filename)] |
| 151 | + dir_path = dir_path.rstrip("/") |
| 152 | + expected_path = expected_path.rstrip("/") |
| 153 | + return fnmatch.fnmatch(dir_path, expected_path) |
0 commit comments