Commit cd8b511

Anton Golub <antongolub@antongolub.com>
2024-06-12 21:39:36
chore(cli): export `isMain` helper (#844)
Co-authored-by: Anton Medvedev <anton@medv.io>
1 parent 49cd6a7
Changed files (2)
src/cli.ts
@@ -286,10 +286,13 @@ export function getVersion(): string {
   return createRequire(import.meta.url)('../package.json').version
 }
 
-function isMain() {
-  if (import.meta.url.startsWith('file:')) {
-    const modulePath = url.fileURLToPath(import.meta.url).replace(/\.\w+$/, '')
-    const mainPath = fs.realpathSync(process.argv[1]).replace(/\.\w+$/, '')
+export function isMain(
+  metaurl = import.meta.url,
+  scriptpath = process.argv[1]
+) {
+  if (metaurl.startsWith('file:')) {
+    const modulePath = url.fileURLToPath(metaurl).replace(/\.\w+$/, '')
+    const mainPath = fs.realpathSync(scriptpath).replace(/\.\w+$/, '')
     return mainPath === modulePath
   }
 
test/cli.test.js
@@ -16,6 +16,9 @@ import assert from 'node:assert'
 import { test, describe, beforeEach } from 'node:test'
 import { fileURLToPath } from 'node:url'
 import '../build/globals.js'
+import { isMain } from '../build/cli.js'
+
+const __filename = fileURLToPath(import.meta.url)
 
 describe('cli', () => {
   // Helps detect unresolved ProcessPromise.
@@ -224,4 +227,28 @@ describe('cli', () => {
     let p = await $`node build/cli.js test/fixtures/exit-code.mjs`.nothrow()
     assert.equal(p.exitCode, 42)
   })
+
+  describe('internals', () => {
+    test('isMain() checks process entry point', () => {
+      assert.equal(isMain(import.meta.url, __filename), true)
+
+      assert.equal(
+        isMain(import.meta.url.replace('.js', '.cjs'), __filename),
+        true
+      )
+
+      try {
+        assert.equal(
+          isMain(
+            'file:///root/zx/test/cli.test.js',
+            '/root/zx/test/all.test.js'
+          ),
+          true
+        )
+        assert.throw()
+      } catch (e) {
+        assert.ok(['EACCES', 'ENOENT'].includes(e.code))
+      }
+    })
+  })
 })