findCommonAncestor function

String findCommonAncestor(
  1. List<String> paths
)

Finds the longest common ancestor directory of the given paths.

Returns '.' when no common ancestor exists.

Implementation

String findCommonAncestor(List<String> paths) {
  if (paths.isEmpty) return '.';
  if (paths.length == 1) return splitPath(paths.first).dir;

  final split = paths.map((p) => normalizePath(p).split('/')).toList();
  final minLen = split.map((s) => s.length).reduce((a, b) => a < b ? a : b);
  final common = <String>[];
  for (var i = 0; i < minLen; i++) {
    final seg = split.first[i];
    if (split.every((s) => s[i] == seg)) {
      common.add(seg);
    } else {
      break;
    }
  }
  if (common.isEmpty) return '.';
  final result = common.join('/');
  return result.isEmpty ? '.' : result;
}