Struct hyper_scripter::script_repo::helper::RepoEntry
source · pub struct RepoEntry<'b> { /* private fields */ }Implementations§
source§impl<'b> RepoEntry<'b>
impl<'b> RepoEntry<'b>
sourcepub async fn update<F: FnOnce(&mut ScriptInfo)>(
&mut self,
handler: F
) -> Result<i64>
pub async fn update<F: FnOnce(&mut ScriptInfo)>(
&mut self,
handler: F
) -> Result<i64>
回傳值為「上一筆記錄到的事件的 id」
Examples found in repository?
src/query/util.rs (line 161)
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
pub async fn do_script_query_strict<'b>(
script_query: &ScriptQuery,
script_repo: &'b mut ScriptRepo,
) -> Result<RepoEntry<'b>> {
// FIXME: 一旦 NLL 進化就修掉這段 unsafe
let ptr = script_repo as *mut ScriptRepo;
if let Some(info) = do_script_query(script_query, script_repo, false, false).await? {
return Ok(info);
}
let script_repo = unsafe { &mut *ptr };
#[cfg(not(feature = "benching"))]
if !script_query.bang {
let filtered = do_script_query(script_query, script_repo, true, true).await?;
if let Some(mut filtered) = filtered {
filtered.update(|script| script.miss()).await?;
return Err(Error::ScriptIsFiltered(filtered.name.key().to_string()));
}
};
Err(Error::ScriptNotFound(script_query.to_string()))
}More examples
src/util/main_util.rs (lines 47-58)
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
pub async fn mv(
entry: &mut RepoEntry<'_>,
new_name: Option<ScriptName>,
ty: Option<ScriptType>,
tags: Option<TagSelector>,
) -> Result {
if ty.is_some() || new_name.is_some() {
let og_path = path::open_script(&entry.name, &entry.ty, Some(true))?;
let new_name = new_name.as_ref().unwrap_or(&entry.name);
let new_ty = ty.as_ref().unwrap_or(&entry.ty);
let new_path = path::open_script(new_name, new_ty, None)?; // NOTE: 不判斷存在性,因為接下來要對新舊腳本同路徑的狀況做特殊處理
if new_path != og_path {
log::debug!("改動腳本檔案:{:?} -> {:?}", og_path, new_path);
if new_path.exists() {
return Err(Error::PathExist(new_path).context("移動成既存腳本"));
}
super::mv(&og_path, &new_path)?;
} else {
log::debug!("相同的腳本檔案:{:?},不做檔案處理", og_path);
}
}
entry
.update(|info| {
if let Some(ty) = ty {
info.ty = ty;
}
if let Some(name) = new_name {
info.name = name.clone();
}
if let Some(tags) = tags {
info.append_tags(tags);
}
info.write();
})
.await?;
Ok(())
}
// XXX 到底幹嘛把新增和編輯的邏輯攪在一處呢…?
pub async fn edit_or_create(
edit_query: EditQuery<ScriptQuery>,
script_repo: &'_ mut ScriptRepo,
ty: Option<ScriptFullType>,
tags: EditTagArgs,
) -> Result<(PathBuf, RepoEntry<'_>, Option<ScriptType>)> {
let final_ty: ScriptFullType;
let (script_name, script_path) = if let EditQuery::Query(query) = edit_query {
match query::do_script_query(&query, script_repo, false, false).await {
// TODO: 手動測試文件?
Err(Error::DontFuzz) | Ok(None) => {
if tags.explicit_select {
return Err(RedundantOpt::Selector.into());
}
final_ty = ty.unwrap_or_default();
let name = query.into_script_name()?;
if script_repo.get_mut(&name, Visibility::All).is_some() {
log::error!("與被篩掉的腳本撞名");
return Err(Error::ScriptIsFiltered(name.to_string()));
}
log::debug!("打開新命名腳本:{:?}", name);
let p = path::open_script(&name, &final_ty.ty, None)
.context(format!("打開新命名腳本失敗:{:?}", name))?;
if p.exists() {
if p.is_dir() {
return Err(Error::PathExist(p).context("與目錄撞路徑"));
}
check_path_collision(&p, script_repo)?;
log::warn!("編輯野生腳本!");
} else {
// NOTE: 創建資料夾
if let Some(parent) = p.parent() {
super::handle_fs_res(&[&p], create_dir_all(parent))?;
}
}
(name, p)
}
Ok(Some(entry)) => {
if ty.is_some() {
return Err(RedundantOpt::Type.into());
}
if tags.explicit_tag {
return Err(RedundantOpt::Tag.into());
}
log::debug!("打開既有命名腳本:{:?}", entry.name);
let p = path::open_script(&entry.name, &entry.ty, Some(true))
.context(format!("打開命名腳本失敗:{:?}", entry.name))?;
// NOTE: 直接返回
// FIXME: 一旦 NLL 進化就修掉這段雙重詢問
// return Ok((p, entry));
let n = entry.name.clone();
return Ok((p, script_repo.get_mut(&n, Visibility::All).unwrap(), None));
}
Err(e) => return Err(e),
}
} else {
if tags.explicit_select {
return Err(RedundantOpt::Selector.into());
}
final_ty = ty.unwrap_or_default();
log::debug!("打開新匿名腳本");
path::open_new_anonymous(&final_ty.ty).context("打開新匿名腳本失敗")?
};
log::info!("編輯 {:?}", script_name);
let ScriptFullType { ty, sub } = final_ty;
// 這裡的 or_insert 其實永遠會發生,所以無需用閉包來傳
let entry = script_repo
.entry(&script_name)
.or_insert(
ScriptInfo::builder(0, script_name, ty, tags.content.into_allowed_iter()).build(),
)
.await?;
Ok((script_path, entry, sub))
}
fn run(
script_path: &Path,
info: &ScriptInfo,
remaining: &[String],
hs_tmpl_val: &serde_json::Value,
remaining_envs: &[EnvPair],
) -> Result<()> {
let conf = Config::get();
let ty = &info.ty;
let script_conf = conf.get_script_conf(ty)?;
let cmd_str = if let Some(cmd) = &script_conf.cmd {
cmd
} else {
return Err(Error::PermissionDenied(vec![script_path.to_path_buf()]));
};
let env = conf.gen_env(&hs_tmpl_val)?;
let ty_env = script_conf.gen_env(&hs_tmpl_val)?;
let pre_run_script = prepare_pre_run(None)?;
let (cmd, shebang) = super::shebang_handle::handle(&pre_run_script)?;
let args = shebang
.iter()
.map(|s| s.as_ref())
.chain(std::iter::once(pre_run_script.as_os_str()))
.chain(remaining.iter().map(|s| s.as_ref()));
let set_cmd_envs = |cmd: &mut Command| {
cmd.envs(ty_env.iter().map(|(a, b)| (a, b)));
cmd.envs(env.iter().map(|(a, b)| (a, b)));
cmd.envs(remaining_envs.iter().map(|p| (&p.key, &p.val)));
};
let mut cmd = super::create_cmd(cmd, args);
set_cmd_envs(&mut cmd);
let stat = super::run_cmd(cmd)?;
log::info!("預腳本執行結果:{:?}", stat);
if !stat.success() {
// TODO: 根據返回值做不同表現
let code = stat.code().unwrap_or_default();
return Err(Error::PreRunError(code));
}
let args = script_conf.args(&hs_tmpl_val)?;
let full_args = args
.iter()
.map(|s| s.as_str())
.chain(remaining.iter().map(|s| s.as_str()));
let mut cmd = super::create_cmd(&cmd_str, full_args);
set_cmd_envs(&mut cmd);
let stat = super::run_cmd(cmd)?;
log::info!("程式執行結果:{:?}", stat);
if !stat.success() {
let code = stat.code().unwrap_or_default();
Err(Error::ScriptError(code))
} else {
Ok(())
}
}
pub async fn run_n_times(
repeat: u64,
dummy: bool,
entry: &mut RepoEntry<'_>,
mut args: Vec<String>,
res: &mut Vec<Error>,
use_previous: bool,
error_no_previous: bool,
dir: Option<PathBuf>,
) -> Result {
log::info!("執行 {:?}", entry.name);
super::hijack_ctrlc_once();
let mut env_vec = vec![];
if use_previous {
let dir = super::option_map_res(dir, |d| path::normalize_path(d))?;
let historian = &entry.get_env().historian;
match historian.previous_args(entry.id, dir.as_deref()).await? {
None if error_no_previous => {
return Err(Error::NoPreviousArgs);
}
None => log::warn!("無前一次參數,當作空的"),
Some((arg_str, envs_str)) => {
log::debug!("撈到前一次呼叫的參數 {}", arg_str);
let mut prev_arg_vec: Vec<String> =
serde_json::from_str(&arg_str).context(format!("反序列失敗 {}", arg_str))?;
env_vec =
serde_json::from_str(&envs_str).context(format!("反序列失敗 {}", envs_str))?;
prev_arg_vec.extend(args.into_iter());
args = prev_arg_vec;
}
}
}
let here = path::normalize_path(".").ok();
let script_path = path::open_script(&entry.name, &entry.ty, Some(true))?;
let content = super::read_file(&script_path)?;
let mut hs_env_desc = vec![];
for (need_save, line) in extract_env_from_content_help_aware(&content) {
hs_env_desc.push(line.to_owned());
if need_save {
EnvPair::process_line(line, &mut env_vec);
}
}
EnvPair::sort(&mut env_vec);
let env_record = serde_json::to_string(&env_vec)?;
let run_id = entry
.update(|info| info.exec(content, &args, env_record, here))
.await?;
if dummy {
log::info!("--dummy 不用真的執行,提早退出");
return Ok(());
}
// Start packing hs tmpl val
let hs_home = path::get_home();
let hs_tags: Vec<_> = entry.tags.iter().map(|t| t.as_ref()).collect();
let hs_cmd = std::env::args().next().unwrap_or_default();
let hs_exe = std::env::current_exe()?;
let hs_exe = hs_exe.to_string_lossy();
let content = &entry.exec_time.as_ref().unwrap().data().unwrap().0;
let hs_tmpl_val = json!({
"path": script_path,
"home": hs_home,
"run_id": run_id,
"tags": hs_tags,
"cmd": hs_cmd,
"exe": hs_exe,
"env_desc": hs_env_desc,
"name": &entry.name.key(),
"content": content,
});
// End packing hs tmpl val
for _ in 0..repeat {
let run_res = run(&script_path, &*entry, &args, &hs_tmpl_val, &env_vec);
let ret_code: i32;
match run_res {
Err(Error::ScriptError(code)) => {
ret_code = code;
res.push(run_res.unwrap_err());
}
Err(e) => return Err(e),
Ok(_) => ret_code = 0,
}
entry
.update(|info| info.exec_done(ret_code, run_id))
.await?;
}
Ok(())
}
pub async fn load_utils(script_repo: &mut ScriptRepo) -> Result {
for u in hyper_scripter_util::get_all().iter() {
log::info!("載入小工具 {}", u.name);
let name = u.name.to_owned().into_script_name()?;
if script_repo.get_mut(&name, Visibility::All).is_some() {
log::warn!("已存在的小工具 {:?},跳過", name);
continue;
}
let ty = u.ty.parse()?;
let tags: Vec<Tag> = if u.is_hidden {
vec!["util".parse().unwrap(), "hide".parse().unwrap()]
} else {
vec!["util".parse().unwrap()]
};
let p = path::open_script(&name, &ty, Some(false))?;
// NOTE: 創建資料夾
if let Some(parent) = p.parent() {
super::handle_fs_res(&[&p], create_dir_all(parent))?;
}
let entry = script_repo
.entry(&name)
.or_insert(ScriptInfo::builder(0, name, ty, tags.into_iter()).build())
.await?;
super::prepare_script(&p, &*entry, None, true, &[u.content])?;
}
Ok(())
}
pub fn prepare_pre_run(content: Option<&str>) -> Result<PathBuf> {
let p = path::get_home().join(path::HS_PRE_RUN);
if content.is_some() || !p.exists() {
let content = content.unwrap_or_else(|| include_str!("hs_prerun"));
log::info!("寫入預執行腳本 {:?} {}", p, content);
super::write_file(&p, content)?;
}
Ok(p)
}
pub fn load_templates() -> Result {
for (ty, tmpl) in iter_default_templates() {
let tmpl_path = path::get_template_path(&ty)?;
if tmpl_path.exists() {
continue;
}
super::write_file(&tmpl_path, tmpl)?;
}
Ok(())
}
/// 判斷是否需要寫入主資料庫(script_infos 表格)
pub fn need_write(arg: &Subs) -> bool {
use Subs::*;
match arg {
Edit { .. } => true,
CP { .. } => true,
RM { .. } => true,
LoadUtils { .. } => true,
MV {
ty,
tags,
new,
origin: _,
} => {
// TODO: 好好測試這個
ty.is_some() || tags.is_some() || new.is_some()
}
_ => false,
}
}
use super::PrepareRespond;
pub async fn after_script(
entry: &mut RepoEntry<'_>,
path: &Path,
prepare_resp: &Option<PrepareRespond>,
) -> Result {
let mut record_write = true;
match prepare_resp {
None => {
log::debug!("不執行後處理");
}
Some(PrepareRespond { is_new, time }) => {
let modified = super::file_modify_time(path)?;
if time >= &modified {
if *is_new {
log::info!("新腳本未變動,應刪除之");
return Err(Error::EmptyCreate);
} else {
log::info!("舊腳本未變動,不記錄寫事件(只記讀事件)");
record_write = false;
}
}
}
}
if record_write {
entry.update(|info| info.write()).await?;
}
Ok(())
}sourcepub fn into_inner(self) -> &'b ScriptInfo
pub fn into_inner(self) -> &'b ScriptInfo
Examples found in repository?
src/list/list_impl.rs (line 223)
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
pub async fn fmt_list<W: Write>(
w: &mut W,
script_repo: &mut ScriptRepo,
opt: ListOptions,
) -> Result<()> {
let latest_script_id = script_repo
.latest_mut(1, Visibility::Normal)
.map_or(-1, |s| s.id);
let scripts_iter = do_list_query(script_repo, &opt.queries)
.await?
.into_iter()
.map(|e| &*e.into_inner());
let scripts_either = ScriptsEither::new(scripts_iter, opt.limit.map(|l| l.get()));
let sorted = scripts_either.sorted();
let final_table: Option<Table>;
match opt.grouping {
Grouping::None => {
let mut opt = convert_opt(opt, Grid::new(scripts_either.len()));
let scripts = scripts_either.collect();
fmt_group(w, scripts, sorted, latest_script_id, &mut opt)?;
final_table = extract_table(opt);
}
Grouping::Tree => {
let mut opt = convert_opt(opt, &mut *w);
let scripts = scripts_either.collect();
tree::fmt(scripts, latest_script_id, &mut opt)?;
final_table = extract_table(opt);
}
Grouping::Tag => {
let mut opt = convert_opt(opt, Grid::new(scripts_either.len()));
let mut script_map: HashMap<TagsKey, Vec<&ScriptInfo>> = HashMap::default();
scripts_either.for_each(|script| {
let key = TagsKey::new(script.tags.iter().cloned());
let v = script_map.entry(key).or_default();
v.push(script);
});
let mut scripts: Vec<_> = script_map.into_iter().collect();
// NOTE: 以群組中執行次數的最大值排序, 無標籤永遠在上
scripts.sort_by_key(|(k, v)| {
if k.is_empty() {
None
} else {
v.iter()
.map(|s| {
if s.exec_time.is_none() {
0
} else {
s.exec_count
}
})
.max()
}
});
for (tags, scripts) in scripts.into_iter() {
if !opt.grouping.is_none() {
let tags = tags.to_string();
let tags_width = tags.len();
let tags_txt = style(opt.plain, tags, |s| s.dimmed().italic());
match &mut opt.display_style {
DisplayStyle::Long(table) => {
table.add_row(vec![Cell::new_with_len(
tags_txt.to_string(),
tags_width,
)]);
}
DisplayStyle::Short(_, _) => {
writeln!(w, "{}", tags_txt)?;
}
}
}
fmt_group(w, scripts, sorted, latest_script_id, &mut opt)?;
}
final_table = extract_table(opt);
}
}
if let Some(mut table) = final_table {
write!(w, "{}", table.display())?;
log::debug!("tree table: {:?}", table);
}
Ok(())
}sourcepub fn get_env(&self) -> &DBEnv
pub fn get_env(&self) -> &DBEnv
Examples found in repository?
src/util/main_util.rs (line 222)
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
pub async fn run_n_times(
repeat: u64,
dummy: bool,
entry: &mut RepoEntry<'_>,
mut args: Vec<String>,
res: &mut Vec<Error>,
use_previous: bool,
error_no_previous: bool,
dir: Option<PathBuf>,
) -> Result {
log::info!("執行 {:?}", entry.name);
super::hijack_ctrlc_once();
let mut env_vec = vec![];
if use_previous {
let dir = super::option_map_res(dir, |d| path::normalize_path(d))?;
let historian = &entry.get_env().historian;
match historian.previous_args(entry.id, dir.as_deref()).await? {
None if error_no_previous => {
return Err(Error::NoPreviousArgs);
}
None => log::warn!("無前一次參數,當作空的"),
Some((arg_str, envs_str)) => {
log::debug!("撈到前一次呼叫的參數 {}", arg_str);
let mut prev_arg_vec: Vec<String> =
serde_json::from_str(&arg_str).context(format!("反序列失敗 {}", arg_str))?;
env_vec =
serde_json::from_str(&envs_str).context(format!("反序列失敗 {}", envs_str))?;
prev_arg_vec.extend(args.into_iter());
args = prev_arg_vec;
}
}
}
let here = path::normalize_path(".").ok();
let script_path = path::open_script(&entry.name, &entry.ty, Some(true))?;
let content = super::read_file(&script_path)?;
let mut hs_env_desc = vec![];
for (need_save, line) in extract_env_from_content_help_aware(&content) {
hs_env_desc.push(line.to_owned());
if need_save {
EnvPair::process_line(line, &mut env_vec);
}
}
EnvPair::sort(&mut env_vec);
let env_record = serde_json::to_string(&env_vec)?;
let run_id = entry
.update(|info| info.exec(content, &args, env_record, here))
.await?;
if dummy {
log::info!("--dummy 不用真的執行,提早退出");
return Ok(());
}
// Start packing hs tmpl val
let hs_home = path::get_home();
let hs_tags: Vec<_> = entry.tags.iter().map(|t| t.as_ref()).collect();
let hs_cmd = std::env::args().next().unwrap_or_default();
let hs_exe = std::env::current_exe()?;
let hs_exe = hs_exe.to_string_lossy();
let content = &entry.exec_time.as_ref().unwrap().data().unwrap().0;
let hs_tmpl_val = json!({
"path": script_path,
"home": hs_home,
"run_id": run_id,
"tags": hs_tags,
"cmd": hs_cmd,
"exe": hs_exe,
"env_desc": hs_env_desc,
"name": &entry.name.key(),
"content": content,
});
// End packing hs tmpl val
for _ in 0..repeat {
let run_res = run(&script_path, &*entry, &args, &hs_tmpl_val, &env_vec);
let ret_code: i32;
match run_res {
Err(Error::ScriptError(code)) => {
ret_code = code;
res.push(run_res.unwrap_err());
}
Err(e) => return Err(e),
Ok(_) => ret_code = 0,
}
entry
.update(|info| info.exec_done(ret_code, run_id))
.await?;
}
Ok(())
}Methods from Deref<Target = &'b mut ScriptInfo>§
pub fn cp(&self, new_name: ScriptName) -> Self
sourcepub fn last_major_time(&self) -> NaiveDateTime
pub fn last_major_time(&self) -> NaiveDateTime
major time 即不包含 read 和 miss 事件的時間,但包含 humble
Examples found in repository?
src/script_repo/mod.rs (line 145)
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
async fn update_last_time(&self, info: &ScriptInfo) -> Result {
let exec_count = info.exec_count as i32;
match self.trace_opt {
TraceOption::NoTrace => return Ok(()),
TraceOption::Normal => (),
TraceOption::Humble => {
// FIXME: what if a script is created with humble?
let humble_time = info.last_major_time();
sqlx::query!(
"UPDATE last_events set humble = ?, exec_count = ? WHERE script_id = ?",
humble_time,
exec_count,
info.id,
)
.execute(&self.info_pool)
.await?;
return Ok(());
}
}
let last_time = info.last_time();
let exec_time = info.exec_time.as_ref().map(|t| **t);
let exec_done_time = info.exec_done_time.as_ref().map(|t| **t);
let neglect_time = info.neglect_time.as_ref().map(|t| **t);
let miss_time = info.miss_time.as_ref().map(|t| **t);
sqlx::query!(
"
INSERT OR REPLACE INTO last_events
(script_id, last_time, read, write, miss, exec, exec_done, neglect, humble, exec_count)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
",
info.id,
last_time,
*info.read_time,
*info.write_time,
miss_time,
exec_time,
exec_done_time,
neglect_time,
info.humble_time,
exec_count
)
.execute(&self.info_pool)
.await?;
Ok(())
}
async fn handle_delete(&self, id: i64) -> Result {
assert!(self.modifies_script);
self.historian.remove(id).await?;
log::debug!("清理腳本 {:?} 的最新事件", id);
sqlx::query!("DELETE FROM last_events WHERE script_id = ?", id)
.execute(&self.info_pool)
.await?;
sqlx::query!("DELETE from script_infos where id = ?", id)
.execute(&self.info_pool)
.await?;
Ok(())
}
async fn handle_insert(&self, info: &ScriptInfo) -> Result<i64> {
assert!(self.modifies_script);
let name_cow = info.name.key();
let name = name_cow.as_ref();
let ty = info.ty.as_ref();
let tags = join_tags(info.tags.iter());
let res = sqlx::query!(
"
INSERT INTO script_infos (name, ty, tags)
VALUES(?, ?, ?)
RETURNING id
",
name,
ty,
tags,
)
.fetch_one(&self.info_pool)
.await?;
Ok(res.id)
}
async fn handle_change(&self, info: &ScriptInfo) -> Result<i64> {
log::debug!("開始修改資料庫 {:?}", info);
if info.changed {
assert!(self.modifies_script);
let name = info.name.key();
let name = name.as_ref();
let tags = join_tags(info.tags.iter());
let ty = info.ty.as_ref();
sqlx::query!(
"UPDATE script_infos SET name = ?, tags = ?, ty = ? where id = ?",
name,
tags,
ty,
info.id,
)
.execute(&self.info_pool)
.await?;
}
if matches!(self.trace_opt, TraceOption::NoTrace) {
return Ok(0);
}
let mut last_event_id = 0;
macro_rules! record_event {
($time:expr, $data:expr) => {
self.historian.record(&Event {
script_id: info.id,
humble: matches!(self.trace_opt, TraceOption::Humble),
time: $time,
data: $data,
})
};
}
if let Some(time) = info.exec_done_time.as_ref() {
if let Some(&(code, main_event_id)) = time.data() {
log::debug!("{:?} 的執行完畢事件", info.name);
last_event_id = record_event!(
**time,
EventData::ExecDone {
code,
main_event_id,
}
)
.await?;
if last_event_id != 0 {
self.update_last_time(info).await?;
} else {
log::info!("{:?} 的執行完畢事件被忽略了", info.name);
}
return Ok(last_event_id); // XXX: 超級醜的作法,為了避免重復記錄其它的事件
}
}
self.update_last_time(info).await?;
if info.read_time.has_changed() {
log::debug!("{:?} 的讀取事件", info.name);
last_event_id = record_event!(*info.read_time, EventData::Read).await?;
}
if info.write_time.has_changed() {
log::debug!("{:?} 的寫入事件", info.name);
last_event_id = record_event!(*info.write_time, EventData::Write).await?;
}
if let Some(time) = info.miss_time.as_ref() {
if time.has_changed() {
log::debug!("{:?} 的錯過事件", info.name);
last_event_id = record_event!(**time, EventData::Miss).await?;
}
}
if let Some(time) = info.exec_time.as_ref() {
if let Some((content, args, envs, dir)) = time.data() {
log::debug!("{:?} 的執行事件", info.name);
last_event_id = record_event!(
**time,
EventData::Exec {
content,
args,
envs,
dir: dir.as_deref(),
}
)
.await?;
}
}
Ok(last_event_id)
}
}
fn join_tags<'a, I: Iterator<Item = &'a Tag>>(tags: I) -> String {
let tags_arr: Vec<&str> = tags.map(|t| t.as_ref()).collect();
tags_arr.join(",")
}
#[derive(Debug)]
pub struct ScriptRepo {
map: HashMap<String, ScriptInfo>,
hidden_map: HashMap<String, ScriptInfo>,
latest_name: Option<String>,
db_env: DBEnv,
}
macro_rules! iter_by_vis {
($self:expr, $vis:expr) => {{
let (iter, iter2) = match $vis {
Visibility::Normal => ($self.map.iter_mut(), None),
Visibility::All => ($self.map.iter_mut(), Some($self.hidden_map.iter_mut())),
Visibility::Inverse => ($self.hidden_map.iter_mut(), None),
};
IterWithoutEnv { iter, iter2 }
}};
}
impl ScriptRepo {
pub async fn close(self) {
self.db_env.close().await;
}
pub fn iter(&self) -> impl Iterator<Item = &ScriptInfo> {
self.map.iter().map(|(_, info)| info)
}
pub fn iter_mut(&mut self, visibility: Visibility) -> Iter<'_> {
Iter {
iter: iter_by_vis!(self, visibility),
env: &self.db_env,
}
}
pub fn historian(&self) -> &Historian {
&self.db_env.historian
}
pub async fn new(
recent: Option<RecentFilter>,
db_env: DBEnv,
selector: &TagSelectorGroup,
) -> Result<ScriptRepo> {
let mut hidden_map = HashMap::<String, ScriptInfo>::default();
let mut map: HashMap<String, ScriptInfo> = Default::default();
let time_bound = recent.map(|r| {
let mut time = Utc::now().naive_utc();
time -= Duration::days(r.recent.into());
(time, r.archaeology)
});
let scripts = sqlx::query!(
"SELECT * FROM script_infos si LEFT JOIN last_events le ON si.id = le.script_id"
)
.fetch_all(&db_env.info_pool)
.await?;
for record in scripts.into_iter() {
let name = record.name;
log::trace!("載入腳本:{} {} {}", name, record.ty, record.tags);
let script_name = name.clone().into_script_name_unchecked()?; // NOTE: 從資料庫撈出來就別檢查了吧
let mut builder = ScriptInfo::builder(
record.id,
script_name,
ScriptType::new_unchecked(record.ty),
record.tags.split(',').filter_map(|s| {
if s.is_empty() {
None
} else {
Some(Tag::new_unchecked(s.to_string()))
}
}),
);
builder.created_time(record.created_time);
if let Some(count) = record.exec_count {
builder.exec_count(count as u64);
}
if let Some(time) = record.write {
builder.write_time(time);
}
if let Some(time) = record.read {
builder.read_time(time);
}
if let Some(time) = record.miss {
builder.miss_time(time);
}
if let Some(time) = record.exec {
builder.exec_time(time);
}
if let Some(time) = record.exec_done {
builder.exec_done_time(time);
}
if let Some(time) = record.neglect {
builder.neglect_time(time);
}
if let Some(time) = record.humble {
builder.humble_time(time);
}
let script = builder.build();
let mut hide = false;
if let Some((mut time_bound, archaeology)) = time_bound {
if let Some(neglect) = record.neglect {
log::debug!("腳本 {} 曾於 {} 被忽略", script.name, neglect);
time_bound = std::cmp::max(neglect, time_bound);
}
let overtime = time_bound > script.last_major_time();
hide = archaeology ^ overtime
}
if !hide {
hide = !selector.select(&script.tags, &script.ty);
}
if hide {
hidden_map.insert(name, script);
} else {
log::trace!("腳本 {:?} 通過篩選", name);
map.insert(name, script);
}
}
Ok(ScriptRepo {
map,
hidden_map,
latest_name: None,
db_env,
})
}sourcepub fn last_time(&self) -> NaiveDateTime
pub fn last_time(&self) -> NaiveDateTime
不包含 humble
Examples found in repository?
More examples
src/script_repo/mod.rs (line 158)
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
async fn update_last_time(&self, info: &ScriptInfo) -> Result {
let exec_count = info.exec_count as i32;
match self.trace_opt {
TraceOption::NoTrace => return Ok(()),
TraceOption::Normal => (),
TraceOption::Humble => {
// FIXME: what if a script is created with humble?
let humble_time = info.last_major_time();
sqlx::query!(
"UPDATE last_events set humble = ?, exec_count = ? WHERE script_id = ?",
humble_time,
exec_count,
info.id,
)
.execute(&self.info_pool)
.await?;
return Ok(());
}
}
let last_time = info.last_time();
let exec_time = info.exec_time.as_ref().map(|t| **t);
let exec_done_time = info.exec_done_time.as_ref().map(|t| **t);
let neglect_time = info.neglect_time.as_ref().map(|t| **t);
let miss_time = info.miss_time.as_ref().map(|t| **t);
sqlx::query!(
"
INSERT OR REPLACE INTO last_events
(script_id, last_time, read, write, miss, exec, exec_done, neglect, humble, exec_count)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
",
info.id,
last_time,
*info.read_time,
*info.write_time,
miss_time,
exec_time,
exec_done_time,
neglect_time,
info.humble_time,
exec_count
)
.execute(&self.info_pool)
.await?;
Ok(())
}
async fn handle_delete(&self, id: i64) -> Result {
assert!(self.modifies_script);
self.historian.remove(id).await?;
log::debug!("清理腳本 {:?} 的最新事件", id);
sqlx::query!("DELETE FROM last_events WHERE script_id = ?", id)
.execute(&self.info_pool)
.await?;
sqlx::query!("DELETE from script_infos where id = ?", id)
.execute(&self.info_pool)
.await?;
Ok(())
}
async fn handle_insert(&self, info: &ScriptInfo) -> Result<i64> {
assert!(self.modifies_script);
let name_cow = info.name.key();
let name = name_cow.as_ref();
let ty = info.ty.as_ref();
let tags = join_tags(info.tags.iter());
let res = sqlx::query!(
"
INSERT INTO script_infos (name, ty, tags)
VALUES(?, ?, ?)
RETURNING id
",
name,
ty,
tags,
)
.fetch_one(&self.info_pool)
.await?;
Ok(res.id)
}
async fn handle_change(&self, info: &ScriptInfo) -> Result<i64> {
log::debug!("開始修改資料庫 {:?}", info);
if info.changed {
assert!(self.modifies_script);
let name = info.name.key();
let name = name.as_ref();
let tags = join_tags(info.tags.iter());
let ty = info.ty.as_ref();
sqlx::query!(
"UPDATE script_infos SET name = ?, tags = ?, ty = ? where id = ?",
name,
tags,
ty,
info.id,
)
.execute(&self.info_pool)
.await?;
}
if matches!(self.trace_opt, TraceOption::NoTrace) {
return Ok(0);
}
let mut last_event_id = 0;
macro_rules! record_event {
($time:expr, $data:expr) => {
self.historian.record(&Event {
script_id: info.id,
humble: matches!(self.trace_opt, TraceOption::Humble),
time: $time,
data: $data,
})
};
}
if let Some(time) = info.exec_done_time.as_ref() {
if let Some(&(code, main_event_id)) = time.data() {
log::debug!("{:?} 的執行完畢事件", info.name);
last_event_id = record_event!(
**time,
EventData::ExecDone {
code,
main_event_id,
}
)
.await?;
if last_event_id != 0 {
self.update_last_time(info).await?;
} else {
log::info!("{:?} 的執行完畢事件被忽略了", info.name);
}
return Ok(last_event_id); // XXX: 超級醜的作法,為了避免重復記錄其它的事件
}
}
self.update_last_time(info).await?;
if info.read_time.has_changed() {
log::debug!("{:?} 的讀取事件", info.name);
last_event_id = record_event!(*info.read_time, EventData::Read).await?;
}
if info.write_time.has_changed() {
log::debug!("{:?} 的寫入事件", info.name);
last_event_id = record_event!(*info.write_time, EventData::Write).await?;
}
if let Some(time) = info.miss_time.as_ref() {
if time.has_changed() {
log::debug!("{:?} 的錯過事件", info.name);
last_event_id = record_event!(**time, EventData::Miss).await?;
}
}
if let Some(time) = info.exec_time.as_ref() {
if let Some((content, args, envs, dir)) = time.data() {
log::debug!("{:?} 的執行事件", info.name);
last_event_id = record_event!(
**time,
EventData::Exec {
content,
args,
envs,
dir: dir.as_deref(),
}
)
.await?;
}
}
Ok(last_event_id)
}
}
fn join_tags<'a, I: Iterator<Item = &'a Tag>>(tags: I) -> String {
let tags_arr: Vec<&str> = tags.map(|t| t.as_ref()).collect();
tags_arr.join(",")
}
#[derive(Debug)]
pub struct ScriptRepo {
map: HashMap<String, ScriptInfo>,
hidden_map: HashMap<String, ScriptInfo>,
latest_name: Option<String>,
db_env: DBEnv,
}
macro_rules! iter_by_vis {
($self:expr, $vis:expr) => {{
let (iter, iter2) = match $vis {
Visibility::Normal => ($self.map.iter_mut(), None),
Visibility::All => ($self.map.iter_mut(), Some($self.hidden_map.iter_mut())),
Visibility::Inverse => ($self.hidden_map.iter_mut(), None),
};
IterWithoutEnv { iter, iter2 }
}};
}
impl ScriptRepo {
pub async fn close(self) {
self.db_env.close().await;
}
pub fn iter(&self) -> impl Iterator<Item = &ScriptInfo> {
self.map.iter().map(|(_, info)| info)
}
pub fn iter_mut(&mut self, visibility: Visibility) -> Iter<'_> {
Iter {
iter: iter_by_vis!(self, visibility),
env: &self.db_env,
}
}
pub fn historian(&self) -> &Historian {
&self.db_env.historian
}
pub async fn new(
recent: Option<RecentFilter>,
db_env: DBEnv,
selector: &TagSelectorGroup,
) -> Result<ScriptRepo> {
let mut hidden_map = HashMap::<String, ScriptInfo>::default();
let mut map: HashMap<String, ScriptInfo> = Default::default();
let time_bound = recent.map(|r| {
let mut time = Utc::now().naive_utc();
time -= Duration::days(r.recent.into());
(time, r.archaeology)
});
let scripts = sqlx::query!(
"SELECT * FROM script_infos si LEFT JOIN last_events le ON si.id = le.script_id"
)
.fetch_all(&db_env.info_pool)
.await?;
for record in scripts.into_iter() {
let name = record.name;
log::trace!("載入腳本:{} {} {}", name, record.ty, record.tags);
let script_name = name.clone().into_script_name_unchecked()?; // NOTE: 從資料庫撈出來就別檢查了吧
let mut builder = ScriptInfo::builder(
record.id,
script_name,
ScriptType::new_unchecked(record.ty),
record.tags.split(',').filter_map(|s| {
if s.is_empty() {
None
} else {
Some(Tag::new_unchecked(s.to_string()))
}
}),
);
builder.created_time(record.created_time);
if let Some(count) = record.exec_count {
builder.exec_count(count as u64);
}
if let Some(time) = record.write {
builder.write_time(time);
}
if let Some(time) = record.read {
builder.read_time(time);
}
if let Some(time) = record.miss {
builder.miss_time(time);
}
if let Some(time) = record.exec {
builder.exec_time(time);
}
if let Some(time) = record.exec_done {
builder.exec_done_time(time);
}
if let Some(time) = record.neglect {
builder.neglect_time(time);
}
if let Some(time) = record.humble {
builder.humble_time(time);
}
let script = builder.build();
let mut hide = false;
if let Some((mut time_bound, archaeology)) = time_bound {
if let Some(neglect) = record.neglect {
log::debug!("腳本 {} 曾於 {} 被忽略", script.name, neglect);
time_bound = std::cmp::max(neglect, time_bound);
}
let overtime = time_bound > script.last_major_time();
hide = archaeology ^ overtime
}
if !hide {
hide = !selector.select(&script.tags, &script.ty);
}
if hide {
hidden_map.insert(name, script);
} else {
log::trace!("腳本 {:?} 通過篩選", name);
map.insert(name, script);
}
}
Ok(ScriptRepo {
map,
hidden_map,
latest_name: None,
db_env,
})
}
pub fn no_trace(&mut self) {
self.db_env.trace_opt = TraceOption::NoTrace;
}
pub fn humble(&mut self) {
self.db_env.trace_opt = TraceOption::Humble;
}
// fn latest_mut_no_cache(&mut self) -> Option<&mut ScriptInfo<'a>> {
// let latest = self.map.iter_mut().max_by_key(|(_, info)| info.last_time());
// if let Some((name, info)) = latest {
// self.latest_name = Some(name.clone());
// Some(info)
// } else {
// None
// }
// }
pub fn latest_mut(&mut self, n: usize, visibility: Visibility) -> Option<RepoEntry<'_>> {
// if let Some(name) = &self.latest_name {
// // FIXME: 一旦 rust nll 進化就修掉這段
// if self.map.contains_key(name) {
// return self.map.get_mut(name);
// }
// log::warn!("快取住的最新資訊已經不見了…?重找一次");
// }
// self.latest_mut_no_cache()
let mut v: Vec<_> = iter_by_vis!(self, visibility).collect();
v.sort_by_key(|s| s.last_time());
if v.len() >= n {
let t = v.remove(v.len() - n);
Some(RepoEntry::new(t, &self.db_env))
} else {
None
}
}sourcepub fn file_path_fallback(&self) -> PathBuf
pub fn file_path_fallback(&self) -> PathBuf
Examples found in repository?
src/list/list_impl.rs (line 24)
21 22 23 24 25 26 27 28 29 30 31 32
fn ident_string(style: &DisplayIdentStyle, ty: &str, script: &ScriptInfo) -> String {
match style {
DisplayIdentStyle::Normal => format!("{}({})", script.name, ty),
DisplayIdentStyle::File => script.file_path_fallback().to_string_lossy().to_string(),
DisplayIdentStyle::Name => script.name.to_string(),
DisplayIdentStyle::NameAndFile => format!(
"{}({})",
script.name.to_string(),
script.file_path_fallback().to_string_lossy().to_string()
),
}
}More examples
src/list/tree.rs (line 34)
30 31 32 33 34 35 36 37 38 39 40 41 42
fn ident_string(style: DisplayIdentStyle, ty: &str, t: &TrimmedScriptInfo<'_>) -> String {
let TrimmedScriptInfo(name, script) = t;
match style {
DisplayIdentStyle::Normal => format!("{}({})", name, ty),
DisplayIdentStyle::File => script.file_path_fallback().to_string_lossy().to_string(),
DisplayIdentStyle::Name => name.to_string(),
DisplayIdentStyle::NameAndFile => format!(
"{}({})",
name.to_string(),
script.file_path_fallback().to_string_lossy().to_string()
),
}
}