findInstructionFiles function

Future<List<InstructionFile>> findInstructionFiles(
  1. String workspaceRoot, {
  2. String? homeDirectory,
})

Collects instruction files from the user's home config and from every directory between the filesystem root and workspaceRoot, outermost first so that the most specific instructions come last.

Implementation

Future<List<InstructionFile>> findInstructionFiles(String workspaceRoot, {String? homeDirectory}) async {
  final home = homeDirectory ?? Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
  final candidates = <String>[
    if (home != null) p.join(home, '.lea', 'LEA.md'),
    for (final directory in _ancestorsOutermostFirst(p.normalize(p.absolute(workspaceRoot))))
      for (final name in projectInstructionFileNames) p.join(directory, name),
  ];

  final files = <InstructionFile>[];
  for (final path in candidates) {
    final file = File(path);
    if (!await file.exists()) {
      continue;
    }
    try {
      var content = (await file.readAsString()).trim();
      if (content.isEmpty) {
        continue;
      }
      if (content.length > _maxInstructionChars) {
        content = '${content.substring(0, _maxInstructionChars)}\n... [truncated]';
      }
      files.add(InstructionFile(path: path, content: content));
    } on FileSystemException {
      continue;
    }
  }
  return files;
}