function importExamples()

in website/scripts/codegen-examples.js [119:183]


function importExamples() {
  for (let spec of EXAMPLE_SPECS) {
    console.log(`\nProcessing ${spec.name}...`);
    const moduleName = `${spec.name}Examples`;
    const moduleBuilder = new ExampleModuleBuilder(moduleName);

    // Delete and remake directory to avoid leaving cruft from prior runs.
    const destDir = path.dirname(
      path.join(EXAMPLE_DEST_ROOT, spec.pathTemplate(0)),
    );
    if (fs.existsSync(destDir)) {
      console.log(`  Removing directory ${destDir}`);
      fs.rmSync(destDir, {recursive: true});
    }
    console.log(`  Making directory ${destDir}`);
    fs.mkdirSync(destDir, {recursive: true});

    // Copy each example from 0..N, trimming the header comment out and
    // generating in-between diffs along the way, from 0->1, 1->2, etc.
    for (let i = 0; ; i++) {
      const sourcePath = path.join(EXAMPLE_SRC_ROOT, spec.pathTemplate(i));
      const destPath = path.join(EXAMPLE_DEST_ROOT, spec.pathTemplate(i));
      const diffPath = path.join(
        EXAMPLE_DEST_ROOT,
        spec.pathTemplate(i) + '.diff',
      );

      if (!fs.existsSync(sourcePath)) {
        break;
      }

      console.log(`  Writing trimmed ${destPath}`);
      const exampleContents = fs.readFileSync(sourcePath, {encoding: 'utf8'});
      const trimmedExampleContents = trimExampleFileHeader(exampleContents);
      fs.writeFileSync(destPath, trimmedExampleContents, {encoding: 'utf8'});
      moduleBuilder.addCodeBlock(i, destPath);

      if (i > 0) {
        console.log(`  Writing trimmed ${diffPath}`);
        const prevPath = path.join(EXAMPLE_DEST_ROOT, spec.pathTemplate(i - 1));
        const diffResult = child_process.spawnSync(
          'diff',
          ['--unified', prevPath, destPath],
          {encoding: 'utf8'},
        );
        const trimmedDiffContents = trimDiffHeader(diffResult.stdout);
        fs.writeFileSync(diffPath, trimmedDiffContents, {encoding: 'utf8'});
        moduleBuilder.addDiffBlock(i, diffPath);
      }
    }

    // Write out React component wrappers for each example contents and diff.
    const modulePath = `src/components/examples/${moduleName}.js`;
    const moduleDir = path.dirname(modulePath);
    const moduleContents = moduleBuilder.build();

    if (!fs.existsSync(moduleDir)) {
      console.log(`  Making directory ${moduleDir}`);
      fs.mkdirSync(moduleDir, {recursive: true});
    }

    console.log(`  Writing React components to ${modulePath}`);
    fs.writeFileSync(modulePath, moduleContents, {encoding: 'utf8'});
  }
}