combine ExecError with LaunchError and use Session::try_get() instead of matching

This commit is contained in:
Joseph Montanaro 2023-08-03 21:57:55 -07:00
parent 890f715388
commit a51b20add7
6 changed files with 38 additions and 43 deletions

View File

@ -1,3 +1,4 @@
use std::ffi::OsString;
use std::process::Command as ChildCommand; use std::process::Command as ChildCommand;
#[cfg(unix)] #[cfg(unix)]
use std::os::unix::process::CommandExt; use std::os::unix::process::CommandExt;
@ -90,15 +91,28 @@ pub fn exec(args: &ArgMatches) -> Result<(), CliError> {
#[cfg(unix)] #[cfg(unix)]
{ {
let e = cmd.exec(); // never returns if successful // cmd.exec() never returns if successful
Err(ExecError::ExecutionFailed(e))?; let e = cmd.exec();
Ok(()) match e.kind() {
std::io::ErrorKind::NotFound => {
let name: OsString = cmd_name.into();
Err(ExecError::NotFound(name).into())
}
e => Err(ExecError::ExecutionFailed(e).into()),
}
} }
#[cfg(windows)] #[cfg(windows)]
{ {
let mut child = cmd.spawn() let mut child = match cmd.spawn() {
.map_err(|e| ExecError::ExecutionFailed(e))?; Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
let name: OsString = cmd_name.into();
return Err(ExecError::NotFound(name).into());
}
Err(e) => return Err(ExecError::ExecutionFailed(e).into()),
};
let status = child.wait() let status = child.wait()
.map_err(|e| ExecError::ExecutionFailed(e))?; .map_err(|e| ExecError::ExecutionFailed(e))?;
std::process::exit(status.code().unwrap_or(1)); std::process::exit(status.code().unwrap_or(1));

View File

@ -136,7 +136,7 @@ fn default_term_config() -> TermConfig {
{ {
if let Ok(path) = which::which("pwsh.exe") { if let Ok(path) = which::which("pwsh.exe") {
return TermConfig { return TermConfig {
name: exe.into(), name: "pwsh.exe".into(),
exec: "conhost.exe".into(), exec: "conhost.exe".into(),
args: vec![path.into_os_string()] args: vec![path.into_os_string()]
}; };

View File

@ -217,16 +217,6 @@ pub enum RequestError {
} }
// Errors encountered while running a subprocess via creddy exec
#[derive(Debug, ThisError, AsRefStr)]
pub enum ExecError {
#[error("Please specify a command")]
NoCommand,
#[error("Failed to execute command: {0}")]
ExecutionFailed(#[from] std::io::Error)
}
#[derive(Debug, ThisError, AsRefStr)] #[derive(Debug, ThisError, AsRefStr)]
pub enum CliError { pub enum CliError {
#[error(transparent)] #[error(transparent)]
@ -240,9 +230,11 @@ pub enum CliError {
// Errors encountered while trying to launch a child process // Errors encountered while trying to launch a child process
#[derive(Debug, ThisError, AsRefStr)] #[derive(Debug, ThisError, AsRefStr)]
pub enum LaunchError { pub enum ExecError {
#[error("Please specify a command")]
NoCommand,
#[error("Executable not found: {0:?}")] #[error("Executable not found: {0:?}")]
ExeNotFound(OsString), NotFound(OsString),
#[error("Failed to execute command: {0}")] #[error("Failed to execute command: {0}")]
ExecutionFailed(#[from] std::io::Error), ExecutionFailed(#[from] std::io::Error),
#[error(transparent)] #[error(transparent)]
@ -342,14 +334,14 @@ impl Serialize for UnlockError {
} }
impl Serialize for LaunchError { impl Serialize for ExecError {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(None)?; let mut map = serializer.serialize_map(None)?;
map.serialize_entry("code", self.as_ref())?; map.serialize_entry("code", self.as_ref())?;
map.serialize_entry("msg", &format!("{self}"))?; map.serialize_entry("msg", &format!("{self}"))?;
match self { match self {
LaunchError::GetCredentials(src) => map.serialize_entry("source", &src)?, ExecError::GetCredentials(src) => map.serialize_entry("source", &src)?,
_ => serialize_upstream_err(self, &mut map)?, _ => serialize_upstream_err(self, &mut map)?,
} }
map.end() map.end()

View File

@ -82,6 +82,6 @@ pub async fn save_config(config: AppConfig, app_state: State<'_, AppState>) -> R
#[tauri::command] #[tauri::command]
pub async fn launch_terminal(base: bool) -> Result<(), LaunchError> { pub async fn launch_terminal(base: bool) -> Result<(), ExecError> {
terminal::launch(base).await terminal::launch(base).await
} }

View File

@ -142,21 +142,15 @@ impl AppState {
} }
pub async fn serialize_base_creds(&self) -> Result<String, GetCredentialsError> { pub async fn serialize_base_creds(&self) -> Result<String, GetCredentialsError> {
let session = self.session.read().await; let app_session = self.session.read().await;
match *session { let (base, _session) = app_session.try_get()?;
Session::Unlocked{ref base, ..} => Ok(serde_json::to_string(base).unwrap()), Ok(serde_json::to_string(base).unwrap())
Session::Locked(_) => Err(GetCredentialsError::Locked),
Session::Empty => Err(GetCredentialsError::Empty),
}
} }
pub async fn serialize_session_creds(&self) -> Result<String, GetCredentialsError> { pub async fn serialize_session_creds(&self) -> Result<String, GetCredentialsError> {
let session = self.session.read().await; let app_session = self.session.read().await;
match *session { let (_bsae, session) = app_session.try_get()?;
Session::Unlocked{ref session, ..} => Ok(serde_json::to_string(session).unwrap()), Ok(serde_json::to_string(session).unwrap())
Session::Locked(_) => Err(GetCredentialsError::Locked),
Session::Empty => Err(GetCredentialsError::Empty),
}
} }
async fn new_session(&self, base: BaseCredentials) -> Result<(), GetSessionError> { async fn new_session(&self, base: BaseCredentials) -> Result<(), GetSessionError> {

View File

@ -7,7 +7,7 @@ use crate::errors::*;
use crate::state::AppState; use crate::state::AppState;
pub async fn launch(use_base: bool) -> Result<(), LaunchError> { pub async fn launch(use_base: bool) -> Result<(), ExecError> {
let state = APP.get().unwrap().state::<AppState>(); let state = APP.get().unwrap().state::<AppState>();
// do all this in a block so we don't hold the lock any longer than necessary // do all this in a block so we don't hold the lock any longer than necessary
let mut cmd = { let mut cmd = {
@ -35,14 +35,9 @@ pub async fn launch(use_base: bool) -> Result<(), LaunchError> {
match cmd.spawn() { match cmd.spawn() {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => { Err(e) if std::io::ErrorKind::NotFound == e.kind() => {
use std::io::ErrorKind::*; Err(ExecError::NotFound(cmd.get_program().to_owned()))
if let NotFound = e.kind() { },
Err(LaunchError::ExeNotFound(cmd.get_program().to_owned())) Err(e) => Err(e.into()),
}
else {
Err(LaunchError::from(e))
}
}
} }
} }