-
-
Save gcuddy/2a897188c5e125ce2d34e64e98587613 to your computer and use it in GitHub Desktop.
obsidian image consolidator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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