Commit dfeb166

Chandan Kumar Mandal <chankruze@gmail.com>
2024-05-17 14:04:03
feat: add a newline after commands that don't end their output with one (#810)
* feat: add a newline after commands that don't end their output with one * Resolves #776 Signed-off-by: chankruze <chankruze@gmail.com> * fix: optimize eol check Signed-off-by: chankruze <chankruze@gmail.com> * chore: encapsulate eol check and add unit test Signed-off-by: chankruze <chankruze@gmail.com> --------- Signed-off-by: chankruze <chankruze@gmail.com>
1 parent 3d24076
Changed files (3)
src/core.ts
@@ -38,6 +38,7 @@ import {
   quote,
   quotePowerShell,
   noquote,
+  ensureEol,
 } from './util.js'
 
 export interface Shell {
@@ -651,7 +652,7 @@ export function log(entry: LogEntry) {
     case 'stdout':
     case 'stderr':
       if (!entry.verbose) return
-      process.stderr.write(entry.data)
+      process.stderr.write(ensureEol(entry.data))
       break
     case 'cd':
       if (!$.verbose) return
src/util.ts
@@ -411,3 +411,11 @@ export function getCallerLocationFromString(stackString = 'unknown') {
       ?.trim() || stackString
   )
 }
+
+export function ensureEol(buffer: Buffer): Buffer {
+  if (buffer.toString('utf8', buffer.length - 1) !== '\n') {
+    return Buffer.concat([buffer, Buffer.from('\n')])
+  }
+
+  return buffer
+}
test/util.test.js
@@ -29,6 +29,7 @@ import {
   getCallerLocationFromString,
   tempdir,
   tempfile,
+  ensureEol,
 } from '../build/util.js'
 
 describe('util', () => {
@@ -165,3 +166,20 @@ test('tempfile() creates temporary files', () => {
   assert.match(tf, /\/zx-.+\/bar\.txt$/)
   assert.equal(fs.readFileSync(tf, 'utf-8'), 'bar')
 })
+
+test('ensureEol() should ensure buffer ends with a newline character', () => {
+  // Test case 1: Buffer without newline
+  const buffer1 = Buffer.from('Hello, world!')
+  const result1 = ensureEol(buffer1).toString()
+  assert.strictEqual(result1, 'Hello, world!\n')
+
+  // Test case 2: Buffer with newline
+  const buffer2 = Buffer.from('Hello, world!\n')
+  const result2 = ensureEol(buffer2).toString()
+  assert.strictEqual(result2, 'Hello, world!\n')
+
+  // Test case 3: Empty buffer
+  const buffer3 = Buffer.from('')
+  const result3 = ensureEol(buffer3).toString()
+  assert.strictEqual(result3, '\n')
+})