addPackageByStringScriptDart method

String addPackageByStringScriptDart({
  1. required String scriptDart,
  2. required List<String> new_packages,
})

Implementation

String addPackageByStringScriptDart({
  required String scriptDart,
  required List<String> new_packages,
}) {
  List<String> scripts = scriptDart.split("\n");
  bool is_found_import_first = false;
  // bool is_found_import_last = false;
  int index_found_import_first = 0;
  int index_found_import_last = 0;
  for (var i = 0; i < scripts.length; i++) {
    String loop_text = scripts[i];
    if (!is_found_import_first) {
      if (RegExp(r"import", caseSensitive: false).hashData(loop_text)) {
        index_found_import_first = i;
        is_found_import_first = true;
      }
      continue;
    }
    if (RegExp(r"import", caseSensitive: false).hashData(loop_text)) {
      // is_found_import_last = true;
      index_found_import_last = i;
    }
  }
  for (var index = 0; index < new_packages.length; index++) {
    String new_package = new_packages[index];
    String package_to_regex = (new_package
        .replaceAll(RegExp(r"([ ]+)"), "([ ]+)?")
        .replaceAll(RegExp("(\"|')"), "(\"|')")
        .replaceAll(RegExp("\n"), ""));
    for (var i = 0; i < index_found_import_last + 1; i++) {
      String loop_text = scripts[i];
      if (i < index_found_import_first) {
        continue;
      }
      if (RegExp(package_to_regex, caseSensitive: false)
          .hashData(loop_text)) {
        break;
      }
      if (index_found_import_last == i) {
        scripts.insert((i + 1), new_package);
        index_found_import_last += 1;
        break;
      }
    }
  }
  return scripts.join("\n");
}