fileRows

tcmts.cli.main.fileRows · #dabxf42v · term · runs on the server

uses node:fs

A file kept as written (Markdown, CSS, an image), as check and save see it: its definition, where it goes (a Markdown file's first line <!-- tcm: path a.b.c --> or <!-- tcm: namespace a.b -->, or --into and its name), and whether that's new. Undefined, said why, if it can't be saved. format is what keptAs says.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { fileDefinition, fileLeaf } from "#codebase/tcmts/cli/files";
import { classifyPaths } from "#codebase/tcmts/cli/main";
import type { Row } from "#codebase/tcmts/cli/main";
import { assetFormat, joinName } from "#codebase/tcmts/cli/mirror";
import { red, yellow } from "#codebase/tcmts/cli/style";
import fs from "node:fs";
import path_1 from "node:path";

export function fileRows(
  cb: Codebase,
  file: string,
  into: string | undefined,
  format = assetFormat(file),
): Row[] | undefined {
  let content = fs.readFileSync(file);
  let target: string | undefined;
  let ns = into;
  if (format.replace(/^\./, "") === "md") {
    const text = content.toString("utf8");
    const pragma = /^<!--\s*tcm:\s*(path|namespace)\s+(\S+)\s*-->\r?\n/.exec(text);
    if (pragma) {
      if (pragma[1] === "path") target = pragma[2];
      else ns ??= pragma[2];
      content = Buffer.from(text.slice(pragma[0].length), "utf8");
    }
  }
  const name = target ?? joinName(ns ?? "", fileLeaf(file));
  const { def, problems, warnings } = fileDefinition(cb, name, format, content);
  for (const w of warnings) console.log(yellow(`warning: ${w}`));
  if (problems.length) {
    for (const p of problems) console.log(red(p));
    console.log(red(`\n${path_1.basename(file)} has problems; nothing was saved.`));
    return undefined;
  }
  return classifyPaths(cb, [{ def, path: name }]);
}

uses

used by