Function hyper_scripter::util::handle_fs_res
source · Examples found in repository?
src/util/mod.rs (line 40)
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
pub fn run_cmd(mut cmd: Command) -> Result<ExitStatus> {
let res = cmd.spawn();
let program = cmd.get_program();
let mut child = handle_fs_res(&[program], res)?;
handle_fs_res(&[program], child.wait())
}
#[cfg(not(target_os = "linux"))]
pub fn create_cmd(cmd_str: &str, args: &[impl AsRef<OsStr>]) -> Command {
log::debug!("在非 linux 上執行,用 sh -c 包一層");
let args: Vec<_> = args
.iter()
.map(|s| {
s.as_ref()
.to_str()
.unwrap()
.to_string()
.replace(r"\", r"\\\\")
})
.collect();
let arg = format!("{} {}", cmd_str, args.join(" "));
let mut cmd = Command::new("sh");
cmd.args(&["-c", &arg]);
cmd
}
#[cfg(target_os = "linux")]
pub fn create_cmd<I, S1, S2>(cmd_str: S2, args: I) -> Command
where
I: IntoIterator<Item = S1>,
S1: AsRef<OsStr>,
S2: AsRef<OsStr>,
{
let mut cmd = Command::new(&cmd_str);
cmd.args(args);
cmd
}
pub fn open_editor(path: &Path) -> Result {
let conf = Config::get();
let cmd = create_concat_cmd(&conf.editor, &[&path]);
let stat = run_cmd(cmd)?;
if !stat.success() {
let code = stat.code().unwrap_or_default();
return Err(Error::EditorError(code, conf.editor.clone()));
}
Ok(())
}
pub fn create_concat_cmd<'a, 'b, I1, S1, I2, S2>(arg1: I1, arg2: I2) -> Command
where
I1: IntoIterator<Item = &'a S1>,
I2: IntoIterator<Item = &'b S2>,
S1: AsRef<OsStr> + 'a,
S2: AsRef<OsStr> + 'b,
{
let mut arg1 = arg1.into_iter();
let cmd = arg1.next().unwrap();
let remaining = arg1
.map(|s| s.as_ref())
.chain(arg2.into_iter().map(|s| s.as_ref()));
create_cmd(cmd, remaining)
}
pub fn file_modify_time(path: &Path) -> Result<DateTime<Utc>> {
let meta = handle_fs_res(&[path], std::fs::metadata(path))?;
let modified = handle_fs_res(&[path], meta.modified())?;
Ok(modified.into())
}
pub fn read_file(path: &Path) -> Result<String> {
let mut file = handle_fs_res(&[path], File::open(path)).context("唯讀開啟檔案失敗")?;
let mut content = String::new();
handle_fs_res(&[path], file.read_to_string(&mut content)).context("讀取檔案失敗")?;
Ok(content)
}
pub fn write_file(path: &Path, content: &str) -> Result<()> {
let mut file = handle_fs_res(&[path], File::create(path))?;
handle_fs_res(&[path], file.write_all(content.as_bytes()))
}
pub fn remove(script_path: &Path) -> Result<()> {
handle_fs_res(&[&script_path], remove_file(&script_path))
}
pub fn mv(origin: &Path, new: &Path) -> Result<()> {
log::info!("修改 {:?} 為 {:?}", origin, new);
// NOTE: 創建資料夾和檔案
if let Some(parent) = new.parent() {
handle_fs_res(&[&new], create_dir_all(parent))?;
}
handle_fs_res(&[&new, &origin], rename(&origin, &new))
}
pub fn cp(origin: &Path, new: &Path) -> Result<()> {
// NOTE: 創建資料夾和檔案
if let Some(parent) = new.parent() {
handle_fs_res(&[parent], create_dir_all(parent))?;
}
let _copied = handle_fs_res(&[&origin, &new], std::fs::copy(&origin, &new))?;
Ok(())
}
pub fn handle_fs_err<P: AsRef<Path>>(path: &[P], err: std::io::Error) -> Error {
use std::sync::Arc;
let mut p = path.iter().map(|p| p.as_ref().to_owned()).collect();
log::warn!("檔案系統錯誤:{:?}, {:?}", p, err);
match err.kind() {
std::io::ErrorKind::PermissionDenied => Error::PermissionDenied(p),
std::io::ErrorKind::NotFound => Error::PathNotFound(p),
std::io::ErrorKind::AlreadyExists => Error::PathExist(p.remove(0)),
_ => Error::GeneralFS(p, Arc::new(err)),
}
}
pub fn handle_fs_res<T, P: AsRef<Path>>(path: &[P], res: std::io::Result<T>) -> Result<T> {
match res {
Ok(t) => Ok(t),
Err(e) => Err(handle_fs_err(path, e)),
}
}
/// check_subtype 是為避免太容易生出子模版
pub fn get_or_create_template_path<T: AsScriptFullTypeRef>(
ty: &T,
force: bool,
check_subtype: bool,
) -> Result<(PathBuf, Option<&'static str>)> {
if !force {
Config::get().get_script_conf(ty.get_ty())?; // 確認類型存在與否
}
let tmpl_path = path::get_template_path(ty)?;
if !tmpl_path.exists() {
if check_subtype && ty.get_sub().is_some() {
return Err(Error::UnknownType(ty.display().to_string()));
}
let default_tmpl = get_default_template(ty);
return write_file(&tmpl_path, default_tmpl).map(|_| (tmpl_path, Some(default_tmpl)));
}
Ok((tmpl_path, None))
}
pub fn get_or_create_template<T: AsScriptFullTypeRef>(
ty: &T,
force: bool,
check_subtype: bool,
) -> Result<String> {
let (tmpl_path, default_tmpl) = get_or_create_template_path(ty, force, check_subtype)?;
if let Some(default_tmpl) = default_tmpl {
return Ok(default_tmpl.to_owned());
}
read_file(&tmpl_path)
}
/// copied from `shell_escape` crate
pub fn to_display_args(arg: String) -> String {
fn non_whitelisted(ch: char) -> bool {
match ch {
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '=' | '/' | ',' | '.' | '+' => false,
_ => true,
}
}
if !arg.is_empty() && !arg.contains(non_whitelisted) {
return arg;
}
let mut es = String::with_capacity(arg.len() + 2);
es.push('\'');
for ch in arg.chars() {
match ch {
'\'' | '!' => {
es.push_str("'\\");
es.push(ch);
es.push('\'');
}
_ => es.push(ch),
}
}
es.push('\'');
es
}
fn relative_to_home(p: &Path) -> Option<&Path> {
const CUR_DIR: &str = ".";
let home = dirs::home_dir()?;
if p == home {
return Some(CUR_DIR.as_ref());
}
p.strip_prefix(&home).ok()
}
fn get_birthplace() -> Result<PathBuf> {
// NOTE: 用 $PWD 可以取到 symlink 還沒解開前的路徑
// 若用 std::env::current_dir,該路徑已為真實路徑
let here = std::env::var("PWD")?;
Ok(here.into())
}
#[derive(Debug)]
pub struct PrepareRespond {
pub is_new: bool,
pub time: DateTime<Utc>,
}
pub fn prepare_script<T: AsRef<str>>(
path: &Path,
script: &ScriptInfo,
sub_type: Option<&ScriptType>,
no_template: bool,
content: &[T],
) -> Result<PrepareRespond> {
log::info!("開始準備 {} 腳本內容……", script.name);
let has_content = !content.is_empty();
let is_new = !path.exists();
if is_new {
let birthplace = get_birthplace()?;
let birthplace_rel = relative_to_home(&birthplace);
let mut file = handle_fs_res(&[path], File::create(&path))?;
let content = content.iter().map(|s| s.as_ref().split('\n')).flatten();
if !no_template {
let content: Vec<_> = content.collect();
let info = json!({
"birthplace_in_home": birthplace_rel.is_some(),
"birthplace_rel": birthplace_rel,
"birthplace": birthplace,
"name": script.name.key().to_owned(),
"content": content,
});
log::debug!("編輯模版資訊:{:?}", info);
// NOTE: 計算 `path` 時早已檢查過腳本類型,這裡直接不檢查了
let template = get_or_create_template(&(&script.ty, sub_type), true, true)?;
handle_fs_res(&[path], write_prepare_script(file, &template, &info))?;
} else {
let mut first = true;
for line in content {
if !first {
writeln!(file, "")?;
}
first = false;
write!(file, "{}", line)?;
}
}
} else {
if has_content {
log::debug!("腳本已存在,往後接上給定的訊息");
let mut file = handle_fs_res(
&[path],
std::fs::OpenOptions::new()
.append(true)
.write(true)
.open(path),
)?;
for content in content.iter() {
handle_fs_res(&[path], writeln!(&mut file, "{}", content.as_ref()))?;
}
}
}
Ok(PrepareRespond {
is_new,
time: file_modify_time(path)?,
})
}More examples
src/path.rs (line 96)
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
fn compute_home_path<T: AsRef<Path>>(p: T, create_on_missing: bool) -> Result<PathBuf> {
let path = join_here_abs(p)?;
log::debug!("計算路徑:{:?}", path);
if !path.exists() {
if create_on_missing {
log::info!("路徑 {:?} 不存在,嘗試創建之", path);
handle_fs_res(&[&path], create_dir(&path))?;
} else {
return Err(Error::PathNotFound(vec![path]));
}
} else {
let redirect = path.join(HS_REDIRECT);
if redirect.is_file() {
let redirect = read_file(&redirect)?;
let redirect = path.join(redirect.trim());
log::info!("重導向至 {:?}", redirect);
return compute_home_path(redirect, create_on_missing);
}
}
Ok(path)
}
pub fn compute_home_path_optional<T: AsRef<Path>>(
p: Option<T>,
create_on_missing: bool,
) -> Result<PathBuf> {
match p {
Some(p) => compute_home_path(p, create_on_missing),
None => compute_home_path(get_sys_home()?, create_on_missing),
}
}
pub fn set_home<T: AsRef<Path>>(p: Option<T>, create_on_missing: bool) -> Result {
let path = compute_home_path_optional(p, create_on_missing)?;
PATH.set(path);
Ok(())
}
#[cfg(not(test))]
pub fn get_home() -> &'static Path {
PATH.get().as_ref()
}
#[cfg(test)]
pub fn get_test_home() -> PathBuf {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
dir.join(".test_hyper_scripter")
}
#[cfg(test)]
pub fn get_home() -> &'static Path {
crate::set_once!(PATH, || { get_test_home() });
PATH.get().as_ref()
}
fn get_anonymous_ids() -> Result<Vec<u32>> {
// TODO: iterator
let dir = get_home().join(ANONYMOUS);
if !dir.exists() {
log::info!("找不到匿名腳本資料夾,創建之");
handle_fs_res(&[&dir], create_dir(&dir))?;
}
let mut ids = vec![];
let re = regex::Regex::new(r"\..+$").unwrap();
for entry in handle_fs_res(&[&dir], read_dir(&dir))? {
let name = entry?.file_name();
let name = name
.to_str()
.ok_or_else(|| Error::msg("檔案實體為空...?"))?;
let name = re.replace(name, "");
match name.parse::<u32>() {
Ok(id) => ids.push(id),
_ => log::warn!("匿名腳本名無法轉為整數:{}", name),
}
}
Ok(ids)
}
pub fn new_anonymous_name() -> Result<ScriptName> {
let ids: HashSet<_> = get_anonymous_ids()
.context("無法取得匿名腳本編號")?
.into_iter()
.collect();
let mut i = 1;
loop {
if !ids.contains(&i) {
return i.into_script_name();
}
i += 1;
}
}
pub fn open_new_anonymous(ty: &ScriptType) -> Result<(ScriptName, PathBuf)> {
let name = new_anonymous_name()?;
let path = open_script(&name, ty, None)?; // NOTE: new_anonymous_name 的邏輯已足以確保不會產生衝突的檔案,不檢查了!
Ok((name, path))
}
/// 若 `check_exist` 有值,則會檢查存在性
/// 需注意:要找已存在的腳本時,允許未知的腳本類型
/// 此情況下會使用 to_file_path_fallback 方法,即以類型名當作擴展名
pub fn open_script(
name: &ScriptName,
ty: &ScriptType,
check_exist: Option<bool>,
) -> Result<PathBuf> {
let mut err_in_fallback = None;
let script_path = if check_exist == Some(true) {
let (p, e) = name.to_file_path_fallback(ty);
err_in_fallback = e;
p
} else {
name.to_file_path(ty)?
};
let script_path = get_home().join(script_path);
if let Some(should_exist) = check_exist {
if !script_path.exists() && should_exist {
if let Some(e) = err_in_fallback {
return Err(e);
}
return Err(
Error::PathNotFound(vec![script_path]).context("開腳本失敗:應存在卻不存在")
);
} else if script_path.exists() && !should_exist {
return Err(Error::PathExist(script_path).context("開腳本失敗:不應存在卻存在"));
}
}
Ok(script_path)
}
pub fn get_template_path<T: AsScriptFullTypeRef>(ty: &T) -> Result<PathBuf> {
let p = get_home()
.join(TEMPLATE)
.join(format!("{}.hbs", ty.display()));
if let Some(dir) = p.parent() {
if !dir.exists() {
log::info!("找不到模板資料夾,創建之");
handle_fs_res(&[&dir], create_dir_all(&dir))?;
}
}
Ok(p)
}
pub fn get_sub_types(ty: &ScriptType) -> Result<Vec<ScriptType>> {
let dir = get_home().join(TEMPLATE).join(ty.as_ref());
if !dir.exists() {
log::info!("找不到子類別資料夾,直接回傳");
return Ok(vec![]);
}
let mut subs = vec![];
let re = regex::Regex::new(r"\.hbs$").unwrap();
for entry in handle_fs_res(&[&dir], read_dir(&dir))? {
let name = entry?.file_name();
let name = name
.to_str()
.ok_or_else(|| Error::msg("檔案實體為空...?"))?;
let name = re.replace(&name, "");
subs.push(name.parse()?);
}
Ok(subs)
}src/config.rs (line 180)
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
pub fn load(p: &Path) -> Result<Self> {
let path = config_file(p);
log::info!("載入設定檔:{:?}", path);
match util::read_file(&path) {
Ok(s) => {
let meta = util::handle_fs_res(&[&path], std::fs::metadata(&path))?;
let modified = util::handle_fs_res(&[&path], meta.modified())?;
let mut conf: Config = toml::from_str(&s).map_err(|err| {
FormatCode::Config.to_err(format!("{}: {}", path.to_string_lossy(), err))
})?;
conf.last_modified = Some(modified);
Ok(conf)
}
Err(Error::PathNotFound(_)) => {
log::debug!("找不到設定檔");
Ok(Default::default())
}
Err(e) => Err(e),
}
}
pub fn store(&self) -> Result {
let path = config_file(path::get_home());
log::info!("寫入設定檔至 {:?}…", path);
match util::handle_fs_res(&[&path], std::fs::metadata(&path)) {
Ok(meta) => {
let modified = util::handle_fs_res(&[&path], meta.modified())?;
// NOTE: 若設定檔是憑空造出來的,但要存入時卻發現已有檔案,同樣不做存入
if self.last_modified.map_or(true, |time| time < modified) {
log::info!("設定檔已被修改,不寫入");
return Ok(());
}
}
Err(Error::PathNotFound(_)) => {
log::debug!("設定檔不存在,寫就對了");
}
Err(err) => return Err(err),
}
util::write_file(&path, &toml::to_string_pretty(self)?)
}src/util/main_util.rs (line 97)
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(())
}