-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathshebang.ts
37 lines (31 loc) · 1 KB
/
shebang.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const SHEBANG_REGEXP = /^#!(.*)/
const SHELL_REGEXP = /bin[/](?:env )?(\w+)/
const BASH_DIALECTS = ['sh', 'bash', 'dash', 'ksh'] as const // why not try to parse zsh? And let treesitter determine if it is supported
type SupportedBashDialect = (typeof BASH_DIALECTS)[number]
export function getShebang(fileContent: string): string | null {
const match = SHEBANG_REGEXP.exec(fileContent)
if (!match || !match[1]) {
return null
}
return match[1].trim()
}
export function getShellDialect(shebang: string): SupportedBashDialect | null {
const match = SHELL_REGEXP.exec(shebang)
if (match && match[1]) {
const bashDialect = match[1].trim() as any
if (BASH_DIALECTS.includes(bashDialect)) {
return bashDialect
}
}
return null
}
export function analyzeShebang(fileContent: string): {
shellDialect: SupportedBashDialect | null
shebang: string | null
} {
const shebang = getShebang(fileContent)
return {
shebang,
shellDialect: shebang ? getShellDialect(shebang) : null,
}
}