summaryrefslogtreecommitdiffstats
path: root/src/utils
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/mod.rs10
-rw-r--r--src/utils/prompt_input.rs58
2 files changed, 68 insertions, 0 deletions
diff --git a/src/utils/mod.rs b/src/utils/mod.rs
index 9e999d4..ab922e3 100644
--- a/src/utils/mod.rs
+++ b/src/utils/mod.rs
@@ -1,6 +1,8 @@
+mod prompt_input;
mod split_line;
mod tiktoken;
+pub use self::prompt_input::*;
pub use self::split_line::*;
pub use self::tiktoken::cl100k_base_singleton;
@@ -63,3 +65,11 @@ pub fn light_theme_from_colorfgbg(colorfgbg: &str) -> Option<bool> {
let light = v > 128.0;
Some(light)
}
+
+pub fn init_tokio_runtime() -> anyhow::Result<tokio::runtime::Runtime> {
+ use anyhow::Context;
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .with_context(|| "Failed to init tokio")
+}
diff --git a/src/utils/prompt_input.rs b/src/utils/prompt_input.rs
new file mode 100644
index 0000000..f63823a
--- /dev/null
+++ b/src/utils/prompt_input.rs
@@ -0,0 +1,58 @@
+use inquire::{required, validator::Validation, Text};
+
+const MSG_REQUIRED: &str = "This field is required";
+const MSG_OPTIONAL: &str = "Optional field - Press ↵ to skip";
+
+pub fn prompt_input_string(desc: &str, required: bool) -> anyhow::Result<String> {
+ let mut text = Text::new(desc);
+ if required {
+ text = text.with_validator(required!(MSG_REQUIRED))
+ } else {
+ text = text.with_help_message(MSG_OPTIONAL)
+ }
+ text.prompt().map_err(prompt_op_err)
+}
+
+pub fn prompt_input_integer(desc: &str, required: bool) -> anyhow::Result<String> {
+ let mut text = Text::new(desc);
+ if required {
+ text = text.with_validator(|text: &str| {
+ let out = if text.is_empty() {
+ Validation::Invalid(MSG_REQUIRED.into())
+ } else {
+ validate_integer(text)
+ };
+ Ok(out)
+ })
+ } else {
+ text = text
+ .with_validator(|text: &str| {
+ let out = if text.is_empty() {
+ Validation::Valid
+ } else {
+ validate_integer(text)
+ };
+ Ok(out)
+ })
+ .with_help_message(MSG_OPTIONAL)
+ }
+ text.prompt().map_err(prompt_op_err)
+}
+
+pub fn prompt_op_err<T>(_: T) -> anyhow::Error {
+ anyhow::anyhow!("Not finish questionnaire, try again later!")
+}
+
+#[derive(Debug, Clone, Copy)]
+pub enum PromptKind {
+ String,
+ Integer,
+}
+
+fn validate_integer(text: &str) -> Validation {
+ if text.parse::<i32>().is_err() {
+ Validation::Invalid("Must be a integer".into())
+ } else {
+ Validation::Valid
+ }
+}