Build a File Owner Aggregator for Code Review Assignment
Trees & GraphsModel answerLast updated
Parse Git diffs and a CSV ownership map to identify which contributor owns the most modified files in a branch comparison.
You're building tooling to suggest code reviewers based on file ownership.
Write a Java program that accepts:
- A path to a Git repository on disk
- Two branch names: a base branch and a comparison branch
- A CSV file mapping file paths to their designated owners
Your program must:
- Use a Git library (such as JGit) to determine which files differ between the two branches
- Load the ownership mapping from the CSV file, which follows this format:
file_path,owner src/payments/ChargeService.java,alice src/payments/RefundService.java,bob src/common/JsonUtil.java,alice - For each modified file that appears in the CSV, record which owner is responsible
- Return the owner responsible for the greatest number of changed files
Rules:
- If a changed file doesn't appear in the CSV, skip it
- If multiple owners tie for the most files, return any one of them
- If no changed files have owners, return an empty result
What to consider:
- Should you compare the branch tips directly, or find their merge base first?
- How should you handle CSV edge cases (headers, blank lines, paths with commas)?
- What if a branch name doesn't exist?
Hints
Hint 1
Break the solution into three independent stages: Git diff extraction, CSV parsing into a map, and pure aggregation logic. Each can be unit-tested separately.
Hint 2
A pull request typically shows the three-dot diff (merge base vs target branch), not a two-dot diff (base tip vs target tip). Choose your comparison points accordingly.
Hint 3
Use JGit's diff API to walk tree objects directly—never check out branches to the working directory. For each DiffEntry, extract the path and accumulate ownership counts in a hash map.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to integrate with version control APIs, parse structured text, and perform straightforward aggregation. Divide it into three clean stages:
- Extract changed files from Git: Compare two branches and collect the set of modified file paths
- Parse ownership data: Read the CSV into a map from path to owner
- Aggregate and select: Count files per owner and return the owner with the maximum count
Keeping these stages separate makes your code testable and demonstrates good separation of concerns.
Stage 1: Git Diff Extraction
Use JGit to open the repository and compare two branches. A critical clarification: should you diff the branch tips directly (two-dot), or find their merge base and diff from there (three-dot)? Pull requests display three-dot diffs, showing only changes introduced on the feature branch. If the base branch moved forward after your feature branch diverged, a two-dot diff would incorrectly include those base changes.
The solution below finds the merge base using JGit's RevWalk with MERGE_BASE filter. If no merge base exists (unrelated histories), fall back to the base branch tip.
Diff the tree objects of the two commits directly—never check out branches to disk. Collect each DiffEntry path into a set. For deletions, use oldPath; for all other changes, use newPath.
Stage 2: CSV Parsing
Read the CSV line by line. Handle:
- Optional header row (skip if it matches
file_path,owner) - Blank lines
- Leading/trailing whitespace
- Paths that may contain commas (split on the last comma only)
- Normalize paths that begin with
./
Store the first owner encountered for each path in a HashMap. Git uses forward-slash paths relative to the repository root, so the CSV must match that format.
Stage 3: Aggregation
For each changed file, look up its owner in the map. If found, increment that owner's count. After processing all files, return the owner with the highest count. If there's a tie, any tied owner is acceptable; sorting by name makes the result deterministic for testing.
Complexity
- Time: O(T + C + K), where T is the tree-walk cost (proportional to differing subtrees), C is the number of CSV rows, and K is the number of changed files
- Space: O(C + K) for the ownership map, changed file set, and count map
Edge Cases
- Nonexistent branch: Fail with a clear error message
- Identical branches: No diffs, return empty
- CSV with duplicate paths: First entry wins
- Malformed CSV rows: Skip rows without exactly one comma or with empty fields
- No owned files changed: Return
Optional.empty()
Implementation
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.revwalk.filter.RevFilter;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class ReviewerSelector {
public static Optional<String> selectReviewer(
Path repoPath, String baseBranch, String targetBranch, Path csvPath)
throws IOException, GitAPIException {
Set<String> modified = extractChangedFiles(repoPath, baseBranch, targetBranch);
Map<String, String> ownership = parseOwnershipCSV(csvPath);
return determineTopOwner(modified, ownership);
}
static Set<String> extractChangedFiles(Path repoPath, String base, String target)
throws IOException, GitAPIException {
try (Git git = Git.open(repoPath.toFile())) {
Repository repo = git.getRepository();
try (RevWalk walk = new RevWalk(repo)) {
RevCommit baseCommit = walk.parseCommit(resolveBranch(repo, base));
RevCommit targetCommit = walk.parseCommit(resolveBranch(repo, target));
// Find merge base for three-dot diff
walk.reset();
walk.setRevFilter(RevFilter.MERGE_BASE);
walk.markStart(baseCommit);
walk.markStart(targetCommit);
RevCommit mergeBase = walk.next();
RevCommit compareFrom = (mergeBase != null) ? mergeBase : baseCommit;
List<DiffEntry> diffs = git.diff()
.setOldTree(prepareTreeParser(repo, compareFrom))
.setNewTree(prepareTreeParser(repo, targetCommit))
.call();
Set<String> paths = new LinkedHashSet<>();
for (DiffEntry entry : diffs) {
String path = (entry.getChangeType() == DiffEntry.ChangeType.DELETE)
? entry.getOldPath()
: entry.getNewPath();
paths.add(path);
}
return paths;
}
}
}
private static ObjectId resolveBranch(Repository repo, String branch) throws IOException {
ObjectId id = repo.resolve("refs/heads/" + branch);
if (id == null) {
throw new IllegalArgumentException("Branch not found: " + branch);
}
return id;
}
private static CanonicalTreeParser prepareTreeParser(Repository repo, RevCommit commit)
throws IOException {
CanonicalTreeParser parser = new CanonicalTreeParser();
try (ObjectReader reader = repo.newObjectReader()) {
parser.reset(reader, commit.getTree().getId());
}
return parser;
}
static Map<String, String> parseOwnershipCSV(Path csvPath) throws IOException {
Map<String, String> ownership = new HashMap<>();
List<String> lines = Files.readAllLines(csvPath, StandardCharsets.UTF_8);
for (String rawLine : lines) {
String line = rawLine.trim();
if (line.isEmpty() || line.equalsIgnoreCase("file_path,owner")) {
continue;
}
int lastComma = line.lastIndexOf(',');
if (lastComma <= 0 || lastComma == line.length() - 1) {
continue; // Skip malformed lines
}
String path = line.substring(0, lastComma).trim();
String owner = line.substring(lastComma + 1).trim();
// Normalize leading ./
if (path.startsWith("./")) {
path = path.substring(2);
}
ownership.putIfAbsent(path, owner);
}
return ownership;
}
static Optional<String> determineTopOwner(
Collection<String> changedFiles, Map<String, String> ownership) {
Map<String, Integer> counts = new HashMap<>();
for (String file : changedFiles) {
String owner = ownership.get(file);
if (owner != null) {
counts.merge(owner, 1, Integer::sum);
}
}
return counts.entrySet().stream()
.max(Comparator.<Map.Entry<String, Integer>>comparingInt(Map.Entry::getValue)
.thenComparing(Map.Entry::getKey))
.map(Map.Entry::getKey);
}
}
Why This Works
- The diff operation produces exactly one entry per changed path. Using a set ensures no double-counting
- Merge-base comparison correctly isolates changes introduced on the target branch
- CSV parsing handles common edge cases: headers, blank lines, commas in paths, and whitespace
- The aggregation phase is a pure function operating on collections, making it easy to unit test
- Returning
Optional.empty()when no owned files changed is more idiomatic than null or throwing
This structure demonstrates the kind of organized, defensive coding that interviewers look for when evaluating integration problems.