writeFile function
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 newFile = File(Structure.replaceAsExpected(path: path));
// Only create or overwrite if the file doesn't exist or overwrite is true
if (!newFile.existsSync() || overwrite) {
// Format content if necessary
if (!skipFormatter && path.endsWith('.dart')) {
try {
content = sortImports(
content,
renameImport: !skipRename,
filePath: path,
useRelative: useRelativeImport,
);
} catch (e) {
if (newFile.existsSync()) {
LogService.info(LocaleKeys.error_invalid_dart.trArgs([newFile.path]));
}
rethrow;
}
}
// Rename file if needed
if (!skipRename && newFile.path != 'pubspec.yaml') {
var separatorFileType = PubspecUtils.separatorFileType ?? '';
if (separatorFileType.isNotEmpty) {
newFile = _renameFileIfNecessary(newFile, path, separatorFileType);
}
}
// Create file and write content
newFile.createSync(recursive: true);
newFile.writeAsStringSync(content);
// Log success
if (logger) {
LogService.success(
LocaleKeys.sucess_file_created
.trArgs([basename(newFile.path), newFile.path]),
);
}
}
return newFile;
}