Skip to content

Commit

Permalink
feat(sh): getExecutablesFromPath
Browse files Browse the repository at this point in the history
  • Loading branch information
Vehmloewff committed Mar 28, 2024
1 parent 76c70f6 commit b73c930
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions sh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,16 +195,34 @@ export async function execCaptureIncremental(segments: string[], options: ExecCa
}

export async function getExecFromPath(name: string): Promise<string> {
const res = await getExecutablesFromPath(name)
const path = res.get(name)?.[0]
if (!path) throw new Error(`Could not find ${name} in $PATH`)

return path
}

export async function getExecutablesFromPath(matcher: string | ((name: string) => boolean)): Promise<Map<string, string[]>> {
const path = Deno.env.get('PATH')
if (!path) throw new Error('Could not detect the $PATH env var')

const matchFn = typeof matcher === 'string' ? (name: string) => name === matcher : matcher

const directories = path.split(':')
const matches = new Map<string, string[]>()

for (const directory of directories) {
for await (const entry of Deno.readDir(directory)) {
if (entry.name === name) return pathUtils.join(directory, name)
if (entry.isDirectory) continue
if (matchFn(entry.name)) {
const exec = pathUtils.join(directory, name)
const existingMatches = matches.get(name)

if (existingMatches) existingMatches.push(exec)
else matches.set(name, [exec])
}
}
}

throw new Error(`Could not find ${name} in $PATH`)
return matches
}

0 comments on commit b73c930

Please sign in to comment.