generateEnvClass static method

Future<void> generateEnvClass([
  1. String? envArgument
])

Generates the AppEnvironment class and updates pubspec.yaml with the selected environment's version.

  • If envArgument is provided, it uses that environment.
  • Otherwise, it defaults to the current_environment value in environment.yaml.

The function does the following:

  1. Reads the environment.yaml file.
  2. Determines the selected environment.
  3. Retrieves the environment-specific version.
  4. Updates pubspec.yaml with the correct version.
  5. Generates a lib/app_environment.dart class with environment variables.

Example usage:

void main() async {
  await EnvManager.generateEnvClass();
}

If the selected environment is marked as isProdEnv: true, the version format is:

version: 1.0.0

Otherwise, the version format is:

version: 1.0.0-staging  // Example for staging

Implementation

static Future<void> generateEnvClass([String? envArgument]) async {
  final envFile = File(envFileName);
  if (!await envFile.exists()) {
    await _createDefaultEnvFile(envFile);
  }

  final yamlString = await envFile.readAsString();
  final yamlMap = loadYaml(yamlString);

  final currentEnv = envArgument ?? yamlMap['current_environment'];
  final environments = yamlMap['environments'] as Map;

  if (!environments.containsKey(currentEnv)) {
    print('Error: Environment "$currentEnv" does not exist in $envFileName.');
    exit(1);
  }

  final envConfig = environments[currentEnv] as YamlMap;
  final baseVersion = envConfig['version'] ?? '1.0.0';

  // Determine if the environment is production
  var isProdEnv = false;
  if (envConfig.containsKey("isProdEnv")) {
    isProdEnv = envConfig['isProdEnv'] == true;
  }

  // Format version based on `isProdEnv`
  final formattedVersion =
  isProdEnv ? baseVersion : '$baseVersion-$currentEnv';

  // Update `pubspec.yaml` with the selected environment version
  await _updatePubspecVersion(formattedVersion);

  // Generate the AppEnvironment class dynamically
  final classContent = '''
// THIS FILE IS GENERATED AUTOMATICALLY. DO NOT EDIT.

/// Contains environment variables and app configuration.
class AppEnvironment {
/// The current selected environment.
static const String currentEnvironment = '$currentEnv';

/// The application version from `environment.yaml`.
static const String version = '$formattedVersion';

${_generateStaticVariables(envConfig)}
}
''';

  final classFile = File(envClassFileName);
  await classFile.writeAsString(classContent);

  print('Environment class generated successfully.');
}