console-app/lib/Sources/InteractiveSource.ts

52 lines
1.4 KiB
TypeScript

/*
* 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
*/
/* eslint-disable no-console */
/* eslint-disable no-process-exit */
import { ErrorCallback } from '../ErrorCallback';
import { Option, OptionValue } from '../Option';
import { OptionSource } from './OptionSource';
import { sources } from './Interactive';
export class InteractiveSource extends OptionSource {
private _exit_on_interrupt: boolean;
public constructor (
exit_on_interrupt: boolean,
error_callback?:ErrorCallback
) {
super (error_callback);
this._exit_on_interrupt = exit_on_interrupt;
}
private async prompt (opt: Option, val:OptionValue): Promise<void> {
if (val.filled)
return;
for (const src of sources) {
// eslint-disable-next-line no-await-in-loop
if (await new src (val, opt)
.parse ())
break;
}
}
public async parse (opt: Option, val:OptionValue): Promise<void> {
while (!val.filled) {
// eslint-disable-next-line no-await-in-loop
await this.prompt (opt, val)
.catch ((e) => {
if (this._exit_on_interrupt)
process.exit (0);
throw e;
});
if (!val.filled)
console.log (opt.error || 'input was invalid');
}
}
}