karma: leaderboard + rank, drop code-noise targets, atomic store writes
All checks were successful
ci / check (push) Successful in 48s
All checks were successful
ci / check (push) Successful in 48s
This commit is contained in:
parent
21e36b9961
commit
af9d5eed25
5 changed files with 159 additions and 16 deletions
|
|
@ -5,11 +5,21 @@ use std::path::PathBuf;
|
|||
use crate::bot::module::{Action, Chat, Command, CommandSpec, Module};
|
||||
use crate::json::{self, Json};
|
||||
|
||||
const COMMANDS: &[CommandSpec] = &[CommandSpec {
|
||||
name: "karma",
|
||||
usage: "karma <thing>",
|
||||
about: "show karma; bump it in chat with thing++ / thing--",
|
||||
}];
|
||||
const COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec {
|
||||
name: "karma",
|
||||
usage: "karma [thing]",
|
||||
about: "karma of <thing> with rank, or the top list; bump with thing++ / thing--",
|
||||
},
|
||||
CommandSpec {
|
||||
name: "karmabottom",
|
||||
usage: "karmabottom",
|
||||
about: "the lowest-karma things",
|
||||
},
|
||||
];
|
||||
|
||||
const MAX_THING_LEN: usize = 32;
|
||||
const TOP_N: usize = 5;
|
||||
|
||||
pub struct Karma {
|
||||
store: Store,
|
||||
|
|
@ -34,6 +44,30 @@ impl Karma {
|
|||
pub fn get(&self, thing: &str) -> i64 {
|
||||
self.store.get(thing)
|
||||
}
|
||||
|
||||
fn report(&self, thing: &str) -> String {
|
||||
if !self.store.has(thing) {
|
||||
return format!("no karma for '{thing}' yet");
|
||||
}
|
||||
let (rank, total) = self.store.rank(thing);
|
||||
format!(
|
||||
"{thing} has {} karma (#{rank} of {total})",
|
||||
self.store.get(thing)
|
||||
)
|
||||
}
|
||||
|
||||
fn leaderboard(&self, bottom: bool) -> String {
|
||||
let entries = self.store.ranked(TOP_N, bottom);
|
||||
if entries.is_empty() {
|
||||
return "no karma yet".to_string();
|
||||
}
|
||||
let items: Vec<String> = entries.iter().map(|(k, v)| format!("{k} ({v})")).collect();
|
||||
format!(
|
||||
"karma {}: {}",
|
||||
if bottom { "bottom" } else { "top" },
|
||||
items.join(", ")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Module for Karma {
|
||||
|
|
@ -46,13 +80,15 @@ impl Module for Karma {
|
|||
}
|
||||
|
||||
fn on_command(&mut self, cmd: &Command) -> Vec<Action> {
|
||||
let Some(thing) = cmd.args.first() else {
|
||||
return vec![Action::reply(format!("usage: {}karma <thing>", cmd.prefix))];
|
||||
let reply = match cmd.name {
|
||||
"karma" => match cmd.args.first() {
|
||||
Some(thing) => self.report(thing),
|
||||
None => self.leaderboard(false),
|
||||
},
|
||||
"karmabottom" => self.leaderboard(true),
|
||||
_ => return vec![],
|
||||
};
|
||||
vec![Action::reply(format!(
|
||||
"{thing} has {} karma",
|
||||
self.store.get(thing)
|
||||
))]
|
||||
vec![Action::reply(reply)]
|
||||
}
|
||||
|
||||
fn on_message(&mut self, chat: &Chat) -> Vec<Action> {
|
||||
|
|
@ -86,7 +122,7 @@ pub fn parse_changes(text: &str, sender: &str) -> Vec<(String, i64)> {
|
|||
continue;
|
||||
};
|
||||
let thing = thing.trim_start_matches('(').trim_end_matches(')');
|
||||
if thing.is_empty() {
|
||||
if !is_valid_target(thing) {
|
||||
continue;
|
||||
}
|
||||
let key = thing.to_lowercase();
|
||||
|
|
@ -100,6 +136,11 @@ pub fn parse_changes(text: &str, sender: &str) -> Vec<(String, i64)> {
|
|||
out
|
||||
}
|
||||
|
||||
fn is_valid_target(thing: &str) -> bool {
|
||||
let len = thing.chars().count();
|
||||
(2..=MAX_THING_LEN).contains(&len) && !thing.chars().all(|c| c.is_ascii_digit())
|
||||
}
|
||||
|
||||
struct Store {
|
||||
map: HashMap<String, i64>,
|
||||
path: PathBuf,
|
||||
|
|
@ -131,7 +172,12 @@ impl Store {
|
|||
.iter()
|
||||
.map(|(k, v)| format!("\"{}\":{}", json::escape(k), v))
|
||||
.collect();
|
||||
fs::write(&self.path, format!("{{{}}}\n", items.join(",")))
|
||||
let body = format!("{{{}}}\n", items.join(","));
|
||||
let mut tmp = self.path.clone().into_os_string();
|
||||
tmp.push(".tmp");
|
||||
let tmp = PathBuf::from(tmp);
|
||||
fs::write(&tmp, body)?;
|
||||
fs::rename(&tmp, &self.path)
|
||||
}
|
||||
|
||||
fn bump(&mut self, thing: &str, delta: i64) {
|
||||
|
|
@ -141,4 +187,30 @@ impl Store {
|
|||
fn get(&self, thing: &str) -> i64 {
|
||||
*self.map.get(&thing.to_lowercase()).unwrap_or(&0)
|
||||
}
|
||||
|
||||
fn has(&self, thing: &str) -> bool {
|
||||
self.map.contains_key(&thing.to_lowercase())
|
||||
}
|
||||
|
||||
fn ranked(&self, n: usize, bottom: bool) -> Vec<(String, i64)> {
|
||||
let mut v: Vec<(String, i64)> = self.map.iter().map(|(k, val)| (k.clone(), *val)).collect();
|
||||
v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
if bottom {
|
||||
v.reverse();
|
||||
}
|
||||
v.truncate(n);
|
||||
v
|
||||
}
|
||||
|
||||
fn rank(&self, thing: &str) -> (usize, usize) {
|
||||
let key = thing.to_lowercase();
|
||||
let mut v: Vec<(&String, &i64)> = self.map.iter().collect();
|
||||
v.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
|
||||
let rank = v
|
||||
.iter()
|
||||
.position(|(k, _)| **k == key)
|
||||
.map(|i| i + 1)
|
||||
.unwrap_or(0);
|
||||
(rank, v.len())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -132,7 +132,12 @@ impl Store {
|
|||
}
|
||||
|
||||
fn save(&self, path: &Path) -> io::Result<()> {
|
||||
fs::write(path, to_json(&self.map) + "\n")
|
||||
let body = to_json(&self.map) + "\n";
|
||||
let mut tmp = path.to_path_buf().into_os_string();
|
||||
tmp.push(".tmp");
|
||||
let tmp = PathBuf::from(tmp);
|
||||
fs::write(&tmp, body)?;
|
||||
fs::rename(&tmp, path)
|
||||
}
|
||||
|
||||
fn get(&self, nick: &str) -> Option<&String> {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue