findTemplatePath static method

String findTemplatePath()

Implementation

static String findTemplatePath() {
  // First check if we're in the source project directory
  final scriptDir = path.dirname(Platform.script.path);
  final possibleProjectRoot = path.dirname(scriptDir);

  // Check if templates exist in the possible root directory
  final templatesDir = path.join(possibleProjectRoot, 'templates');
  if (Directory(templatesDir).existsSync()) {
    return possibleProjectRoot;
  }

  // If not found, look in parent directory (for bin/ case)
  final parentDir = path.dirname(possibleProjectRoot);
  final parentTemplatesDir = path.join(parentDir, 'templates');
  if (Directory(parentTemplatesDir).existsSync()) {
    return parentDir;
  }

  // Check if we're running from a globally installed package
  // Look for the package in pub cache
  final pubCacheDir = path.join(
    Platform.environment['HOME'] ?? '',
    '.pub-cache',
    'hosted',
    'pub.flutter-io.cn',
  );

  if (Directory(pubCacheDir).existsSync()) {
    // Find flutter_base_kit package directory (latest version)
    final entries = Directory(pubCacheDir).listSync();
    String? latestVersionPath;
    String? latestVersion;

    for (final entry in entries) {
      if (entry is Directory && entry.path.contains('flutter_base_kit-')) {
        final globalTemplatesDir = path.join(entry.path, 'templates');
        if (Directory(globalTemplatesDir).existsSync()) {
          // Extract version from path
          final pathParts = entry.path.split('flutter_base_kit-');
          if (pathParts.length > 1) {
            final version = pathParts.last;
            if (latestVersion == null ||
                _compareVersions(version, latestVersion) > 0) {
              latestVersion = version;
              latestVersionPath = entry.path;
            }
          }
        }
      }
    }

    if (latestVersionPath != null) {
      return latestVersionPath;
    }
  }

  // If still not found, return current directory
  return Directory.current.path;
}