ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/norms-core/checks/pagelib.ts

checks/pagelib.ts

97 líneas, 4.3 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // Shared part of the checks of norms-core, decisions and owner: records of a project folder, read with the collections
  2. // package's parser. The `decisions` and `owner` packages require norms-core and import this file by the sibling path
  3. // `../../norms-core/checks/pagelib.ts` (in a project: .shtukbase/packages/norms-core/checks/pagelib.ts).
  4. //
  5. // The working directory is the project root. A record is a page `<folder>/**/<name>.md`; its address is the path from the
  6. // project root without `.md` (`norms/rules/norms-core/NS-R01`). A finding is one line on stdout, in Russian, naming the
  7. // record; `report` exits 1 when there are findings and 0 when there are none.
  8. // The page parser is the collections package's (this package requires it through contours and frame), side by side
  9. // in .shtukbase/packages/ of a project and in apps/standard/packages/ of the standard.
  10. import { existsSync, statSync } from 'node:fs';
  11. import { posix } from 'node:path';
  12. import { type Head, pystr, parseYaml, readText, splitFrontMatter, truthy, walk } from '../../collections/checks/lib/pages.ts';
  13. export type { Head };
  14. /** A record: its address, front matter and body text. */
  15. export type Page = [address: string, head: Head, body: string];
  16. /** What a check module exports: its rule (id, title) and the function that returns the findings, one line each. */
  17. export type Check = { RULE: { id: string; title: string }; check: () => string[] };
  18. export const ROOT = process.cwd();
  19. /** The records of the pages under `folder` (recursive, hidden folders skipped); [] when the folder is missing. */
  20. export function records(folder: string): Page[] {
  21. const base = posix.join(ROOT, folder);
  22. const out: Page[] = [];
  23. if (!existsSync(base) || !statSync(base).isDirectory()) return out;
  24. for (const [rel, files] of walk(base, (name) => !name.startsWith('.'))) {
  25. for (const f of files) {
  26. if (!f.endsWith('.md')) continue;
  27. const [head, body] = read(posix.join(base, rel, f));
  28. out.push([posix.normalize(posix.join(folder, rel, f)).slice(0, -3), head, body]);
  29. }
  30. }
  31. return out;
  32. }
  33. /** The header and the body text of a page; a header that does not parse is `{}`. */
  34. export function read(full: string): [Head, string] {
  35. const [fm, body] = splitFrontMatter(readText(full));
  36. let head: unknown;
  37. try {
  38. head = parseYaml(fm);
  39. } catch {
  40. head = {}; // a broken header is the collections checks' finding
  41. }
  42. return [head && typeof head === 'object' && !Array.isArray(head) ? (head as Head) : {}, body || ''];
  43. }
  44. export function empty(v: unknown): boolean {
  45. if (Array.isArray(v)) return v.every(empty);
  46. return v === null || v === undefined || v === false || pystr(v).trim() === '';
  47. }
  48. /** A field as a list of non-empty strings. */
  49. export function values(v: unknown): string[] {
  50. const items = Array.isArray(v) ? v : [v];
  51. return items.filter((x) => !empty(x)).map((x) => pystr(x).trim());
  52. }
  53. /** '/norms/rules/x/NS-R01.md', 'norms/rules/x/NS-R01' -> 'norms/rules/x/NS-R01'. */
  54. export function address(v: unknown): string {
  55. let s = (truthy(v) ? pystr(v) : '').trim().replace(/^["']+|["']+$/g, '');
  56. if (s.endsWith('.md')) s = s.slice(0, -3);
  57. return s.replace(/^\/+|\/+$/g, '');
  58. }
  59. /** Phase name of a record: `active` for both `active` and `/norms/contours/rules/active.md`. */
  60. export function status(head: Head): string {
  61. return address(head.status).split('/').pop()!;
  62. }
  63. /** A YYYY-MM-DD field as a day (the same text, so days compare as strings), or null. */
  64. export function day(v: unknown): string | null {
  65. const s = pystr(v).trim().slice(0, 10);
  66. const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
  67. if (!m) return null;
  68. const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));
  69. return d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3] ? s : null;
  70. }
  71. /** Today in the local time zone, as YYYY-MM-DD. */
  72. export function today(): string {
  73. const d = new Date();
  74. const p = (n: number) => String(n).padStart(2, '0');
  75. return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
  76. }
  77. /** Prints the findings, one per line, and sets the exit code: 1 when there are findings, 0 when none. */
  78. export function report(findings: string[]): void {
  79. if (findings.length) console.log(findings.join('\n'));
  80. process.exitCode = findings.length ? 1 : 0;
  81. }
  82. /** Runs a check module as an action. */
  83. export function main(mod: Check): void {
  84. report(mod.check());
  85. }