1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
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
use crate::error::{Contextable, Error, RedundantOpt, Result};
use crate::path;
use crate::query::{self, EditQuery};
use crate::script::{IntoScriptName, ScriptInfo, ScriptName};
use crate::script_repo::{ScriptRepo, ScriptRepoEntry};
use crate::script_type::ScriptType;
use crate::tag::{Tag, TagFilter};
use chrono::Utc;
use hyper_scripter_historian::{Event, EventData, Historian};
use std::path::PathBuf;
pub struct EditTagArgs {
pub content: TagFilter,
pub append_namespace: bool,
pub explicit_tag: bool,
pub explicit_filter: bool,
}
pub async fn mv<'b>(
entry: &mut ScriptRepoEntry<'b>,
new_name: Option<ScriptName>,
ty: Option<ScriptType>,
tags: Option<TagFilter>,
) -> Result {
let og_path = path::open_script(&entry.name, &entry.ty, Some(true))?;
if ty.is_some() || new_name.is_some() {
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)?;
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;
}
if let Some(tags) = tags {
if tags.append {
log::debug!("附加上標籤:{:?}", tags);
info.tags.extend(tags.into_allowed_iter());
} else {
log::debug!("設定標籤:{:?}", tags);
info.tags = tags.into_allowed_iter().collect();
}
}
info.write();
})
.await
}
pub async fn edit_or_create<'b>(
edit_query: EditQuery,
script_repo: &'b mut ScriptRepo,
ty: Option<ScriptType>,
tags: EditTagArgs,
) -> Result<(PathBuf, ScriptRepoEntry<'b>)> {
let final_ty: ScriptType;
let mut new_namespaces: Vec<Tag> = vec![];
let (script_name, script_path) = if let EditQuery::Query(query) = edit_query {
macro_rules! new_named {
() => {{
if tags.explicit_filter {
return Err(RedundantOpt::Filter.into());
}
final_ty = ty.unwrap_or_default();
let name = query.into_script_name()?;
if script_repo.get_hidden_mut(&name).is_some() {
log::error!("與被篩掉的腳本撞名");
return Err(Error::ScriptExist(name.to_string()));
}
log::debug!("打開新命名腳本:{:?}", name);
if tags.append_namespace {
new_namespaces = name
.namespaces()
.iter()
.map(|s| s.parse())
.collect::<Result<Vec<Tag>>>()?;
}
let p = path::open_script(&name, &final_ty, None)
.context(format!("打開新命名腳本失敗:{:?}", name))?;
if p.exists() {
log::warn!("編輯野生腳本!");
}
(name, p)
}};
}
match query::do_script_query(&query, script_repo).await {
Err(Error::DontFuzz) => new_named!(),
Ok(None) => new_named!(),
Ok(Some(entry)) => {
if let Some(_) = ty {
return Err(RedundantOpt::Category.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))?;
let n = entry.name.clone();
return Ok((p, script_repo.get_mut(&n, true).unwrap()));
}
Err(e) => return Err(e),
}
} else {
final_ty = ty.unwrap_or_default();
log::debug!("打開新匿名腳本");
path::open_new_anonymous(&final_ty).context("打開新匿名腳本失敗")?
};
log::info!("編輯 {:?}", script_name);
let entry = script_repo
.entry(&script_name)
.or_insert(
ScriptInfo::builder(
0,
script_name,
final_ty,
tags.content
.into_allowed_iter()
.chain(new_namespaces.into_iter()),
)
.build(),
)
.await?;
Ok((script_path, entry))
}
pub async fn run_n_times(
repeat: u64,
dummy: bool,
entry: &mut ScriptRepoEntry<'_>,
mut args: &[String],
historian: Historian,
res: &mut Vec<Error>,
previous_args: bool,
) -> Result {
log::info!("執行 {:?}", entry.name);
let previous_arg_vec: Vec<String>;
if previous_args {
if args.len() > 0 {
return Err(RedundantOpt::CommandArgs.into());
}
match historian.last_args(entry.id).await? {
None => return Err(Error::NoPreviousArgs),
Some(arg_str) => {
log::debug!("撈到前一次呼叫的參數 {}", arg_str);
previous_arg_vec =
serde_json::from_str(&arg_str).context(format!("反序列失敗 {}", arg_str))?;
args = &previous_arg_vec;
}
}
}
let script_path = path::open_script(&entry.name, &entry.ty, Some(true))?;
let content = super::read_file(&script_path)?;
entry.update(|info| info.exec(content, args)).await?;
if dummy {
log::info!("--dummy 不用真的執行,提早退出");
return Ok(());
}
for _ in 0..repeat {
let run_res = super::run(
&script_path,
&*entry,
&args,
&entry.exec_time.as_ref().unwrap().data().unwrap().0,
);
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,
}
historian
.record(&Event {
data: EventData::ExecDone {
code: ret_code,
main_event_id: entry.last_event_id(),
},
time: Utc::now().naive_utc(),
script_id: entry.id,
})
.await?;
}
Ok(())
}
pub async fn load_utils(script_repo: &mut ScriptRepo) -> Result {
let utils = hyper_scripter_util::get_all();
for u in utils.into_iter() {
log::info!("載入小工具 {}", u.name);
let name = u.name.to_owned().into_script_name()?;
if script_repo.get_mut(&name, true).is_some() {
log::warn!("已存在的小工具 {:?},跳過", name);
continue;
}
let ty = u.category.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))?;
let mut entry = script_repo
.entry(&name)
.or_insert(ScriptInfo::builder(0, name, ty, tags.into_iter()).build())
.await?;
super::prepare_script(&p, &*entry, true, &[u.content])?;
entry.update(|info| info.write()).await?;
}
Ok(())
}