commit method

Commits a previously prepared section to the filesystem. Restores line endings and BOM, writes via the env, and records a fresh snapshot in the store keyed by the env-canonical path.

Implementation

Future<HashlineSectionResult> commit(HashlinePreparedSection prepared) async {
  final section = prepared.section;
  final normalized = prepared.normalized;
  final after = prepared.applyResult.text;
  final warnings = [
    ...prepared.parseWarnings,
    ...prepared.applyResult.warnings,
  ];

  if (after == normalized) {
    final hash = snapshots.record(prepared.canonicalPath, normalized);
    return HashlineSectionResult(
      path: section.path,
      canonicalPath: prepared.canonicalPath,
      op: HashlineSectionOp.noop,
      before: normalized,
      after: normalized,
      persisted: prepared.rawContent,
      fileHash: hash,
      header: formatHashlineHeader(section.path, hash),
      warnings: warnings,
    );
  }

  final persisted =
      prepared.bom + restoreLineEndings(after, prepared.lineEnding);
  final written = await env.writeFile(section.path, persisted);
  if (written.isErr) throw StateError('${written.errorOrNull}');
  final fileHash = snapshots.record(prepared.canonicalPath, after);

  return HashlineSectionResult(
    path: section.path,
    canonicalPath: prepared.canonicalPath,
    op: HashlineSectionOp.update,
    before: normalized,
    after: after,
    persisted: persisted,
    fileHash: fileHash,
    header: formatHashlineHeader(section.path, fileHash),
    firstChangedLine: prepared.applyResult.firstChangedLine,
    warnings: warnings,
  );
}