updateDotEnv static method

Future<void> updateDotEnv({
  1. required String filePath,
  2. required Map<String, String> updates,
})

Implementation

static Future<void> updateDotEnv({
  required String filePath,
  required Map<String, String> updates,
}) async {
  final file = File(filePath);

  if (!file.existsSync()) {
    throw Exception('File not found: $filePath');
  }

  final lines = await file.readAsLines();
  final updatedLines = <String>[];
  final keysToUpdate = updates.keys.toSet();

  for (var line in lines) {
    // Kiểm tra dòng có phải dạng `key=value`
    final match = RegExp(r'^([^#\s=]+)=(.*)$').firstMatch(line);
    if (match != null) {
      final key = match.group(1)?.trim();
      if (key != null && keysToUpdate.contains(key)) {
        // Nếu key nằm trong `updates`, cập nhật giá trị
        updatedLines.add('$key=${updates[key]}');
        keysToUpdate.remove(key);
      } else {
        // Nếu không, giữ nguyên dòng
        updatedLines.add(line);
      }
    } else {
      // Các dòng không khớp định dạng `key=value`, giữ nguyên
      updatedLines.add(line);
    }
  }

  // Thêm các cặp `key=value` còn lại vào cuối file
  for (var key in keysToUpdate) {
    updatedLines.add('$key=${updates[key]}');
  }

  // Ghi lại file với nội dung đã cập nhật
  await file.writeAsString(updatedLines.join('\n'));
}