|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/* eslint-disable-next-line @typescript-eslint/no-require-imports */ |
| 4 | +const { spawn } = require('child_process'); |
| 5 | + |
| 6 | +// Get prefix and command from process.argv |
| 7 | +const [,, prefix, ...commandArgs] = process.argv; |
| 8 | + |
| 9 | +if (!prefix || commandArgs.length === 0) { |
| 10 | + console.error('Usage: node prefix-output.js <prefix> -- <command> [args...]'); |
| 11 | + process.exit(1); |
| 12 | +} |
| 13 | + |
| 14 | +// Remove the '--' separator if present |
| 15 | +const separatorIndex = commandArgs.indexOf('--'); |
| 16 | +const actualCommandArgs = separatorIndex >= 0 ? commandArgs.slice(separatorIndex + 1) : commandArgs; |
| 17 | + |
| 18 | +const [command, ...args] = actualCommandArgs; |
| 19 | + |
| 20 | +// Spawn the process |
| 21 | +const childProcess = spawn(command, args, { |
| 22 | + stdio: ['inherit', 'pipe', 'pipe'] |
| 23 | +}); |
| 24 | + |
| 25 | +// Prefix stdout lines |
| 26 | +childProcess.stdout.on('data', (data) => { |
| 27 | + const lines = data.toString().split('\n'); |
| 28 | + lines.forEach((line, index) => { |
| 29 | + if (index === lines.length - 1 && line === '') { |
| 30 | + // Don't add prefix to final empty line |
| 31 | + return; |
| 32 | + } |
| 33 | + try { |
| 34 | + process.stdout.write(prefix + line + '\n'); |
| 35 | + } catch (err) { |
| 36 | + if (err.code !== 'EPIPE') { |
| 37 | + throw err; |
| 38 | + } |
| 39 | + } |
| 40 | + }); |
| 41 | +}); |
| 42 | + |
| 43 | +// Prefix stderr lines |
| 44 | +childProcess.stderr.on('data', (data) => { |
| 45 | + const lines = data.toString().split('\n'); |
| 46 | + lines.forEach((line, index) => { |
| 47 | + if (index === lines.length - 1 && line === '') { |
| 48 | + // Don't add prefix to final empty line |
| 49 | + return; |
| 50 | + } |
| 51 | + try { |
| 52 | + process.stderr.write(prefix + line + '\n'); |
| 53 | + } catch (err) { |
| 54 | + if (err.code !== 'EPIPE') { |
| 55 | + throw err; |
| 56 | + } |
| 57 | + } |
| 58 | + }); |
| 59 | +}); |
| 60 | + |
| 61 | +// Handle EPIPE errors gracefully |
| 62 | +process.stdout.on('error', (err) => { |
| 63 | + if (err.code === 'EPIPE') { |
| 64 | + process.exit(0); |
| 65 | + } |
| 66 | + throw err; |
| 67 | +}); |
| 68 | + |
| 69 | +process.stderr.on('error', (err) => { |
| 70 | + if (err.code === 'EPIPE') { |
| 71 | + process.exit(0); |
| 72 | + } |
| 73 | + throw err; |
| 74 | +}); |
| 75 | + |
| 76 | +// Forward exit code |
| 77 | +childProcess.on('close', (code) => { |
| 78 | + process.exit(code); |
| 79 | +}); |
0 commit comments