addOrReplaceFile method

void addOrReplaceFile(
  1. String path,
  2. String contents, {
  3. List<String> imports = const [],
})

Adds or replaces file in this terminal's working directory

path is relative path to file e.g. "lib/src/file.dart" contents is the string contents of the file imports are import uri strings, e.g. 'package:aqueduct/aqueduct.dart' (don't use quotes)

Implementation

void addOrReplaceFile(
  String path,
  String contents, {
  List<String> imports = const [],
}) {
  final pathComponents = path.split("/");

  final relativeDirectoryComponents =
      pathComponents.sublist(0, pathComponents.length - 1);

  final uri = relativeDirectoryComponents.fold(
    workingDirectory.uri,
    (Uri prev, elem) => prev.resolve("$elem/"),
  );

  final directory = Directory.fromUri(uri);
  if (!directory.existsSync()) {
    directory.createSync(recursive: true);
  }

  final file = File.fromUri(directory.uri.resolve(pathComponents.last));
  final directives = imports.map((i) => "import '$i';").join("\n");
  file.writeAsStringSync("$directives\n$contents");
}