merge-gitignore.mjs 1.09 KB
// lib/merge-gitignore.mjs
export function mergeGitignore(baseText, addText) {
  const seen = new Set()
  const out = []
  const push = (line) => {
    const key = line.trim()
    if (!key) return            // drop blank lines
    if (seen.has(key)) return   // dedupe by trimmed content
    seen.add(key)
    out.push(line)
  }
  for (const l of baseText.split('\n')) push(l)
  for (const l of addText.split('\n')) push(l)
  let text = out.join('\n').replace(/\n+$/,'') + '\n'
  return text
}

// CLI entry: node lib/merge-gitignore.mjs <basePath> <addPath>
// Use pathToFileURL so the guard matches even when the path contains spaces or
// non-ASCII chars (import.meta.url is percent-encoded; process.argv[1] is raw).
const { pathToFileURL } = await import('node:url')
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const [basePath, addPath] = process.argv.slice(2)
  const { readFileSync, writeFileSync } = await import('node:fs')
  const base = readFileSync(basePath, 'utf8')
  const add = readFileSync(addPath, 'utf8')
  writeFileSync(basePath, mergeGitignore(base, add))
}