OverviewFilesCommitsIssuesDocsReleasesPeers

pear-git / sidecar.js

48 lines · javascript ref:
#!/usr/bin/env bare
/**
 * Pear-Git Sidecar — spawns the server and restarts on exit.
 *
 * This file NEVER changes. It's outside the update cycle.
 * pear-git-server.js self-updates by pulling new code and exiting.
 * This sidecar detects the exit and restarts with the new code.
 *
 * Usage:
 *   bare sidecar.js serve 5005 --network --prefix=/git
 *
 * All arguments are forwarded to pear-git-server.js.
 */

await import('bare-node-runtime/global')

import { spawn } from 'bare-subprocess'
import path from 'bare-path'

const serverScript = path.join(path.dirname(new URL(import.meta.url).pathname), 'pear-git-server.js')
// process.argv = ['bare', 'sidecar.js', 'serve', '5005', ...]
// We want to forward everything after 'sidecar.js' to pear-git-server.js
const args = process.argv.slice(2)
const RESTART_DELAY = 5000 // 5s to ensure locks are released

function start () {
  console.log('[Sidecar] Starting pear-git-server.js ' + args.join(' '))

  const child = spawn('bare', [serverScript, ...args], {
    stdio: 'inherit',
    cwd: path.dirname(serverScript)
  })

  child.on('exit', (code) => {
    console.log(`[Sidecar] Process exited with code ${code}`)
    console.log(`[Sidecar] Restarting in ${RESTART_DELAY / 1000}s...`)
    setTimeout(start, RESTART_DELAY)
  })

  child.on('error', (err) => {
    console.error(`[Sidecar] Spawn error: ${err.message}`)
    console.log(`[Sidecar] Retrying in ${RESTART_DELAY / 1000}s...`)
    setTimeout(start, RESTART_DELAY)
  })
}

start()