Function hyper_scripter::path::get_home
source · pub fn get_home() -> &'static PathExamples found in repository?
More examples
src/path.rs (line 144)
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 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 198)
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
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)?)
}
pub fn is_from_dafault(&self) -> bool {
self.last_modified.is_none()
}
pub fn init() -> Result {
CONFIG.set(Config::load(path::get_home())?);
Ok(())
}src/util/main_util.rs (line 263)
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
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)
}