Created
November 18, 2022 11:17
-
-
Save bergie/40d710852eed7bf86bf7a46b3856ff59 to your computer and use it in GitHub Desktop.
Rename notes from GitJournal Zettelkasten to Obsidian
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
const { readdir, readFile, writeFile } = require('node:fs/promises'); | |
const { spawn } = require('node:child_process'); | |
const path = require('path'); | |
const frontmatter = require('frontmatter'); | |
let notedir = process.env.PWD; | |
if (process.argv.length > 2) { | |
notedir = path.resolve(process.env.PWD, process.argv[2]); | |
} | |
const notesmap = {}; | |
const titlemap = {}; | |
readdir(notedir) | |
.then((files) => files.filter((name) => name.indexOf('.md') !== -1)) | |
.then((notes) => { | |
return notes.reduce((previousPromise, notefile) => { | |
return previousPromise.then(() => { | |
const filepath = path.resolve(notedir, notefile); | |
return readFile(filepath, 'utf-8') | |
.then((content) => { | |
const parsed = frontmatter(content); | |
let title; | |
if (parsed.data.title) { | |
title = parsed.data.title; | |
} else { | |
const matched = parsed.content.match(/^\# (.*)\n/m); | |
if (matched.length) { | |
title = matched[1]; | |
} | |
} | |
titlemap[notefile] = title; | |
}) | |
.then(() => { | |
if (!titlemap[notefile]) { | |
// No title, ignore | |
return Promise.resolve(); | |
} | |
const newname = `${titlemap[notefile]}.md`; | |
return new Promise((resolve, reject) => { | |
console.log(`git mv ${notefile} ${newname}`); | |
let err; | |
const rename = spawn('git', [ | |
'mv', | |
notefile, | |
`${titlemap[notefile]}.md` | |
], { | |
cwd: notedir, | |
}); | |
rename.stderr.on('data', (d) => { | |
err += d; | |
}); | |
rename.on('close', (code) => { | |
if (code !== 0) { | |
reject(new Error(err)); | |
return; | |
} | |
notesmap[notefile] = newname; | |
resolve(); | |
}); | |
}); | |
}); | |
}); | |
}, Promise.resolve()); | |
}) | |
.then(() => { | |
// All files renamed, fix links | |
return Promise.all(Object.keys(notesmap).map((notefile) => { | |
const filepath = path.resolve(notedir, notesmap[notefile]); | |
return readFile(filepath, 'utf-8') | |
.then((content) => { | |
let updated = content; | |
Object.keys(notesmap).forEach((oldname) => { | |
updated = updated.replace(oldname, encodeURI(notesmap[oldname])); | |
}); | |
if (content === updated) { | |
return Promise.resolve(); | |
} | |
console.log(`Updated links in ${filepath}`); | |
return writeFile(filepath, updated, 'utf-8'); | |
}); | |
})); | |
}) | |
.then(() => { | |
console.log(notesmap); | |
process.exit(0); | |
}) | |
.catch((e) => { | |
console.error(e); | |
process.exit(1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment