Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save OleksandrKucherenko/3a79b315bf284c0eb1ca9fc7ab9f546e to your computer and use it in GitHub Desktop.

Select an option

Save OleksandrKucherenko/3a79b315bf284c0eb1ca9fc7ab9f546e to your computer and use it in GitHub Desktop.

Revisions

  1. OleksandrKucherenko created this gist Jun 2, 2023.
    41 changes: 41 additions & 0 deletions directory-autocomplete-prompts.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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)
    },
    },