modifyFile method
Updates the contents of an existing file
path
is relative path to file e.g. "lib/src/file.dart"
contents
is a function that takes the current contents of the file and returns
the modified contents of the file
Implementation
void modifyFile(String path, String Function(String current) contents) {
final pathComponents = path.split("/");
final relativeDirectoryComponents =
pathComponents.sublist(0, pathComponents.length - 1);
final directory = Directory.fromUri(
relativeDirectoryComponents.fold(
workingDirectory.uri,
(Uri prev, elem) => prev.resolve("$elem/"),
),
);
final file = File.fromUri(directory.uri.resolve(pathComponents.last));
if (!file.existsSync()) {
throw ArgumentError("File at '${file.uri}' doesn't exist.");
}
final output = contents(file.readAsStringSync());
file.writeAsStringSync(output);
}