setEnvironment static method

Future<bool> setEnvironment(
  1. String key,
  2. String value
)

Implementation

static Future<bool> setEnvironment(String key, String value) async {
  if (dart.isWeb) {
    return false;
  }
  if (dart.isLinux || dart.isMacOS) {
    File file = File(path.join(
        Directory(Platform.environment['XDG_CONFIG_HOME'] ??
                path.join(Platform.environment['HOME']!))
            .path,
        ".bashrc"));
    if (!file.existsSync()) {
      return false;
    }
    String readFile = await file.readAsString();
    List<String> bashrcs = readFile.split("\n");

    RegExp regExp = RegExp(
        "export([ ]+)${key}=${RegExp.escape(json.encode(value))}",
        caseSensitive: false);
    bool is_not_found_path = true;
    for (var i = 0; i < bashrcs.length; i++) {
      String bashrc = bashrcs[i];
      if (regExp.hasMatch(bashrc)) {
        is_not_found_path = false;
      }
    }
    if (is_not_found_path) {
      bashrcs.add("export ${key}=${json.encode(value)}");
      await file.writeAsString(bashrcs.join("\n"));
      await Process.run(
        "source",
        [
          file.path,
        ],
        runInShell: true,
      );
      return true;
    }
    return true;
  }
  if (dart.isWindows) {
    await Process.run(
      "setx",
      [
        key,
        value,
      ],
      runInShell: true,
    );

    return true;
  }

  return false;
}