Skip to content

Instantly share code, notes, and snippets.

@JosXa
Created February 19, 2025 17:31
Show Gist options
  • Save JosXa/8b1f32b4582f52bfa1de90e926026172 to your computer and use it in GitHub Desktop.
Save JosXa/8b1f32b4582f52bfa1de90e926026172 to your computer and use it in GitHub Desktop.
// noinspection JSDeprecatedSymbols
import "@johnlindquist/kit"
import { parseMetadata } from "@johnlindquist/kit"
metadata = {
name: "Migrate Snippets to Scriptlets",
description: "Reads your legacy snippets folder and migrates them to the new markdown-based scriptlets syntax",
author: "JosXa",
}
const snippetsDir = kenvPath("snippets")
const snippetFiles = (await readdir(snippetsDir, { encoding: "utf8", recursive: false })).filter((x) =>
x.endsWith(".txt"),
)
const scriptletParts = ["# Migrated Snippets"]
for (const fileName of snippetFiles) {
const fileContent = await readFile(path.join(snippetsDir, fileName), { encoding: "utf8" })
const contentRegex = /(?:\/\/.*\r?\n)*([\s\S]+)$/
const text = fileContent.match(contentRegex)?.[1]?.trim()
debugger
if (!text) {
console.error(`No text found for snippet ${fileName}`)
continue
}
// @ts-expect-error Typings bug
const { name, snippet, expand, type: _, ...rest } = parseMetadata(fileContent)
const expandMetadata = expand ?? snippet
if (!expandMetadata) {
console.error(`Snippet ${fileName} has no expand or snippet property!`)
continue
}
scriptletParts.push(`## ${name}`)
const metadataStr = [] as string[]
metadataStr.push(`Expand: ${expandMetadata}`)
for (const [key, value] of Object.entries(rest)) {
metadataStr.push(`${titleCase(key)}: ${value}`)
}
scriptletParts.push(`<!--\n${metadataStr.join("\n")}\n-->`)
scriptletParts.push(`\`\`\`paste\n${text}\n\`\`\`\n`)
}
const finalScriptlet = scriptletParts.join("\n\n")
const outFile = kenvPath("scriptlets", "migrated-snippets.md")
if (await pathExists(outFile)) {
const choice = await select<"Abort" | "Yes">(
{ hint: `File at ${outFile} already exists! Overwrite it?`, strict: true, multiple: false },
["Abort", "Yes"],
)
if (choice === "Abort") {
exit()
}
await unlink(outFile)
}
await writeFile(outFile, finalScriptlet)
await edit(outFile)
function titleCase(str: string) {
return str.slice(0, 1).toUpperCase() + str.slice(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment