commonPath function
Finds the longest common path from a list of absolute paths.
This function is the Dart equivalent of Python's os.path.commonpath
.
It correctly handles different path separators for Windows, Linux, and macOS.
paths
A list of absolute paths to compare.
Returns the common path as a string. If the list is empty or there is no common path (e.g., different drives on Windows), it returns an empty string.
Created with Gemini 2.5 pro
Implementation
String? commonPath(List<String> paths) {
if (paths.isEmpty) return null;
// Split all paths into their individual components.
// e.g., "/home/user/docs" -> ["/", "home", "user", "docs"]
final List<List<String>> allParts = paths.map((path) => p.split(path)).toList();
// Find the path with the fewest components to set the loop boundary.
List<String> shortestPath = allParts.reduce((a, b) => a.length < b.length ? a : b);
final commonParts = <String>[];
for (int i = 0; i < shortestPath.length; i++) {
// Get the component to check from the first path.
final String currentPart = allParts[0][i];
// Check if this component is the same in all other paths.
for (int j = 1; j < allParts.length; j++) {
if (allParts[j][i] != currentPart) {
// Mismatch found, the common path is what we have so far.
return p.joinAll(commonParts);
}
}
// All paths have this part in common, add it to our list.
commonParts.add(currentPart);
}
// If we get here, the shortest path is a common prefix for all paths.
return p.joinAll(commonParts);
}