Skip to content

Commit

Permalink
feat(alias): force option for make sub command
Browse files Browse the repository at this point in the history
closes #15
  • Loading branch information
kawaemon committed Mar 20, 2022
1 parent 7da21eb commit acf761e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 14 deletions.
29 changes: 20 additions & 9 deletions src/bot/alias/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,12 @@ pub(super) async fn make(
key: &str,
msg: Option<&str>,
attachments: &[&dyn Attachment],
force: bool,
) -> Result<String> {
let key = key.trim();
let msg = msg.unwrap_or("").trim();

if db.get(key).await?.is_some() {
return Ok("すでにそのキーにはエイリアスが登録されています。上書きしたい場合は先に削除してください。".to_string());
}

let mut error_msgs = vec![];

let key_len = key.chars().count();
let msg_len = msg.chars().count();

if key.is_empty() {
error_msgs.push("キーが空白です。".to_string());
}
Expand Down Expand Up @@ -84,6 +77,9 @@ pub(super) async fn make(
}
}

let key_len = key.chars().count();
let msg_len = msg.chars().count();

if key_len > KEY_LENGTH_LIMIT {
error_msgs.push(format!(
"長すぎるキー({}文字)です。{}文字以下にしてください。",
Expand All @@ -102,6 +98,17 @@ pub(super) async fn make(
return Ok(error_msgs.join("\n"));
}

let mut force_applied = false;

if db.get(key).await?.is_some() {
if !force {
return Ok("すでにそのキーにはエイリアスが登録されています。上書きしたい場合は先に削除してください。".to_string());
}

db.delete(key).await?;
force_applied = true;
}

// we cannot use iter().map() because download method is async function.
let mut downloadad_attachments = vec![];

Expand All @@ -122,7 +129,11 @@ pub(super) async fn make(

db.save(entry).await.context("failed to save new alias")?;

Ok("作成しました".into())
Ok(if force_applied {
"既存のエイリアスを削除し、作成しました"
} else {
"作成しました"
}.into())
}

pub(super) async fn delete(db: &impl MessageAliasDatabase, key: &str) -> Result<String> {
Expand Down
22 changes: 17 additions & 5 deletions src/bot/alias/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ enum Command {

/// 送信するメッセージ
message: Option<String>,

/// 既存のエイリアスがあったとき、上書きします
#[clap(short, long)]
force: bool,
},
}

Expand Down Expand Up @@ -140,11 +144,19 @@ impl<D: MessageAliasDatabase> MessageAliasBot<D> {

Command::Delete { key } => delete(&self.db, &key).await.map(Some),

Command::Make { key, message: text } => {
make(&self.db, &key, text.as_deref(), message.attachments())
.await
.map(Some)
}
Command::Make {
key,
message: text,
force,
} => make(
&self.db,
&key,
text.as_deref(),
message.attachments(),
force,
)
.await
.map(Some),
}
}
}

0 comments on commit acf761e

Please sign in to comment.