setSources

tcmts.cli.libraries.setSources · #k6thixno · term · runs on the server

uses Buffer

tcm lib sources: add a place to fetch a library from (tried after the others), or remove one (not its last). Its record changes; its names don't.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { fileDefinition } from "#codebase/tcmts/cli/files";
import { libraryNamed, recordAt, recordText } from "#codebase/tcmts/cli/libraries";
import { bold, dim } from "#codebase/tcmts/cli/style";
import { UsageError } from "#codebase/tcmts/cli/ui";

export function setSources(
  cb: Codebase,
  which: string,
  o: { add?: string | undefined; rm?: string | undefined },
) {
  const lib = libraryNamed(cb.store, which);
  let sources = lib.sources;
  if (o.add && !sources.includes(o.add)) sources = [...sources, o.add];
  if (o.rm) {
    if (!sources.includes(o.rm)) throw new UsageError(`${lib.path} isn't fetched from ${o.rm}`);
    if (sources.length === 1)
      throw new UsageError(`${o.rm} is where ${lib.path} comes from; add another first`);
    sources = sources.filter((s) => s !== o.rm);
  }
  if (sources !== lib.sources) {
    const name = lib.path.slice(lib.path.lastIndexOf(".") + 1);
    const entries = {
      ...recordAt(cb.store, lib.record),
      [name]: { ...recordAt(cb.store, lib.record)[name]!, sources },
    };
    const { def } = fileDefinition(cb, lib.record, "json", Buffer.from(recordText(entries)));
    cb.putDefs([def]);
    // (the record says where libraries come from; `tcm lib` changes it, so the guard is set aside)
    cb.store.unguarded(() =>
      cb.store.updateName(lib.record, def.hash, "file", `lib sources ${lib.path}`),
    );
  }
  console.log(`${bold(lib.path)} ${dim("comes from")} ${sources.join(dim(", then "))}`);
}

uses

used by