Allow using -m outside of xplr shell for debugging

Also validate the message before passing.
pull/522/head
Arijit Basu 2 years ago committed by Arijit Basu
parent 111a648818
commit 3fb174cdc0

@ -1,5 +1,6 @@
use crate::app; use crate::app;
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use app::ExternalMsg;
use serde_json as json; use serde_json as json;
use std::fs::File; use std::fs::File;
use std::io::{BufRead, BufReader, Write}; use std::io::{BufRead, BufReader, Write};
@ -181,19 +182,23 @@ pub fn pipe_msg_in(args: Vec<String>) -> Result<()> {
bail!("too many arguments") bail!("too many arguments")
} }
let path = std::env::var("XPLR_PIPE_MSG_IN") // Validate
.context("passing messages in only works inside xplr shell")?; let mut msg = json::to_string(&ExternalMsg::try_from(msg.as_str())?)?;
let delimiter = fs::read(&path)? if let Ok(path) = std::env::var("XPLR_PIPE_MSG_IN") {
.first() let delimiter = fs::read(&path)?
.cloned() .first()
.context("failed to detect delimmiter")?; .cloned()
.context("failed to detect delimmiter")?;
msg.push(delimiter.try_into()?);
File::options() msg.push(delimiter.try_into()?);
.append(true) File::options()
.open(&path)? .append(true)
.write_all(msg.as_bytes())?; .open(&path)?
.write_all(msg.as_bytes())?;
} else {
println!("{}", msg);
}
Ok(()) Ok(())
} }

@ -2,6 +2,8 @@ use crate::{app::Node, input::InputOperation};
use indexmap::IndexSet; use indexmap::IndexSet;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json as json;
use serde_yaml as yaml;
use std::cmp::Ordering; use std::cmp::Ordering;
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
@ -1084,17 +1086,20 @@ pub enum ExternalMsg {
} }
impl TryFrom<&str> for ExternalMsg { impl TryFrom<&str> for ExternalMsg {
type Error = serde_yaml::Error; type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> { fn try_from(value: &str) -> Result<Self, Self::Error> {
if value.starts_with('!') { let msg = if let Ok(val) = json::from_str(&value) {
serde_yaml::from_str(value) val
} else if value.starts_with('!') {
yaml::from_str(value)?
} else if let Some((msg, args)) = value.split_once(' ') { } else if let Some((msg, args)) = value.split_once(' ') {
let msg = format!("!{} {}", msg.trim_end_matches(':'), args); let msg = format!("!{} {}", msg.trim_end_matches(':'), args);
serde_yaml::from_str(&msg) yaml::from_str(&msg)?
} else { } else {
serde_yaml::from_str(value) yaml::from_str(value)?
} };
Ok(msg)
} }
} }

Loading…
Cancel
Save