import { process_frontmatter } from '@doc-utils/markdown2html'; import { promises as fs } from 'fs'; import { resolve as resolve_path } from 'path'; import { parse as parse_yaml, stringify as to_yaml } from 'yaml'; import { hash_str } from './hash'; export async function load_from_dir(dir: string, file: string) { if (! dir) { return null; } const rel_path = resolve_path('/', file); const abs_path = resolve_path(dir, '.' + rel_path); return await fs.readFile(abs_path, 'utf8'); } export function mkdirp(dir: string, mode = 0o700) { return fs.mkdir(dir, { mode, recursive: true }); } export async function with_default_if_missing(read_promise: Promise, default_value: T) : Promise { try { return await read_promise; } catch (error) { if (error?.code === 'ENOENT') { return default_value; } throw error; } } export async function read_text(file: string, check_for_frontmatter = true, compute_hash = true) { const text = await fs.readFile(file, 'utf8'); const hash = compute_hash ? hash_str(text) : null; if (check_for_frontmatter) { const { frontmatter, document } = process_frontmatter(text); return { frontmatter, text: document, hash }; } return { text, frontmatter: null, hash }; } export async function read_json(file: string, check_for_frontmatter = true, compute_hash = true) { const json = await fs.readFile(file, 'utf8'); const hash = compute_hash ? hash_str(json) : null; if (check_for_frontmatter) { const { frontmatter, document } = process_frontmatter(json); const parsed = JSON.parse(document); return { frontmatter, json: document, parsed, hash }; } const parsed = JSON.parse(json); return { json, parsed, frontmatter: null, hash }; } export async function read_yaml(file: string, check_for_frontmatter = true, compute_hash = true) { const yaml = await fs.readFile(file, 'utf8'); const hash = compute_hash ? hash_str(yaml) : null; if (check_for_frontmatter) { const { frontmatter, document } = process_frontmatter(yaml); const parsed = parse_yaml(document); return { frontmatter, yaml: document, parsed, hash }; } const parsed = parse_yaml(yaml); return { yaml, parsed, frontmatter: null, hash }; } export function write_text(file: string, text: string) { return fs.writeFile(file, text, 'utf8'); } export function write_json(file: string, obj: any, pretty = true) { const json = JSON.stringify(obj, null, pretty ? ' ' : null); return fs.writeFile(file, json, 'utf8'); } export function write_yaml(file: string, obj: any) { const yaml = to_yaml(obj); return fs.writeFile(file, yaml, 'utf8'); }