Skip to content

Instantly share code, notes, and snippets.

@mbbroberg
Created August 7, 2024 19:46
Show Gist options
  • Save mbbroberg/ab138cd75aac50f76f8c5362940503cc to your computer and use it in GitHub Desktop.
Save mbbroberg/ab138cd75aac50f76f8c5362940503cc to your computer and use it in GitHub Desktop.
A quick way to add `up` values for a Linking Your Thinking logic in Obsidian.
const fs = require('fs').promises;
const path = require('path');
const yaml = require('js-yaml');
const term = 'search term here'
const lyt = '"[[File to Link]]"'
async function updateLinks(vaultPath) {
let updatedCount = 0;
async function processFile(filePath) {
const content = await fs.readFile(filePath, 'utf8');
if (!content.toLowerCase().includes(term)) return false;
const parts = content.split('---');
let frontmatter = {};
let body = content;
if (parts.length > 2) {
try {
frontmatter = yaml.load(parts[1]) || {};
body = parts.slice(2).join('---').trim();
} catch (e) {
console.warn(`Error parsing frontmatter in ${filePath}: ${e.message}`);
return false;
}
}
let updated = false;
if (!frontmatter.up) {
frontmatter.up = lyt;
updated = true;
} else if (!frontmatter.related) {
frontmatter.related = [lyt];
updated = true;
} else if (Array.isArray(frontmatter.related) && !frontmatter.related.includes(lyt)) {
frontmatter.related.push(lyt);
updated = true;
}
if (updated) {
const newContent = `---
${yaml.dump(frontmatter)}---
${body}`;
await fs.writeFile(filePath, newContent, 'utf8');
return true;
}
return false;
}
async function walkDir(dir) {
const files = await fs.readdir(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stats = await fs.stat(filePath);
if (stats.isDirectory()) {
await walkDir(filePath);
} else if (path.extname(file) === '.md') {
if (await processFile(filePath)) {
updatedCount++;
console.log(`Updated: ${filePath}`);
}
}
}
}
await walkDir(vaultPath);
console.log(`Update complete. ${updatedCount} file(s) were updated.`);
}
// Usage
const vaultPath = process.argv[2];
if (!vaultPath) {
console.error('Please provide the path to your Obsidian vault');
process.exit(1);
}
updateLinks(vaultPath).catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment