package com.ankurm.crud; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Path; /** * Writes a numbered transcript under {@code output/} and echoes it to the console. * Every console block quoted in the article comes out of one of these files verbatim. */ public final class Transcript implements AutoCloseable { private final Path path; private final StringWriter buffer = new StringWriter(); private final PrintWriter out = new PrintWriter(buffer); public Transcript(String fileName, String title) { this.path = Path.of("output", fileName); out.println("# " + title); out.println(); } public Transcript line(String format, Object... args) { out.println(args.length == 0 ? format : String.format(format, args)); return this; } public Transcript blank() { out.println(); return this; } public Transcript section(String heading) { out.println(); out.println("--- " + heading + " ---"); return this; } @Override public void close() { out.flush(); // Absolute paths of whoever ran the build are environment noise, not a finding. String text = buffer.toString().replace(System.getProperty("user.dir"), ""); try { Files.createDirectories(path.getParent()); Files.writeString(path, text); } catch (IOException e) { throw new IllegalStateException("could not write " + path, e); } System.out.print(text); } }