zShGenerator top-level property

FigGenerator zShGenerator
final

Implementation

final FigGenerator zShGenerator = FigGenerator(
  script: [
    'zsh',
    '-c',
    r'cat ${${ZSHZ_DATA:-${_Z_DATA:-${HOME}/.z}}:A} && echo "___SEP___" && pwd && ls -d */'
  ],
  postProcess: (String out, [List<String>? tokens]) {
    final parts = out.split('___SEP___');
    final historyOut = parts[0];
    final cwdOut = parts.length > 1 ? parts[1] : '';

    final historySuggestions = <FigSuggestion>[];
    if (historyOut.isNotEmpty) {
      final lines = historyOut.split('\n');
      for (final line in lines) {
        if (line.trim().isEmpty) continue;
        final p = line.split('|');
        if (p.length < 3) continue;
        final path = p[0];
        final weight = double.tryParse(p[1]) ?? 0;

        final splitPath = path.split('/');
        final name = splitPath.isNotEmpty ? splitPath.last : path;
        final priority = (75 + (weight * 25) / 9000).toInt();

        historySuggestions.add(FigSuggestion(
          name: name,
          description: path,
          priority: priority,
          icon: '📁',
          insertValue: name,
          displayName: name,
        ));
      }
    }

    final cwdSuggestions = <FigSuggestion>[];
    if (cwdOut.isNotEmpty) {
      final lines = cwdOut.trim().split('\n');
      if (lines.isNotEmpty) {
        final cwd = lines[0].trim();
        for (var i = 1; i < lines.length; i++) {
          final line = lines[i].trim();
          if (line.isEmpty) continue;
          final name = line.replaceAll('/', '');
          final fullPath = '$cwd/$name';

          cwdSuggestions.add(FigSuggestion(
            name: name,
            description: fullPath,
            priority: 50, // Default
            icon: '📁',
            insertValue: name,
            displayName: name,
          ));
        }
      }
    }

    // Merge: history + cwd, remove duplicates by path
    final merged = <String, FigSuggestion>{}; // path -> suggestion

    for (final s in historySuggestions) {
      final path = s.description as String;
      merged[path] = s;
    }

    for (final s in cwdSuggestions) {
      final path = s.description as String;
      if (!merged.containsKey(path)) {
        merged[path] = s;
      }
    }

    final allSuggestions = merged.values.toList();

    // Filter by tokens
    if (tokens == null || tokens.isEmpty) return allSuggestions;

    // tokens[0] is 'z' usually.
    // filter args: skip 'z' and flags.
    final args = tokens
        .where((t) => t.isNotEmpty && t != 'z' && !t.startsWith('-'))
        .toList();

    return _filterHistoryBySearchTerms(args, allSuggestions);
  },
);