selectFolderPath method

String selectFolderPath()

Selects a folder path.

This function allows the user to select a folder path from the file system.

Returns: A String representing the selected folder path.

Implementation

String selectFolderPath() {
  String currentDir = Directory.current.absolute.path;

  while (true) {
    final entries = Directory(currentDir)
        .listSync()
        .where((entity) =>
            entity is Directory &&
            !entity.path
                .split(Platform.pathSeparator)
                .last
                .startsWith('.')) // Exclude hidden folders
        .map((entity) => entity.path.split(Platform.pathSeparator).last)
        .toList();

    if (entries.isEmpty) {
      exit(1);
    }

    // Display folder options in a cleaner format
    final selectedIndex = Select(
      prompt: 'Choose a folder:',
      options: [
        ...entries,
        '.. (Go back)' // Add '..' option to go up one level
      ],
    ).interact();
    // If the user wants to go back
    if (selectedIndex == entries.length) {
      print('🔧 Going back...');
      // Going up one level
      if (Directory(currentDir).parent.path == currentDir) {
        print('🔧 Already at the root directory.');
        continue;
      }
      currentDir = Directory(currentDir).parent.path;
      print('🔧 New current directory: $currentDir');
    } else {
      final selectedFolder = entries[selectedIndex];
      print('🔧 Selected folder: $selectedFolder');
      final selectedFolderPath =
          '$currentDir${Platform.pathSeparator}$selectedFolder';
      print('🔧 Selected folder path: $selectedFolderPath');
      // If the user selects a folder, go into that folder
      if (Directory(selectedFolderPath).existsSync()) {
        currentDir = selectedFolderPath;
      }
    }

    // When a valid folder is selected
    if (Directory(currentDir).existsSync()) {
      return currentDir;
    } else {
      exit(1);
    }
  }
}