console-app/lib/Sources/InteractiveSource.ts

52 lines
1.4 KiB
TypeScript
Raw Permalink 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-06-09 13:13:27 +02:00
import { ErrorCallback } from '../ErrorCallback';
2020-06-09 21:03:10 +02:00
import { Option, OptionValue } from '../Option';
2020-05-09 19:51:43 +02:00
import { OptionSource } from './OptionSource';
import { sources } from './Interactive';
2020-05-09 19:51:43 +02:00
export class InteractiveSource extends OptionSource {
2020-05-22 11:50:07 +02:00
private _exit_on_interrupt: boolean;
public constructor (
2020-05-28 18:54:34 +02:00
exit_on_interrupt: boolean,
error_callback?:ErrorCallback
) {
super (error_callback);
2020-05-22 11:50:07 +02:00
this._exit_on_interrupt = exit_on_interrupt;
}
2020-06-09 21:03:10 +02:00
private async prompt (opt: Option, val:OptionValue): Promise<void> {
if (val.filled)
2020-05-09 19:51:43 +02:00
return;
for (const src of sources) {
// eslint-disable-next-line no-await-in-loop
if (await new src (val, opt)
.parse ())
break;
}
2020-05-09 19:51:43 +02:00
}
2020-06-09 21:03:10 +02:00
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');
2020-05-09 19:51:43 +02:00
}
}
}