Skip to content

Commit

Permalink
Merge pull request #35 from fixstars/thiserror
Browse files Browse the repository at this point in the history
thiserrorを使うようにした
  • Loading branch information
toru-fukaya authored Sep 2, 2024
2 parents c3ebb45 + d73d3c1 commit a511e53
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 174 deletions.
83 changes: 16 additions & 67 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ repository = "https://github.com/fixstars/sacana"
[dependencies]
chrono = "0.4.31"
env_logger = "0.10.0"
failure = "0.1.8"
log = "0.4.20"
reqwest = { version = "0.11.22", features = ["blocking", "json"] }
serde = { version = "1.0.192", features = ["derive"] }
serde_json = "1.0.108"
thiserror = "1.0.56"
tungstenite = { version = "0.20.1", features = ["native-tls"] }
79 changes: 28 additions & 51 deletions src/linux_user_manage.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,27 @@
use std::io::{BufRead, Write};

use crate::runtime_error::{path_join, Result, RuntimeError};
use crate::runtime_error::{path_join, Result};
#[derive(thiserror::Error, Debug)]
pub enum LinuxError {
#[error("can't access {0}: {1}")]
HeadPublicKey(String, String),
#[error("get public key from {0} failed: {1}")]
GetPublicKey(String, String),
#[error("`{0}` failed. status code: {1}")]
Command(&'static str, i32),
#[error("`{0}` is killed by signal")]
CommandKilled(&'static str),
}

fn from_command_status(command: &'static str, es: std::process::ExitStatus) -> Result<()> {
if es.success() {
Ok(())
} else if let Some(c) = es.code() {
Err(LinuxError::Command(command, c).into())
} else {
Err(LinuxError::CommandKilled(command).into())
}
}

/// uri_format が指すuriに user_id のpublic keyが存在するかどうかを判定
fn public_keys_exist(uri_format: &str, user_id: &str) -> Result<()> {
Expand All @@ -9,7 +30,7 @@ fn public_keys_exist(uri_format: &str, user_id: &str) -> Result<()> {
if response.status().is_success() {
Ok(())
} else {
Err(RuntimeError::new(format!("can't access {}: {}", uri, response.text()?)).into())
Err(LinuxError::HeadPublicKey(uri, response.text()?).into())
}
}

Expand All @@ -20,12 +41,7 @@ fn get_public_keys(uri_format: &str, user_id: &str) -> Result<String> {
if response.status().is_success() {
Ok(response.text()?)
} else {
Err(RuntimeError::new(format!(
"get public key from {} failed: {}",
uri,
response.text()?
))
.into())
Err(LinuxError::GetPublicKey(uri, response.text()?).into())
}
}

Expand Down Expand Up @@ -65,17 +81,7 @@ fn add_user(user_name: &str, local_host_name: &str) -> Result<()> {
.arg("")
.arg(user_name)
.output()?;
if !useradd.status.success() {
return Err(RuntimeError::new(format!(
"`useradd` failed. status code: {}",
useradd
.status
.code()
.ok_or_else(|| RuntimeError::new("`useradd` is killed by signal"))?
))
.into());
}
Ok(())
from_command_status("useradd", useradd.status)
}

/// user_name の $HOME に .ssh を作成し、そのパスを取得
Expand Down Expand Up @@ -107,32 +113,13 @@ fn set_owner_and_permission(ssh_dir: &str, user_name: &str) -> Result<()> {
.arg("700")
.arg(ssh_dir)
.output()?;
if !chmod.status.success() {
return Err(RuntimeError::new(format!(
"`chmod` failed. status code: {}",
chmod
.status
.code()
.ok_or_else(|| RuntimeError::new("chmod is killed by signal"))?
))
.into());
}
from_command_status("chmod", chmod.status)?;
let chown = std::process::Command::new("chown")
.arg("-R")
.arg(format!("{0}:{0}", user_name))
.arg(ssh_dir)
.output()?;
if !chown.status.success() {
return Err(RuntimeError::new(format!(
"chown failed. status code: {}",
chown
.status
.code()
.ok_or_else(|| RuntimeError::new("chown is killed by signal"))?
))
.into());
}
Ok(())
from_command_status("chown", chown.status)
}

/// ユーザーのauthorized_keysを更新
Expand Down Expand Up @@ -162,15 +149,5 @@ pub fn join_group(user_name: &str, group_name: &str, local_host_name: &str) -> R
.arg(group_name)
.arg(user_name)
.output()?;
if !usermod.status.success() {
return Err(RuntimeError::new(format!(
"usermod failed. status code: {}",
usermod
.status
.code()
.ok_or_else(|| RuntimeError::new("usermod is killed by signal"))?
))
.into());
}
Ok(())
from_command_status("usermod", usermod.status)
}
12 changes: 4 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::collections::HashMap;
use std::io::Read;

mod runtime_error;
use crate::runtime_error::{as_str, Result, RuntimeError};
use crate::runtime_error::{as_str, Error, Result};

mod slack;
use crate::slack::{
Expand Down Expand Up @@ -147,7 +147,7 @@ fn check_channels(api_token: &str, channel_names: &[String]) -> Result<Vec<Strin
.map(|c| {
Ok(public_channels
.get(c)
.ok_or_else(|| RuntimeError::new(format!("there is no channel named {}", c)))?
.ok_or_else(|| Error::NoChannel(c.clone()))?
.to_string())
})
.collect()
Expand Down Expand Up @@ -589,11 +589,7 @@ impl CommandHandler {
match mes_type.trim_matches('"') {
"message" => false,
"hello" => true,
"goodbye" => {
return Err(
RuntimeError::new("goodbye event was caught. try to reconenct...").into(),
)
}
"goodbye" => return Err(Error::CaughtGoodBye),
"user_change" => {
if let Some(x) = self.users.get_mut(as_str(&mes_json["user"]["id"])?) {
*x = as_str(&mes_json["user"]["profile"]["display_name_normalized"])?
Expand All @@ -620,7 +616,7 @@ impl CommandHandler {
_ => false,
}
} else {
return Err(RuntimeError::new("receive non-event object on RTM").into());
return Err(Error::NonEvent);
})
}

Expand Down
Loading

0 comments on commit a511e53

Please sign in to comment.