Skip to content

Commit ab3083a

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

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-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

+29
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.
@@ -114,13 +117,15 @@ describe('cli', () => {
114117

115118
test('scripts from https', async () => {
116119
$`cat ${path.resolve('test/fixtures/echo.http')} | nc -l 8080`
120+
await sleep(50)
117121
let out =
118122
await $`node build/cli.js --verbose http://127.0.0.1:8080/echo.mjs`
119123
assert.match(out.stderr, /test/)
120124
})
121125

122126
test('scripts from https not ok', async () => {
123127
$`echo $'HTTP/1.1 500\n\n' | nc -l 8081`
128+
await sleep(50)
124129
let out = await $`node build/cli.js http://127.0.0.1:8081`.nothrow()
125130
assert.match(out.stderr, /Error: Can't get/)
126131
})
@@ -224,4 +229,28 @@ describe('cli', () => {
224229
let p = await $`node build/cli.js test/fixtures/exit-code.mjs`.nothrow()
225230
assert.equal(p.exitCode, 42)
226231
})
232+
233+
describe('internals', () => {
234+
test('isMain() checks process entry point', () => {
235+
assert.equal(isMain(import.meta.url, __filename), true)
236+
237+
assert.equal(
238+
isMain(import.meta.url.replace('.js', '.cjs'), __filename),
239+
true
240+
)
241+
242+
try {
243+
assert.equal(
244+
isMain(
245+
'file:///root/zx/test/cli.test.js',
246+
'/root/zx/test/all.test.js'
247+
),
248+
true
249+
)
250+
assert.throw()
251+
} catch (e) {
252+
assert.equal(e.code, 'ENOENT')
253+
}
254+
})
255+
})
227256
})

0 commit comments

Comments
 (0)