findAncestor method

Project findAncestor({
  1. Directory? directory,
})

Recursive look up to find nested project directory Can start at a specific directory if provided

This method performs a recursive search to find the nearest ancestor directory that contains a Flutter project. If a specific directory is provided, the search starts from that directory. Otherwise, the search starts from the current working directory.

Returns the Project instance for the found project.

Implementation

Project findAncestor({Directory? directory}) {
  // Get directory, defined root or current
  directory ??= Directory(context.workingDirectory);

  logger.detail('Searching for project in ${directory.path}');

  // Checks if the directory is root
  final isRootDir = path.rootPrefix(directory.path) == directory.path;

  // Gets project from directory
  final project = Project.loadFromPath(directory.path);

  // If project has a config return it
  if (project.hasConfig) {
    logger.detail('Found project config in ${project.path}');

    return project;
  }

  // Return working directory if has reached root
  if (isRootDir) {
    logger.detail('No project found in ${context.workingDirectory}');

    return Project.loadFromPath(context.workingDirectory);
  }

  return findAncestor(directory: directory.parent);
}