Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save OleksandrKucherenko/3a79b315bf284c0eb1ca9fc7ab9f546e to your computer and use it in GitHub Desktop.
Save OleksandrKucherenko/3a79b315bf284c0eb1ca9fc7ab9f546e to your computer and use it in GitHub Desktop.
Prompts NPM, ask for current working directory with autocomplete/autosuggestions with use of globs
import { glob } from 'glob'
import fs from 'node:fs'
const cwd = {
message: `Current working directory (ex. ~/project, ../project, ./project):`,
type: `autocomplete`,
limit: 10,
choices: [
/* force prompts to render 10 lines */
{ title: `Current working directory`, value: process.cwd() },
{ title: `Parent directory`, value: `../` },
{ title: `Grand directory`, value: `../../` },
{ title: `Home directory`, value: `~` },
{ title: `Root directory`, value: `/` },
{ title: `reserved-1`, value: `./` },
{ title: `reserved-2`, value: `./` },
{ title: `reserved-3`, value: `./` },
{ title: `reserved-4`, value: `./` },
{ title: `reserved-5`, value: `./` },
],
suggest: async (input, _choices) => {
const cwd = process.cwd()
const start = (input.length === 0 ? cwd : input).replace('~', process.env.HOME)
const files = await glob(`${start}*`, { cwd, maxDepth: 1 })
const value = files?.[0] ?? start
const suggestions = files ?? [value]
return suggestions
.filter((f) => f !== '.' && f !== '..')
.filter((f) => {
try {
return fs.lstatSync(f).isDirectory()
} catch (error) {
return false
}
})
.map((f) => ({ title: f }))
.slice(0, 10)
},
},
@OleksandrKucherenko
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment