使用Pathbuf代替String

This commit is contained in:
HouXiaoxuan
2023-12-19 17:20:45 +08:00
parent 247347a76e
commit 70f1d1dbc1
2 changed files with 14 additions and 10 deletions

View File

@@ -1,7 +1,9 @@
use std::path::PathBuf;
use super::utils::util;
pub struct Store {
store_path: String,
store_path: PathBuf,
}
impl Store {
@@ -11,14 +13,14 @@ impl Store {
}
let store_path = util::get_storage_path().unwrap();
Store {
store_path: store_path,
store_path,
}
}
pub fn load(&self, hash: &String) -> String {
/* 读取文件内容 */
let mut path = self.store_path.clone();
path.push_str("/objects/");
path.push_str(hash);
path.push("objects");
path.push(hash);
match std::fs::read_to_string(path) {
Ok(content) => content,
Err(_) => panic!("储存库疑似损坏,无法读取文件"),
@@ -26,11 +28,13 @@ impl Store {
}
pub fn save(&self, content: &String) -> String {
/* 保存文件内容 */
println!("store_path: {:?}", self.store_path);
let hash = util::calc_hash(content);
let mut path = self.store_path.clone();
path.push_str("/objects/");
path.push_str(&hash);
println!("path: {:?}", path);
path.push("objects");
path.push(&hash);
println!("path: {:?}", path);
match std::fs::write(path, content) {
Ok(_) => hash,
Err(_) => panic!("储存库疑似损坏,无法写入文件"),

View File

@@ -26,14 +26,14 @@ pub fn check_repo_exist() {
}
}
pub fn get_storage_path() -> Result<String, std::io::Error> {
pub fn get_storage_path() -> Result<PathBuf, std::io::Error> {
/*递归获取储存库 */
let mut current_dir = std::env::current_dir()?;
loop {
let mut git_path = current_dir.clone();
git_path.push(".mit");
if git_path.exists() {
return Ok(git_path.to_str().unwrap().to_string());
return Ok(git_path);
}
if !current_dir.pop() {
return Err(std::io::Error::new(
@@ -89,7 +89,7 @@ mod tests {
fn test_get_storage_path() {
let path = get_storage_path();
match path {
Ok(path) => println!("{}", path),
Ok(path) => println!("{:?}", path),
Err(err) => match err.kind() {
std::io::ErrorKind::NotFound => println!("Not a git repository"),
_ => assert!(false, "Unexpected error"),