writeFile function

File writeFile(
  1. String path,
  2. String content, {
  3. bool overwrite = false,
  4. bool skipFormatter = false,
  5. bool logger = true,
  6. bool skipRename = false,
  7. bool useRelativeImport = false,
})

Create or edit the contents of a file

Implementation

File writeFile(String path, String content,
    {bool overwrite = false,
    bool skipFormatter = false,
    bool logger = true,
    bool skipRename = false,
    bool useRelativeImport = false}) {
  var _file = File(Structure.replaceAsExpected(path: path));

  if (!_file.existsSync() || overwrite) {
    if (!skipFormatter) {
      if (path.endsWith('.dart')) {
        try {
          content = sortImports(
            content,
            renameImport: !skipRename,
            filePath: path,
            useRelative: useRelativeImport,
          );
        } on Exception catch (_) {
          if (_file.existsSync()) {
            LogService.info(LocaleKeys.error_invalid_dart.trArgs([_file.path]));
          }
          rethrow;
        }
      }
    }
    if (!skipRename && _file.path != 'pubspec.yaml') {
      var separatorFileType = PubspecUtils.separatorFileType!;
      if (separatorFileType.isNotEmpty) {
        _file = _file.existsSync()
            ? _file = _file
                .renameSync(replacePathTypeSeparator(path, separatorFileType))
            : File(replacePathTypeSeparator(path, separatorFileType));
      }
    }

    _file.createSync(recursive: true);
    _file.writeAsStringSync(content);
    if (logger) {
      LogService.success(
        LocaleKeys.success_file_created.trArgs(
          [basename(_file.path), _file.path],
        ),
      );
    }
  }
  return _file;
}