generateEssentials function

void generateEssentials(
  1. File pubspecFile,
  2. File configFile,
  3. CliConfig cliConfig
)

Generates a new app id (as UUID) for the app, if not already present. The new id is persisted in the config file.

The ns parameter is used to generate a namespaced UUID, if provided.

Implementation

void generateEssentials(
  File pubspecFile,
  File configFile,
  CliConfig cliConfig,
) {
  // if neither app id nor publisher is to be generated, do nothing
  if (!cliConfig.generateAppId && !cliConfig.generatePublisher) return;

  final pubspecJson = readYaml(pubspecFile);

  if (!configFile.existsSync()) {
    CliLogger.exitError('The CLI param --path has an invalid value, '
        'the given path does not exist.');
  }

  // if config file is a custom one, read 'inno_bundle' section from it,
  // otherwise, read 'inno_bundle' section from pubspec.yaml.
  final configJson =
      configFile == pubspecFile ? pubspecJson : readYaml(configFile);
  final inno = configJson['inno_bundle'] ?? {};

  // if inno_bundle essentials are already present, do nothing
  if (inno['id'] != null || inno['publisher'] != null) return;

  final lines = configFile.readAsLinesSync();
  var innoInsertLine = lines.indexWhere((l) => l.startsWith("inno_bundle:"));

  // if inno_bundle section is not found, add it at the end of the file
  if (innoInsertLine == -1) {
    // if the last line is not empty, add an empty line before the new section
    if (lines.last.trim().isNotEmpty) lines.add("");

    lines.add("inno_bundle:");
    innoInsertLine = lines.length - 1;
  }

  // this does not check if [id] is type string or if it is valid UUID,
  // at this point it is user's responsibility to make sure [id] is valid.
  if (cliConfig.generateAppId && inno['id'] == null) {
    const uuid = Uuid();
    final appId = cliConfig.appIdNamespace != null
        ? uuid.v5(Namespace.url.value, cliConfig.appIdNamespace)
        : uuid.v1();
    innoInsertLine += 1;
    lines.insert(innoInsertLine, "  id: $appId");
  }

  if (cliConfig.generatePublisher &&
      pubspecJson['maintainer'] == null &&
      inno['publisher'] == null) {
    innoInsertLine += 1;
    final publisher = getSystemUserName() ?? "Unknown Publisher";
    lines.insert(innoInsertLine, "  publisher: $publisher");
  }

  configFile.writeAsStringSync(lines.join('\n'));
}