writeFile function

File writeFile(
  1. String path,
  2. String content, {
  3. bool overwrite = false,
  4. bool skipFormatter = false,
  5. bool skipRename = false,
  6. 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 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()) {
            print('file not found ${_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);
  }
  return _file;
}