Skip to content

Commit

Permalink
chore: start moving away from deprecated inquirer package
Browse files Browse the repository at this point in the history
  • Loading branch information
karl-run committed Nov 1, 2024
1 parent 27c9116 commit 5e93f55
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 83 deletions.
Binary file modified bun.lockb
Binary file not shown.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
"postinstall": "bun x prettier package.json --write && echo \"Prettiered package.json\""
},
"dependencies": {
"@inquirer/prompts": "^7.0.1",
"chalk": "^5.3.0",
"date-fns": "^3.6.0",
"date-fns": "^4.1.0",
"fs-extra": "^11.2.0",
"inquirer": "^9.2.21",
"inquirer-autocomplete-prompt": "^3.0.1",
"octokit": "^3.2.0",
"open": "^10.1.0",
"remeda": "^2.16.0",
Expand Down
21 changes: 9 additions & 12 deletions src/actions/gh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import path from 'node:path'

import * as R from 'remeda'
import chalk from 'chalk'
import { search } from '@inquirer/prompts'

import { BaseRepoNodeFragment, ghGqlQuery, OrgTeamRepoResult } from '../common/octokit.ts'
import inquirer from '../common/inquirer.ts'
import { CACHE_DIR } from '../common/cache.ts'
import { log, logError } from '../common/log.ts'
import { getTeam } from '../common/config.ts'
Expand All @@ -26,29 +26,26 @@ const reposForTeamQuery = /* GraphQL */ `
${BaseRepoNodeFragment}
`

export async function openRepoWeb(search: string | null, noCache: true | undefined): Promise<void> {
export async function openRepoWeb(initialTerm: string | null, noCache: true | undefined): Promise<void> {
const repos = await getRepos(!noCache)

const perfectMatch = repos.find((it) => it === search)
const perfectMatch = repos.find((it) => it === initialTerm)
if (perfectMatch != null) {
await openRepo(perfectMatch)
return
}

const initialFilter = repos.filter((name) => name.includes(search ?? ''))
const initialFilter = repos.filter((name) => name.includes(initialTerm ?? ''))
if (initialFilter.length === 1) {
await openRepo(initialFilter[0])
return
}

const { item } = await inquirer.prompt([
{
type: 'autocomplete',
name: 'item',
message: 'Which repo do you want to open in browser?',
source: async (_: unknown, input: string) => repos.filter((name) => name.includes(input ?? search ?? '')),
},
])
const item = await search({
message: 'Which repo do you want to open in browser?',
source: (term) =>
repos.filter((name) => name.includes(term ?? initialTerm ?? '')).map((name) => ({ name, value: name })),
})

await openRepo(item)
}
Expand Down
46 changes: 27 additions & 19 deletions src/actions/open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import fs from 'node:fs'
import * as child_process from 'child_process'

import chalk from 'chalk'
import { search } from '@inquirer/prompts'

import { getConfig } from '../common/config.ts'
import { log, logError } from '../common/log.ts'
import inquirer from '../common/inquirer.ts'

async function openProject(projectDir: string): Promise<void> {
const absolutePath: string = path.resolve(projectDir)
Expand All @@ -21,36 +21,44 @@ async function openProject(projectDir: string): Promise<void> {
}
})
}
export async function open(projectDir: string | undefined | null): Promise<void> {
export async function open(initialQuery: string | undefined | null): Promise<void> {
const config = await getConfig()
log(`projectDir is ${projectDir}`)
if (config.gitDir == null) {
log(`${chalk.red('Git dir not set, run: ')}${chalk.yellow('tsm config --git-dir=<dir>')}`)
process.exit(1)
}

const files = fs.readdirSync(config.gitDir)
const myInput = projectDir || ''
const response = await inquirer.prompt([
{
type: 'autocomplete',
name: 'selectedFile',
message: 'Start typing to search for a directory',
source: function (_: unknown, input: string) {
return new Promise(function (resolve) {
const results = files.filter((file) => file.includes(input || myInput))
resolve(results)
})
},
const perfectMatch = files.find((it) => it === initialQuery)
if (perfectMatch) {
const absolutePath = path.resolve(config.gitDir, perfectMatch)
await openProject(absolutePath)
return
}

const initialSuggestions = files.filter((file) => file.includes(initialQuery || ''))
const selectedDirectory = await search({
message: 'Type to filter projects',
source: (input) => {
if (input == null || input.trim() === '') {
return initialSuggestions
}

return (initialSuggestions.length === 0 ? files : initialSuggestions)
.filter((file) => file.includes(input))
.map((it) => ({
name: it,
value: it,
}))
},
])
})

projectDir = response.selectedFile
if (!projectDir) {
if (!selectedDirectory) {
log('No project selected')
process.exit(1)
}
const absolutePath = path.resolve(config.gitDir, projectDir)

const absolutePath = path.resolve(config.gitDir, selectedDirectory)
if (fs.existsSync(absolutePath)) {
log(`Opening ${absolutePath} in IDE...`)
await openProject(absolutePath)
Expand Down
25 changes: 11 additions & 14 deletions src/actions/sync-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from 'node:path'
import * as R from 'remeda'
import chalk from 'chalk'
import { PushResult } from 'simple-git'
import { search } from '@inquirer/prompts'

import { BaseRepoNode } from '../common/octokit.ts'
import { log } from '../common/log.ts'
Expand Down Expand Up @@ -79,25 +80,21 @@ export async function syncFileAcrossRepos(query: string): Promise<void> {
log(`! Your query ${chalk.yellow(query)} matched ${chalk.green(relevantRepos.length)} repos:`)

// Step 1, selecting the source repo
const sourceRepo = await inquirer.prompt<{ source: string }>([
{
type: 'autocomplete',
name: 'source',
message: 'Select source repository',
source: (_: unknown, input: string) =>
relevantRepos
.filter((it) => (input == null ? true : it.name.includes(input)))
.map((it) => ({ name: it.name, value: it.name })),
},
])
const sourceRepo = await search({
message: 'Select source repository',
source: (term) =>
relevantRepos
.filter((it) => (term == null ? true : it.name.includes(term)))
.map((it) => ({ name: it.name, value: it.name })),
})

// Step 2, selecting a valid file in the source repo
await hackilyFixBackToBackPrompt()
const fileToSync = await getValidFileInSource(sourceRepo.source)
const fileToSync = await getValidFileInSource(sourceRepo)

// Step 3, selecting target repos
await hackilyFixBackToBackPrompt()
const otherRepos = relevantRepos.filter((it) => it.name !== sourceRepo.source)
const otherRepos = relevantRepos.filter((it) => it.name !== sourceRepo)
const targetRepos = await getTargetRepos(otherRepos)

// Step 4, writing commit message
Expand All @@ -121,7 +118,7 @@ export async function syncFileAcrossRepos(query: string): Promise<void> {
})

if (confirmResult.confirm) {
await copyFileToRepos(sourceRepo.source, targetRepos, fileToSync, commitMessage.message)
await copyFileToRepos(sourceRepo, targetRepos, fileToSync, commitMessage.message)
} else {
log(chalk.red('Aborting!'))
}
Expand Down
15 changes: 6 additions & 9 deletions src/actions/web.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as R from 'remeda'
import chalk from 'chalk'
import { search } from '@inquirer/prompts'

import inquirer, { hackilyFixBackToBackPrompt } from '../common/inquirer.ts'
import { log } from '../common/log.ts'
Expand Down Expand Up @@ -137,16 +138,12 @@ async function openApp(app: AppKeys, env: keyof Envs): Promise<void> {

async function getAppEnv(app: AppKeys): Promise<keyof Envs> {
const envs = availableApps[app]
const { selectedEnv } = await inquirer.prompt([
{
type: 'autocomplete',
name: 'selectedEnv',
message: `What environment for ${app} do you want to open?`,
source: async (_: unknown, input: string) => R.keys(envs).filter((page) => page.includes(input ?? '')),
},
])
const selectedEnv = await search({
message: `What environment for ${app} do you want to open?`,
source: (term) => R.keys(envs).filter((page) => page.includes(term ?? '')),
})

return selectedEnv
return selectedEnv as keyof Envs
}

function isPage(what: string): what is PageKeys {
Expand Down
19 changes: 9 additions & 10 deletions src/common/authors.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import path from 'node:path'

import chalk from 'chalk'
import { checkbox } from '@inquirer/prompts'

import { CACHE_DIR } from './cache.ts'
import inquirer from './inquirer.ts'
import { log } from './log.ts'

export type Author = [name: string, email: string, user: string]
Expand All @@ -24,27 +24,26 @@ export async function promptForCoAuthors(): Promise<Author[]> {
const bonusCoAuthors = await getBonusCoAuthors()
const combinedAuthorOptions = [...authorOptions, ...bonusCoAuthors]

const selectedAuthors = await inquirer.prompt({
type: 'checkbox',
const selectedAuthors: Author[] = await checkbox({
message: 'Select co-authors',
choices: combinedAuthorOptions
.filter(([, , user]) => Bun.env.USER !== user)
.map(([name, email, user]) => ({
name: `${name.split(' ')[0]}`,
value: [name, email, user],
checked: previouslyUsedCoAuthors?.find((prev) => name === prev[0]),
value: [name, email, user] satisfies Author,
checked: previouslyUsedCoAuthors?.find((prev) => name === prev[0]) != null,
})),
message: 'Select co-authors',
name: 'coAuthors',
pageSize: 15,
})

if (selectedAuthors.coAuthors.length === 0) {
if (selectedAuthors.length === 0) {
log(chalk.red('You must select at least one co-author'))
return promptForCoAuthors()
}

await cacheCoAuthors(selectedAuthors.coAuthors)
await cacheCoAuthors(selectedAuthors)

return selectedAuthors.coAuthors
return selectedAuthors
}

export function createCoAuthorsText(authors: Author[]): string {
Expand Down
3 changes: 0 additions & 3 deletions src/common/inquirer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import autocomplete from 'inquirer-autocomplete-prompt'
import inquirer from 'inquirer'

inquirer.registerPrompt('autocomplete', autocomplete)

/**
* Sometimes when inquirer propmts are invoked back to back, the second prompt
* will not be able to receive input. This is a hacky workaround to fix that.
Expand Down
25 changes: 11 additions & 14 deletions src/common/kubectl.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { $ } from 'bun'
import chalk from 'chalk'
import { search } from '@inquirer/prompts'

import inquirer from './inquirer.ts'
import { log } from './log.ts'

// eslint-disable-next-line
Expand All @@ -19,22 +19,19 @@ export function getAllAppNames(pods: any[]): Map<string, any[]> {

// eslint-disable-next-line
export async function promptForAppName(appPodMap: Map<string, any>, appname: string | undefined | null) {
// Convert Map keys into an array of app names
const appNames: string[] = Array.from(appPodMap.keys())
const appInput = appname || ''
const { appName } = await inquirer.prompt([
{
type: 'autocomplete',
name: 'appName',
message: 'Start typing to search for an app',
source: function (_: unknown, input: string) {
return new Promise(function (resolve) {
const results = appNames.filter((app) => app.includes(input ?? appInput))
resolve(results)
})
},
const appName = await search({
message: 'Start typing to search for an app',
source: (term) => {
return appNames
.filter((app) => app.includes(term ?? appInput))
.map((app) => ({
name: app,
value: app,
}))
},
])
})

return {
appName,
Expand Down

0 comments on commit 5e93f55

Please sign in to comment.