console-app/lib/Sources/InteractiveSource.ts

94 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-05-15 16:53:45 +02:00
/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of console-app which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, May 2020
*/
2020-05-09 19:51:43 +02:00
/* eslint-disable no-console */
/* eslint-disable no-process-exit */
2020-05-18 12:34:44 +02:00
import { Confirm, Input, List, AutoComplete } from 'enquirer';
2020-05-09 21:30:37 +02:00
import { OptionProcess, Option } from '../Option';
2020-05-09 19:51:43 +02:00
import { OptionSource } from './OptionSource';
export class InteractiveSource extends OptionSource {
2020-05-22 11:50:07 +02:00
private _exit_on_interrupt: boolean;
public constructor (exit_on_interrupt: boolean) {
super ();
this._exit_on_interrupt = exit_on_interrupt;
}
2020-05-09 21:30:37 +02:00
private get_message (opt: Option): string {
return typeof opt.message === 'undefined'
? `input ${opt.name}`
: opt.message;
}
2020-05-09 19:51:43 +02:00
private async prompt (opt: OptionProcess): Promise<void> {
if (opt.filled)
return;
2020-05-09 21:30:37 +02:00
let value = null;
2020-05-09 19:51:43 +02:00
if (
opt.type === 'string'
|| opt.type === 'file'
|| opt.type === 'folder'
|| opt.type === 'path'
|| opt.type === 'number'
) {
2020-05-18 12:34:44 +02:00
if (typeof opt.preset === 'undefined') {
value = await new Input ({
message: this.get_message (opt),
default: opt.default
})
.run ();
}
else {
value = await new AutoComplete ({
message: this.get_message (opt),
default: opt.default,
2020-05-18 13:08:05 +02:00
choices: opt.preset,
limit: 10
2020-05-18 12:34:44 +02:00
})
.run ();
}
2020-05-09 19:51:43 +02:00
}
if (
opt.type === 'boolean'
) {
2020-05-09 21:30:37 +02:00
value = await new Confirm ({
message: this.get_message (opt),
2020-05-09 19:51:43 +02:00
default: opt.default
})
.run ();
}
2020-05-09 21:30:37 +02:00
if (opt.type === 'array') {
value = await new List ({
message: this.get_message (opt),
default: opt.default
})
.run ();
}
if (value === null)
return;
await this.assign_arg (opt, value);
2020-05-09 19:51:43 +02:00
}
public async parse (options: OptionProcess[]): Promise<void> {
for (const opt of options) {
while (!opt.filled) {
// eslint-disable-next-line no-await-in-loop
2020-05-22 11:50:07 +02:00
await this.prompt (opt)
.catch ((e) => {
if (this._exit_on_interrupt)
process.exit (0);
throw e;
});
2020-05-09 19:51:43 +02:00
if (!opt.filled)
2020-05-27 15:11:40 +02:00
console.log (opt.error || 'input was invalid');
2020-05-09 19:51:43 +02:00
}
}
}
}