We are going to design a code search platform that emphasizes four key aspects: ownership, freshness, trust, and links.
Let's break down what each of these might mean in the context of a code search platform:
-
Ownership: We need to track who owns or maintains a piece of code. This could be at the repository level or even at the file/function level. We might want to display the owner (individual or team) and allow filtering by owner.
-
Freshness: The code should be up-to-date. We might want to consider the last commit date, the frequency of updates, or the presence of recent activity. We could also consider the age of the code (e.g., how long since the last commit).
-
Trust: This could be a measure of how reliable the code is. Factors might include the number of stars, forks, the reputation of the owner (e.g., known maintainers), the presence of tests, CI status, and maybe external signals like known vulnerabilities (from dependency scanning). We might also consider the quality of the documentation.
-
Links: Code often references other code (dependencies, imports, etc.). We want to be able to traverse these links. Also, we might want to show related code (e.g., other files in the same repository, code that uses a particular function, etc.). Additionally, we might want to include links to external resources (documentation, issue trackers, etc.).
Given these, we can design a platform that indexes code (from GitHub, GitLab, etc.) and provides a search interface with advanced filtering and ranking based on these four pillars.
We'll need:
- A way to ingest code repositories (webhooks for updates, periodic scans).
- A database to store metadata about the code (file paths, content, ownership, timestamps, trust metrics, etc.) and links (imports, dependencies, cross-references).
- A search engine (like Elasticsearch) to index the code and metadata for fast full-text search and faceted filtering.
- A backend service to handle search queries, compute rankings, and serve results.
- A frontend to display the search results with the four pillars highlighted.
Let's outline the steps:
-
Data Ingestion:
- We'll use a crawler to fetch repositories from source code hosting platforms (GitHub, GitLab, etc.) based on user accounts/organizations or by discovering popular repositories.
- For each repository, we'll clone it and parse the code to extract:
- File structure and content.
- Ownership: from the repository owner and possibly from CODEOWNERS files or commit history (who committed most to a file?).
- Freshness: from the last commit date, commit frequency.
- Trust: from the repository's stars, forks, issues, CI status (if we can get from the platform), and maybe run static analysis tools (like linters, security scanners) to get a score.
- Links: parse imports and dependencies (e.g., for Python, parse
import statements; for JavaScript, parse require/import). We can also track cross-repository links if we index multiple repositories (e.g., if a repository in our index is used as a dependency in another).
- We'll store the extracted data in a structured format in our database and index it in the search engine.
-
Database Schema:
- We'll have tables for:
repositories: id, url, owner (user/org), name, description, default branch, created_at, updated_at, last_commit_date, stars, forks, etc.
files: id, repository_id, path, content (maybe not in DB but in search index), last_modified, etc.
ownership: table to track ownership at file or repository level. Could be: id, file_id or repository_id, owner (user/team), confidence (if derived from commit history).
trust_metrics: id, repository_id or file_id, metric_type (e.g., 'stars', 'ci_status', 'test_coverage'), value, timestamp.
links: id, source_file_id, target_file_id (or target repository and path), link_type (import, dependency, reference), etc.
However, note that for search we'll use Elasticsearch which will have its own mapping. We can use the database for structured queries and joins, but for search we'll index denormalized documents.
-
Search Index (Elasticsearch):
- We'll create an index for code files. Each document represents a file (or a code block?).
- The document might include:
id: unique identifier (maybe file id).
repository_id: to group by repo.
path: file path.
content: the code content (for full-text search).
owner: the owner of the repository (and maybe file owner if available).
last_commit_date: for freshness.
trust_score: a composite score (we can compute on ingestion or at query time).
links: an array of linked file ids or repository names (for cross-repo links).
- Other metadata: language, size, etc.
We might also have a separate index for repositories if we want to search repos directly.
-
Ranking:
- We want to combine the four pillars into a ranking function. We can use a linear combination of normalized scores for ownership (maybe the reputation of the owner), freshness (recency), trust (trust score), and link relevance (how many links to/from this code?).
- Alternatively, we can use a Learning to Rank (LTR) approach if we have enough training data (user clicks, etc.). But for simplicity, we can start with a formula.
-
API:
- We'll have an endpoint for search:
GET /api/search?q=...&filters=...
- Filters might include: owner, min_freshness (e.g., last commit within X days), min_trust_score, etc.
- We might also want to allow sorting by any of the four pillars.
-
Frontend:
- A search box.
- Filters for ownership, freshness (date range), trust (score range), and maybe a way to show links (like "show me code that imports X").
- Results page showing each file with:
- File path and repository.
- Owner (with link to owner's profile).
- Freshness: last commit date (and maybe a badge if recent).
- Trust: a trust score or badges (e.g., high stars, CI passing).
- Links: show a few incoming and outgoing links (with ability to expand).
Given the complexity, we'll start by outlining the system architecture and then dive into one component, say the ingestion and indexing pipeline.
But note: the user asked for code. Since this is a large system, we cannot write the entire codebase. Instead, we'll provide a simplified version that demonstrates the core concepts.
Let's choose to write:
- A script that ingests a GitHub repository (using the GitHub API and cloning the repo) and extracts metadata and code.
- A function to compute trust score (simple version: based on stars, forks, and maybe if the repo has a README and CI config).
- A function to extract links (for a specific language, say Python) by parsing import statements.
- Then we'll index the extracted data into Elasticsearch (we'll simulate with a simple in-memory index for demonstration, but note that in production we'd use Elasticsearch).
However, the user might expect a full-stack application? But the instruction says "Create a code search platform", which is a big project. We'll have to make assumptions and simplify.
Alternatively, we can design a minimal viable product (MVP) in a single language (like Python) with a simple web server (Flask) and an in-memory index, but that won't scale. But for demonstration, it's okay.
Given the complexity, I think it's better to outline the design and then provide a proof-of-concept for the ingestion and indexing.
But the user might be looking for a code example that shows how to implement the four pillars. Let's try to write a simplified version that:
- Takes a GitHub repo URL.
- Clones it (or uses the API to get file contents without cloning? but for link extraction we need the full codebase, so cloning is easier).
- For each file, we'll extract:
- content
- path
- last commit date (from git log)
- owner (from the repo)
- trust: we'll get repo's stars, forks, and check if it has a CI file (like .travis.yml) and a README.
- links: for Python files, we'll parse import statements and try to resolve them to other files in the repo (or to external packages? we'll focus on internal links).
Then we'll store these in a list of documents and allow searching over the content. We'll also compute a composite score for trust and freshness? But the user wants to emphasize the four aspects, so we'll make them available as separate fields.
We'll then run a simple search (like grep) and then sort by a combination of these factors. But note: we are not using a real search engine, so for a demo we can just use Python's re or grep and then filter/sort by our metadata.
But the user might expect a more integrated solution. Since we cannot build a full-scale system in one response, I'll provide a conceptual design and then a small script that demonstrates the ingestion for one repository and then a simple search.
Alternatively, we can build a small Flask app that:
- Has a route to ingest a repo (by URL) - this will run the ingestion and store the data in a global variable (in-memory).
- Has a search route that queries the in-memory data and returns results sorted by a score that combines trust, freshness, and ownership (links we can show in the result details).
But note: the user said "code search platform", so we need to show code. Let's do:
app.py: Flask app with two endpoints: /ingest and /search.
- We'll use
gitpython to clone and get git history.
- We'll use
ast for Python parsing to get imports.
But we must note: this is a proof of concept and not production-ready.
Let's write the code accordingly.
We'll assume the following:
- The platform will index only Python repositories for now.
- We'll run the ingestion on the server side (cloning the repo) which is not scalable and a security risk (malicious code). In production, we would run in a sandbox and maybe use the GitHub API without cloning? But for links we need the code. Alternatively, we can use the GitHub API to get file contents but then we cannot run static analysis easily. So for demo, we'll clone.
Steps for ingestion:
-
Given a GitHub repo URL (like https://github.com/owner/repo), we'll clone it to a temporary directory.
-
We'll get the repo's metadata from GitHub API (stars, forks, etc.) and also check for CI and README.
-
We'll walk through all .py files and for each:
- read the content.
- get the last commit date for that file (using
git log -1 --format=%ci -- path).
- parse the file with
ast to get import statements (both absolute and relative). We'll try to resolve the imported module to a file in the repo if possible.
-
We'll create a document for each file that includes:
id: a unique id (maybe repo+path).
repo: the repo name.
owner: the repo owner.
path: file path.
content: the code (for full-text search).
last_commit_date: of the file.
trust_score: a number we compute (e.g., 0-100) based on:
- stars: 0-50 points (log scale?).
- forks: 0-20 points.
- has README: 10 points.
- has CI: 10 points.
- maybe test coverage? we don't have that, skip.
imports: list of imported modules (or file paths if internal).
links: we'll store as the list of internal file paths that this file imports (so we can show "this file links to these files").
-
We'll store these documents in a list and also index them in Elasticsearch? For simplicity, we'll just store in a global list and do a linear search for the demo.
-
For search, we'll have a query string. We'll search in the content field (simple substring) and then also allow filtering by owner, freshness (e.g., last commit date within 30 days), and trust_score (minimum). Then we'll sort by a combined score: maybe we want to show fresh and trustworthy code first? We can do: score = trust_score * (some factor for freshness) but we need to normalize.
But note: the user wants the four pillars to be highlighted, so we'll return the four values for each result and let the frontend decide how to display.
We'll design the search endpoint to return a list of results, each with:
- file path, repo, owner
- last_commit_date
- trust_score
- links (the internal imports)
And we'll also return the snippet of the content around the match? That would be nice.
But for simplicity, we'll just return the whole content? Or we can return a snippet by finding the context of the match.
Given time, we'll do:
- Ingest: clone, parse, compute trust, extract imports, store.
- Search: linear scan over all files, if the query string is in the content, then include the file. Then apply filters (owner, min_trust, max_age). Then sort by trust_score descending and then by last_commit_date descending (so fresh and trustworthy first). But note: the user might want to sort by any pillar.
We'll allow a sort parameter: can be 'trust', 'freshness', 'ownership' (maybe by owner reputation? we don't have that, so we can sort by owner name? not useful). For ownership, we might want to show results from owners the user trusts first? But we don't have user preferences. So maybe we skip sorting by ownership and just filter by owner.
We'll do:
q: query string (optional, if not provided, return all files subject to filters).
owner: filter by owner (optional).
min_trust: minimum trust score (0-100, optional).
max_age_days: maximum age of last commit in days (optional, if provided, only files with last_commit_date within that many days from now).
sort: one of ['trust', 'freshness'] (default: 'trust').
Then we return:
{
"results": [
{
"id": "...",
"repo": "...",
"owner": "...",
"path": "...",
"last_commit_date": "...",
"trust_score": 85,
"links": ["other_file1.py", ...],
"snippet": " ... " // if query provided, we can show a snippet around the first occurrence
}
]
}
Now, let's write the code.
We'll need:
- Flask
- gitpython
- requests (for GitHub API)
- ast (standard library)
We'll create:
ingest_repo(repo_url): does the work and returns a list of file documents, and also stores them in a global CODE_INDEX list.
search(query, owner=None, min_trust=0, max_age_days=None, sort='trust'): searches the CODE_INDEX.
But note: we are storing all code in memory, so we cannot index many repos. This is just a demo.
We'll also need a way to clear the index? Maybe an admin endpoint.
Let's code accordingly.
We'll also compute the trust score for the repository (same for all files in the repo) because trust is at the repo level? Or per file? We can do per repository and assign that to every file in that repo. But if we have per-file trust (like if a file has tests, it might be more trustworthy) we could adjust, but for simplicity we'll use repo-level trust.
Steps for trust score (repo-level):
- Get repo info from GitHub API:
- stars: s
- forks: f
- Check if repository has a README (we can check if there's a file named README.md or similar).
- Check if there's a CI configuration (like .travis.yml, .github/workflows, etc.). We'll just check for the existence of common CI files.
We'll compute:
trust_score =
min(50, log10(stars+1)*10) // log scale: 0 stars -> 0, 10 stars -> 10, 100 -> 20, 1000 -> 30, 10000 -> 40, 100000 -> 50 (capped at 50)
+ min(20, log10(forks+1)*5) // similarly: 0 forks -> 0, 10 -> 5, 100 -> 10, 1000 -> 15, 10000 -> 20 (capped)
+ (10 if has_readme else 0)
+ (10 if has_ci else 0)
So max 100.
But note: we don't have the repo's language? We are only indexing Python files, but the repo might have other languages. That's okay.
For freshness:
- We'll get the last commit date for each file (from git log). But note: the last commit date for a file might be older than the repo's last commit if the file hasn't been changed recently. So we'll use per file.
We'll store last_commit_date as a datetime object.
For ownership:
- We'll get the repo owner from the GitHub API (the user or organization). We'll store that as
owner.
For links:
-
We'll parse Python files with ast and get all imports. Then we'll try to resolve them to files in the same repo. We'll do:
For each import statement:
- If it's a relative import (like from . import module), we'll try to find the module in the same directory.
- If it's absolute and the first part is the repo name? Or if it's a top-level module that exists in the repo? We'll assume that the repo is a Python package (has a top-level directory with the same name as the repo? Not necessarily). This is tricky.
Alternatively, we can just record the imported module names and not try to resolve to files. But then we cannot show links to other files in the same repo. We want to show internal links.
We can do:
- If the import is absolute and the first part is a top-level package that exists in the repo (i.e., there's a directory with that name in the repo root), then we can assume it's internal and try to map to a file.
But this is complex and error-prone.
For the demo, we can skip resolving and just show the import statements. But then we don't have links to other files. The requirement says "links", so we should try to show code that is linked.
Alternatively, we can use the fact that we are indexing all files and we know the module structure? We can build a mapping from module name to file path. For example, import foo would map to foo.py or foo/__init__.py. We can build this mapping by:
- For each file, we know its path. We can convert the path to a module name: remove `.py`, replace `/` with `.`, and if it's `__init__.py` then the module is the directory.
But note: the repo might not be a proper Python package. We'll do our best.
Steps:
- Build a dictionary `module_to_files` mapping module name (string) to list of file paths (since multiple files can define the same module? Not in Python, but we might have multiple files with the same module name in different directories? Actually, module name is determined by the path. So we can map:
For a file at `path/to/module.py`, the module name could be `path.to.module` if we consider the repo root as the top-level. But if the repo has a top-level package (like `myrepo/`), then the module name might be `myrepo.path.to.module`.
How to determine the top-level? We can assume the repo root is the top-level. But if the repo has a `setup.py` that defines a package, we might use that? Too complex.
We'll do:
- Let the repo root be the base.
- For each file, we compute its module name by:
- Remove the `.py` extension.
- Replace `/` with `.`.
- If the file is `__init__.py`, then the module is the directory (so the path without `__init__.py` and the last part is the directory name).
But note: if the file is directly in the repo root, then the module name is just the filename without `.py`.
Then we store in a dict: `module_name -> file_path`.
Then when we parse an import:
- For `import x.y.z`, we check if `x.y.z` exists in the dict. If yes, then it's an internal link to that file.
- For `from x.y import z`, we try `x.y.z` and `x.y` (if `z` is a module, it could be `x.y.z` or if `z` is a function/class we cannot link to a file, so we skip? We can only link to modules).
We'll only consider module-level imports. We'll ignore `from x import y` if `y` is not a module? We can't know without executing the code.
So we'll only link if the imported name is itself a module (i.e., we have a file for it). We'll do:
For `import x.y.z` -> try `x.y.z` (module) and if found, link to that file.
For `from x.y import z` -> try `x.y.z` (if `z` is a module) and `x.y` (if `z` is the module? Actually, `from x.y import z` could mean `z` is a module inside `x.y` or a name defined in `x.y/__init__.py`. We'll try `x.y.z` first, then `x.y` (but `x.y` is a module, so we link to `x.y/__init__.py`?).
This is getting complicated.
Given the time, we'll simplify:
We'll only record the import string (like "os", "numpy", "myrepo.utils") and not try to resolve. Then we can show the links as the raw import. But then we cannot link to other files in the platform. However, if we also index external packages? We are not indexing external packages.
Alternatively, we can skip the link extraction for now and just focus on the other three pillars. But the requirement says "links".
Let's think: we can extract the import statements and then when displaying a file, we can show the list of imports. And if any of those imports correspond to a file in our index (i.e., another file in the same repo that we indexed), then we can make that a link to that file's search result? That would require cross-referencing in the frontend.
In the backend, we can store for each file the list of import strings. Then when we return the result, we also return that list. The frontend can then make another request to search for those import strings? Not efficient.
We can do:
In the ingestion, for each file, we compute the set of internal module names (that are in our `module_to_files` map) that this file imports. Then we store the list of file paths (or ids) that are linked.
We'll do that.
Now, let's code accordingly.
We'll structure:
-
ingest_repo(repo_url):
- Use GitHub API to get repo metadata (stars, forks, etc.). We need an API token? For public repos, we can do without but we are rate limited. We'll ask the user to set a token? For demo, we'll do without and hope we don't hit rate limit.
- Clone the repo to a temp dir.
- Walk the repo and for each
.py file:
- read content.
- get last commit date for that file:
git log -1 --format=%ci -- path
- parse with
ast to get imports (but we'll do that in a second pass after building the module map? Actually, we need the module map to resolve imports, which requires knowing all files. So we'll first collect all files and build the module map, then in a second pass parse each file to extract imports and resolve.
So:
Step 1: collect all `.py` files and their paths. For each, compute the module name and store in `module_to_files` (a dict: module_name -> list of file paths). Note: multiple files can have the same module name? In Python, if you have two `mod.py` in different directories, they have different module names (because the directory is part of the module name). So the module name is unique per file? Not necessarily: if you have a package with `__init__.py` and also a module with the same name as the package? Actually, the package (directory with `__init__.py`) is a module and the file inside with the same name would be a submodule? We'll avoid that confusion.
We'll compute the module name as:
if file is `dir/__init__.py`:
module_name = dir.replace('/', '.') (and if dir is empty, then it's the root package? Actually, the root of the repo might not be a package. But if there's a `setup.py` that defines a package, we don't know. We'll just use the path.)
else:
module_name = path without .py, with slashes replaced by dots.
Example:
repo/
foo.py -> module_name = 'foo'
bar/
__init__.py -> module_name = 'bar'
baz.py -> module_name = 'bar.baz'
But what if the repo has a top-level package named `myrepo`? Then `myrepo/foo.py` would be `myrepo.foo`. That's fine.
We'll build `module_to_files` accordingly.
Step 2: For each file, parse with `ast` and get imports. For each import, try to resolve to a module in `module_to_files` and if found, record the linked file path(s) (there might be multiple files for the same module? No, because module name is unique per file? Actually, if we have both `mod.py` and `mod/__init__.py` in the same directory? That's not allowed. So we assume one file per module.
But wait: what about namespace packages? We ignore.
So for each import, if we find a module in `module_to_files`, we get the file path (or paths? we'll take the first). We'll store the linked file path.
We'll store the linked file paths in the document's `links` field.
Step 3: For each file, create a document with:
- id: we can use repo + path (but need to escape). We'll use a hash of repo+path? Or just a string.
- repo: repo name (from the URL)
- owner: from the URL (the GitHub user/org)
- path: relative path within the repo.
- content: the file content as string.
- last_commit_date: the date we got from git log (as a string? We'll store as datetime object for sorting, but when returning we can format).
- trust_score: the same for all files in the repo (computed from repo metadata).
- links: list of linked file paths (relative to repo root).
We'll also need to handle the case where the repo is not a Python repo? We only index .py files.
Now, let's write the code.
We'll create:
app.py: with Flask routes.
- We'll have a global
CODE_INDEX = [].
We'll also need to handle the GitHub API. We'll use requests to get repo metadata.
But note: the GitHub API requires a User-Agent. We'll set one.
We'll also need to handle errors (repo not found, not a Python repo, etc.)
Let's code step by step.
Due to the complexity, I'll write the code in one file for simplicity.
Note: This is a proof of concept and not production code. It's for demonstration only.
We'll assume the user has set up a virtual environment and installed:
pip install flask gitpython requests
Now, the code:
import os
import tempfile
import shutil
import ast
from datetime import datetime, timedelta
from flask import Flask, request, jsonify
import git
import requests
app = Flask(__name__)
# Global in-memory index
CODE_INDEX = []
# GitHub API base
GITHUB_API = "https://api.github.com"
# We should use a token to avoid rate limiting, but for demo we'll do without and hope.
# If you have a token, set it in the environment variable GITHUB_TOKEN.
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN', None)
HEADERS = {'User-Agent': 'CodeSearchPlatform/1.0'}
if GITHUB_TOKEN:
HEADERS['Authorization'] = f'token {GITHUB_TOKEN}'
def get_repo_metadata(owner, repo):
"""Get repository metadata from GitHub API."""
url = f"{GITHUB_API}/repos/{owner}/{repo}"
resp = requests.get(url, headers=HEADERS)
if resp.status_code != 200:
raise Exception(f"Failed to get repo metadata: {resp.status_code}")
data = resp.json()
return {
'stars': data['stargazers_count'],
'forks': data['forks_count'],
'has_readme': False, # we'll check later by looking for README file in the repo
'has_ci': False, # we'll check for CI files
}
def compute_trust_score(stars, forks, has_readme, has_ci):
"""Compute trust score (0-100) for a repository."""
# Log scale for stars and forks
import math
star_score = min(50, math.log10(stars + 1) * 10)
fork_score = min(20, math.log10(forks + 1) * 5)
readme_score = 10 if has_readme else 0
ci_score = 10 if has_ci else 0
total = star_score + fork_score + readme_score + ci_score
return int(total)
def build_module_map(repo_dir):
"""Build a mapping from module name to file path for all .py files in the repo."""
module_to_files = {}
for root, dirs, files in os.walk(repo_dir):
# Skip hidden directories and __pycache__
dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']
for file in files:
if file.endswith('.py'):
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, repo_dir)
# Compute module name
# Remove .py
mod_name = rel_path[:-3]
# If the file is __init__.py, then the module is the directory
if file == '__init__.py':
mod_name = os.path.dirname(mod_name).replace(os.sep, '.')
# If the directory is empty (i.e., root), then mod_name becomes empty string -> we set to '.'? But then it's the root package.
if mod_name == '':
mod_name = '.' # but we want a name? Actually, the root package is the repo name? We don't know. We'll leave as empty? But then we cannot import it as '.' in absolute imports.
# We'll not handle root __init__.py specially? Actually, if the repo root has __init__.py, then the repo is a package and the root module is the repo name? We don't have the repo name here.
# For simplicity, we'll treat __init__.py as the module of the directory.
else:
mod_name = mod_name.replace(os.sep, '.')
# Store in map
if mod_name not in module_to_files:
module_to_files[mod_name] = []
module_to_files[mod_name].append(rel_path)
return module_to_files
def extract_imports_from_file(file_path, content, module_to_files):
"""Extract internal imports from a Python file and return list of linked file paths."""
try:
tree = ast.parse(content)
except SyntaxError:
return [] # skip if syntax error
links = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
full_name = alias.name
if full_name in module_to_files:
# There might be multiple files for the same module? We take the first.
linked_file = module_to_files[full_name][0]
links.add(linked_file)
elif isinstance(node, ast.ImportFrom):
# Only handle absolute imports (level=0)
if node.level != 0:
continue
if node.module is None:
continue
for alias in node.names:
if alias.name == '*':
continue
candidate = node.module + '.' + alias.name
if candidate in module_to_files:
linked_file = module_to_files[candidate][0]
links.add(linked_file)
# Also try the module itself? For `from x import y` we are importing `y` from `x`. If `y` is a module, then candidate is `x.y`. If `y` is a name, we don't link.
# But what about `from x import y as z`? We use alias.name which is 'y'. So we try `x.y`.
# We don't try `x` because we are not importing the module `x` but a name from it.
return list(links)
def ingest_repo(repo_url):
"""Ingest a GitHub repository and add its code to the index."""
# Parse repo_url: expected format https://github.com/owner/repo
parts = repo_url.rstrip('/').split('/')
if len(parts) < 5 or parts[2] != 'github.com':
raise ValueError("Invalid GitHub URL")
owner = parts[3]
repo = parts[4]
# Get repo metadata
meta = get_repo_metadata(owner, repo)
# Check for README and CI files in the repo? We'll do after cloning.
# Clone repo to a temporary directory
with tempfile.TemporaryDirectory() as tmpdir:
clone_dir = os.path.join(tmpdir, repo)
try:
git.Repo.clone_from(f"https://github.com/{owner}/{repo}.git", clone_dir)
except Exception as e:
raise Exception(f"Failed to clone repo: {e}")
# Check for README and CI
readme_files = ['README.md', 'README.rst', 'README', 'readme.md']
has_readme = any(os.path.exists(os.path.join(clone_dir, f)) for f in readme_files)
ci_files = ['.travis.yml', '.circleci/config.yml', '.github/workflows'] # for workflows it's a directory
has_ci = False
for ci_file in ci_files:
path = os.path.join(clone_dir, ci_file)
if os.path.exists(path):
has_ci = True
break
# For .github/workflows, it's a directory, so check if exists and has yaml files?
if ci_file == '.github/workflows' and os.path.isdir(path):
# Check if there's at least one yaml file
if any(f.endswith('.yml') or f.endswith('.yaml') for f in os.listdir(path)):
has_ci = True
break
meta['has_readme'] = has_readme
meta['has_ci'] = has_ci
trust_score = compute_trust_score(meta['stars'], meta['forks'], has_readme, has_ci)
# Build module map
module_to_files = build_module_map(clone_dir)
# Now walk again and process each .py file
for root, dirs, files in os.walk(clone_dir):
dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']
for file in files:
if file.endswith('.py'):
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, clone_dir)
with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
# Get last commit date for this file
try:
# Get the last commit that touched this file
log_output = git.Git(clone_dir).log('-1', '--format=%ci', '--', rel_path)
last_commit_date = datetime.strptime(log_output.strip(), '%Y-%m-%d %H:%M:%S %z')
except Exception:
# If no commit history? Use the repo's last commit date? Or skip?
# We'll use the repo's updated_at as fallback? But we don't have it for the file.
# We'll set to a very old date.
last_commit_date = datetime.min
# Extract internal links
links = extract_imports_from_file(full_path, content, module_to_files)
# Create document
doc = {
'id': f"{owner}/{repo}/{rel_path}",
'repo': repo,
'owner': owner,
'path': rel_path,
'content': content,
'last_commit_date': last_commit_date,
'trust_score': trust_score,
'links': links,
}
CODE_INDEX.append(doc)
return len(CODE_INDEX)
@app.route('/ingest', methods=['POST'])
def ingest():
data = request.get_json()
if not data or 'repo_url' not in data:
return jsonify({'error': 'Missing repo_url'}), 400
try:
count = ingest_repo(data['repo_url'])
return jsonify({'message': f'Ingested {count} files'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/search', methods=['GET'])
def search():
query = request.args.get('q', '')
owner_filter = request.args.get('owner', None)
min_trust = request.args.get('min_trust', type=int, default=0)
max_age_days = request.args.get('max_age_days', type=int, default=None)
sort_by = request.args.get('sort', 'trust') # 'trust' or 'freshness'
now = datetime.now()
max_age_date = None
if max_age_days is not None:
max_age_date = now - timedelta(days=max_age_days)
results = []
for doc in CODE_INDEX:
# Apply filters
if owner_filter and doc['owner'] != owner_filter:
continue
if min_trust > 0 and doc['trust_score'] < min_trust:
continue
if max_age_date is not None:
# Ensure last_commit_date is timezone-aware? We'll assume naive for now.
if doc['last_commit_date'] < max_age_date:
continue
if query and query not in doc['content']:
continue
# Prepare result
result = {
'id': doc['id'],
'repo': doc['repo'],
'owner': doc['owner'],
'path': doc['path'],
'last_commit_date': doc['last_commit_date'].isoformat() if doc['last_commit_date'] != datetime.min else None,
'trust_score': doc['trust_score'],
'links': doc['links'],
}
# If there's a query, create a snippet
if query:
idx = doc['content'].find(query)
if idx != -1:
start = max(0, idx - 50)
end = min(len(doc['content']), idx + len(query) + 50)
snippet = doc['content'][start:end]
# Highlight the query? We'll just return the snippet.
result['snippet'] = snippet
results.append(result)
# Sort
if sort_by == 'trust':
results.sort(key=lambda x: (-x['trust_score'], -x['last_commit_date'].timestamp() if x['last_commit_date'] else 0))
elif sort_by == 'freshness':
results.sort(key=lambda x: (-x['last_commit_date'].timestamp() if x['last_commit_date'] else 0, -x['trust_score']))
else:
pass # default order
return jsonify({'results': results, 'count': len(results)})
if __name__ == '__main__':
app.run(debug=True)
This is a very basic implementation. There are many limitations:
- Only works for Python files.
- Only handles absolute imports (no relative imports).
- The trust score is computed once per repo and assigned to every file.
- The module resolution is naive and may not work for all Python projects (especially those with complex package structures or namespace packages).
- We are storing the entire file content in memory, which is not scalable.
- We are doing linear search, which is very slow for large indexes.
- We are not indexing the code for full-text search (just substring match).
- We are not handling the case where the same module name might be defined in multiple files (which shouldn't happen in normal Python, but could with namespace packages? We ignore).
- We are not indexing external packages, so links only work for internal files.
- The GitHub API call for repo metadata might fail due to rate limits.
- We are not verifying the clone is secure (malicious code could be executed? We are just reading files, but still, cloning a repo with a huge number of files could fill up disk).
But for a demonstration of the four pillars (ownership, freshness, trust, links) in a code search platform, this shows the concept.
We can improve by:
- Using a real search engine (Elasticsearch) and indexing the code properly (with analyzers, etc.).
- Parsing more languages (using tree-sitter or language-specific parsers).
- Better trust metrics (including commit history, issue response time, etc.).
- Better link extraction (including cross-repo links if we index multiple repos).
- Scalable ingestion (using a task queue, storing in a database, etc.).
But this should be a starting point.
How to run:
- Save the code as
app.py.
- Set up a virtual environment and install dependencies.
- Run
python app.py.
- Ingest a repo by sending a POST request to
http://localhost:5000/ingest with JSON body: {"repo_url": "https://github.com/owner/repo"}
Example: {"repo_url": "https://github.com/django/django"}
- Then search at
http://localhost:5000/search?q=... with optional filters.
Note: Ingesting a large repo may take time and memory.
We can also add an endpoint to clear the index? But for demo, just restart the server.
This is a minimal viable product for the concept.
I'll design a code search platform that emphasizes ownership, freshness, trust, and links - four critical dimensions for evaluating code quality and relevance. This is a sophisticated system that would typically require a distributed architecture, but I'll provide a functional prototype with core components.
System Architecture Overview
graph TB
A[User Interface] --> B[Search API]
B --> C[Query Parser]
C --> D[Search Engine<br/>Elasticsearch]
D --> E[Metadata Store<br/>PostgreSQL]
F[Code Ingestion Pipeline] --> D
F --> E
G[Trust Scoring Service] --> E
H[Link Graph Builder] --> E
I[GitHub/GitLab Webhooks] --> F
Core Implementation
1. Database Schema (PostgreSQL)
-- Main code files table
CREATE TABLE code_files (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
repository_id UUID NOT NULL,
path TEXT NOT NULL,
content TEXT,
language VARCHAR(50),
size_bytes INTEGER,
last_commit_sha CHAR(40),
last_commit_date TIMESTAMPTZ,
line_count INTEGER,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(repository_id, path)
);
-- Repository metadata with ownership
CREATE TABLE repositories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
url TEXT UNIQUE NOT NULL,
name VARCHAR(255) NOT NULL,
owner_id UUID NOT NULL, -- References users table
organization_id UUID, -- References organizations table
default_branch VARCHAR(100),
stars INTEGER DEFAULT 0,
forks INTEGER DEFAULT 0,
is_archived BOOLEAN DEFAULT FALSE,
is_disabled BOOLEAN DEFAULT FALSE,
last_sync TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Ownership tracking (per file or per repository)
CREATE TABLE ownership (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
code_file_id UUID REFERENCES code_files(id) ON DELETE CASCADE,
repository_id UUID REFERENCES repositories(id) ON DELETE CASCADE,
owner_type VARCHAR(20) CHECK (owner_type IN ('individual', 'team', 'organization')),
owner_id UUID NOT NULL, -- References users/teams/orgs
confidence FLOAT DEFAULT 1.0, -- Based on commit history, CODEOWNERS, etc.
is_primary BOOLEAN DEFAULT TRUE,
source VARCHAR(50) NOT NULL, -- 'git_log', 'codeowners', 'manual'
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Trust metrics (aggregated per repository/file)
CREATE TABLE trust_metrics (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
repository_id UUID REFERENCES repositories(id) ON DELETE CASCADE,
code_file_id UUID REFERENCES code_files(id) ON DELETE CASCADE,
metric_type VARCHAR(50) NOT NULL, -- 'ci_status', 'test_coverage', 'vulnerabilities', 'maintainer_response'
value FLOAT NOT NULL,
confidence FLOAT DEFAULT 1.0,
last_updated TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(repository_id, code_file_id, metric_type)
);
-- Code links (imports, dependencies, references)
CREATE TABLE code_links (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
source_file_id UUID NOT NULL REFERENCES code_files(id) ON DELETE CASCADE,
target_file_id UUID NOT NULL REFERENCES code_files(id) ON DELETE CASCADE,
link_type VARCHAR(50) NOT NULL, -- 'import', 'dependency', 'function_call', 'inheritance'
language VARCHAR(50),
symbol TEXT, -- function/class name if applicable
line_number INTEGER,
confidence FLOAT DEFAULT 1.0,
created_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(source_file_id, target_file_id, link_type, symbol, line_number)
);
-- Freshness tracking
CREATE TABLE freshness_metrics (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
repository_id UUID REFERENCES repositories(id) ON DELETE CASCADE,
code_file_id UUID REFERENCES code_files(id) ON DELETE CASCADE,
days_since_last_commit INTEGER,
commit_frequency_weekly FLOAT, -- Average commits per week
is_stale BOOLEAN DEFAULT FALSE,
last_updated TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(repository_id, code_file_id)
);
-- Comprehensive indexes for performance
CREATE INDEX idx_code_files_repo_path ON code_files(repository_id, path);
CREATE INDEX idx_code_files_updated ON code_files(updated_at DESC);
CREATE INDEX idx_ownership_owner ON ownership(owner_id, owner_type);
CREATE INDEX idx_code_links_source ON code_links(source_file_id);
CREATE INDEX idx_code_links_target ON code_links(target_file_id);
CREATE INDEX idx_trust_metrics_repo ON trust_metrics(repository_id, metric_type);
2. Core Trust Scoring Service
# services/trust_scorer.py
from dataclasses import dataclass
from typing import Dict, List, Optional
from datetime import datetime, timedelta
import numpy as np
@dataclass
class TrustFactors:
"""Components that contribute to trust score"""
ci_status: float = 0.0 # 0-1 (CI passing/healthy)
test_coverage: float = 0.0 # 0-1 (test coverage percentage)
vulnerability_count: float = 0.0 # 0-1 (inverse of vulnerabilities)
maintainer_response: float = 0.0 # 0-1 (issue response time)
commit_frequency: float = 0.0 # 0-1 (recent activity)
documentation_quality: float = 0.0 # 0-1 (has docs, doc coverage)
community_adoption: float = 0.0 # 0-1 (stars, forks, dependent repos)
security_audit: float = 0.0 # 0-1 (security scan results)
class TrustScorer:
"""Calculate composite trust score for code repositories/files"""
WEIGHTS = {
'ci_status': 0.20,
'test_coverage': 0.18,
'vulnerability_count': 0.15,
'maintainer_response': 0.12,
'commit_frequency': 0.10,
'documentation_quality': 0.10,
'community_adoption': 0.10,
'security_audit': 0.05
}
def __init__(self):
self.factor_scores = TrustFactors()
def calculate_score(self,
repository_metrics: Dict,
file_metrics: Optional[Dict] = None) -> float:
"""
Calculate overall trust score (0-100)
Args:
repository_metrics: Dict with trust metrics at repo level
file_metrics: Optional dict with file-specific metrics
"""
scores = []
weights = []
# 1. CI/CD Status
ci_score = self._score_ci_status(
repository_metrics.get('ci_status'),
repository_metrics.get('ci_last_build_duration')
)
scores.append(ci_score)
weights.append(self.WEIGHTS['ci_status'])
# 2. Test Coverage
coverage = repository_metrics.get('test_coverage', 0)
coverage_score = min(1.0, coverage / 100.0) if coverage else 0
scores.append(coverage_score)
weights.append(self.WEIGHTS['test_coverage'])
# 3. Security/Vulnerabilities
vuln_score = self._score_vulnerabilities(
repository_metrics.get('vulnerability_count', 0),
repository_metrics.get('vulnerability_severity', [])
)
scores.append(vuln_score)
weights.append(self.WEIGHTS['vulnerability_count'])
# 4. Maintainer Responsiveness
response_score = self._score_maintainer_response(
repository_metrics.get('avg_issue_response_days'),
repository_metrics.get('open_issue_ratio')
)
scores.append(response_score)
weights.append(self.WEIGHTS['maintainer_response'])
# 5. Recent Activity
freq_score = self._score_commit_frequency(
repository_metrics.get('commits_last_30d', 0)
)
scores.append(freq_score)
weights.append(self.WEIGHTS['commit_frequency'])
# 6. Documentation
doc_score = self._score_documentation(
repository_metrics.get('has_readme'),
repository_metrics.get('doc_coverage', 0),
repository_metrics.get('api_docs_quality', 0)
)
scores.append(doc_score)
weights.append(self.WEIGHTS['documentation_quality'])
# 7. Community Adoption
adoption_score = self._score_adoption(
repository_metrics.get('stars', 0),
repository_metrics.get('forks', 0),
repository_metrics.get('dependent_repos_count', 0)
)
scores.append(adoption_score)
weights.append(self.WEIGHTS['community_adoption'])
# 8. Security Audits
audit_score = self._score_security_audit(
repository_metrics.get('last_security_scan_days'),
repository_metrics.get('security_scan_score')
)
scores.append(audit_score)
weights.append(self.WEIGHTS['security_audit'])
# Add file-specific adjustments if provided
if file_metrics:
file_adjustment = self._calculate_file_adjustment(file_metrics)
composite = np.average(scores, weights=weights)
return min(100, (composite * 0.7 + file_adjustment * 0.3) * 100)
return np.average(scores, weights=weights) * 100
def _score_ci_status(self, status: str, build_time: Optional[float]) -> float:
"""Score CI/CD health"""
if status == 'passing':
return 1.0
elif status == 'failing':
return 0.0
elif status == 'pending':
return 0.5
return 0.1
def _score_vulnerabilities(self, count: int, severities: List[str]) -> float:
"""Inverse score - fewer vulnerabilities = higher score"""
if count == 0:
return 1.0
severity_weights = {'critical': 3.0, 'high': 2.0, 'medium': 1.0, 'low': 0.5}
weighted_sum = sum(severity_weights.get(s, 1.0) for s in severities)
return max(0, 1.0 - (count * 0.2) - (weighted_sum * 0.1))
def _score_maintainer_response(self, avg_days: Optional[float],
open_ratio: Optional[float]) -> float:
"""Score based on maintainer responsiveness"""
if avg_days is None:
return 0.5
# Response time score (faster = better)
if avg_days <= 1:
resp_score = 1.0
elif avg_days <= 7:
resp_score = 0.8
elif avg_days <= 30:
resp_score = 0.6
elif avg_days <= 90:
resp_score = 0.3
else:
resp_score = 0.1
# Open issue ratio penalty
if open_ratio and open_ratio > 0.5:
resp_score *= 0.7
return resp_score
def _score_commit_frequency(self, commits_30d: int) -> float:
"""Score based on recent commit activity"""
if commits_30d >= 30:
return 1.0
elif commits_30d >= 10:
return 0.8
elif commits_30d >= 1:
return 0.5
return 0.1
def _score_documentation(self, has_readme: bool,
doc_coverage: float,
api_quality: float) -> float:
"""Score documentation quality"""
score = 0.0
if has_readme:
score += 0.4
score += min(0.3, doc_coverage * 0.3)
score += min(0.3, api_quality * 0.3)
return score
def _score_adoption(self, stars: int, forks: int, dependents: int) -> float:
"""Score based on community adoption"""
# Log scale for stars
star_score = min(0.6, np.log10(stars + 1) * 0.15)
fork_score = min(0.3, np.log10(forks + 1) * 0.1)
dep_score = min(0.1, np.log10(dependents + 1) * 0.05)
return star_score + fork_score + dep_score
def _score_security_audit(self, days_since_scan: int,
scan_score: Optional[float]) -> float:
"""Score based on recent security scans"""
if scan_score is None:
return 0.3 if days_since_scan > 180 else 0.5
freshness_penalty = max(0, (days_since_scan - 30) * 0.005) if days_since_scan > 30 else 0
return max(0, scan_score - freshness_penalty)
def _calculate_file_adjustment(self, file_metrics: Dict) -> float:
"""Adjust trust score based on file-specific factors"""
adjustment = 0.0
# File complexity penalty
complexity = file_metrics.get('cyclomatic_complexity', 0)
if complexity > 20:
adjustment -= 0.2
elif complexity > 10:
adjustment -= 0.1
# Code smells
code_smells = file_metrics.get('code_smell_count', 0)
adjustment -= min(0.2, code_smells * 0.02)
# Recent changes bonus
days_since_update = file_metrics.get('days_since_update', 999)
if days_since_update < 7:
adjustment += 0.1
elif days_since_update < 30:
adjustment += 0.05
return max(-0.5, min(0.5, adjustment))
3. Link Graph Builder
# services/link_graph.py
from typing import List, Dict, Set, Tuple
from dataclasses import dataclass
import ast
import re
from collections import defaultdict
@dataclass
class CodeLink:
source_file: str
target_file: str
link_type: str
symbol: Optional[str]
line: int
confidence: float
class LinkGraphBuilder:
"""Build cross-reference graph between code files"""
def __init__(self):
self.graph = defaultdict(set) # {source: set of (target, type, symbol)}
self.reverse_graph = defaultdict(set) # For reverse lookups
def extract_links_from_file(self, file_path: str, content: str,
language: str) -> List[CodeLink]:
"""Extract all links from a single file"""
links = []
if language == 'python':
links.extend(self._extract_python_links(file_path, content))
elif language in ['javascript', 'typescript']:
links.extend(self._extract_js_links(file_path, content))
elif language == 'java':
links.extend(self._extract_java_links(file_path, content))
# Add more languages as needed
return links
def _extract_python_links(self, file_path: str, content: str) -> List[CodeLink]:
"""Extract links from Python code using AST"""
links = []
try:
tree = ast.parse(content)
self._find_python_imports(tree, file_path, links)
self._find_python_calls(tree, file_path, links)
self._find_python_inheritance(tree, file_path, links)
except SyntaxError:
pass # Skip files with syntax errors
return links
def _find_python_imports(self, tree: ast.AST, file_path: str,
links: List[CodeLink]):
"""Find import statements"""
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
links.append(CodeLink(
source_file=file_path,
target_file=self._resolve_python_module(alias.name),
link_type='import',
symbol=alias.asname or alias.name,
line=node.lineno,
confidence=1.0
))
elif isinstance(node, ast.ImportFrom):
module = node.module or ''
for alias in node.names:
if alias.name == '*':
continue
full_name = f"{module}.{alias.name}" if module else alias.name
links.append(CodeLink(
source_file=file_path,
target_file=self._resolve_python_module(full_name),
link_type='import',
symbol=alias.asname or alias.name,
line=node.lineno,
confidence=0.9 if node.level > 0 else 1.0 # Relative imports less certain
))
def _find_python_calls(self, tree: ast.AST, file_path: str,
links: List[CodeLink]):
"""Find function/method calls"""
for node in ast.walk(tree):
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name):
links.append(CodeLink(
source_file=file_path,
target_file=self._find_local_definition(node.func.id, file_path),
link_type='function_call',
symbol=node.func.id,
line=node.lineno,
confidence=0.7
))
elif isinstance(node.func, ast.Attribute):
# Handle method calls like obj.method()
if isinstance(node.func.value, ast.Name):
links.append(CodeLink(
source_file=file_path,
target_file=self._find_class_definition(node.func.value.id, file_path),
link_type='method_call',
symbol=node.func.attr,
line=node.lineno,
confidence=0.6
))
def _resolve_python_module(self, module_name: str) -> str:
"""Convert module name to file path (simplified)"""
# In practice, would need to analyze the repository structure
return module_name.replace('.', '/') + '.py'
def _find_local_definition(self, symbol: str, file_path: str) -> str:
"""Find local function definition - would need symbol table"""
return file_path # Simplified
def _extract_js_links(self, file_path: str, content: str) -> List[CodeLink]:
"""Extract links from JavaScript/TypeScript"""
links = []
# Regex-based extraction (simplified - use TypeScript compiler API for production)
import_patterns = [
r"import\s+.*\s+from\s+['\"]([^'\"]+)['\"]",
r"import\s*\(['\"]([^'\"]+)['\"]\)",
r"require\(['\"]([^'\"]+)['\"]\)",
]
for pattern in import_patterns:
for match in re.finditer(pattern, content):
module = match.group(1)
links.append(CodeLink(
source_file=file_path,
target_file=f"{module}.js", # Simplified
link_type='import',
symbol=None,
line=content[:match.start()].count('\n') + 1,
confidence=0.8
))
return links
def build_repository_graph(self, repository_files: List[Dict]) -> Dict:
"""Build complete link graph for a repository"""
file_paths = [f['path'] for f in repository_files]
language = repository_files[0]['language'] if repository_files else 'unknown'
for file_data in repository_files:
links = self.extract_links_from_file(
file_data['path'],
file_data['content'],
language
)
for link in links:
if link.target_file in file_paths: # Only internal links
self.graph[file_data['path']].add((
link.target_file,
link.link_type,
link.symbol
))
self.reverse_graph[link.target_file].add((
file_data['path'],
link.link_type,
link.symbol
))
return {
'forward': dict(self.graph),
'reverse': dict(self.reverse_graph),
'stats': {
'total_links': sum(len(v) for v in self.graph.values()),
'files_with_links': len([k for k in self.graph if self.graph[k]]),
'avg_links_per_file': sum(len(v) for v in self.graph.values()) / max(1, len(self.graph))
}
}
def find_related_files(self, file_path: str, depth: int = 1) -> Dict:
"""Find files related to a given file through the link graph"""
related = {'outgoing': set(), 'incoming': set()}
# BFS to find connected files
visited = set()
queue = [(file_path, 0)]
while queue:
current, current_depth = queue.pop(0)
if current in visited or current_depth > depth:
continue
visited.add(current)
# Outgoing links
for target, link_type, symbol in self.graph.get(current, set()):
related['outgoing'].add((target, link_type, symbol))
if current_depth < depth:
queue.append((target, current_depth + 1))
# Incoming links
for source, link_type, symbol in self.reverse_graph.get(current, set()):
related['incoming'].add((source, link_type, symbol))
if current_depth < depth:
queue.append((source, current_depth + 1))
return {
'file': file_path,
'depth': depth,
'outgoing': list(related['outgoing']),
'incoming': list(related['incoming'])
}
4. Search API with Ranking
# api/search.py
from typing import List, Dict, Optional
from datetime import datetime, timedelta
from elasticsearch import Elasticsearch
import numpy as np
class CodeSearchAPI:
"""Advanced code search with multi-dimensional ranking"""
def __init__(self, es_client: Elasticsearch):
self.es = es_client
self.trust_scorer = TrustScorer()
def search(self,
query: str,
repository: Optional[str] = None,
owner: Optional[str] = None,
language: Optional[str] = None,
min_trust: float = 0.0,
max_age_days: Optional[int] = None,
link_scope: str = 'all', # 'all', 'internal', 'external'
sort_by: str = 'relevance', # 'relevance', 'trust', 'freshness', 'ownership'
size: int = 20) -> Dict:
"""
Execute search with multi-dimensional ranking
Args:
query: Search query
repository: Filter by repository
owner: Filter by owner
language: Filter by language
min_trust: Minimum trust score (0-100)
max_age_days: Maximum age of code in days
link_scope: Filter by link relationships
sort_by: Primary sort dimension
size: Number of results
"""
# Build Elasticsearch query
es_query = self._build_es_query(
query, repository, owner, language, min_trust, max_age_days, link_scope
)
# Execute search
response = self.es.search(
index='code_files',
body=es_query,
size=size
)
# Process and rerank results based on sort preference
results = self._process_results(response['hits']['hits'], sort_by)
return {
'query': query,
'total': response['hits']['total']['value'],
'results': results,
'facets': self._extract_facets(response),
'took_ms': response['took']
}
def _build_es_query(self, query: str, repository: Optional[str],
owner: Optional[str], language: Optional[str],
min_trust: float, max_age_days: Optional[int],
link_scope: str) -> Dict:
"""Construct Elasticsearch query with filters"""
# Base query
must = []
if query:
must.append({
"multi_match": {
"query": query,
"fields": ["content^3", "path^2", "symbol_names^1.5"],
"type": "best_fields",
"fuzziness": "AUTO"
}
})
# Filters
filter_clause = []
if repository:
filter_clause.append({"term": {"repository.name.keyword": repository}})
if owner:
filter_clause.append({"term": {"repository.owner.login.keyword": owner}})
if language:
filter_clause.append({"term": {"language.keyword":language}})
if min_trust > 0:
filter_clause.append({"range": {"trust_score": {"gte": min_trust}}})
if max_age_days:
cutoff_date = datetime.utcnow() - timedelta(days=max_age_days)
filter_clause.append({
"range": {"last_commit_date": {"gte": cutoff_date.isoformat()}}
})
# Link scope filter
if link_scope == 'internal':
filter_clause.append({"term": {"link_scope": "internal"}})
elif link_scope == 'external':
filter_clause.append({"term": {"link_scope": "external"}})
return {
"query": {
"bool": {
"must": must,
"filter": filter_clause
}
},
"track_scores": True,
"highlight": {
"fields": {
"content": {"fragment_size": 150, "number_of_fragments": 3}
}
}
}
def _process_results(self, hits: List[Dict], sort_by: str) -> List[Dict]:
"""Process and rerank results based on sort preference"""
processed = []
for hit in hits:
source = hit['_source']
score = hit['_score']
# Extract trust and freshness from source or calculate
trust_score = source.get('trust_score', 50)
last_commit = source.get('last_commit_date')
freshness_score = self._calculate_freshness_score(last_commit) if last_commit else 0
# Calculate ownership score (based on owner reputation)
ownership_score = self._calculate_ownership_score(source)
# Combined ranking score
if sort_by == 'trust':
combined_score = trust_score * 0.6 + freshness_score * 0.3 + score * 0.1
elif sort_by == 'freshness':
combined_score = freshness_score * 0.6 + trust_score * 0.3 + score * 0.1
elif sort_by == 'ownership':
combined_score = ownership_score * 0.6 + trust_score * 0.3 + score * 0.1
else: # relevance (default ES score)
combined_score = score * 0.4 + trust_score * 0.3 + freshness_score * 0.3
processed.append({
'id': hit['_id'],
'path': source.get('path'),
'repository': source.get('repository', {}).get('full_name'),
'owner': source.get('repository', {}).get('owner', {}).get('login'),
'language': source.get('language'),
'snippet': hit.get('highlight', {}).get('content', [source.get('content', '')[:200]])[0],
'trust_score': trust_score,
'freshness_score': freshness_score,
'ownership_score': ownership_score,
'last_commit': last_commit,
'links': source.get('links', []),
'combined_score': combined_score,
'es_score': score
})
# Sort by combined score
processed.sort(key=lambda x: x['combined_score'], reverse=True)
return processed
def _calculate_freshness_score(self, last_commit: str) -> float:
"""Convert last commit date to 0-100 freshness score"""
if not last_commit:
return 0
commit_date = datetime.fromisoformat(last_commit.replace('Z', '+00:00'))
days_old = (datetime.utcnow() - commit_date.replace(tzinfo=None)).days
if days_old <= 1:
return 100
elif days_old <= 7:
return 90 - (days_old - 1) * 10
elif days_old <= 30:
return 80 - (days_old - 7) * 2.5
elif days_old <= 90:
return 50 - (days_old - 30) * 0.7
elif days_old <= 365:
return 30 - (days_old - 90) * 0.1
else:
return max(0, 10 - (days_old - 365) * 0.01)
def _calculate_ownership_score(self, source: Dict) -> float:
"""Calculate ownership score based on owner reputation"""
owner = source.get('repository', {}).get('owner', {})
stars = owner.get('star_count', 0) # Would need to join with user data
is_org = owner.get('type') == 'Organization'
# Simple heuristic: orgs with many stars score higher
if is_org:
return min(100, stars * 0.1)
else:
return min(100, stars * 0.05)
def _extract_facets(self, response: Dict) -> Dict:
"""Extract faceted search results"""
aggregations = response.get('aggregations', {})
return {
'languages': [
{'key': b['key'], 'count': b['doc_count']}
for b in aggregations.get('languages', {}).get('buckets', [])
],
'owners': [
{'key': b['key'], 'count': b['doc_count']}
for b in aggregations.get('owners', {}).get('buckets', [])[:10]
],
'trust_ranges': [
{'key': b['key'], 'count': b['doc_count']}
for b in aggregations.get('trust_ranges', {}).get('buckets', [])
]
}
5. Elasticsearch Index Mapping
{
"mappings": {
"properties": {
"id": {"type": "keyword"},
"repository": {
"properties": {
"id": {"type": "keyword"},
"full_name": {"type": "keyword"},
"owner": {
"properties": {
"login": {"type": "keyword"},
"type": {"type": "keyword"},
"star_count": {"type": "integer"}
}
}
}
},
"path": {
"type": "text",
"analyzer": "path_analyzer",
"fields": {
"keyword": {"type": "keyword"}
}
},
"content": {
"type": "text",
"analyzer": "code_analyzer"
},
"language": {"type": "keyword"},
"symbol_names": {
"type": "keyword"
},
"last_commit_date": {"type": "date"},
"trust_score": {"type": "float"},
"freshness_score": {"type": "float"},
"ownership": {
"properties": {
"owner_id": {"type": "keyword"},
"owner_type": {"type": "keyword"},
"confidence": {"type": "float"}
}
},
"links": {
"type": "nested",
"properties": {
"target_file": {"type": "keyword"},
"link_type": {"type": "keyword"},
"symbol": {"type": "keyword"},
"confidence": {"type": "float"}
}
},
"link_scope": {
"type": "keyword"
},
"size_bytes": {"type": "integer"},
"line_count": {"type": "integer"}
}
},
"settings": {
"analysis": {
"analyzer": {
"code_analyzer": {
"type": "custom",
"tokenizer": "code_tokenizer",
"filter": ["lowercase", "stemmer"]
},
"path_analyzer": {
"type": "pattern",
"pattern": "/"
}
},
"tokenizer": {
"code_tokenizer": {
"type": "pattern",
"pattern": "[\\s\\n]|(?=[\\W])|(?<=[\\W])"
}
}
}
}
}
6. Webhook Handler for Freshness
# ingestion/webhook_handler.py
import hmac
import hashlib
from flask import Flask, request, jsonify
from datetime import datetime
app = Flask(__name__)
class GitHubWebhookHandler:
def __init__(self, secret: str, ingestion_queue):
self.secret = secret
self.queue = ingestion_queue
def verify_signature(self, payload: bytes, signature: str) -> bool:
"""Verify GitHub webhook signature"""
expected = 'sha256=' + hmac.new(
self.secret.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)
def handle_push(self, data: Dict):
"""Handle push event"""
repository = data['repository']
commits = data['commits']
for commit in commits:
# Enrichment jobs for:
# 1. Update file freshness metrics
# 2. Update trust metrics if CI status changed
# 3. Update ownership if CODEOWNERS changed
# 4. Rebuild link graph if structure changed
job = {
'type': 'commit_update',
'repo_full_name': repository['full_name'],
'commit_sha': commit['id'],
'timestamp': commit['timestamp'],
'added_files': commit.get('added', []),
'modified_files': commit.get('modified', []),
'removed_files': commit.get('removed', [])
}
self.queue.put(job)
def handle_pull_request(self, data: Dict):
"""Handle PR events for trust scoring"""
pr = data['pull_request']
job = {
'type': 'pr_update',
'repo_full_name': data['repository']['full_name'],
'pr_number': pr['number'],
'state': pr['state'],
'merged': pr.get('merged', False),
'review_count': len(pr.get('requested_reviewers', [])),
'has_ci_status': 'status' in pr,
'timestamp': pr['updated_at']
}
self.queue.put(job)
@app.route('/webhook/github', methods=['POST'])
def github_webhook():
handler = GitHubWebhookHandler(secret=app.config['WEBHOOK_SECRET'])
# Verify signature
signature = request.headers.get('X-Hub-Signature-256')
if not signature or not handler.verify_signature(request.data, signature):
return jsonify({'error': 'Invalid signature'}), 403
event = request.headers.get('X-GitHub-Event')
data = request.json
if event == 'push':
handler.handle_push(data)
elif event == 'pull_request':
handler.handle_pull_request(data)
return jsonify({'status': 'queued'}), 202
7. Ownership Resolution Engine
# services/ownership_resolver.py
from typing import List, Dict, Tuple
from dataclasses import dataclass
import re
@dataclass
class OwnershipRecord:
path: str
owner: str
owner_type: str # 'user', 'team', 'org'
confidence: float
sources: List[str] # ['codeowners', 'git_log', 'manual']
class OwnershipResolver:
"""Determine code ownership through multiple signals"""
def __init__(self):
self.codeowners_pattern = re.compile(r'^([^\s@#]+)\s+(@[\w-]+|\S+)')
def resolve_repository_ownership(self, repo_data: Dict) -> List[OwnershipRecord]:
"""
Resolve ownership at repository level
Returns primary owner and maintainer teams
"""
records = []
# 1. Primary owner (from GitHub)
primary_owner = repo_data['owner']['login']
records.append(OwnershipRecord(
path='/',
owner=primary_owner,
owner_type='user' if repo_data['owner']['type'] == 'User' else 'org',
confidence=1.0,
sources=['github_api']
))
# 2. Check CODEOWNERS file if exists
if 'codeowners' in repo_data:
records.extend(self._parse_codeowners(
repo_data['codeowners'],
repo_data['default_branch']
))
# 3. Analyze commit history for maintainers
maintainers = self._find_maintainers_from_git(repo_data)
for maintainer, confidence in maintainers.items():
records.append(OwnershipRecord(
path='/',
owner=maintainer,
owner_type='user',
confidence=confidence,
sources=['git_history']
))
return records
def resolve_file_ownership(self, repo_path: str, file_path: str,
codeowners_content: Optional[str],
git_history: List[Dict]) -> List[OwnershipRecord]:
"""
Resolve ownership for specific file
"""
records = []
# 1. Check CODEOWNERS patterns (most specific match wins)
if codeowners_content:
codeowners_owners = self._match_codeowners_pattern(
file_path, codeowners_content
)
for owner, pattern in codeowners_owners:
records.append(OwnershipRecord(
path=file_path,
owner=owner,
owner_type='team' if owner.startswith('@') else 'user',
confidence=0.9, # CODEOWNERS is explicit
sources=['codeowners']
))
# 2. Git history analysis
git_owners = self._analyze_git_history(file_path, git_history)
for owner, commits in git_owners.items():
# Normalize to percentage of total commits
total_commits = sum(git_owners.values())
confidence = min(0.8, commits / total_commits * 0.8)
records.append(OwnershipRecord(
path=file_path,
owner=owner,
owner_type='user',
confidence=confidence,
sources=['git_log']
))
# 3. Fallback to repository owners
repo_owners = self._get_repository_owners(repo_path)
for owner in repo_owners:
records.append(OwnershipRecord(
path=file_path,
owner=owner,
owner_type='user',
confidence=0.3, # Low confidence fallback
sources=['repo_fallback']
))
return records
def _parse_codeowners(self, content: str, branch: str) -> List[OwnershipRecord]:
"""Parse CODEOWNERS file"""
records = []
lines = content.split('\n')
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
match = self.codeowners_pattern.match(line)
if match:
pattern = match.group(1)
owners = match.group(2).split()
for owner in owners:
records.append(OwnershipRecord(
path=pattern,
owner=owner.lstrip('@') if owner.startswith('@') else owner,
owner_type='team' if owner.startswith('@') else 'user',
confidence=0.95,
sources=['codeowners']
))
return records
def _match_codeowners_pattern(self, file_path: str,
codeowners_content: str) -> List[Tuple[str, str]]:
"""Find matching CODEOWNERS patterns for a file path"""
matches = []
lines = codeowners_content.split('\n')
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) < 2:
continue
pattern = parts[0]
owners = parts[1:]
if self._path_matches_pattern(file_path, pattern):
for owner in owners:
matches.append((owner.lstrip('@') if owner.startswith('@') else owner, pattern))
# Return most specific match first (longest pattern)
matches.sort(key=lambda x: len(x[1]), reverse=True)
return matches
def _path_matches_pattern(self, path: str, pattern: str) -> bool:
"""Check if path matches CODEOWNERS pattern"""
# Convert pattern to regex (simplified)
pattern = pattern.replace('*', '.*').replace('?', '.')
pattern = f"^{pattern}$"
return bool(re.match(pattern, path))
def _analyze_git_history(self, file_path: str,
commits: List[Dict]) -> Dict[str, int]:
"""Analyze git commit history for file ownership"""
ownership = {}
for commit in commits:
if file_path in commit.get('modified_files', []) or \
file_path in commit.get('added_files', []):
author = commit['author']['login']
ownership[author] = ownership.get(author, 0) + 1
return ownership
def _find_maintainers_from_git(self, repo_data: Dict) -> Dict[str, float]:
"""Identify maintainers based on commit patterns"""
# This would integrate with actual git log analysis
# Simplified: look for users with many commits in last 90 days
maintainers = {}
# Implementation would query database/git logs
return maintainers
8. Frontend Components (React)
// components/SearchResults.jsx
import React, { useState } from 'react';
import {
Star,
Clock,
Shield,
User,
Link2,
AlertCircle,
CheckCircle
} from 'lucide-react';
const TrustBadge = ({ score }) => {
const getLevel = (score) => {
if (score >= 80) return { level: 'high', color: 'green', label: 'High Trust' };
if (score >= 60) return { level: 'medium', color: 'yellow', label: 'Medium Trust' };
return { level: 'low', color: 'red', label: 'Low Trust' };
};
const { level, color, label } = getLevel(score);
return (
<div className={`flex items-center gap-1 px-2 py-1 rounded-full bg-${color}-100 text-${color}-800 text-xs`}>
<Shield size={12} />
<span>{label}</span>
</div>
);
};
const FreshnessBadge = ({ days }) => {
if (!days) return null;
const getStatus = (days) => {
if (days <= 1) return { status: 'fresh', label: 'Just updated', color: 'green' };
if (days <= 7) return { status: 'recent', label: `${days}d ago`, color: 'blue' };
if (days <= 30) return { status: 'stale', label: `${days}d ago`, color: 'yellow' };
return { status: 'old', label: `${days}d ago`, color: 'red' };
};
const { status, label, color } = getStatus(days);
return (
<div className={`flex items-center gap-1 px-2 py-1 rounded-full bg-${color}-100 text-${color}-800 text-xs`}>
<Clock size={12} />
<span>{label}</span>
</div>
);
};
const OwnershipBadge = ({ owner, type }) => (
<div className="flex items-center gap-1 px-2 py-1 rounded-full bg-gray-100 text-gray-800 text-xs">
<User size={12} />
<span>{owner}</span>
{type === 'org' && <span className="font-semibold">(Org)</span>}
</div>
);
const LinkPreview = ({ links, onNavigate }) => (
<div className="mt-2 border-t pt-2">
<div className="flex items-center gap-2 text-xs text-gray-600 mb-1">
<Link2 size={12} />
<span>Linked files:</span>
</div>
<div className="flex flex-wrap gap-1">
{links.slice(0, 5).map((link, idx) => (
<button
key={idx}
onClick={() => onNavigate(link.target_file)}
className="text-xs bg-blue-50 hover:bg-blue-100 text-blue-700 px-2 py-0.5 rounded"
>
{link.target_file.split('/').pop()}
{link.symbol && `.${link.symbol}`}
<span className="text-gray-400">#{link.line}</span>
</button>
))}
{links.length > 5 && (
<span className="text-xs text-gray-500">+{links.length - 5} more</span>
)}
</div>
</div>
);
const SearchResult = ({ result, onNavigate }) => {
const daysAgo = result.last_commit ?
Math.floor((new Date() - new Date(result.last_commit)) / (1000 * 60 * 60 * 24)) :
null;
return (
<div
className="p-4 border-b hover:bg-gray-50 cursor-pointer transition-colors"
onClick={() => onNavigate(result.repository, result.path)}
>
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-mono text-sm font-medium text-gray-900 truncate">
{result.path}
</h3>
<span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded">
{result.language}
</span>
</div>
<div className="flex items-center gap-2 mb-2 flex-wrap">
<OwnershipBadge owner={result.owner} type={result.owner_type} />
<FreshnessBadge days={daysAgo} />
<TrustBadge score={result.trust_score} />
<span className="text-xs text-gray-500">
Score: {result.combined_score.toFixed(1)}
</span>
</div>
<p className="text-sm text-gray-600 mb-2 line-clamp-2">
{result.snippet}
</p>
{result.links && result.links.length > 0 && (
<LinkPreview links={result.links} onNavigate={onNavigate} />
)}
</div>
</div>
</div>
);
};
const SearchResults = ({ results, onNavigate }) => {
if (!results.length) {
return (
<div className="p-8 text-center text-gray-500">
<AlertCircle className="mx-auto mb-2 opacity-50" size={48} />
<p>No results found</p>
</div>
);
}
return (
<div className="divide-y">
{results.map(result => (
<SearchResult
key={result.id}
result={result}
onNavigate={onNavigate}
/>
))}
</div>
);
};
export default SearchResults;
9. Main Application Entry Point
# main.py
from flask import Flask, render_template, request, jsonify
from elasticsearch import Elasticsearch
from api.search import CodeSearchAPI
from services.link_graph import LinkGraphBuilder
import json
import os
app = Flask(__name__)
# Initialize components
es = Elasticsearch(
[os.environ.get('ELASTICSEARCH_URL', 'localhost:9200')],
basic_auth=(os.environ.get('ES_USER'), os.environ.get('ES_PASSWORD'))
)
search_api = CodeSearchAPI(es)
link_graph = LinkGraphBuilder()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/search')
def api_search():
"""Main search endpoint"""
query = request.args.get('q', '')
repository = request.args.get('repo')
owner = request.args.get('owner')
language = request.args.get('lang')
min_trust = float(request.args.get('min_trust', 0))
max_age = request.args.get('max_age')
sort_by = request.args.get('sort', 'relevance')
try:
results = search_api.search(
query=query,
repository=repository,
owner=owner,
language=language,
min_trust=min_trust,
max_age_days=int(max_age) if max_age else None,
sort_by=sort_by
)
return jsonify(results)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/link-graph/<path:file_path>')
def get_link_graph(file_path):
"""Get link relationships for a file"""
try:
# In production, would fetch from database
# For demo, we'd rebuild or query pre-built graph
graph_data = link_graph.find_related_files(file_path, depth=2)
return jsonify(graph_data)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/ownership/<path:file_path>')
def get_ownership(file_path):
"""Get ownership information for a file"""
# Would query ownership table
return jsonify({
'file': file_path,
'owners': [
{'user': 'team-frontend', 'type': 'team', 'confidence': 0.9},
{'user': 'alice', 'type': 'user', 'confidence': 0.7}
]
})
if __name__ == '__main__':
app.run(debug=True, port=5000)
Key Features Implemented
1. Ownership
- Multi-source ownership resolution (CODEOWNERS, git history, manual)
- Confidence scoring for ownership claims
- Team and individual ownership tracking
- Ownership inheritance through directory structures
2. Freshness
- Last commit tracking per file
- Commit frequency analysis
- Stale code detection
- Time-based scoring (newer = higher score)
3. Trust
- Composite trust score from 8 dimensions
- CI/CD status integration
- Security vulnerability scanning
- Community adoption metrics
- Maintainer responsiveness
- Adjustable weights per organization needs
4. Links
- Cross-file dependency graph
- Multiple link types (imports, calls, inheritance)
- Bidirectional navigation (incoming/outgoing links)
- Symbol-level linking (function/class level)
- Link confidence scoring
Deployment Considerations
# docker-compose.yml
version: '3.8'
services:
elasticsearch:
image: elasticsearch:8.11.0
environment:
- discovery.type=single-node
- xpack.security.enabled=false
ports:
- "9200:9200"
volumes:
- es_data:/usr/share/elasticsearch/data
postgres:
image: postgres:15
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
ingestion-worker:
build: ./ingestion
environment:
- ELASTICSEARCH_URL=http://elasticsearch:9200
- DATABASE_URL=postgresql://postgres:${DB_PASSWORD}@postgres/code_search
depends_on:
- elasticsearch
- postgres
web:
build: .
ports:
- "5000:5000"
environment:
- ELASTICSEARCH_URL=http://elasticsearch:9200
- DATABASE_URL=postgresql://postgres:${DB_PASSWORD}@postgres/code_search
depends_on:
- elasticsearch
- postgres
volumes:
es_data:
postgres_data:
Usage Example
# Search with all four dimensions
curl "http://localhost:5000/api/search?q=auth&min_trust=70&max_age=30&sort=trust"
# Response highlights:
{
"results": [
{
"path": "src/auth/middleware.py",
"repository": "acme/security-lib",
"owner": "security-team",
"trust_score": 92,
"freshness_score": 95,
"ownership_score": 88,
"links": [
{"target_file": "src/auth/validators.py", "type": "import", "symbol": "validate_token"}
]
}
]
}
Scalability Enhancements
- Distributed Link Graph: Use Neo4j or JanusGraph for billion-edge graphs
- Trust Calculation: Implement Spark streaming for real-time trust updates
- Ownership ML: Train models on commit patterns to predict ownership
- Delta Indexing: UseCDC for Elasticsearch to handle frequent updates
- Caching Layer: Redis for frequent queries and trust scores
This platform provides a principled approach to code search where results are ranked not just by textual relevance but by who maintains it (ownership), how current it is (freshness), how reliable it is (trust), and how it connects (links) - creating a comprehensive quality signal for developers.