Struct hyper_scripter::script_repo::ScriptRepo
source · pub struct ScriptRepo { /* private fields */ }Implementations§
source§impl ScriptRepo
impl ScriptRepo
pub fn iter(&self) -> impl Iterator<Item = &ScriptInfo>
sourcepub fn iter_mut(&mut self, visibility: Visibility) -> Iter<'_> ⓘ
pub fn iter_mut(&mut self, visibility: Visibility) -> Iter<'_> ⓘ
Examples found in repository?
More examples
src/query/util.rs (line 25)
20 21 22 23 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
pub async fn do_list_query<'a>(
repo: &'a mut ScriptRepo,
queries: &[ListQuery],
) -> Result<Vec<RepoEntry<'a>>> {
if queries.is_empty() {
return Ok(repo.iter_mut(Visibility::Normal).collect());
}
let mut mem = HashSet::<i64>::default();
let mut ret = vec![];
let repo_ptr = repo as *mut ScriptRepo;
for query in queries.iter() {
macro_rules! insert {
($script:ident) => {
if mem.contains(&$script.id) {
continue;
}
mem.insert($script.id);
ret.push($script);
};
}
// SAFETY: `mem` 已保證回傳的陣列不可能包含相同的資料
let repo = unsafe { &mut *repo_ptr };
match query {
ListQuery::Pattern(re, og, bang) => {
let mut is_empty = true;
for script in repo.iter_mut(compute_vis(*bang)) {
if re.is_match(&script.name.key()) {
is_empty = false;
insert!(script);
}
}
if is_empty {
return Err(Error::ScriptNotFound(og.to_owned()));
}
}
ListQuery::Query(query) => {
let script = match do_script_query_strict(query, repo).await {
Err(Error::DontFuzz) => continue,
Ok(entry) => entry,
Err(e) => return Err(e),
};
insert!(script);
}
}
}
if ret.is_empty() {
log::debug!("列表查不到東西,卻又不是因為 pattern not match,想必是因為使用者取消了模糊搜");
Err(Error::DontFuzz)
} else {
Ok(ret)
}
}
impl<'a> MultiFuzzObj for RepoEntry<'a> {
fn beats(&self, other: &Self) -> bool {
self.last_time() > other.last_time()
}
}
pub async fn do_script_query<'b>(
script_query: &ScriptQuery,
script_repo: &'b mut ScriptRepo,
finding_filtered: bool,
forbid_prompt: bool,
) -> Result<Option<RepoEntry<'b>>> {
log::debug!("開始尋找 `{:?}`", script_query);
let mut visibility = compute_vis(script_query.bang);
if finding_filtered {
visibility = visibility.invert();
}
match &script_query.inner {
ScriptQueryInner::Prev(prev) => {
assert!(!finding_filtered); // XXX 很難看的作法,應設法靜態檢查
let latest = script_repo.latest_mut(prev.get(), visibility);
log::trace!("找最新腳本");
return if latest.is_some() {
Ok(latest)
} else {
Err(Error::Empty)
};
}
ScriptQueryInner::Exact(name) => Ok(script_repo.get_mut(name, visibility)),
ScriptQueryInner::Fuzz(name) => {
let level = if forbid_prompt {
PromptLevel::Never
} else {
Config::get_prompt_level()
};
let iter = script_repo.iter_mut(visibility);
let fuzz_res = fuzzy::fuzz(name, iter, SEP).await?;
let mut is_low = false;
let mut is_multi_fuzz = false;
let entry = match fuzz_res {
Some(fuzzy::High(entry)) => entry,
Some(fuzzy::Low(entry)) => {
is_low = true;
entry
}
#[cfg(feature = "benching")]
Some(fuzzy::Multi { ans, .. }) => {
is_multi_fuzz = true;
ans
}
#[cfg(not(feature = "benching"))]
Some(fuzzy::Multi { ans, others, .. }) => {
is_multi_fuzz = true;
the_multifuzz_algo(ans, others)
}
None => return Ok(None),
};
let need_prompt = {
match level {
PromptLevel::Always => true,
PromptLevel::Never => false,
PromptLevel::Smart => is_low || is_multi_fuzz,
PromptLevel::OnMultiFuzz => is_multi_fuzz,
}
};
if need_prompt {
prompt_fuzz_acceptable(&*entry)?;
}
Ok(Some(entry))
}
}
}src/util/completion_util.rs (line 86)
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
pub async fn handle_completion(comp: Completion, repo: &mut Option<ScriptRepo>) -> Result {
match comp {
Completion::LS { name, args } => {
let mut new_root = match Root::try_parse_from(args) {
Ok(Root {
subcmd: Some(Subs::Tags(_) | Subs::Types(_)),
..
}) => {
// TODO: 在補全腳本中處理,而不要在這邊
return Err(Error::Completion);
}
Ok(t) => t,
Err(e) => {
log::warn!("補全時出錯 {}", e);
// NOTE: -V 或 --help 也會走到這裡
return Err(Error::Completion);
}
};
log::info!("補完模式,參數為 {:?}", new_root);
new_root.set_home_unless_from_alias(false)?;
new_root.sanitize_flags();
*repo = Some(init_repo(new_root.root_args, false).await?);
let iter = repo.as_mut().unwrap().iter_mut(Visibility::Normal);
let scripts = if let Some(name) = name {
fuzz_arr(&name, iter).await?
} else {
let mut t: Vec<_> = iter.collect();
sort(&mut t);
t
};
print_iter(scripts.iter().map(|s| s.name.key()), " ");
}
Completion::NoSubcommand { args } => {
if let Ok(root) = parse_alias_root(&args) {
if root.subcmd.is_some() {
log::debug!("子命令 = {:?}", root.subcmd);
return Err(Error::Completion);
}
} // else: 解析錯誤當然不可能有子命令啦
}
Completion::Alias { args } => {
let root = parse_alias_root(&args)?;
if root.root_args.no_alias {
log::info!("無別名模式");
return Err(Error::Completion);
}
let home = path::compute_home_path_optional(root.root_args.hs_home.as_ref(), false)?;
let conf = Config::load(&home)?;
if let Some(new_args) = root.expand_alias(&args, &conf) {
print_iter(new_args, " ");
} else {
log::info!("並非別名");
return Err(Error::Completion);
};
}
Completion::Home { args } => {
let root = parse_alias_root(&args)?;
let home = root.root_args.hs_home.ok_or_else(|| Error::Completion)?;
print!("{}", home);
}
Completion::ParseRun { args } => {
let mut root = Root::try_parse_from(args).map_err(|e| {
log::warn!("補全時出錯 {}", e);
Error::Completion
})?;
root.sanitize()?;
match root.subcmd {
Some(Subs::Run {
script_query, args, ..
}) => {
let iter = std::iter::once(script_query.to_string())
.chain(args.into_iter().map(|s| to_display_args(s)));
print_iter(iter, " ");
}
res @ _ => {
log::warn!("非執行指令 {:?}", res);
return Err(Error::Completion);
}
}
}
}
Ok(())
}pub fn historian(&self) -> &Historian
sourcepub async fn new(
recent: Option<RecentFilter>,
db_env: DBEnv,
selector: &TagSelectorGroup
) -> Result<ScriptRepo>
pub async fn new(
recent: Option<RecentFilter>,
db_env: DBEnv,
selector: &TagSelectorGroup
) -> Result<ScriptRepo>
Examples found in repository?
src/util/init_repo.rs (line 60)
23 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
pub async fn init_repo(args: RootArgs, need_journal: bool) -> Result<ScriptRepo> {
let RootArgs {
no_trace,
humble,
archaeology,
select,
toggle,
recent,
timeless,
..
} = args;
let conf = Config::get();
let recent = if timeless {
None
} else {
recent.or(conf.recent).map(|recent| RecentFilter {
recent,
archaeology,
})
};
// TODO: 測試 toggle 功能,以及名字不存在的錯誤
let tag_group = {
let mut toggle: HashSet<_> = toggle.into_iter().collect();
let mut tag_group = conf.get_tag_selector_group(&mut toggle);
if let Some(name) = toggle.into_iter().next() {
return Err(Error::TagSelectorNotFound(name));
}
for select in select.into_iter() {
tag_group.push(select);
}
tag_group
};
let (env, init) = init_env(need_journal).await?;
let mut repo = ScriptRepo::new(recent, env, &tag_group)
.await
.context("載入腳本倉庫失敗")?;
if no_trace {
repo.no_trace();
} else if humble {
repo.humble();
}
if init {
log::info!("初次使用,載入好用工具和預執行腳本");
main_util::load_utils(&mut repo).await?;
main_util::prepare_pre_run(None)?;
main_util::load_templates()?;
}
Ok(repo)
}sourcepub fn no_trace(&mut self)
pub fn no_trace(&mut self)
Examples found in repository?
src/util/init_repo.rs (line 64)
23 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
pub async fn init_repo(args: RootArgs, need_journal: bool) -> Result<ScriptRepo> {
let RootArgs {
no_trace,
humble,
archaeology,
select,
toggle,
recent,
timeless,
..
} = args;
let conf = Config::get();
let recent = if timeless {
None
} else {
recent.or(conf.recent).map(|recent| RecentFilter {
recent,
archaeology,
})
};
// TODO: 測試 toggle 功能,以及名字不存在的錯誤
let tag_group = {
let mut toggle: HashSet<_> = toggle.into_iter().collect();
let mut tag_group = conf.get_tag_selector_group(&mut toggle);
if let Some(name) = toggle.into_iter().next() {
return Err(Error::TagSelectorNotFound(name));
}
for select in select.into_iter() {
tag_group.push(select);
}
tag_group
};
let (env, init) = init_env(need_journal).await?;
let mut repo = ScriptRepo::new(recent, env, &tag_group)
.await
.context("載入腳本倉庫失敗")?;
if no_trace {
repo.no_trace();
} else if humble {
repo.humble();
}
if init {
log::info!("初次使用,載入好用工具和預執行腳本");
main_util::load_utils(&mut repo).await?;
main_util::prepare_pre_run(None)?;
main_util::load_templates()?;
}
Ok(repo)
}sourcepub fn humble(&mut self)
pub fn humble(&mut self)
Examples found in repository?
src/util/init_repo.rs (line 66)
23 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
pub async fn init_repo(args: RootArgs, need_journal: bool) -> Result<ScriptRepo> {
let RootArgs {
no_trace,
humble,
archaeology,
select,
toggle,
recent,
timeless,
..
} = args;
let conf = Config::get();
let recent = if timeless {
None
} else {
recent.or(conf.recent).map(|recent| RecentFilter {
recent,
archaeology,
})
};
// TODO: 測試 toggle 功能,以及名字不存在的錯誤
let tag_group = {
let mut toggle: HashSet<_> = toggle.into_iter().collect();
let mut tag_group = conf.get_tag_selector_group(&mut toggle);
if let Some(name) = toggle.into_iter().next() {
return Err(Error::TagSelectorNotFound(name));
}
for select in select.into_iter() {
tag_group.push(select);
}
tag_group
};
let (env, init) = init_env(need_journal).await?;
let mut repo = ScriptRepo::new(recent, env, &tag_group)
.await
.context("載入腳本倉庫失敗")?;
if no_trace {
repo.no_trace();
} else if humble {
repo.humble();
}
if init {
log::info!("初次使用,載入好用工具和預執行腳本");
main_util::load_utils(&mut repo).await?;
main_util::prepare_pre_run(None)?;
main_util::load_templates()?;
}
Ok(repo)
}sourcepub fn latest_mut(
&mut self,
n: usize,
visibility: Visibility
) -> Option<RepoEntry<'_>>
pub fn latest_mut(
&mut self,
n: usize,
visibility: Visibility
) -> Option<RepoEntry<'_>>
Examples found in repository?
src/query/util.rs (line 93)
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
pub async fn do_script_query<'b>(
script_query: &ScriptQuery,
script_repo: &'b mut ScriptRepo,
finding_filtered: bool,
forbid_prompt: bool,
) -> Result<Option<RepoEntry<'b>>> {
log::debug!("開始尋找 `{:?}`", script_query);
let mut visibility = compute_vis(script_query.bang);
if finding_filtered {
visibility = visibility.invert();
}
match &script_query.inner {
ScriptQueryInner::Prev(prev) => {
assert!(!finding_filtered); // XXX 很難看的作法,應設法靜態檢查
let latest = script_repo.latest_mut(prev.get(), visibility);
log::trace!("找最新腳本");
return if latest.is_some() {
Ok(latest)
} else {
Err(Error::Empty)
};
}
ScriptQueryInner::Exact(name) => Ok(script_repo.get_mut(name, visibility)),
ScriptQueryInner::Fuzz(name) => {
let level = if forbid_prompt {
PromptLevel::Never
} else {
Config::get_prompt_level()
};
let iter = script_repo.iter_mut(visibility);
let fuzz_res = fuzzy::fuzz(name, iter, SEP).await?;
let mut is_low = false;
let mut is_multi_fuzz = false;
let entry = match fuzz_res {
Some(fuzzy::High(entry)) => entry,
Some(fuzzy::Low(entry)) => {
is_low = true;
entry
}
#[cfg(feature = "benching")]
Some(fuzzy::Multi { ans, .. }) => {
is_multi_fuzz = true;
ans
}
#[cfg(not(feature = "benching"))]
Some(fuzzy::Multi { ans, others, .. }) => {
is_multi_fuzz = true;
the_multifuzz_algo(ans, others)
}
None => return Ok(None),
};
let need_prompt = {
match level {
PromptLevel::Always => true,
PromptLevel::Never => false,
PromptLevel::Smart => is_low || is_multi_fuzz,
PromptLevel::OnMultiFuzz => is_multi_fuzz,
}
};
if need_prompt {
prompt_fuzz_acceptable(&*entry)?;
}
Ok(Some(entry))
}
}
}More examples
src/list/list_impl.rs (line 217)
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_mut(
&mut self,
name: &ScriptName,
visibility: Visibility
) -> Option<RepoEntry<'_>>
pub fn get_mut(
&mut self,
name: &ScriptName,
visibility: Visibility
) -> Option<RepoEntry<'_>>
Examples found in repository?
src/query/util.rs (line 101)
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
pub async fn do_script_query<'b>(
script_query: &ScriptQuery,
script_repo: &'b mut ScriptRepo,
finding_filtered: bool,
forbid_prompt: bool,
) -> Result<Option<RepoEntry<'b>>> {
log::debug!("開始尋找 `{:?}`", script_query);
let mut visibility = compute_vis(script_query.bang);
if finding_filtered {
visibility = visibility.invert();
}
match &script_query.inner {
ScriptQueryInner::Prev(prev) => {
assert!(!finding_filtered); // XXX 很難看的作法,應設法靜態檢查
let latest = script_repo.latest_mut(prev.get(), visibility);
log::trace!("找最新腳本");
return if latest.is_some() {
Ok(latest)
} else {
Err(Error::Empty)
};
}
ScriptQueryInner::Exact(name) => Ok(script_repo.get_mut(name, visibility)),
ScriptQueryInner::Fuzz(name) => {
let level = if forbid_prompt {
PromptLevel::Never
} else {
Config::get_prompt_level()
};
let iter = script_repo.iter_mut(visibility);
let fuzz_res = fuzzy::fuzz(name, iter, SEP).await?;
let mut is_low = false;
let mut is_multi_fuzz = false;
let entry = match fuzz_res {
Some(fuzzy::High(entry)) => entry,
Some(fuzzy::Low(entry)) => {
is_low = true;
entry
}
#[cfg(feature = "benching")]
Some(fuzzy::Multi { ans, .. }) => {
is_multi_fuzz = true;
ans
}
#[cfg(not(feature = "benching"))]
Some(fuzzy::Multi { ans, others, .. }) => {
is_multi_fuzz = true;
the_multifuzz_algo(ans, others)
}
None => return Ok(None),
};
let need_prompt = {
match level {
PromptLevel::Always => true,
PromptLevel::Never => false,
PromptLevel::Smart => is_low || is_multi_fuzz,
PromptLevel::OnMultiFuzz => is_multi_fuzz,
}
};
if need_prompt {
prompt_fuzz_acceptable(&*entry)?;
}
Ok(Some(entry))
}
}
}More examples
src/util/main_util.rs (line 80)
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
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 get_mut_by_id(&mut self, id: i64) -> Option<RepoEntry<'_>>
pub async fn remove(&mut self, id: i64) -> Result
sourcepub fn entry(&mut self, name: &ScriptName) -> RepoEntryOptional<'_>
pub fn entry(&mut self, name: &ScriptName) -> RepoEntryOptional<'_>
Examples found in repository?
src/util/main_util.rs (line 134)
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
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(())
}