writeFile method

FileWriteResult writeFile({
  1. required String targetPath,
  2. required String sourcePath,
  3. required Iterable<Variable> variables,
  4. required Iterable<Variable> outOfFileVariables,
  5. required Iterable<Partial> partials,
})

writes the targetPath content using the sourcePath's content and replacing the variables and partials with their configured values

outOfFileVariables are variables that are not configured in the brick_oven.yaml file, they are variables from the brick_oven project
outOfFileVariables are not included in the sync (brick.yaml or brick_oven.yaml) list

Implementation

FileWriteResult writeFile({
  required String targetPath,
  required String sourcePath,
  required Iterable<Variable> variables,
  required Iterable<Variable> outOfFileVariables,
  required Iterable<Partial> partials,
}) {
  final targetFile = di<FileSystem>().file(targetPath)
    ..createSync(recursive: true);
  final sourceFile = di<FileSystem>().file(sourcePath);

  if (!sourceFile.existsSync()) {
    di<Logger>().err(
      '${sourceFile.path} does not exist, please provide the correct path',
    );

    return const FileWriteResult.empty();
  }

  if (variables.isEmpty && partials.isEmpty) {
    sourceFile.copySync(targetFile.path);

    return const FileWriteResult.empty();
  }

  // ignore: parameter_assignments
  variables = [...variables, ...outOfFileVariables];

  /// used to check if variable/partials is goes unused
  final usedVariables = <String>{};
  final usedPartials = <String>{};

  if (!sourceFile.existsSync()) {
    di<Logger>().warn('source file does not exist: ${sourceFile.path}');
    return const FileWriteResult.empty();
  }

  var content = sourceFile.readAsStringSync();

  for (final variable in variables) {
    // formats the content
    final sectionResult = checkForSections(content, variable);
    content = sectionResult.content;
    usedVariables.addAll(sectionResult.used);

    final variableResult = checkForVariables(content, variable);
    content = variableResult.content;
    usedVariables.addAll(variableResult.used);
  }

  final partialsResult =
      checkForPartials(partials: partials, content: content);
  content = partialsResult.content;
  usedPartials.addAll(partialsResult.used);

  final ignoreVariables = {
    ...outOfFileVariables.map((v) => v.name),
    Constants.kIndexValue,
  };

  final variableNames = variables.map((v) => v.name).toSet();
  final unusedVariables =
      variableNames.difference({...usedVariables, ...ignoreVariables});

  if (unusedVariables.isNotEmpty) {
    final vars = '"${unusedVariables.map((e) => e).join('", "')}"';
    di<Logger>().warn(
      'Unused variables ($vars) in `${sourceFile.path}`',
    );
  }

  targetFile.writeAsStringSync(content);

  return FileWriteResult(
    usedVariables: usedVariables.toSet(),
    usedPartials: usedPartials.toSet(),
  );
}