Skip to content

Commit 6db4ce4

Browse files
committed
chore(cli): export isMain helper
1 parent 4c52ec5 commit 6db4ce4

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/cli.ts

+7-4
Original file line numberDiff line numberDiff line change
@@ -286,10 +286,13 @@ export function getVersion(): string {
286286
return createRequire(import.meta.url)('../package.json').version
287287
}
288288

289-
function isMain() {
290-
if (import.meta.url.startsWith('file:')) {
291-
const modulePath = url.fileURLToPath(import.meta.url).replace(/\.\w+$/, '')
292-
const mainPath = fs.realpathSync(process.argv[1]).replace(/\.\w+$/, '')
289+
export function isMain(
290+
metaurl = import.meta.url,
291+
scriptpath = process.argv[1]
292+
) {
293+
if (metaurl.startsWith('file:')) {
294+
const modulePath = url.fileURLToPath(metaurl).replace(/\.\w+$/, '')
295+
const mainPath = fs.realpathSync(scriptpath).replace(/\.\w+$/, '')
293296
return mainPath === modulePath
294297
}
295298

test/cli.test.js

+27
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ import assert from 'node:assert'
1616
import { test, describe, beforeEach } from 'node:test'
1717
import { fileURLToPath } from 'node:url'
1818
import '../build/globals.js'
19+
import { isMain } from '../build/cli.js'
20+
21+
const __filename = fileURLToPath(import.meta.url)
1922

2023
describe('cli', () => {
2124
// Helps detect unresolved ProcessPromise.
@@ -224,4 +227,28 @@ describe('cli', () => {
224227
let p = await $`node build/cli.js test/fixtures/exit-code.mjs`.nothrow()
225228
assert.equal(p.exitCode, 42)
226229
})
230+
231+
describe('internals', () => {
232+
test('isMain() checks process entry point', () => {
233+
assert.equal(isMain(import.meta.url, __filename), true)
234+
235+
assert.equal(
236+
isMain(import.meta.url.replace('.js', '.cjs'), __filename),
237+
true
238+
)
239+
240+
try {
241+
assert.equal(
242+
isMain(
243+
'file:///root/zx/test/cli.test.js',
244+
'/root/zx/test/all.test.js'
245+
),
246+
true
247+
)
248+
assert.throw()
249+
} catch (e) {
250+
assert.equal(e.code, 'ENOENT')
251+
}
252+
})
253+
})
227254
})

0 commit comments

Comments
 (0)