Преглед изворни кода

【修复】解决安装软件包时 metadata.json 未复制到目标目录的问题

PJ568 пре 1 година
родитељ
комит
b8222466ab
11 измењених фајлова са 35 додато и 55 уклоњено
  1. 1 1
      Cargo.lock
  2. 1 1
      Cargo.toml
  3. 1 1
      src/app.rs
  4. 4 4
      src/config.rs
  5. 2 2
      src/crypto.rs
  6. 2 2
      src/fsxg.rs
  7. 4 4
      src/main.rs
  8. 2 25
      src/metadata.rs
  9. 6 7
      src/net.rs
  10. 1 2
      src/path.rs
  11. 11 6
      src/repo.rs

+ 1 - 1
Cargo.lock

@@ -891,7 +891,7 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
 
 [[package]]
 name = "pageos-pkgr"
-version = "2.0.3"
+version = "2.0.4"
 dependencies = [
  "anyhow",
  "clap",

+ 1 - 1
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "pageos-pkgr"
-version = "2.0.3"
+version = "2.0.4"
 authors = ["PJ568 <[email protected]>"]
 edition = "2024"
 license = "MPL-2.0"

+ 1 - 1
src/app.rs

@@ -82,7 +82,7 @@ pub fn new<S: AsRef<str>, P: AsRef<Path>>(package_id: S, base_dir: P) -> Result<
     let base_dir = base_dir.as_ref();
     let package_path = base_dir.join(package_id);
 
-    init(&package_path).with_context(|| format!("无法初始化新应用包: {}", package_id))?;
+    init(&package_path).with_context(|| format!("无法初始化新应用包: {package_id}"))?;
 
     Ok(package_path)
 }

+ 4 - 4
src/config.rs

@@ -80,8 +80,8 @@ impl ConfigManager {
         }
 
         // 解析 TOML 配置
-        let mut config: RepositoryConfig =
-            load_toml(&Path::new(&self.config_path))
+        let config: RepositoryConfig =
+            load_toml(Path::new(&self.config_path))
                 .with_context(|| format!("无法读取或解析配置文件: {}", self.config_path))?;
 
         // 验证配置的有效性
@@ -106,7 +106,7 @@ impl ConfigManager {
         }
 
         // 写入文件
-        save_toml(config, &Path::new(&self.config_path))
+        save_toml(config, Path::new(&self.config_path))
             .with_context(|| format!("无法保存配置文件: {}", self.config_path))?;
 
         // 设置文件权限(如果可能)
@@ -214,7 +214,7 @@ impl ConfigManager {
         // 检查源ID是否唯一
         let mut source_ids = HashMap::new();
         for source in &config.source {
-            if let Some(_) = source_ids.insert(&source.id, ()) {
+            if source_ids.insert(&source.id, ()).is_some() {
                 return Err(anyhow::anyhow!("软件源ID '{}' 重复", source.id));
             }
         }

+ 2 - 2
src/crypto.rs

@@ -5,7 +5,7 @@
 use anyhow::Result;
 use sha2::{Digest, Sha256};
 use std::fs::File;
-use std::io::{self, Read};
+use std::io::Read;
 
 /// 计算文件的 SHA256 哈希值
 ///
@@ -34,7 +34,7 @@ pub fn file_hash(file_path: &str) -> Result<String> {
     }
 
     let result = hasher.finalize();
-    Ok(format!("{:x}", result))
+    Ok(format!("{result:x}"))
 }
 
 /// 验证文件的完整性

+ 2 - 2
src/fsxg.rs

@@ -145,7 +145,7 @@ pub fn get_directory_files<P: AsRef<Path>>(path: P, recursive: bool) -> Result<V
                 } else {
                     // 将相对路径转换为绝对路径
                     std::fs::canonicalize(&file_path)
-                        .with_context(|| format!("无法解析路径: {:?}", file_path))?
+                        .with_context(|| format!("无法解析路径: {file_path:?}"))?
                 };
                 files.push(abs_path);
             }
@@ -164,7 +164,7 @@ pub fn get_directory_files<P: AsRef<Path>>(path: P, recursive: bool) -> Result<V
                 let full_path = path.join(&entry_path);
                 // 将相对路径转换为绝对路径
                 std::fs::canonicalize(&full_path)
-                    .with_context(|| format!("无法解析路径: {:?}", full_path))?
+                    .with_context(|| format!("无法解析路径: {full_path:?}"))?
             };
 
             if abs_path.is_file() {

+ 4 - 4
src/main.rs

@@ -239,9 +239,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
                 } => {
                     let mut repo_manager = repo::RepoManager::open(repo.clone())?;
                     repo_manager
-                        .install_package(&source_package_version, None)
+                        .install_package(source_package_version, None)
                         .await?;
-                    println!("已成功安装软件包 {}", source_package_version);
+                    println!("已成功安装软件包 {source_package_version}");
                 }
                 RepoCommands::Remove {
                     package_version,
@@ -258,12 +258,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 
                     let mut repo_manager = repo::RepoManager::open(repo.clone())?;
                     repo_manager.remove_package(package_id, version)?;
-                    println!("已成功卸载软件包 {}", package_id);
+                    println!("已成功卸载软件包 {package_id}");
                 }
                 RepoCommands::Upgrade { package_id, repo } => {
                     let mut repo_manager = repo::RepoManager::open(repo.clone())?;
                     repo_manager.upgrade_package(package_id).await?;
-                    println!("已成功升级软件包 {}", package_id);
+                    println!("已成功升级软件包 {package_id}");
                 }
                 RepoCommands::Sync {
                     source_id,

+ 2 - 25
src/metadata.rs

@@ -7,6 +7,7 @@ use std::collections::HashMap;
 
 /// 包元数据
 #[derive(Serialize, Deserialize, Debug, Clone)]
+#[derive(Default)]
 pub struct PackageMetadata {
     /// 应用名称
     pub name: String,
@@ -37,6 +38,7 @@ pub struct PackageMetadata {
 /// 用于表示单个文件的路径和其对应的 SHA256 哈希值。
 /// 在 `PackageMetadata` 中,`all_files` 字段使用 `HashMap<String, String>` 来存储多个文件。
 #[derive(Serialize, Deserialize, Debug, Clone)]
+#[derive(Default)]
 pub struct FileManifest {
     /// 文件相对路径
     pub path: String,
@@ -78,23 +80,6 @@ impl VersionHistory {
     }
 }
 
-impl Default for PackageMetadata {
-    fn default() -> Self {
-        Self {
-            name: String::new(),
-            id: String::new(),
-            version: String::new(),
-            description: String::new(),
-            icon: String::new(),
-            author: String::new(),
-            r#type: String::new(),
-            category: String::new(),
-            permissions: Vec::new(),
-            entry: String::new(),
-            all_files: HashMap::new(),
-        }
-    }
-}
 
 impl PackageMetadata {
     /// 创建一个新的包元数据实例
@@ -123,14 +108,6 @@ impl PackageMetadata {
     }
 }
 
-impl Default for FileManifest {
-    fn default() -> Self {
-        Self {
-            path: String::new(),
-            hash: String::new(),
-        }
-    }
-}
 
 impl FileManifest {
     /// 创建一个新的文件清单项

+ 6 - 7
src/net.rs

@@ -2,7 +2,6 @@
 // License, v. 2.0. If a copy of the MPL was not distributed with this
 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
 
-use reqwest;
 use tokio::io::AsyncWriteExt;
 
 /// 从指定URL下载文件到本地路径
@@ -43,7 +42,7 @@ pub async fn download_file(url: &str, path: &str) -> Result<(), Box<dyn std::err
     // 确保目标目录存在
     let parent_dir = std::path::Path::new(path)
         .parent()
-        .ok_or_else(|| "无法获取父目录")?;
+        .ok_or("无法获取父目录")?;
     tokio::fs::create_dir_all(parent_dir).await?;
 
     // 创建本地文件
@@ -60,7 +59,7 @@ pub async fn download_file(url: &str, path: &str) -> Result<(), Box<dyn std::err
     // 显示进度
     if total_size > 0 {
         let progress = (downloaded as f64 / total_size as f64 * 100.0) as u8;
-        eprint!("\r下载进度: {}%", progress);
+        eprint!("\r下载进度: {progress}%");
     }
 
     // 确保所有数据都写入磁盘
@@ -167,18 +166,18 @@ pub async fn mirror_sync(
                 let location = if location.ends_with('/') {
                     location.to_string()
                 } else {
-                    format!("{}/", location)
+                    format!("{location}/")
                 };
 
                 // 获取包的文件列表
-                let files_url = format!("{}metadata.json", location);
+                let files_url = format!("{location}metadata.json");
                 let files_index = fetch_index(&files_url).await?;
 
                 // 同步包中的所有文件
                 if let Some(files) = files_index["all_files"].as_object() {
                     for (file_path, _hash) in files {
-                        let file_url = format!("{}{}", location, file_path);
-                        let local_path = format!("{}/{}", target_dir, file_path);
+                        let file_url = format!("{location}{file_path}");
+                        let local_path = format!("{target_dir}/{file_path}");
 
                         // 确保本地目录存在
                         if let Some(parent) = std::path::Path::new(&local_path).parent() {

+ 1 - 2
src/path.rs

@@ -2,7 +2,6 @@
 // License, v. 2.0. If a copy of the MPL was not distributed with this
 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
 
-use dirs;
 use std::fs;
 use std::path::{Path, PathBuf};
 
@@ -46,7 +45,7 @@ pub fn create_dir_all<P: AsRef<Path>>(path: P) -> std::io::Result<()> {
 pub fn normalize_path<P: AsRef<Path>>(path: P) -> PathBuf {
     let path = path.as_ref();
     let mut components = Vec::new();
-    let mut is_absolute = path.is_absolute();
+    let is_absolute = path.is_absolute();
 
     for component in path.components() {
         match component {

+ 11 - 6
src/repo.rs

@@ -9,7 +9,7 @@ use crate::net;
 use crate::path::{expand_path, get_cache_dir};
 use crate::serde_utils::{load_json, save_json};
 use crate::transaction::Transaction;
-use crate::{crypto, index};
+use crate::crypto;
 use anyhow::{Context, Result, anyhow};
 use serde::{Deserialize, Serialize};
 use std::fs;
@@ -60,7 +60,7 @@ impl RepoManager {
         let config_path = repo_path.join("config.toml");
 
         // 创建仓库目录结构
-        fsxg::create_directory(&repo_path.join("packages"))
+        fsxg::create_directory(repo_path.join("packages"))
             .with_context(|| format!("无法创建 packages 目录: {}", repo_path.display()))?;
 
         // 初始化配置文件
@@ -186,7 +186,7 @@ impl RepoManager {
         }
 
         // 将 HashMap 中的值转换为 Vec,作为新的 source 部分
-        local_index.source = merged_source.into_iter().map(|(_, v)| v).collect();
+        local_index.source = merged_source.into_values().collect();
 
         // 保存更新后的索引
         save_json(&local_index, &index_path)?;
@@ -210,7 +210,7 @@ impl RepoManager {
         fsxg::create_directory(&package_dir)?;
 
         // 确保 metadata.all_files 至少包含一项
-        if metadata.all_files.len() < 1 {
+        if metadata.all_files.is_empty() {
             return Err(anyhow!("metadata.all_files 必须至少包含一项"));
         }
 
@@ -235,7 +235,7 @@ impl RepoManager {
         }
 
         // 复制所有文件
-        for (file_path, _hash) in &metadata.all_files {
+        for file_path in metadata.all_files.keys() {
             let src_path = package_path.join(file_path);
             let dest_path = package_dir.join(file_path);
 
@@ -383,6 +383,11 @@ impl RepoManager {
             }
         }
 
+        // 复制 metadata.json 文件
+        let src_metadata_path = metadata_path; // 缓存目录中的 metadata.json
+        let dest_metadata_path = package_dir.join("metadata.json");
+        fs::copy(src_metadata_path, dest_metadata_path)?;
+
         // 更新版本历史
         update_version_history(&metadata.id, &metadata.version, &self.repo_path)?;
 
@@ -462,7 +467,7 @@ impl RepoManager {
         if latest_version != current_version {
             // 安装新版本
             self.install_package(
-                &format!("{}:{}", source_id, package_id),
+                &format!("{source_id}:{package_id}"),
                 Some(&latest_version),
             )
             .await?;