Files
Mermaid-Preview-Nova/Scripts/util.js
T
2026-08-20 22:51:22 -03:00

83 lines
2.4 KiB
JavaScript

//
// util.js — configuration, logging and the small filesystem helpers the rest
// of the extension leans on.
//
// Nova's fs API is deliberately thin: mkdir is not recursive, copy refuses to
// overwrite, and stat returns null rather than throwing. Everything here exists
// to paper over one of those.
//
/** Reads an extension preference, falling back to `fallback` when unset. */
function conf(key, fallback) {
const value = nova.workspace.config.get(key) ?? nova.config.get(key);
return value === null || value === undefined || value === "" ? fallback : value;
}
function log(...args) {
console.log(...args);
}
function warn(...args) {
console.warn(...args);
}
/** True when a file or directory exists at `path`. */
function exists(path) {
return nova.fs.access(path, nova.fs.F_OK);
}
/** Creates `path` and any missing parents. */
function mkdirp(path) {
if (exists(path)) return;
const parent = nova.path.dirname(path);
if (parent && parent !== path) mkdirp(parent);
nova.fs.mkdir(path);
}
/** Writes `contents` to `path`, replacing whatever was there. */
function writeFile(path, contents) {
mkdirp(nova.path.dirname(path));
const file = nova.fs.open(path, "w");
try {
file.write(contents);
} finally {
file.close();
}
}
/** Copies `src` over `dest`, which nova.fs.copy on its own refuses to do. */
function copyFile(src, dest) {
mkdirp(nova.path.dirname(dest));
if (exists(dest)) nova.fs.remove(dest);
nova.fs.copy(src, dest);
}
/** Removes a directory and everything in it. */
function removeTree(path) {
if (!exists(path)) return;
const stats = nova.fs.stat(path);
if (stats && stats.isDirectory()) {
for (const entry of nova.fs.listdir(path)) {
removeTree(nova.path.join(path, entry));
}
nova.fs.rmdir(path);
} else {
nova.fs.remove(path);
}
}
/**
* FNV-1a, as an 8-character hex string. Used to keep the generated filename for
* two same-named Markdown files in different folders from colliding.
*/
function shortHash(text) {
let hash = 0x811c9dc5;
for (let i = 0; i < text.length; i++) {
hash ^= text.charCodeAt(i);
hash = Math.imul(hash, 0x01000193) >>> 0;
}
return hash.toString(16).padStart(8, "0");
}
module.exports = { conf, log, warn, exists, mkdirp, writeFile, copyFile, removeTree, shortHash };