console-app/lib/Sources/InteractiveSource.ts

56 lines
1.7 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-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';
2020-06-15 11:56:33 +02:00
import { ArraySubSource } from './Interactive/ArraySubSource';
import { BooleanSubSource } from './Interactive/BooleanSubSource';
import { PresetSubSource } from './Interactive/PresetSubSource';
import { StringSubSource } from './Interactive/StringSubSource';
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;
2020-06-15 11:56:33 +02:00
await new StringSubSource (val, opt)
.parse ();
await new PresetSubSource (val, opt)
.parse ();
await new BooleanSubSource (val, opt)
.parse ();
await new ArraySubSource (val, opt)
.parse ();
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
}
}
}