run static method

Future<(InitResult?, String?)> run(
  1. String projectPath, {
  2. required bool write,
})

Reads the pubspec in projectPath and creates the config for it, adding it to the end of the pubspec when write is true

The pubspec is only changed when it has no build_pipe config yet, and the config is valid

Implementation

static Future<(InitResult?, String?)> run(String projectPath, {required bool write}) async {
  File pubspec = File(p.join(projectPath, "pubspec.yaml"));
  if (!await pubspec.exists()) {
    return (null, "pubspec.yaml could not be found. Run the command in the root of your Flutter project");
  }

  String content = await pubspec.readAsString();
  (yaml.YamlMap?, String?) parsed = _parse(content);
  if (parsed.$2 != null) {
    return (null, "pubspec.yaml could not be read -> ${parsed.$2}");
  }
  if (parsed.$1!.containsKey("build_pipe")) {
    return (null, "pubspec.yaml already has a build_pipe config, so nothing has been changed");
  }

  List<TargetPlatform> platforms = ConfigScaffold.detectPlatforms(projectPath);
  String scaffold = ConfigScaffold.generate(appName: parsed.$1!["name"]?.toString() ?? "your_app", platforms: platforms);
  // Separated from the rest of the pubspec by an empty line
  String updated = "$content${content.endsWith("\n") ? "" : "\n"}\n$scaffold";

  // The pubspec is checked before it is written, so that a broken config never replaces a working pubspec
  String? invalid = _checkConfig(updated);
  if (invalid != null) {
    return (null, "The generated config is invalid, so nothing has been changed -> $invalid");
  }

  if (write) {
    try {
      await pubspec.writeAsString(updated);
    } on FileSystemException catch (e) {
      return (null, "pubspec.yaml could not be written -> ${e.message}");
    }
  }
  return (InitResult(platforms: platforms, scaffold: scaffold), null);
}