Skip to content

Commit

Permalink
merging ask code
Browse files Browse the repository at this point in the history
  • Loading branch information
pelikhan committed Nov 5, 2023
1 parent 207858a commit 270207a
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
6 changes: 6 additions & 0 deletions cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
incVerbose,
setConsoleColors,
setDeveloperMode,
setInteractive,
setQuiet,
verboseLog,
} from "./command"
Expand Down Expand Up @@ -75,6 +76,10 @@ export async function mainCli() {
.version(cliVersion())
.option("-v, --verbose", "more logging (can be repeated)")
.option("--quiet", "less logging")
.option(
"--ci",
"disable interactions with user, default is false unless CI env var is set"
)
.option("--no-colors", "disable color output")
.option("--dev", "developer mode")

Expand Down Expand Up @@ -429,6 +434,7 @@ export async function mainCli() {
.action(binPatch)

program.on("option:quiet", () => setQuiet(true))
program.on("option:ci", () => setInteractive(false))
program.on("option:verbose", incVerbose)
program.on("option:no-colors", () => setConsoleColors(false))
program.on("option:dev", () => {
Expand Down
5 changes: 5 additions & 0 deletions cli/src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export function logToConsole(priority: LoggerPriority, message: string) {

export let isVerbose = 0
export let isQuiet = false
export let isInteractive = !!Boolean(process.env.CI)

export function incVerbose() {
isVerbose++
Expand All @@ -80,6 +81,10 @@ export function setQuiet(v: boolean) {
isQuiet = v
}

export function setInteractive(v: boolean) {
isInteractive = v
}

export function verboseLog(msg: string) {
if (isVerbose) console.debug(wrapColor(90, msg))
}
29 changes: 29 additions & 0 deletions cli/src/prompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export function consoleBooleanAsk(
question: string,
defValue = true
): Promise<boolean> {
return new Promise(resolve => {
const ask = (q: string) =>
process.stdout.write(`${q} ${defValue ? "(Y/n)" : "(y/N)"}?`)
const handler = (data: Buffer) => {
const response = data.toString().trim().toLowerCase()
if (response === "y") {
process.stdin.removeListener("data", handler)
resolve(true)
} else if (response === "n") {
process.stdin.removeListener("data", handler)
process.stdin.end()
resolve(false)
} else if (response === "") {
process.stdin.removeListener("data", handler)
resolve(defValue)
} else {
ask(
`Unknown option: ${response}. Use y/n and try again \n${question}`
)
}
}
process.stdin.addListener("data", handler)
ask(question)
})
}

0 comments on commit 270207a

Please sign in to comment.