Skip to content

Instantly share code, notes, and snippets.

@gcuddy

gcuddy/index.ts Secret

Created April 12, 2024 01:15
Show Gist options
  • Save gcuddy/2a897188c5e125ce2d34e64e98587613 to your computer and use it in GitHub Desktop.
Save gcuddy/2a897188c5e125ce2d34e64e98587613 to your computer and use it in GitHub Desktop.
obsidian image consolidator
import { $ } from "bun";
import path from "node:path";
import MagicString from "magic-string";
import slugify from "slugify";
const VAULT = "/Users/guscuddy/Mainframe";
const file = Bun.argv.slice(2)[0];
const text = await Bun.file(file).text();
const r = /!\[\[(.*?)\]\]/g;
const IMAGE_EXTS = [".jpg", ".png", ".gif", ".svg"];
function escapeParentheses(str: string) {
return str.replace(/([()])/g, "\\$1");
}
const matches = Array.from(text.matchAll(r));
const folder = path.dirname(file);
const s = new MagicString(text);
for (const match of matches) {
if (IMAGE_EXTS.some((i) => match[1].endsWith(i))) {
const escaped = escapeParentheses(match[1]);
const slug = slugify(match[1], { lower: true });
try {
const file = (await $`fd ${escaped} ${VAULT}`.text()).trim();
await $`mkdir -p ${folder}/assets && cp ${file} ${folder}/assets/${slug}`;
const startingIndex = match.index;
const endingIndex = match.index + match[0].length;
s.update(startingIndex, endingIndex, `![](./assets/${slug})`);
} catch (e) {
console.error(e);
}
}
}
const finalText = s.toString();
await Bun.write(file, finalText);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment