瀏覽代碼

fix(rootfs): merge old codes to reduce difference

v1正常跑

用cargo clippy --fix修了一下

Merge remote-tracking branch 'upstream/main' into fk_merge
Vitus213 1 周之前
父節點
當前提交
fe8ff7b057
共有 41 個文件被更改,包括 856 次插入1137 次删除
  1. 219 204
      Cargo.lock
  2. 2 2
      crates/test_base/src/dadk_config.rs
  3. 1 1
      dadk-config/Cargo.toml
  4. 1 0
      dadk-config/src/common/target_arch.rs
  5. 6 6
      dadk-config/src/common/task.rs
  6. 1 1
      dadk-config/src/manifest.rs
  7. 2 2
      dadk-config/src/rootfs/fstype.rs
  8. 3 5
      dadk-config/src/utils.rs
  9. 2 2
      dadk-config/tests/test_boot_config.rs
  10. 3 3
      dadk-config/tests/test_dadk_manifest.rs
  11. 2 2
      dadk-config/tests/test_rootfs_config.rs
  12. 2 2
      dadk-user/Cargo.toml
  13. 16 16
      dadk-user/src/executor/cache.rs
  14. 36 30
      dadk-user/src/executor/mod.rs
  15. 26 30
      dadk-user/src/executor/source.rs
  16. 1 1
      dadk-user/src/executor/tests.rs
  17. 6 6
      dadk-user/src/parser/mod.rs
  18. 10 10
      dadk-user/src/parser/task.rs
  19. 6 0
      dadk-user/src/parser/task_log.rs
  20. 28 23
      dadk-user/src/scheduler/mod.rs
  21. 3 3
      dadk-user/src/scheduler/task_deque.rs
  22. 12 6
      dadk-user/src/utils/lazy_init.rs
  23. 2 2
      dadk-user/src/utils/stdio.rs
  24. 1 1
      dadk/Cargo.toml
  25. 4 11
      dadk/src/actions/mod.rs
  26. 7 7
      dadk/src/actions/profile/mod.rs
  27. 231 118
      dadk/src/actions/rootfs/disk_img.rs
  28. 1 1
      dadk/src/actions/rootfs/loopdev_v1.rs
  29. 123 114
      dadk/src/actions/rootfs/loopdev_v2.rs
  30. 35 2
      dadk/src/actions/rootfs/mod.rs
  31. 1 1
      dadk/src/actions/rootfs/sysroot.rs
  32. 0 19
      dadk/src/actions/rootfs/v1/mod.rs
  33. 0 26
      dadk/src/actions/rootfs/v1/sysroot.rs
  34. 0 430
      dadk/src/actions/rootfs/v2/disk_img.rs
  35. 0 19
      dadk/src/actions/rootfs/v2/mod.rs
  36. 1 1
      dadk/src/actions/user.rs
  37. 1 1
      dadk/src/console/mod.rs
  38. 10 10
      dadk/src/console/tests.rs
  39. 6 6
      dadk/src/console/user.rs
  40. 43 11
      dadk/src/context/mod.rs
  41. 2 2
      dadk/src/utils.rs

文件差異過大導致無法顯示
+ 219 - 204
Cargo.lock


+ 2 - 2
crates/test_base/src/dadk_config.rs

@@ -42,9 +42,9 @@ impl TestContext for DadkConfigTestContext {
         // 设置workdir
         std::env::set_current_dir(&test_base_path).expect("Failed to setup test base path");
 
-        let r = DadkConfigTestContext { test_base_path };
+        
 
-        r
+        DadkConfigTestContext { test_base_path }
     }
 }
 

+ 1 - 1
dadk-config/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "dadk-config"
-version = "0.3.0"
+version = "0.3.1"
 edition = "2021"
 authors = [
     "longjin <longjin@DragonOS.org>",

+ 1 - 0
dadk-config/src/common/target_arch.rs

@@ -83,6 +83,7 @@ impl Display for TargetArch {
             TargetArch::X86_64 => write!(f, "x86_64"),
             TargetArch::RiscV64 => write!(f, "riscv64"),
             TargetArch::AArch64 => write!(f, "aarch64"),
+            TargetArch::LoongArch64 => write!(f, "loongarch64"),    
         }
     }
 }

+ 6 - 6
dadk-config/src/common/task.rs

@@ -69,7 +69,7 @@ impl BuildConfig {
     }
 
     pub fn validate(&self) -> Result<()> {
-        return Ok(());
+        Ok(())
     }
 
     pub fn trim(&mut self) {
@@ -101,7 +101,7 @@ impl InstallConfig {
                 "InstallConfig: in_dragonos_path should be an Absolute path",
             ));
         }
-        return Ok(());
+        Ok(())
     }
 
     pub fn trim(&mut self) {}
@@ -121,7 +121,7 @@ impl CleanConfig {
     }
 
     pub fn validate(&self) -> Result<()> {
-        return Ok(());
+        Ok(())
     }
 
     pub fn trim(&mut self) {
@@ -153,7 +153,7 @@ impl Dependency {
         if self.version.is_empty() {
             return Err(Error::msg("version is empty"));
         }
-        return Ok(());
+        Ok(())
     }
 
     pub fn trim(&mut self) {
@@ -162,7 +162,7 @@ impl Dependency {
     }
 
     pub fn name_version(&self) -> String {
-        return format!("{}-{}", self.name, self.version);
+        format!("{}-{}", self.name, self.version)
     }
 }
 
@@ -200,7 +200,7 @@ impl TaskEnv {
         if self.key.is_empty() {
             return Err(Error::msg("Env: key is empty"));
         }
-        return Ok(());
+        Ok(())
     }
 }
 

+ 1 - 1
dadk-config/src/manifest.rs

@@ -256,7 +256,7 @@ mod tests {
         temp_file.write_all(toml_content.as_bytes())?;
         let path = temp_file.path().to_path_buf();
         let manifest = DadkManifestFile::load(&path)?;
-        assert_eq!(manifest.used_default, true);
+        assert!(manifest.used_default);
         assert_eq!(
             manifest.metadata.rootfs_config,
             PathBuf::from("config/rootfs.toml")

+ 2 - 2
dadk-config/src/rootfs/fstype.rs

@@ -33,7 +33,7 @@ mod tests {
     #[test]
     fn test_deserialize_fat32_lowercase() {
         let r = deserialize_fs_type("fat32");
-        assert_eq!(r.is_ok(), true);
+        assert!(r.is_ok());
         let fs_type = r.unwrap();
         assert_eq!(fs_type, FsType::Fat32);
     }
@@ -41,7 +41,7 @@ mod tests {
     #[test]
     fn test_deserialize_fat32_mixed_case() {
         let r = deserialize_fs_type("FAT32");
-        assert_eq!(r.is_ok(), true);
+        assert!(r.is_ok());
         let fs_type = r.unwrap();
         assert_eq!(fs_type, FsType::Fat32);
     }

+ 3 - 5
dadk-config/src/utils.rs

@@ -90,12 +90,10 @@ pub fn apply_kv_array(
 
             key_strings.insert(key, arg.to_owned());
             continue;
+        } else if single_value_keys.contains(&arg.as_str()) || multi_value_keys.contains(arg) {
+            return Err(anyhow!("Invalid argument: {}", arg));
         } else {
-            if single_value_keys.contains(&arg.as_str()) || multi_value_keys.contains(arg) {
-                return Err(anyhow!("Invalid argument: {}", arg));
-            } else {
-                key_strings.insert(arg.to_owned(), arg.to_owned());
-            }
+            key_strings.insert(arg.to_owned(), arg.to_owned());
         }
     }
 

+ 2 - 2
dadk-config/tests/test_boot_config.rs

@@ -11,8 +11,8 @@ const BOOT_CONFIG_FILE_NAME: &str = "config/boot.toml";
 #[test]
 fn test_load_boot_config_template(ctx: &DadkConfigTestContext) {
     let boot_config_path = ctx.templates_dir().join(BOOT_CONFIG_FILE_NAME);
-    assert_eq!(boot_config_path.exists(), true);
-    assert_eq!(boot_config_path.is_file(), true);
+    assert!(boot_config_path.exists());
+    assert!(boot_config_path.is_file());
     let _manifest = BootConfigFile::load(&boot_config_path).expect("Failed to load boot config");
     // TODO 校验 manifest 中的字段是否齐全
 }

+ 3 - 3
dadk-config/tests/test_dadk_manifest.rs

@@ -11,9 +11,9 @@ const DADK_MANIFEST_FILE_NAME: &str = "dadk-manifest.toml";
 #[test]
 fn test_load_dadk_manifest_template(ctx: &DadkConfigTestContext) {
     let manifest_path = ctx.templates_dir().join(DADK_MANIFEST_FILE_NAME);
-    assert_eq!(manifest_path.exists(), true);
-    assert_eq!(manifest_path.is_file(), true);
+    assert!(manifest_path.exists());
+    assert!(manifest_path.is_file());
     let manifest = DadkManifestFile::load(&manifest_path).expect("Failed to load manifest");
     // 验证 dadk-manifest.toml 已经包含了所有字段
-    assert_eq!(manifest.used_default, false);
+    assert!(!manifest.used_default);
 }

+ 2 - 2
dadk-config/tests/test_rootfs_config.rs

@@ -14,8 +14,8 @@ const ROOTFS_CONFIG_FILE_NAME: &str = "config/rootfs.toml";
 #[test]
 fn test_load_rootfs_manifest_template(ctx: &DadkConfigTestContext) {
     let rootfs_manifest_path = ctx.templates_dir().join(ROOTFS_CONFIG_FILE_NAME);
-    assert_eq!(rootfs_manifest_path.exists(), true);
-    assert_eq!(rootfs_manifest_path.is_file(), true);
+    assert!(rootfs_manifest_path.exists());
+    assert!(rootfs_manifest_path.is_file());
     let manifest =
         RootFSConfigFile::load(&rootfs_manifest_path).expect("Failed to load rootfs manifest");
     assert_eq!(manifest.partition.partition_type, PartitionType::None);

+ 2 - 2
dadk-user/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "dadk-user"
-version = "0.3.0"
+version = "0.3.1"
 edition = "2021"
 description = "DragonOS Application Development Kit - user prog build"
 license = "GPL-2.0-only"
@@ -9,7 +9,7 @@ license = "GPL-2.0-only"
 anyhow = { version = "1.0.90", features = ["std", "backtrace"] }
 chrono = { version = "=0.4.35", features = ["serde"] }
 clap = { version = "=4.5.20", features = ["derive"] }
-dadk-config = { version = "0.3.0", path = "../dadk-config" }
+dadk-config = { version = "0.3.1", path = "../dadk-config" }
 derive_builder = "0.20.0"
 lazy_static = "1.4.0"
 log = "0.4.17"

+ 16 - 16
dadk-user/src/executor/cache.rs

@@ -86,7 +86,7 @@ pub fn cache_root_init(path: Option<PathBuf>) -> Result<(), ExecutorError> {
     // 设置环境变量
     std::env::set_var("DADK_CACHE_ROOT", CACHE_ROOT.get().to_str().unwrap());
     info!("Cache root dir: {:?}", CACHE_ROOT.get());
-    return Ok(());
+    Ok(())
 }
 
 #[derive(Debug, Clone, Copy)]
@@ -122,7 +122,7 @@ impl CacheDir {
 
         result.create()?;
 
-        return Ok(result);
+        Ok(result)
     }
 
     fn get_path(task: &DADKTask, cache_type: CacheDirType) -> PathBuf {
@@ -147,29 +147,29 @@ impl CacheDir {
     }
 
     pub fn build_dir(entity: Arc<SchedEntity>) -> Result<PathBuf, ExecutorError> {
-        return Ok(Self::new(entity.clone(), CacheDirType::Build)?.path);
+        Ok(Self::new(entity.clone(), CacheDirType::Build)?.path)
     }
 
     pub fn source_dir(entity: Arc<SchedEntity>) -> Result<PathBuf, ExecutorError> {
-        return Ok(Self::new(entity.clone(), CacheDirType::Source)?.path);
+        Ok(Self::new(entity.clone(), CacheDirType::Source)?.path)
     }
 
     pub fn build_dir_env_key(entity: &Arc<SchedEntity>) -> Result<String, ExecutorError> {
         let name_version_env = entity.task().name_version_env();
-        return Ok(format!(
+        Ok(format!(
             "{}_{}",
             Self::DADK_BUILD_CACHE_DIR_ENV_KEY_PREFIX,
             name_version_env
-        ));
+        ))
     }
 
     pub fn source_dir_env_key(entity: &Arc<SchedEntity>) -> Result<String, ExecutorError> {
         let name_version_env = entity.task().name_version_env();
-        return Ok(format!(
+        Ok(format!(
             "{}_{}",
             Self::DADK_SOURCE_CACHE_DIR_ENV_KEY_PREFIX,
             name_version_env
-        ));
+        ))
     }
 
     pub fn need_source_cache(entity: &Arc<SchedEntity>) -> bool {
@@ -210,7 +210,7 @@ impl CacheDir {
             ));
         }
 
-        return Ok(());
+        Ok(())
     }
 
     /// 判断缓存目录是否为空
@@ -223,7 +223,7 @@ impl CacheDir {
             return Ok(false);
         }
 
-        return Ok(true);
+        Ok(true)
     }
 
     /// # 递归删除自身目录
@@ -235,7 +235,7 @@ impl CacheDir {
         if path.exists() {
             std::fs::remove_dir_all(path).map_err(|e| ExecutorError::IoError(e.to_string()))?;
         }
-        return Ok(());
+        Ok(())
     }
 }
 
@@ -248,7 +248,7 @@ impl TaskDataDir {
     const TASK_LOG_FILE_NAME: &'static str = "task_log.toml";
     pub fn new(entity: Arc<SchedEntity>) -> Result<Self, ExecutorError> {
         let dir = CacheDir::new(entity.clone(), CacheDirType::TaskData)?;
-        return Ok(Self { dir });
+        Ok(Self { dir })
     }
 
     /// # 获取任务日志
@@ -257,9 +257,9 @@ impl TaskDataDir {
         if path.exists() {
             let content = std::fs::read_to_string(&path).unwrap();
             let task_log: TaskLog = toml::from_str(&content).unwrap();
-            return task_log;
+            task_log
         } else {
-            return TaskLog::new();
+            TaskLog::new()
         }
     }
 
@@ -267,7 +267,7 @@ impl TaskDataDir {
     pub fn save_task_log(&self, task_log: &TaskLog) -> Result<(), ExecutorError> {
         let path = self.dir.path.join(Self::TASK_LOG_FILE_NAME);
         let content = toml::to_string(task_log).unwrap();
-        std::fs::write(&path, content).map_err(|e| ExecutorError::IoError(e.to_string()))?;
-        return Ok(());
+        std::fs::write(path, content).map_err(|e| ExecutorError::IoError(e.to_string()))?;
+        Ok(())
     }
 }

+ 36 - 30
dadk-user/src/executor/mod.rs

@@ -89,7 +89,7 @@ impl Executor {
             dragonos_sysroot,
         };
 
-        return Ok(result);
+        Ok(result)
     }
 
     /// # 执行任务
@@ -107,7 +107,7 @@ impl Executor {
         let r = self.do_execute();
         self.save_task_data(r.clone());
         info!("Task {} finished", self.entity.task().name_version());
-        return r;
+        r
     }
 
     /// # 保存任务数据
@@ -174,7 +174,7 @@ impl Executor {
             }
         }
 
-        return Ok(());
+        Ok(())
     }
 
     fn pre_build(&mut self) -> Result<(), ExecutorError> {
@@ -217,7 +217,7 @@ impl Executor {
             }
         }
 
-        return self.do_build();
+        self.do_build()
     }
 
     fn post_build(&mut self) -> Result<(), ExecutorError> {
@@ -256,7 +256,7 @@ impl Executor {
                 self.entity.task().name_version(),
             );
         }
-        return Ok(());
+        Ok(())
     }
 
     fn install(&self) -> Result<(), ExecutorError> {
@@ -284,7 +284,7 @@ impl Executor {
             "dadk-user: to do install {}",
             self.entity.task().name_version()
         );
-        return self.do_install();
+        self.do_install()
     }
 
     /// # 执行安装操作,把构建结果安装到DragonOS
@@ -309,16 +309,16 @@ impl Executor {
         debug!("install_path: {:?}", install_path);
         // 创建安装路径
         std::fs::create_dir_all(&install_path).map_err(|e| {
-            ExecutorError::InstallError(format!("Failed to create install path: {}", e.to_string()))
+            ExecutorError::InstallError(format!("Failed to create install path: {}", e))
         })?;
 
         // 拷贝构建结果到安装路径
         let build_dir: PathBuf = self.build_dir.path.clone();
         FileUtils::copy_dir_all(&build_dir, &install_path)
-            .map_err(|e| ExecutorError::InstallError(e))?;
+            .map_err(ExecutorError::InstallError)?;
         info!("Task {} installed.", self.entity.task().name_version());
 
-        return Ok(());
+        Ok(())
     }
 
     fn clean(&self) -> Result<(), ExecutorError> {
@@ -353,7 +353,7 @@ impl Executor {
             return Err(e);
         }
 
-        return Ok(());
+        Ok(())
     }
 
     fn clean_all(&self) -> Result<(), ExecutorError> {
@@ -363,7 +363,7 @@ impl Executor {
         self.clean_target()?;
         // 清理缓存
         self.clean_cache()?;
-        return Ok(());
+        Ok(())
     }
 
     /// 在源文件目录执行清理
@@ -381,7 +381,7 @@ impl Executor {
 
         let cmd = cmd.unwrap();
         self.run_command(cmd)?;
-        return Ok(());
+        Ok(())
     }
 
     /// 清理构建输出目录
@@ -392,7 +392,7 @@ impl Executor {
             self.build_dir.path
         );
 
-        return self.build_dir.remove_self_recursive();
+        self.build_dir.remove_self_recursive()
     }
 
     /// 清理下载缓存
@@ -407,7 +407,7 @@ impl Executor {
             self.entity.task().name_version(),
             self.src_work_dir().display()
         );
-        return cache_dir.unwrap().remove_self_recursive();
+        cache_dir.unwrap().remove_self_recursive()
     }
 
     /// 获取源文件的工作目录
@@ -419,7 +419,7 @@ impl Executor {
     }
 
     fn task_log(&self) -> TaskLog {
-        return self.task_data_dir.task_log();
+        self.task_data_dir.task_log()
     }
 
     /// 为任务创建命令
@@ -472,7 +472,7 @@ impl Executor {
             command.env(key, value.value.clone());
         }
 
-        return Ok(Some(command));
+        Ok(Some(command))
     }
 
     /// # 准备工作线程本地环境变量
@@ -493,7 +493,7 @@ impl Executor {
             self.build_dir.path.to_str().unwrap().to_string(),
         ));
 
-        return Ok(());
+        Ok(())
     }
 
     fn prepare_input(&self) -> Result<(), ExecutorError> {
@@ -508,7 +508,7 @@ impl Executor {
                 match cs {
                     CodeSource::Git(git) => {
                         git.prepare(source_dir)
-                            .map_err(|e| ExecutorError::PrepareEnvError(e))?;
+                            .map_err(ExecutorError::PrepareEnvError)?;
                     }
                     // 本地源文件,不需要拉取
                     CodeSource::Local(_) => return Ok(()),
@@ -516,7 +516,7 @@ impl Executor {
                     CodeSource::Archive(archive) => {
                         archive
                             .download_unzip(source_dir)
-                            .map_err(|e| ExecutorError::PrepareEnvError(e))?;
+                            .map_err(ExecutorError::PrepareEnvError)?;
                     }
                 }
             }
@@ -526,21 +526,21 @@ impl Executor {
                     PrebuiltSource::Local(local_source) => {
                         let local_path = local_source.path();
                         let target_path = &self.build_dir.path;
-                        FileUtils::copy_dir_all(&local_path, &target_path)
-                            .map_err(|e| ExecutorError::TaskFailed(e))?; // let mut cmd = "cp -r ".to_string();
+                        FileUtils::copy_dir_all(local_path, target_path)
+                            .map_err(ExecutorError::TaskFailed)?; // let mut cmd = "cp -r ".to_string();
                         return Ok(());
                     }
                     // 在线压缩包,需要下载
                     PrebuiltSource::Archive(archive) => {
                         archive
                             .download_unzip(&self.build_dir)
-                            .map_err(|e| ExecutorError::PrepareEnvError(e))?;
+                            .map_err(ExecutorError::PrepareEnvError)?;
                     }
                 }
             }
         }
 
-        return Ok(());
+        Ok(())
     }
 
     fn run_command(&self, mut command: Command) -> Result<(), ExecutorError> {
@@ -557,7 +557,7 @@ impl Executor {
         if r.is_ok() {
             let r = r.unwrap();
             if r.success() {
-                return Ok(());
+                Ok(())
             } else {
                 // 执行失败,获取最后100行stderr输出
                 let errmsg = format!(
@@ -584,7 +584,7 @@ impl Executor {
                 for line in last_100_outputs {
                     error!("{}", line);
                 }
-                return Err(ExecutorError::TaskFailed(errmsg));
+                Err(ExecutorError::TaskFailed(errmsg))
             }
         } else {
             let errmsg = format!(
@@ -593,7 +593,7 @@ impl Executor {
                 r.err().unwrap()
             );
             error!("{errmsg}");
-            return Err(ExecutorError::TaskFailed(errmsg));
+            Err(ExecutorError::TaskFailed(errmsg))
         }
     }
 }
@@ -603,6 +603,12 @@ pub struct EnvMap {
     pub envs: BTreeMap<String, EnvVar>,
 }
 
+impl Default for EnvMap {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
 impl EnvMap {
     pub fn new() -> Self {
         Self {
@@ -664,7 +670,7 @@ pub fn prepare_env(
     // 写入全局环境变量列表
     let mut global_env_list = ENV_LIST.write().unwrap();
     *global_env_list = env_list;
-    return Ok(());
+    Ok(())
 }
 
 /// # 创建全局环境变量列表
@@ -681,7 +687,7 @@ fn create_global_env_list(
         // 导出任务的构建目录环境变量
         let build_dir = CacheDir::build_dir(entity.clone())?;
 
-        let build_dir_key = CacheDir::build_dir_env_key(&entity)?;
+        let build_dir_key = CacheDir::build_dir_env_key(entity)?;
         env_list.add(EnvVar::new(
             build_dir_key,
             build_dir.to_str().unwrap().to_string(),
@@ -690,7 +696,7 @@ fn create_global_env_list(
         // 如果需要源码缓存目录,则导出
         if CacheDir::need_source_cache(entity) {
             let source_dir = CacheDir::source_dir(entity.clone())?;
-            let source_dir_key = CacheDir::source_dir_env_key(&entity)?;
+            let source_dir_key = CacheDir::source_dir_env_key(entity)?;
             env_list.add(EnvVar::new(
                 source_dir_key,
                 source_dir.to_str().unwrap().to_string(),
@@ -702,7 +708,7 @@ fn create_global_env_list(
     let target_arch = execute_ctx.target_arch();
     env_list.add(EnvVar::new("ARCH".to_string(), (*target_arch).into()));
 
-    return Ok(env_list);
+    Ok(env_list)
 }
 
 /// # 获取文件最后的更新时间

+ 26 - 30
dadk-user/src/executor/source.rs

@@ -53,17 +53,13 @@ impl GitSource {
             return Err(Error::msg("branch and revision are both specified"));
         }
 
-        if self.branch.is_some() {
-            if self.branch.as_ref().unwrap().is_empty() {
-                return Err(Error::msg("branch is empty"));
-            }
+        if self.branch.is_some() && self.branch.as_ref().unwrap().is_empty() {
+            return Err(Error::msg("branch is empty"));
         }
-        if self.revision.is_some() {
-            if self.revision.as_ref().unwrap().is_empty() {
-                return Err(Error::msg("revision is empty"));
-            }
+        if self.revision.is_some() && self.revision.as_ref().unwrap().is_empty() {
+            return Err(Error::msg("revision is empty"));
         }
-        return Ok(());
+        Ok(())
     }
 
     pub fn trim(&mut self) {
@@ -116,7 +112,7 @@ impl GitSource {
 
         self.pull(target_dir)?;
 
-        return Ok(());
+        Ok(())
     }
 
     fn check_repo(&self, target_dir: &CacheDir) -> Result<bool, String> {
@@ -140,11 +136,11 @@ impl GitSource {
             r.pop();
             Ok(r == self.url)
         } else {
-            return Err(format!(
+            Err(format!(
                 "git remote get-url origin failed, status: {:?},  stderr: {:?}",
                 output.status,
                 StdioUtils::tail_n_str(StdioUtils::stderr_to_lines(&output.stderr), 5)
-            ));
+            ))
         }
     }
 
@@ -236,10 +232,10 @@ impl GitSource {
                     String::from_utf8_lossy(&suboutput.stdout)
                 ));
             }
-            return Ok(());
+            Ok(())
         };
 
-        if let Err(_) = do_checkout() {
+        if do_checkout().is_err() {
             // 如果切换分支失败,则尝试重新fetch
             if self.revision.is_some() {
                 self.set_fetch_config(target_dir)?;
@@ -250,7 +246,7 @@ impl GitSource {
             do_checkout()?;
         }
 
-        return Ok(());
+        Ok(())
     }
 
     pub fn clone_repo(&self, cache_dir: &CacheDir) -> Result<(), String> {
@@ -308,7 +304,7 @@ impl GitSource {
                 StdioUtils::tail_n_str(StdioUtils::stderr_to_lines(&suboutput.stderr), 5)
             ));
         }
-        return Ok(());
+        Ok(())
     }
 
     /// 设置fetch所有分支
@@ -333,11 +329,11 @@ impl GitSource {
                 StdioUtils::tail_n_str(StdioUtils::stderr_to_lines(&output.stderr), 5)
             ));
         }
-        return Ok(());
+        Ok(())
     }
     /// # 把浅克隆的仓库变成深克隆
     fn unshallow(&self, target_dir: &CacheDir) -> Result<(), String> {
-        if self.is_shallow(target_dir)? == false {
+        if !(self.is_shallow(target_dir)?) {
             return Ok(());
         }
 
@@ -361,7 +357,7 @@ impl GitSource {
                 StdioUtils::tail_n_str(StdioUtils::stderr_to_lines(&output.stderr), 5)
             ));
         }
-        return Ok(());
+        Ok(())
     }
 
     /// 判断当前仓库是否是浅克隆
@@ -385,7 +381,7 @@ impl GitSource {
         }
 
         let is_shallow = String::from_utf8_lossy(&output.stdout).trim() == "true";
-        return Ok(is_shallow);
+        Ok(is_shallow)
     }
 
     fn fetch_all(&self, target_dir: &CacheDir) -> Result<(), String> {
@@ -412,12 +408,12 @@ impl GitSource {
             ));
         }
 
-        return Ok(());
+        Ok(())
     }
 
     fn pull(&self, target_dir: &CacheDir) -> Result<(), String> {
         // 如果没有指定branch,则不执行pull
-        if !self.branch.is_some() {
+        if self.branch.is_none() {
             return Ok(());
         }
         info!("git pulling: {}", target_dir.path.display());
@@ -445,7 +441,7 @@ impl GitSource {
             ));
         }
 
-        return Ok(());
+        Ok(())
     }
 }
 
@@ -480,7 +476,7 @@ impl LocalSource {
             }
         }
 
-        return Ok(());
+        Ok(())
     }
 
     pub fn trim(&mut self) {}
@@ -518,7 +514,7 @@ impl ArchiveSource {
         } else {
             return Err(Error::msg(format!("url {:?} is not a valid url", self.url)));
         }
-        return Ok(());
+        Ok(())
     }
 
     pub fn trim(&mut self) {
@@ -565,7 +561,7 @@ impl ArchiveSource {
         archive_file.unzip()?;
         //删除创建的临时文件夹
         std::fs::remove_dir_all(path).map_err(|e| e.to_string())?;
-        return Ok(());
+        Ok(())
     }
 }
 
@@ -642,7 +638,7 @@ impl ArchiveFile {
             }
 
             ArchiveType::Zip => {
-                let file = File::open(&self.archive_path.join(&self.archive_name))
+                let file = File::open(self.archive_path.join(&self.archive_name))
                     .map_err(|e| e.to_string())?;
                 let mut archive = ZipArchive::new(file).map_err(|e| e.to_string())?;
                 for i in 0..archive.len() {
@@ -656,7 +652,7 @@ impl ArchiveFile {
                     } else {
                         if let Some(p) = outpath.parent() {
                             if !p.exists() {
-                                std::fs::create_dir_all(&p).map_err(|e| e.to_string())?;
+                                std::fs::create_dir_all(p).map_err(|e| e.to_string())?;
                             }
                         }
                         let mut outfile = File::create(&outpath).map_err(|e| e.to_string())?;
@@ -686,12 +682,12 @@ impl ArchiveFile {
         for entry in path.read_dir().map_err(|e| e.to_string())? {
             let entry = entry.map_err(|e| e.to_string())?;
             let path = entry.path();
-            FileUtils::move_files(&path, &self.archive_path.parent().unwrap())
+            FileUtils::move_files(&path, self.archive_path.parent().unwrap())
                 .map_err(|e| e.to_string())?;
             //删除空的单独文件夹
             std::fs::remove_dir_all(&path).map_err(|e| e.to_string())?;
         }
-        return Ok(());
+        Ok(())
     }
 }
 

+ 1 - 1
dadk-user/src/executor/tests.rs

@@ -39,7 +39,7 @@ fn setup_executor<T: TestContextExt>(config_file: PathBuf, ctx: &T) -> Executor
     assert!(executor.is_ok(), "Create executor error: {:?}", executor);
 
     let executor = executor.unwrap();
-    return executor;
+    executor
 }
 
 /// 测试能否正确设置本地环境变量

+ 6 - 6
dadk-user/src/parser/mod.rs

@@ -147,7 +147,7 @@ impl Parser {
         if r.is_err() {
             error!("Error while parsing config files: {:?}", r);
         }
-        return r;
+        r
     }
 
     /// # 扫描配置文件目录,找到所有配置文件
@@ -158,9 +158,9 @@ impl Parser {
         // 将config目录加入队列
         dir_queue.push(self.config_dir.clone());
 
-        while !dir_queue.is_empty() {
+        while let Some(dir) = dir_queue.pop() {
             // 扫描目录,找到所有*.dadk文件
-            let dir = dir_queue.pop().unwrap();
+            
             let entries: ReadDir = std::fs::read_dir(&dir)?;
 
             for entry in entries {
@@ -184,7 +184,7 @@ impl Parser {
             }
         }
 
-        return Ok(());
+        Ok(())
     }
 
     /// # 解析所有配置文件,生成任务列表
@@ -203,7 +203,7 @@ impl Parser {
             result_vec.push((config_file.clone(), task));
         }
 
-        return Ok(result_vec);
+        Ok(result_vec)
     }
 
     /// # 解析单个配置文件,生成任务
@@ -227,7 +227,7 @@ impl Parser {
         // 校验DADKTask的参数是否合法
         task.validate()?;
 
-        return Ok(task);
+        Ok(task)
     }
 
     /// 解析toml文件,生成DADKTask

+ 10 - 10
dadk-user/src/parser/task.rs

@@ -118,7 +118,7 @@ impl DADKTask {
         self.validate_envs()?;
         self.validate_target_arch()?;
 
-        return Ok(());
+        Ok(())
     }
 
     pub fn trim(&mut self) {
@@ -137,7 +137,7 @@ impl DADKTask {
         for depend in &self.depends {
             depend.validate()?;
         }
-        return Ok(());
+        Ok(())
     }
 
     fn trim_depends(&mut self) {
@@ -152,14 +152,14 @@ impl DADKTask {
                 env.validate()?;
             }
         }
-        return Ok(());
+        Ok(())
     }
 
     fn validate_target_arch(&self) -> Result<()> {
         if self.target_arch.is_empty() {
             return Err(anyhow::Error::msg("target_arch is empty"));
         }
-        return Ok(());
+        Ok(())
     }
 
     fn trim_envs(&mut self) {
@@ -186,7 +186,7 @@ impl DADKTask {
                 }
             }
         }
-        return Ok(());
+        Ok(())
     }
 
     pub fn name_version(&self) -> String {
@@ -194,11 +194,11 @@ impl DADKTask {
         for (src, dst) in &NAME_VERSION_REPLACE_TABLE {
             name_version = name_version.replace(src, dst);
         }
-        return name_version;
+        name_version
     }
 
     pub fn name_version_env(&self) -> String {
-        return Self::name_version_uppercase(&self.name, &self.version);
+        Self::name_version_uppercase(&self.name, &self.version)
     }
 
     pub fn name_version_uppercase(name: &str, version: &str) -> String {
@@ -206,7 +206,7 @@ impl DADKTask {
         for (src, dst) in &NAME_VERSION_REPLACE_TABLE {
             name_version = name_version.replace(src, dst);
         }
-        return name_version;
+        name_version
     }
 
     /// # 获取源码目录
@@ -219,7 +219,7 @@ impl DADKTask {
                     return Some(lc.path().clone());
                 }
                 _ => {
-                    return None;
+                    None
                 }
             },
             TaskType::InstallFromPrebuilt(ps) => match ps {
@@ -227,7 +227,7 @@ impl DADKTask {
                     return Some(lc.path().clone());
                 }
                 _ => {
-                    return None;
+                    None
                 }
             },
         }

+ 6 - 0
dadk-user/src/parser/task_log.rs

@@ -32,6 +32,12 @@ where
     Ok(r.unwrap_or_default())
 }
 
+impl Default for TaskLog {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
 impl TaskLog {
     pub fn new() -> Self {
         Self {

+ 28 - 23
dadk-user/src/scheduler/mod.rs

@@ -109,7 +109,7 @@ impl SchedEntity {
                 zero_child.push(child.clone());
             }
         }
-        return zero_child;
+        zero_child
     }
 }
 
@@ -122,6 +122,12 @@ pub struct SchedEntities {
     id2entity: RwLock<BTreeMap<i32, Arc<SchedEntity>>>,
 }
 
+impl Default for SchedEntities {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
 impl SchedEntities {
     pub fn new() -> Self {
         Self {
@@ -147,7 +153,7 @@ impl SchedEntities {
                 return Some(e.1.clone());
             }
         }
-        return None;
+        None
     }
 
     pub fn entities(&self) -> Vec<Arc<SchedEntity>> {
@@ -155,7 +161,7 @@ impl SchedEntities {
         for e in self.id2entity.read().unwrap().iter() {
             v.push(e.1.clone());
         }
-        return v;
+        v
     }
 
     pub fn id2entity(&self) -> BTreeMap<i32, Arc<SchedEntity>> {
@@ -192,7 +198,7 @@ impl SchedEntities {
                 }
             }
         }
-        return result;
+        result
     }
 
     fn dfs(
@@ -244,7 +250,7 @@ impl SchedEntities {
         }
         visited.insert(entity.id(), true);
         result.push(entity.clone());
-        return Ok(());
+        Ok(())
     }
 }
 
@@ -316,7 +322,7 @@ impl Scheduler {
             return Err(r.err().unwrap());
         }
 
-        return Ok(scheduler);
+        Ok(scheduler)
     }
 
     /// # 添加多个任务
@@ -333,7 +339,7 @@ impl Scheduler {
             }
         }
 
-        return Ok(());
+        Ok(())
     }
 
     /// # 任务是否匹配当前目标架构
@@ -387,12 +393,12 @@ impl Scheduler {
         self.target.add(entity.clone());
 
         info!("Task added: {}", entity.task().name_version());
-        return Ok(entity);
+        Ok(entity)
     }
 
     fn generate_task_id(&self) -> i32 {
         static TASK_ID: AtomicI32 = AtomicI32::new(0);
-        return TASK_ID.fetch_add(1, Ordering::SeqCst);
+        TASK_ID.fetch_add(1, Ordering::SeqCst)
     }
 
     /// # 执行调度器中的所有任务
@@ -408,7 +414,7 @@ impl Scheduler {
             Action::Clean(_) => self.run_without_topo_sort()?,
         }
 
-        return Ok(());
+        Ok(())
     }
 
     /// Action需要按照拓扑序执行
@@ -425,7 +431,7 @@ impl Scheduler {
         // 对调度实体进行拓扑排序
         let r: Vec<Arc<SchedEntity>> = self.target.topo_sort();
 
-        let action = self.action.clone();
+        let action = self.action;
         let dragonos_dir = self.sysroot_dir.clone();
         let id2entity = self.target.id2entity();
         let count = r.len();
@@ -437,13 +443,13 @@ impl Scheduler {
 
         handler.join().expect("Could not join deamon");
 
-        return Ok(());
+        Ok(())
     }
 
     /// Action不需要按照拓扑序执行
     fn run_without_topo_sort(&self) -> Result<(), SchedulerError> {
         // 启动守护线程
-        let action = self.action.clone();
+        let action = self.action;
         let dragonos_dir = self.sysroot_dir.clone();
         let mut r = self.target.entities();
         let handler = std::thread::spawn(move || {
@@ -451,11 +457,11 @@ impl Scheduler {
         });
 
         handler.join().expect("Could not join deamon");
-        return Ok(());
+        Ok(())
     }
 
     pub fn execute(action: Action, dragonos_dir: PathBuf, entity: Arc<SchedEntity>) {
-        let mut executor = Executor::new(entity.clone(), action.clone(), dragonos_dir.clone())
+        let mut executor = Executor::new(entity.clone(), action, dragonos_dir.clone())
             .map_err(|e| {
                 error!(
                     "Error while creating executor for task {} : {:?}",
@@ -512,7 +518,7 @@ impl Scheduler {
             // 将入度为0的任务实体加入任务队列中,直至没有入度为0的任务实体 或 任务队列满了
             while !zero_entity.is_empty()
                 && guard.build_install_task(
-                    action.clone(),
+                    action,
                     dragonos_dir.clone(),
                     zero_entity.last().unwrap().clone(),
                 )
@@ -534,7 +540,7 @@ impl Scheduler {
                     }
                     return false;
                 }
-                return true;
+                true
             })
         }
     }
@@ -564,10 +570,9 @@ impl Scheduler {
         for entity in self.target.entities().iter() {
             for dependency in entity.task().depends.iter() {
                 let name_version = (dependency.name.clone(), dependency.version.clone());
-                if !self
+                if self
                     .target
-                    .get_by_name_version(&name_version.0, &name_version.1)
-                    .is_some()
+                    .get_by_name_version(&name_version.0, &name_version.1).is_none()
                 {
                     return Err(SchedulerError::DependencyNotFound(
                         entity.clone(),
@@ -577,7 +582,7 @@ impl Scheduler {
             }
         }
 
-        return Ok(());
+        Ok(())
     }
 }
 
@@ -634,7 +639,7 @@ impl DependencyCycleError {
         let mut tmp = self.dependencies.clone();
         tmp.reverse();
 
-        let mut ret = format!("Dependency cycle detected: \nStart ->\n");
+        let mut ret = "Dependency cycle detected: \nStart ->\n".to_string();
         for (current, dep) in tmp.iter() {
             ret.push_str(&format!(
                 "->\t{} ({})\t--depends-->\t{} ({})\n",
@@ -645,6 +650,6 @@ impl DependencyCycleError {
             ));
         }
         ret.push_str("-> End");
-        return ret;
+        ret
     }
 }

+ 3 - 3
dadk-user/src/scheduler/task_deque.rs

@@ -56,7 +56,7 @@ impl TaskDeque {
             self.queue.push(handler);
             return true;
         }
-        return false;
+        false
     }
 
     /// 将清理DADK任务添加到任务队列中
@@ -80,11 +80,11 @@ impl TaskDeque {
     }
 
     pub fn queue(&self) -> &Vec<JoinHandle<()>> {
-        return &self.queue;
+        &self.queue
     }
 
     pub fn queue_mut(&mut self) -> &mut Vec<JoinHandle<()>> {
-        return &mut self.queue;
+        &mut self.queue
     }
 
     pub fn set_thread(&mut self, mut thread: usize) {

+ 12 - 6
dadk-user/src/utils/lazy_init.rs

@@ -33,6 +33,12 @@ pub struct Lazy<T> {
     initialized: AtomicBool,
 }
 
+impl<T> Default for Lazy<T> {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
 impl<T> Lazy<T> {
     /// Creates a new `Lazy` value that will be initialized with the
     /// result of the closure `init`.
@@ -51,7 +57,7 @@ impl<T> Lazy<T> {
         if initialized {
             return true;
         }
-        return false;
+        false
     }
 
     /// Ensures that this lazy value is initialized. If the value has not
@@ -93,7 +99,7 @@ impl<T> Lazy<T> {
         if self.initialized() {
             return Some(unsafe { self.get_unchecked() });
         }
-        return None;
+        None
     }
 
     /// Forces the evaluation of this lazy value and returns a mutable
@@ -107,12 +113,12 @@ impl<T> Lazy<T> {
 
     #[inline(always)]
     pub unsafe fn get_unchecked(&self) -> &T {
-        return &*(*self.value.get()).as_ptr();
+        &*(*self.value.get()).as_ptr()
     }
 
     #[inline(always)]
     pub unsafe fn get_mut_unchecked(&mut self) -> &mut T {
-        return &mut *(*self.value.get()).as_mut_ptr();
+        &mut *(*self.value.get()).as_mut_ptr()
     }
 }
 
@@ -135,9 +141,9 @@ impl<T> DerefMut for Lazy<T> {
 impl<T: Debug> Debug for Lazy<T> {
     fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
         if let Some(value) = self.try_get() {
-            return write!(f, "Lazy({:?})", value);
+            write!(f, "Lazy({:?})", value)
         } else {
-            return write!(f, "Lazy(uninitialized)");
+            write!(f, "Lazy(uninitialized)")
         }
     }
 }

+ 2 - 2
dadk-user/src/utils/stdio.rs

@@ -14,8 +14,8 @@ impl StdioUtils {
         let start = if lines.len() > n { lines.len() - n } else { 0 };
         for line in lines.iter().skip(start) {
             result.push_str(line);
-            result.push_str("\n");
+            result.push('\n');
         }
-        return result;
+        result
     }
 }

+ 1 - 1
dadk/Cargo.toml

@@ -6,7 +6,7 @@ authors = [
     "xuzihao <xuzihao@DragonOS.org>"
 ]
 
-version = "0.3.0"
+version = "0.3.1"
 edition = "2021"
 description = "DragonOS Application Development Kit\nDragonOS应用开发工具"
 license = "GPL-2.0-only"

+ 4 - 11
dadk/src/actions/mod.rs

@@ -5,21 +5,14 @@ pub mod rootfs;
 pub mod user;
 
 pub fn run(ctx: DADKExecContext) {
+
     match &ctx.command.action {
+        
         crate::console::Action::Kernel => {
             unimplemented!("kernel command has not implemented for run yet.")
         }
         crate::console::Action::Rootfs(rootfs_command) => {
-            match ctx.manifest().metadata.builder_version.as_str() {
-                "v2" => {
-                    // v2版本的rootfs命令
-                    rootfs::v2::run(&ctx, rootfs_command).expect("Run rootfs action error.")
-                }
-                "v1" | _ => {
-                    // v1版本的rootfs命令
-                    rootfs::v1::run(&ctx, rootfs_command).expect("Run rootfs action error.")
-                }
-            }
+            rootfs::run(&ctx, rootfs_command).expect("Run rootfs action error.")
         }
         crate::console::Action::User(user_command) => {
             user::run(&ctx, user_command).expect("Run user action error.")
@@ -28,4 +21,4 @@ pub fn run(ctx: DADKExecContext) {
             profile::run(&ctx, profile_command).expect("Run profile action error.")
         }
     }
-}
+}

+ 7 - 7
dadk/src/actions/profile/mod.rs

@@ -71,7 +71,7 @@ impl Sample {
     }
 
     fn push_new_line(&mut self, line: &str) {
-        if line.starts_with("#") {
+        if line.starts_with('#') {
             self.parse_frame_line(line);
         } else {
             self.parse_thread_line(line);
@@ -81,7 +81,7 @@ impl Sample {
     fn parse_frame_line(&mut self, line: &str) {
         let line = line.trim();
         // todo: 支持调整删除的`<>`的层级,以便打印更详细的信息
-        let line = remove_angle_bracket_content(&line);
+        let line = remove_angle_bracket_content(line);
         let line = remove_guest_address(&line);
         let mut line = remove_rust_impl_pattern(&line);
         line = line.replace("(...)", "");
@@ -109,8 +109,8 @@ impl Sample {
                     .unwrap(),
             );
 
-            if !self.data.contains_key(&self.current_cpu.unwrap()) {
-                self.data.insert(self.current_cpu.unwrap(), Vec::new());
+            if let std::collections::btree_map::Entry::Vacant(e) = self.data.entry(self.current_cpu.unwrap()) {
+                e.insert(Vec::new());
             } else {
                 log::error!(
                     "current cpu {} is already set in hashmap",
@@ -395,10 +395,10 @@ impl ToString for FoldedSampleBuffer {
     }
 }
 
-impl Into<SampleBuffer> for FoldedSampleBuffer {
-    fn into(self) -> SampleBuffer {
+impl From<FoldedSampleBuffer> for SampleBuffer {
+    fn from(val: FoldedSampleBuffer) -> Self {
         let mut samples = SampleBuffer::new();
-        for (stack, count) in self.data {
+        for (stack, count) in val.data {
             let mut sample = Sample::new(0, 0);
             for frame in stack.split(';').rev() {
                 sample.push_new_line(frame);

+ 231 - 118
dadk/src/actions/rootfs/v1/disk_img.rs → dadk/src/actions/rootfs/disk_img.rs

@@ -1,10 +1,29 @@
+use std::sync::OnceLock;
 use std::{fs::File, io::Write, mem::ManuallyDrop, path::PathBuf, process::Command};
 
 use crate::context::DADKExecContext;
 use anyhow::{anyhow, Result};
 use dadk_config::rootfs::{fstype::FsType, partition::PartitionType};
 
-use super::loopdev::LoopDeviceBuilder;
+use super::loopdev_v1::LoopDeviceBuilder as LoopDeviceBuilderV1;
+use super::loopdev_v2::LoopDeviceBuilder as LoopDeviceBuilderV2;
+use crate::actions::rootfs::BuilderVersion;
+pub static BUILDER_VERSION: OnceLock<BuilderVersion> = OnceLock::new();
+
+pub fn set_builder_version(ctx: &DADKExecContext) {
+    let version = BuilderVersion::from_str(ctx.manifest().metadata.builder_version.as_str());
+    BUILDER_VERSION.set(version).expect("Failed to set builder version");
+    log::info!("Current builder version: {:?}", get_builder_version());
+}
+pub fn get_builder_version() -> BuilderVersion{
+    log::info!("Current builder version: {:?}", BUILDER_VERSION.get());
+
+    BUILDER_VERSION.get()
+                    .cloned()
+                    .unwrap_or(BuilderVersion::V1) 
+}  
+
+   
 pub(super) fn create(ctx: &DADKExecContext, skip_if_exists: bool) -> Result<()> {
     let disk_image_path = ctx.disk_image_path();
     if disk_image_path.exists() {
@@ -36,7 +55,6 @@ pub(super) fn create(ctx: &DADKExecContext, skip_if_exists: bool) -> Result<()>
     }
     r
 }
-
 pub(super) fn delete(ctx: &DADKExecContext, skip_if_not_exists: bool) -> Result<()> {
     let disk_image_path = ctx.disk_image_path();
     if !disk_image_path.exists() {
@@ -54,7 +72,6 @@ pub(super) fn delete(ctx: &DADKExecContext, skip_if_not_exists: bool) -> Result<
         .map_err(|e| anyhow!("Failed to remove disk image: {}", e))?;
     Ok(())
 }
-
 pub fn mount(ctx: &DADKExecContext) -> Result<()> {
     let disk_image_path = ctx.disk_image_path();
     if !disk_image_path.exists() {
@@ -79,30 +96,6 @@ pub fn mount(ctx: &DADKExecContext) -> Result<()> {
     log::info!("Disk image mounted at {}", disk_mount_path.display());
     Ok(())
 }
-
-fn mount_partitioned_image(
-    ctx: &DADKExecContext,
-    disk_image_path: &PathBuf,
-    disk_mount_path: &PathBuf,
-) -> Result<()> {
-    let mut loop_device = ManuallyDrop::new(
-        LoopDeviceBuilder::new()
-            .img_path(disk_image_path.clone())
-            .detach_on_drop(false)
-            .build()
-            .map_err(|e| anyhow!("Failed to create loop device: {}", e))?,
-    );
-
-    loop_device
-        .attach()
-        .map_err(|e| anyhow!("mount: Failed to attach loop device: {}", e))?;
-
-    let dev_path = loop_device.partition_path(1)?;
-    mount_unpartitioned_image(ctx, &dev_path, disk_mount_path)?;
-
-    Ok(())
-}
-
 fn mount_unpartitioned_image(
     _ctx: &DADKExecContext,
     disk_image_path: &PathBuf,
@@ -121,61 +114,6 @@ fn mount_unpartitioned_image(
     }
     Ok(())
 }
-
-pub fn umount(ctx: &DADKExecContext) -> Result<()> {
-    let disk_img_path = ctx.disk_image_path();
-    let disk_mount_path = ctx.disk_mount_path();
-    let mut loop_device = LoopDeviceBuilder::new().img_path(disk_img_path).build();
-
-    let should_detach_loop_device: bool;
-    if let Ok(loop_device) = loop_device.as_mut() {
-        if let Err(e) = loop_device.attach_by_exists() {
-            log::trace!("umount: Failed to attach loop device: {}", e);
-        }
-
-        should_detach_loop_device = loop_device.attached();
-    } else {
-        should_detach_loop_device = false;
-    }
-
-    if disk_mount_path.exists() {
-        let cmd = Command::new("umount")
-            .arg(disk_mount_path)
-            .output()
-            .map_err(|e| anyhow!("Failed to umount disk image: {}", e));
-        match cmd {
-            Ok(cmd) => {
-                if !cmd.status.success() {
-                    let e = anyhow!(
-                        "Failed to umount disk image: {}",
-                        String::from_utf8_lossy(&cmd.stderr)
-                    );
-                    if should_detach_loop_device {
-                        log::error!("{}", e);
-                    } else {
-                        return Err(e);
-                    }
-                }
-            }
-            Err(e) => {
-                if should_detach_loop_device {
-                    log::error!("{}", e);
-                } else {
-                    return Err(e);
-                }
-            }
-        }
-    }
-
-    if let Ok(loop_device) = loop_device {
-        let loop_dev_path = loop_device.dev_path().cloned();
-
-        log::info!("Loop device going to detached: {:?}", loop_dev_path);
-    }
-
-    Ok(())
-}
-
 /// Ensures the provided disk image path is not a device node.
 fn disk_path_safety_check(disk_image_path: &PathBuf) -> Result<()> {
     const DONT_ALLOWED_PREFIX: [&str; 5] =
@@ -192,30 +130,11 @@ fn disk_path_safety_check(disk_image_path: &PathBuf) -> Result<()> {
     Ok(())
 }
 
-fn create_partitioned_image(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
-    let part_type = ctx.rootfs().partition.partition_type;
-    DiskPartitioner::create_partitioned_image(disk_image_path, part_type)?;
-    // 挂载loop设备
-    let mut loop_device = LoopDeviceBuilder::new()
-        .img_path(disk_image_path.clone())
-        .build()
-        .map_err(|e| anyhow!("Failed to create loop device: {}", e))?;
-    loop_device
-        .attach()
-        .map_err(|e| anyhow!("creat: Failed to attach loop device: {}", e))?;
-
-    let partition_path = loop_device.partition_path(1)?;
-    let fs_type = ctx.rootfs().metadata.fs_type;
-    DiskFormatter::format_disk(&partition_path, &fs_type)?;
-    Ok(())
-}
-
 fn create_unpartitioned_image(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
     // 直接对整块磁盘镜像进行格式化
     let fs_type = ctx.rootfs().metadata.fs_type;
     DiskFormatter::format_disk(disk_image_path, &fs_type)
 }
-
 /// 创建全0的raw镜像
 fn create_raw_img(disk_image_path: &PathBuf, image_size: usize) -> Result<()> {
     log::trace!("Creating raw disk image: {}", disk_image_path.display());
@@ -242,7 +161,6 @@ fn create_raw_img(disk_image_path: &PathBuf, image_size: usize) -> Result<()> {
 
     Ok(())
 }
-
 pub fn check_disk_image_exists(ctx: &DADKExecContext) -> Result<()> {
     let disk_image_path = ctx.disk_image_path();
     if disk_image_path.exists() {
@@ -258,21 +176,6 @@ pub fn show_mount_point(ctx: &DADKExecContext) -> Result<()> {
     println!("{}", disk_mount_path.display());
     Ok(())
 }
-
-pub fn show_loop_device(ctx: &DADKExecContext) -> Result<()> {
-    let disk_image_path = ctx.disk_image_path();
-    let mut loop_device = LoopDeviceBuilder::new()
-        .detach_on_drop(false)
-        .img_path(disk_image_path)
-        .build()?;
-    if let Err(e) = loop_device.attach_by_exists() {
-        log::error!("Failed to attach loop device: {}", e);
-    } else {
-        println!("{}", loop_device.dev_path().unwrap());
-    }
-    Ok(())
-}
-
 struct DiskPartitioner;
 
 impl DiskPartitioner {
@@ -357,6 +260,216 @@ impl DiskFormatter {
     }
 }
 
+
+fn mount_partitioned_image(
+    ctx: &DADKExecContext,
+    disk_image_path: &PathBuf,
+    disk_mount_path: &PathBuf,
+) -> Result<()> {
+    match get_builder_version() {
+        BuilderVersion::V2 => mount_partitioned_image_v2(ctx, disk_image_path, disk_mount_path),
+        BuilderVersion::V1 => mount_partitioned_image_v1(ctx, disk_image_path, disk_mount_path),
+    }
+}
+fn create_partitioned_image(
+    ctx: &DADKExecContext,
+    disk_image_path: &PathBuf,
+) -> Result<()> {
+    match get_builder_version() {
+        BuilderVersion::V2 => create_partitioned_image_v2(ctx, disk_image_path),
+        BuilderVersion::V1 => create_partitioned_image_v1(ctx, disk_image_path),   
+    } 
+}
+
+
+pub fn show_loop_device(ctx: &DADKExecContext) -> Result<()> {
+    match BUILDER_VERSION.get().expect("Builder version is not set").clone() {
+        BuilderVersion::V2 => show_loop_device_v2(ctx),
+        BuilderVersion::V1 => show_loop_device_v1(ctx),   
+        } 
+}
+
+fn mount_partitioned_image_v1(
+    ctx: &DADKExecContext,
+    disk_image_path: &PathBuf,
+    disk_mount_path: &PathBuf,
+) -> Result<()> {
+    let mut loop_device = ManuallyDrop::new(
+        LoopDeviceBuilderV1::new()
+            .img_path(disk_image_path.clone())
+            .detach_on_drop(false)
+            .build()
+            .map_err(|e| anyhow!("Failed to create loop device: {}", e))?,
+    );
+
+    loop_device
+        .attach()
+        .map_err(|e| anyhow!("mount: Failed to attach loop device: {}", e))?;
+
+    let dev_path = loop_device.partition_path(1)?;
+    mount_unpartitioned_image(ctx, &dev_path, disk_mount_path)?;
+
+    Ok(())
+}
+fn mount_partitioned_image_v2(
+    ctx: &DADKExecContext,
+    disk_image_path: &PathBuf,
+    disk_mount_path: &PathBuf,
+) -> Result<()> {
+    let loop_device = ManuallyDrop::new(
+        LoopDeviceBuilderV2::new()
+            .img_path(disk_image_path.clone())
+            .detach_on_drop(false)
+            .build()
+            .map_err(|e| anyhow!("Failed to create loop device: {}", e))?,
+    );
+
+    let dev_path = loop_device.partition_path(1)?;
+    mount_unpartitioned_image(ctx, &dev_path, disk_mount_path)?;
+
+    Ok(())
+}
+pub fn umount(ctx: &DADKExecContext) -> Result<()> {
+    match get_builder_version() {
+    BuilderVersion::V2 => umount_v2(ctx),
+    BuilderVersion::V1 => umount_v1(ctx),   
+    }   
+}
+pub fn umount_v1(ctx: &DADKExecContext) -> Result<()> {
+    let disk_img_path = ctx.disk_image_path();
+    let disk_mount_path = ctx.disk_mount_path();
+    let mut loop_device = LoopDeviceBuilderV1::new().img_path(disk_img_path).build();
+    let should_detach_loop_device: bool;
+    if let Ok(loop_device ) =loop_device.as_mut() {
+        if let Err(e) = loop_device.attach_by_exists() {
+            log::trace!("umount: Failed to attach loop device: {}", e);
+        }
+
+        should_detach_loop_device = loop_device.attached();
+    } else {
+        should_detach_loop_device = false;
+    }
+
+    if disk_mount_path.exists() {
+        let cmd = Command::new("umount")
+            .arg(disk_mount_path)
+            .output()
+            .map_err(|e| anyhow!("Failed to umount disk image: {}", e));
+        match cmd {
+            Ok(cmd) => {
+                if !cmd.status.success() {
+                    let e = anyhow!(
+                        "Failed to umount disk image: {}",
+                        String::from_utf8_lossy(&cmd.stderr)
+                    );
+                    if should_detach_loop_device {
+                        log::error!("{}", e);
+                    } else {
+                        return Err(e);
+                    }
+                }
+            }
+            Err(e) => {
+                if should_detach_loop_device {
+                    log::error!("{}", e);
+                } else {
+                    return Err(e);
+                }
+            }
+        }
+    }
+
+    if let Ok(loop_device) = loop_device {
+        let loop_dev_path = loop_device.dev_path().cloned();
+
+        log::info!("Loop device going to detached: {:?}", loop_dev_path);
+    }
+
+    Ok(())
+}
+pub fn umount_v2(ctx: &DADKExecContext) -> Result<()> {
+    let disk_img_path = ctx.disk_image_path();
+    let disk_mount_path = ctx.disk_mount_path();
+
+    if disk_mount_path.exists() {
+        log::trace!("Unmounted disk image at {}", disk_mount_path.display());
+
+        let cmd = Command::new("umount").arg(disk_mount_path).output()?;
+
+        if !cmd.status.success() {
+            return Err(anyhow!(
+                "Failed to umount disk image: {}",
+                String::from_utf8_lossy(&cmd.stderr)
+            ));
+        }
+
+        let loop_device = LoopDeviceBuilderV2::new()
+            .img_path(disk_img_path)
+            .detach_on_drop(true)
+            .build()?;
+        // the loop device will be detached automatically when _loop_device is dropped
+        log::trace!("Detaching {}", loop_device.dev_path());
+        Ok(())
+    } else {
+        Err(anyhow!(
+            "Disk image mount point does not exist: {}",
+            disk_mount_path.display()
+        ))
+    }
+}
+fn create_partitioned_image_v1(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
+    let part_type = ctx.rootfs().partition.partition_type;
+    DiskPartitioner::create_partitioned_image(disk_image_path, part_type)?;
+    // 挂载loop设备
+    let mut loop_device = LoopDeviceBuilderV1::new()
+        .img_path(disk_image_path.clone())
+        .build()
+        .map_err(|e| anyhow!("Failed to create loop device: {}", e))?;
+    loop_device
+        .attach()
+        .map_err(|e| anyhow!("creat: Failed to attach loop device: {}", e))?;
+
+    let partition_path = loop_device.partition_path(1)?;
+    let fs_type = ctx.rootfs().metadata.fs_type;
+    DiskFormatter::format_disk(&partition_path, &fs_type)?;
+    Ok(())
+}
+fn create_partitioned_image_v2(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
+    let part_type = ctx.rootfs().partition.partition_type;
+    DiskPartitioner::create_partitioned_image(disk_image_path, part_type)?;
+    // 挂载loop设备
+    let loop_device = LoopDeviceBuilderV2::new()
+        .img_path(disk_image_path.clone())
+        .detach_on_drop(false)
+        .build()?;
+
+    let partition_path = loop_device.partition_path(1)?;
+    let fs_type = ctx.rootfs().metadata.fs_type;
+    DiskFormatter::format_disk(&partition_path, &fs_type)?;
+    Ok(())
+}
+pub fn show_loop_device_v1(ctx: &DADKExecContext) -> Result<()> {
+    let disk_image_path = ctx.disk_image_path();
+    let mut loop_device = LoopDeviceBuilderV1::new()
+        .detach_on_drop(false)
+        .img_path(disk_image_path)
+        .build()?;
+    if let Err(e) = loop_device.attach_by_exists() {
+        log::error!("Failed to attach loop device: {}", e);
+    } else {
+        println!("{}", loop_device.dev_path().unwrap());
+    }
+    Ok(())
+}
+pub fn show_loop_device_v2(ctx: &DADKExecContext) -> Result<()> {
+    let disk_image_path = ctx.disk_image_path();
+    let loop_device = LoopDeviceBuilderV2::new()
+        .img_path(disk_image_path)
+        .detach_on_drop(false)
+        .build()?;
+    println!("{}", loop_device.dev_path());
+    Ok(())
+}
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -461,4 +574,4 @@ mod tests {
 
         Ok(())
     }
-}
+}

+ 1 - 1
dadk/src/actions/rootfs/v1/loopdev.rs → dadk/src/actions/rootfs/loopdev_v1.rs

@@ -145,7 +145,7 @@ impl LoopDevice {
 
         let output = Command::new("losetup").arg("-d").arg(&loop_device).output();
 
-        if !output.is_ok() {
+        if output.is_err() {
             log::error!(
                 "losetup failed to detach loop device [{}]: {}",
                 &loop_device,

+ 123 - 114
dadk/src/actions/rootfs/v2/loopdev.rs → dadk/src/actions/rootfs/loopdev_v2.rs

@@ -7,42 +7,89 @@ use crate::utils::abs_path;
 
 const LOOP_DEVICE_LOSETUP_A_REGEX: &str = r"^/dev/loop(\d+)";
 
-#[derive(Debug)]
-pub enum LoopError {
-    InvalidUtf8,
-    ImageNotFound,
-    LoopDeviceNotFound,
-    NoMapperAvailable,
-    NoPartitionAvailable,
-    Losetup(String),
-    Kpartx(String),
-    #[allow(dead_code)]
-    Other(anyhow::Error),
+
+pub struct LoopDevice {
+    path: PathBuf,
+    detach_on_drop: bool,
+    mapper: Mapper,
 }
 
-impl From<std::string::FromUtf8Error> for LoopError {
-    fn from(_: std::string::FromUtf8Error) -> Self {
-        LoopError::InvalidUtf8
+impl LoopDevice {
+    fn new(img_path: PathBuf, detach_on_drop: bool) -> Result<Self, LoopError> {
+        if !img_path.exists() {
+            return Err(LoopError::ImageNotFound);
+        }
+        let str_img_path = img_path.to_str().ok_or(LoopError::InvalidUtf8)?;
+
+        let may_attach = attach_exists_loop_by_image(str_img_path);
+
+        let loop_device_path = match may_attach {
+            Ok(loop_device_path) => {
+                log::trace!("Loop device already attached: {}", loop_device_path);
+                loop_device_path
+            }
+            Err(LoopError::LoopDeviceNotFound) => {
+                log::trace!("No loop device found, try to attach");
+                attach_loop_by_image(str_img_path)?
+            }
+            Err(err) => {
+                log::error!("Failed to attach loop device: {}", err);
+                return Err(err);
+            }
+        };
+
+        let path = PathBuf::from(loop_device_path);
+        sleep(Duration::from_millis(100));
+        if !path.exists() {
+            return Err(LoopError::LoopDeviceNotFound);
+        }
+
+        let mapper = Mapper::new(path.clone(), detach_on_drop)?;
+
+        Ok(Self {
+            path,
+            detach_on_drop,
+            mapper,
+        })
     }
-}
 
-impl std::fmt::Display for LoopError {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        match self {
-            LoopError::InvalidUtf8 => write!(f, "Invalid UTF-8"),
-            LoopError::ImageNotFound => write!(f, "Image not found"),
-            LoopError::LoopDeviceNotFound => write!(f, "Loop device not found"),
-            LoopError::NoMapperAvailable => write!(f, "No mapper available"),
-            LoopError::NoPartitionAvailable => write!(f, "No partition available"),
-            LoopError::Losetup(err) => write!(f, "Losetup error: {}", err),
-            LoopError::Kpartx(err) => write!(f, "Kpartx error: {}", err),
-            LoopError::Other(err) => write!(f, "Other error: {}", err),
+    pub fn dev_path(&self) -> String {
+        self.path.to_string_lossy().to_string()
+    }
+
+    pub fn partition_path(&self, nth: u8) -> Result<PathBuf, LoopError> {
+        self.mapper.partition_path(nth)
+    }
+
+    // #[allow(dead_code)]
+    // pub fn detach_on_drop(&self) -> bool {
+    //     self.detach_on_drop
+    // }
+
+    // #[allow(dead_code)]
+    // pub fn set_detach_on_drop(&mut self, detach_on_drop: bool) {
+    //     self.detach_on_drop = detach_on_drop;
+    // }
+}
+impl Drop for LoopDevice {
+    fn drop(&mut self) {
+        if !self.detach_on_drop {
+            return;
+        }
+        log::trace!(
+            "Detach loop device: {}, exists: {}",
+            &self.path.display(),
+            self.path.exists()
+        );
+        if self.path.exists() {
+            let path = self.path.to_string_lossy();
+            if let Err(err) = LosetupCmd::new().arg("-d").arg(&path).output() {
+                log::error!("Failed to detach loop device: {}", err);
+            }
         }
     }
 }
 
-impl std::error::Error for LoopError {}
-
 pub struct LoopDeviceBuilder {
     img_path: Option<PathBuf>,
     // loop_device_path: Option<String>,
@@ -82,26 +129,10 @@ impl LoopDeviceBuilder {
         );
 
         let loop_device = LoopDevice::new(img_path, self.detach_on_drop)?;
-        return Ok(loop_device);
+        Ok(loop_device)
     }
 }
 
-fn attach_loop_by_image(img_path: &str) -> Result<String, LoopError> {
-    LosetupCmd::new()
-        .arg("-f")
-        .arg("--show")
-        .arg("-P")
-        .arg(img_path)
-        .output()
-        .map(|output_path| output_path.trim().to_string())
-}
-
-fn attach_exists_loop_by_image(img_path: &str) -> Result<String, LoopError> {
-    // losetup -a 查看是否有已经attach了的,如果有,就附着上去
-    let output = LosetupCmd::new().arg("-a").output()?;
-
-    __loop_device_path_by_disk_image_path(img_path, &output)
-}
 
 fn __loop_device_path_by_disk_image_path(
     disk_img_path: &str,
@@ -122,90 +153,68 @@ fn __loop_device_path_by_disk_image_path(
         return Ok(loop_device);
     }
     Err(LoopError::LoopDeviceNotFound)
+} 
+#[derive(Debug)]
+pub enum LoopError {
+    InvalidUtf8,
+    ImageNotFound,
+    LoopDeviceNotFound,
+    NoMapperAvailable,
+    NoPartitionAvailable,
+    Losetup(String),
+    Kpartx(String),
+    #[allow(dead_code)]
+    Other(anyhow::Error),
 }
 
-pub struct LoopDevice {
-    path: PathBuf,
-    detach_on_drop: bool,
-    mapper: Mapper,
+impl From<std::string::FromUtf8Error> for LoopError {
+    fn from(_: std::string::FromUtf8Error) -> Self {
+        LoopError::InvalidUtf8
+    }
 }
 
-impl LoopDevice {
-    fn new(img_path: PathBuf, detach_on_drop: bool) -> Result<Self, LoopError> {
-        if !img_path.exists() {
-            return Err(LoopError::ImageNotFound);
+impl std::fmt::Display for LoopError {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            LoopError::InvalidUtf8 => write!(f, "Invalid UTF-8"),
+            LoopError::ImageNotFound => write!(f, "Image not found"),
+            LoopError::LoopDeviceNotFound => write!(f, "Loop device not found"),
+            LoopError::NoMapperAvailable => write!(f, "No mapper available"),
+            LoopError::NoPartitionAvailable => write!(f, "No partition available"),
+            LoopError::Losetup(err) => write!(f, "Losetup error: {}", err),
+            LoopError::Kpartx(err) => write!(f, "Kpartx error: {}", err),
+            LoopError::Other(err) => write!(f, "Other error: {}", err),
         }
-        let str_img_path = img_path.to_str().ok_or(LoopError::InvalidUtf8)?;
+    }
+}
 
-        let may_attach = attach_exists_loop_by_image(str_img_path);
+impl std::error::Error for LoopError {}
 
-        let loop_device_path = match may_attach {
-            Ok(loop_device_path) => {
-                log::trace!("Loop device already attached: {}", loop_device_path);
-                loop_device_path
-            }
-            Err(LoopError::LoopDeviceNotFound) => {
-                log::trace!("No loop device found, try to attach");
-                attach_loop_by_image(str_img_path)?
-            }
-            Err(err) => {
-                log::error!("Failed to attach loop device: {}", err);
-                return Err(err);
-            }
-        };
 
-        let path = PathBuf::from(loop_device_path);
-        sleep(Duration::from_millis(100));
-        if !path.exists() {
-            return Err(LoopError::LoopDeviceNotFound);
-        }
 
-        let mapper = Mapper::new(path.clone(), detach_on_drop)?;
 
-        Ok(Self {
-            path,
-            detach_on_drop,
-            mapper,
-        })
-    }
+fn attach_loop_by_image(img_path: &str) -> Result<String, LoopError> {
+    LosetupCmd::new()
+        .arg("-f")
+        .arg("--show")
+        .arg("-P")
+        .arg(img_path)
+        .output()
+        .map(|output_path| output_path.trim().to_string())
+}
+
+fn attach_exists_loop_by_image(img_path: &str) -> Result<String, LoopError> {
+    // losetup -a 查看是否有已经attach了的,如果有,就附着上去
+    let output = LosetupCmd::new().arg("-a").output()?;
+
+    __loop_device_path_by_disk_image_path(img_path, &output)
+}
+
 
-    pub fn dev_path(&self) -> String {
-        self.path.to_string_lossy().to_string()
-    }
 
-    pub fn partition_path(&self, nth: u8) -> Result<PathBuf, LoopError> {
-        self.mapper.partition_path(nth)
-    }
 
-    // #[allow(dead_code)]
-    // pub fn detach_on_drop(&self) -> bool {
-    //     self.detach_on_drop
-    // }
 
-    // #[allow(dead_code)]
-    // pub fn set_detach_on_drop(&mut self, detach_on_drop: bool) {
-    //     self.detach_on_drop = detach_on_drop;
-    // }
-}
 
-impl Drop for LoopDevice {
-    fn drop(&mut self) {
-        if !self.detach_on_drop {
-            return;
-        }
-        log::trace!(
-            "Detach loop device: {}, exists: {}",
-            &self.path.display(),
-            self.path.exists()
-        );
-        if self.path.exists() {
-            let path = self.path.to_string_lossy();
-            if let Err(err) = LosetupCmd::new().arg("-d").arg(&path).output() {
-                log::error!("Failed to detach loop device: {}", err);
-            }
-        }
-    }
-}
 
 struct LosetupCmd {
     inner: Command,

+ 35 - 2
dadk/src/actions/rootfs/mod.rs

@@ -1,2 +1,35 @@
-pub mod v1;
-pub mod v2;
+use crate::{console::rootfs::RootFSCommand, context::DADKExecContext};
+use anyhow::Result;
+use disk_img::set_builder_version;
+
+pub mod disk_img;
+mod loopdev_v1;
+mod loopdev_v2;
+mod sysroot;
+#[derive(Debug, PartialEq, Eq, Clone)]
+pub enum BuilderVersion {
+    V1,
+    V2,
+}
+impl BuilderVersion {
+    fn from_str(version: &str) -> Self {
+        match version {
+            "v2" => BuilderVersion::V2,
+            "v1" | _ => BuilderVersion::V1,
+            
+        }
+    }
+}
+pub fn run(ctx: &DADKExecContext, rootfs_cmd: &RootFSCommand) -> Result<()> {
+    set_builder_version(ctx);
+    match rootfs_cmd {
+        RootFSCommand::Create(param) => disk_img::create(ctx, param.skip_if_exists),
+        RootFSCommand::Delete => disk_img::delete(ctx, false),
+        RootFSCommand::DeleteSysroot => sysroot::delete(ctx),
+        RootFSCommand::Mount => disk_img::mount(ctx),
+        RootFSCommand::Umount => disk_img::umount(ctx),
+        RootFSCommand::CheckDiskImageExists => disk_img::check_disk_image_exists(ctx),
+        RootFSCommand::ShowMountPoint => disk_img::show_mount_point(ctx),
+        RootFSCommand::ShowLoopDevice => disk_img::show_loop_device(ctx),
+    }
+}

+ 1 - 1
dadk/src/actions/rootfs/v2/sysroot.rs → dadk/src/actions/rootfs/sysroot.rs

@@ -15,7 +15,7 @@ pub(super) fn delete(ctx: &DADKExecContext) -> Result<()> {
     }
 
     // 检查 sysroot_dir 是否是当前工作目录的子目录
-    if !sysroot_dir.starts_with(&ctx.workdir()) {
+    if !sysroot_dir.starts_with(ctx.workdir()) {
         return Err(anyhow!(
             "Sysroot directory must be a subdirectory of the current working directory"
         ));

+ 0 - 19
dadk/src/actions/rootfs/v1/mod.rs

@@ -1,19 +0,0 @@
-use crate::{console::rootfs::RootFSCommand, context::DADKExecContext};
-use anyhow::Result;
-
-mod disk_img;
-mod loopdev;
-mod sysroot;
-
-pub fn run(ctx: &DADKExecContext, rootfs_cmd: &RootFSCommand) -> Result<()> {
-    match rootfs_cmd {
-        RootFSCommand::Create(param) => disk_img::create(ctx, param.skip_if_exists),
-        RootFSCommand::Delete => disk_img::delete(ctx, false),
-        RootFSCommand::DeleteSysroot => sysroot::delete(ctx),
-        RootFSCommand::Mount => disk_img::mount(ctx),
-        RootFSCommand::Umount => disk_img::umount(ctx),
-        RootFSCommand::CheckDiskImageExists => disk_img::check_disk_image_exists(ctx),
-        RootFSCommand::ShowMountPoint => disk_img::show_mount_point(ctx),
-        RootFSCommand::ShowLoopDevice => disk_img::show_loop_device(ctx),
-    }
-}

+ 0 - 26
dadk/src/actions/rootfs/v1/sysroot.rs

@@ -1,26 +0,0 @@
-use anyhow::{anyhow, Result};
-
-use crate::context::DADKExecContext;
-
-pub(super) fn delete(ctx: &DADKExecContext) -> Result<()> {
-    let sysroot_dir = ctx.sysroot_dir()?;
-    // 检查 sysroot_dir 是否存在
-    if !sysroot_dir.exists() {
-        return Err(anyhow!("Sysroot directory does not exist"));
-    }
-
-    // 检查 sysroot_dir 是否是一个目录
-    if !sysroot_dir.is_dir() {
-        return Err(anyhow!("Sysroot path is not a directory"));
-    }
-
-    // 检查 sysroot_dir 是否是当前工作目录的子目录
-    if !sysroot_dir.starts_with(&ctx.workdir()) {
-        return Err(anyhow!(
-            "Sysroot directory must be a subdirectory of the current working directory"
-        ));
-    }
-
-    std::fs::remove_dir_all(sysroot_dir)?;
-    Ok(())
-}

+ 0 - 430
dadk/src/actions/rootfs/v2/disk_img.rs

@@ -1,430 +0,0 @@
-use std::{fs::File, io::Write, mem::ManuallyDrop, path::PathBuf, process::Command};
-
-use crate::context::DADKExecContext;
-use anyhow::{anyhow, Result};
-use dadk_config::rootfs::{fstype::FsType, partition::PartitionType};
-
-use super::loopdev::LoopDeviceBuilder;
-pub(super) fn create(ctx: &DADKExecContext, skip_if_exists: bool) -> Result<()> {
-    let disk_image_path = ctx.disk_image_path();
-    if disk_image_path.exists() {
-        if skip_if_exists {
-            return Ok(());
-        }
-        return Err(anyhow!(
-            "Disk image already exists: {}",
-            disk_image_path.display()
-        ));
-    }
-
-    disk_path_safety_check(&disk_image_path)?;
-
-    // 获取镜像大小
-    let image_size = ctx.disk_image_size();
-    create_raw_img(&disk_image_path, image_size).expect("Failed to create raw disk image");
-
-    // 判断是否需要分区?
-
-    let r = if ctx.rootfs().partition.image_should_be_partitioned() {
-        create_partitioned_image(ctx, &disk_image_path)
-    } else {
-        create_unpartitioned_image(ctx, &disk_image_path)
-    };
-
-    if r.is_err() {
-        std::fs::remove_file(&disk_image_path).expect("Failed to remove disk image");
-    }
-    r
-}
-
-pub(super) fn delete(ctx: &DADKExecContext, skip_if_not_exists: bool) -> Result<()> {
-    let disk_image_path = ctx.disk_image_path();
-    if !disk_image_path.exists() {
-        if skip_if_not_exists {
-            return Ok(());
-        }
-        return Err(anyhow!(
-            "Disk image does not exist: {}",
-            disk_image_path.display()
-        ));
-    }
-    disk_path_safety_check(&disk_image_path)?;
-
-    std::fs::remove_file(&disk_image_path)
-        .map_err(|e| anyhow!("Failed to remove disk image: {}", e))?;
-    Ok(())
-}
-
-pub fn mount(ctx: &DADKExecContext) -> Result<()> {
-    let disk_image_path = ctx.disk_image_path();
-    if !disk_image_path.exists() {
-        return Err(anyhow!(
-            "Disk image does not exist: {}",
-            disk_image_path.display()
-        ));
-    }
-    let disk_mount_path = ctx.disk_mount_path();
-
-    // 尝试创建挂载点
-    std::fs::create_dir_all(&disk_mount_path)
-        .map_err(|e| anyhow!("Failed to create disk mount path: {}", e))?;
-
-    let partitioned = ctx.rootfs().partition.image_should_be_partitioned();
-    log::trace!("Disk image is partitioned: {}", partitioned);
-    if partitioned {
-        mount_partitioned_image(ctx, &disk_image_path, &disk_mount_path)?
-    } else {
-        mount_unpartitioned_image(ctx, &disk_image_path, &disk_mount_path)?
-    }
-    log::info!("Disk image mounted at {}", disk_mount_path.display());
-    Ok(())
-}
-
-fn mount_partitioned_image(
-    ctx: &DADKExecContext,
-    disk_image_path: &PathBuf,
-    disk_mount_path: &PathBuf,
-) -> Result<()> {
-    let loop_device = ManuallyDrop::new(
-        LoopDeviceBuilder::new()
-            .img_path(disk_image_path.clone())
-            .detach_on_drop(false)
-            .build()
-            .map_err(|e| anyhow!("Failed to create loop device: {}", e))?,
-    );
-
-    let dev_path = loop_device.partition_path(1)?;
-    mount_unpartitioned_image(ctx, &dev_path, disk_mount_path)?;
-
-    Ok(())
-}
-
-fn mount_unpartitioned_image(
-    _ctx: &DADKExecContext,
-    disk_image_path: &PathBuf,
-    disk_mount_path: &PathBuf,
-) -> Result<()> {
-    let cmd = Command::new("mount")
-        .arg(disk_image_path)
-        .arg(disk_mount_path)
-        .output()
-        .map_err(|e| anyhow!("Failed to mount disk image: {}", e))?;
-    if !cmd.status.success() {
-        return Err(anyhow!(
-            "Failed to mount disk image: {}",
-            String::from_utf8_lossy(&cmd.stderr)
-        ));
-    }
-    Ok(())
-}
-
-pub fn umount(ctx: &DADKExecContext) -> Result<()> {
-    let disk_img_path = ctx.disk_image_path();
-    let disk_mount_path = ctx.disk_mount_path();
-
-    if disk_mount_path.exists() {
-        log::trace!("Unmounted disk image at {}", disk_mount_path.display());
-
-        let cmd = Command::new("umount").arg(disk_mount_path).output()?;
-
-        if !cmd.status.success() {
-            return Err(anyhow!(
-                "Failed to umount disk image: {}",
-                String::from_utf8_lossy(&cmd.stderr)
-            ));
-        }
-
-        let loop_device = LoopDeviceBuilder::new()
-            .img_path(disk_img_path)
-            .detach_on_drop(true)
-            .build()?;
-        // the loop device will be detached automatically when _loop_device is dropped
-        log::trace!("Detaching {}", loop_device.dev_path());
-        Ok(())
-    } else {
-        Err(anyhow!(
-            "Disk image mount point does not exist: {}",
-            disk_mount_path.display()
-        ))
-    }
-}
-
-/// Ensures the provided disk image path is not a device node.
-fn disk_path_safety_check(disk_image_path: &PathBuf) -> Result<()> {
-    const DONT_ALLOWED_PREFIX: [&str; 5] =
-        ["/dev/sd", "/dev/hd", "/dev/vd", "/dev/nvme", "/dev/mmcblk"];
-    let path = disk_image_path.to_str().ok_or(anyhow!(
-        "disk path safety check failed: disk path is not valid utf-8"
-    ))?;
-
-    DONT_ALLOWED_PREFIX.iter().for_each(|prefix| {
-        if path.starts_with(prefix) {
-            panic!("disk path safety check failed: disk path is not allowed to be a device node(except loop dev)");
-        }
-    });
-    Ok(())
-}
-
-fn create_partitioned_image(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
-    let part_type = ctx.rootfs().partition.partition_type;
-    DiskPartitioner::create_partitioned_image(disk_image_path, part_type)?;
-    // 挂载loop设备
-    let loop_device = LoopDeviceBuilder::new()
-        .img_path(disk_image_path.clone())
-        .detach_on_drop(false)
-        .build()?;
-
-    let partition_path = loop_device.partition_path(1)?;
-    let fs_type = ctx.rootfs().metadata.fs_type;
-    DiskFormatter::format_disk(&partition_path, &fs_type)?;
-    Ok(())
-}
-
-fn create_unpartitioned_image(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
-    // 直接对整块磁盘镜像进行格式化
-    let fs_type = ctx.rootfs().metadata.fs_type;
-    DiskFormatter::format_disk(disk_image_path, &fs_type)
-}
-
-/// 创建全0的raw镜像
-fn create_raw_img(disk_image_path: &PathBuf, image_size: usize) -> Result<()> {
-    log::trace!("Creating raw disk image: {}", disk_image_path.display());
-    // 创建父目录
-    if let Some(parent) = disk_image_path.parent() {
-        log::trace!("Creating parent directory: {}", parent.display());
-        std::fs::create_dir_all(parent)?;
-    }
-    // 打开或创建文件
-    let mut file = File::create(disk_image_path)?;
-
-    // 将文件大小设置为指定大小
-    file.set_len(image_size.try_into().unwrap())?;
-
-    // 写入全0数据
-    let zero_buffer = vec![0u8; 4096]; // 4KB buffer for writing zeros
-    let mut remaining_size = image_size;
-
-    while remaining_size > 0 {
-        let write_size = std::cmp::min(remaining_size, zero_buffer.len());
-        file.write_all(&zero_buffer[..write_size as usize])?;
-        remaining_size -= write_size;
-    }
-
-    Ok(())
-}
-
-pub fn check_disk_image_exists(ctx: &DADKExecContext) -> Result<()> {
-    let disk_image_path = ctx.disk_image_path();
-    if disk_image_path.exists() {
-        println!("1");
-    } else {
-        println!("0");
-    }
-    Ok(())
-}
-
-pub fn show_mount_point(ctx: &DADKExecContext) -> Result<()> {
-    let disk_mount_path = ctx.disk_mount_path();
-    println!("{}", disk_mount_path.display());
-    Ok(())
-}
-
-pub fn show_loop_device(ctx: &DADKExecContext) -> Result<()> {
-    let disk_image_path = ctx.disk_image_path();
-    let loop_device = LoopDeviceBuilder::new()
-        .img_path(disk_image_path)
-        .detach_on_drop(false)
-        .build()?;
-    println!("{}", loop_device.dev_path());
-    Ok(())
-}
-
-struct DiskPartitioner;
-
-impl DiskPartitioner {
-    fn create_partitioned_image(disk_image_path: &PathBuf, part_type: PartitionType) -> Result<()> {
-        match part_type {
-            PartitionType::None => {
-                // This case should not be reached as we are in the partitioned image creation function
-                return Err(anyhow::anyhow!("Invalid partition type: None"));
-            }
-            PartitionType::Mbr => {
-                // Create MBR partitioned disk image
-                Self::create_mbr_partitioned_image(disk_image_path)?;
-            }
-            PartitionType::Gpt => {
-                // Create GPT partitioned disk image
-                Self::create_gpt_partitioned_image(disk_image_path)?;
-            }
-        }
-        Ok(())
-    }
-
-    fn create_mbr_partitioned_image(disk_image_path: &PathBuf) -> Result<()> {
-        let disk_image_path_str = disk_image_path.to_str().expect("Invalid path");
-
-        // 检查 fdisk 是否存在
-        let output = Command::new("fdisk")
-            .arg("--help")
-            .stdin(std::process::Stdio::piped())
-            .stdout(std::process::Stdio::piped())
-            .spawn()?
-            .wait_with_output()?;
-
-        if !output.status.success() {
-            return Err(anyhow::anyhow!("Command fdisk not found"));
-        }
-
-        // 向 fdisk 发送命令
-        let fdisk_commands = "o\nn\n\n\n\n\na\nw\n";
-        let mut fdisk_child = Command::new("fdisk")
-            .arg(disk_image_path_str)
-            .stdin(std::process::Stdio::piped())
-            .stdout(std::process::Stdio::piped())
-            .spawn()?;
-
-        let fdisk_stdin = fdisk_child.stdin.as_mut().expect("Failed to open stdin");
-        fdisk_stdin.write_all(fdisk_commands.as_bytes())?;
-        fdisk_stdin.flush()?;
-        fdisk_child
-            .wait()
-            .unwrap_or_else(|e| panic!("Failed to run fdisk: {}", e));
-        Ok(())
-    }
-
-    fn create_gpt_partitioned_image(_disk_image_path: &PathBuf) -> Result<()> {
-        // Implement the logic to create a GPT partitioned disk image
-        // This is a placeholder for the actual implementation
-        unimplemented!("Not implemented: create_gpt_partitioned_image");
-    }
-}
-
-struct DiskFormatter;
-
-impl DiskFormatter {
-    fn format_disk(disk_image_path: &PathBuf, fs_type: &FsType) -> Result<()> {
-        match fs_type {
-            FsType::Fat32 => Self::format_fat32(disk_image_path),
-        }
-    }
-
-    fn format_fat32(disk_image_path: &PathBuf) -> Result<()> {
-        // Use the `mkfs.fat` command to format the disk image as FAT32
-        let status = Command::new("mkfs.fat")
-            .arg("-F32")
-            .arg(disk_image_path.to_str().unwrap())
-            .status()?;
-
-        if status.success() {
-            Ok(())
-        } else {
-            Err(anyhow::anyhow!("Failed to format disk image as FAT32"))
-        }
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use std::fs;
-    use std::io::Read;
-    use tempfile::NamedTempFile;
-
-    #[test]
-    fn test_create_raw_img_functional() -> Result<()> {
-        // 创建一个临时文件路径
-        let temp_file = NamedTempFile::new()?;
-        let disk_image_path = temp_file.path().to_path_buf();
-        let disk_image_size = 1024 * 1024usize;
-
-        // 调用函数
-        create_raw_img(&disk_image_path, disk_image_size)?;
-
-        // 验证文件大小
-        let metadata = fs::metadata(&disk_image_path)?;
-        assert_eq!(metadata.len(), disk_image_size as u64);
-
-        // 验证文件内容是否全为0
-        let mut file = File::open(&disk_image_path)?;
-        let mut buffer = vec![0u8; 4096];
-        let mut all_zeros = true;
-
-        while file.read(&mut buffer)? > 0 {
-            for byte in &buffer {
-                if *byte != 0 {
-                    all_zeros = false;
-                    break;
-                }
-            }
-        }
-
-        assert!(all_zeros, "File content is not all zeros");
-
-        Ok(())
-    }
-
-    #[test]
-    fn test_format_fat32() {
-        // Create a temporary file to use as the disk image
-        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
-        let disk_image_path = temp_file.path().to_path_buf();
-
-        // 16MB
-        let image_size = 16 * 1024 * 1024usize;
-        create_raw_img(&disk_image_path, image_size).expect("Failed to create raw disk image");
-
-        // Call the function to format the disk image
-        DiskFormatter::format_disk(&disk_image_path, &FsType::Fat32)
-            .expect("Failed to format disk image as FAT32");
-
-        // Optionally, you can check if the disk image was actually formatted as FAT32
-        // by running a command to inspect the filesystem type
-        let output = Command::new("file")
-            .arg("-sL")
-            .arg(&disk_image_path)
-            .output()
-            .expect("Failed to execute 'file' command");
-
-        let output_str = String::from_utf8_lossy(&output.stdout);
-        assert!(
-            output_str.contains("FAT (32 bit)"),
-            "Disk image is not formatted as FAT32"
-        );
-    }
-
-    #[test]
-    fn test_create_mbr_partitioned_image() -> Result<()> {
-        // Create a temporary file to use as the disk image
-        let temp_file = NamedTempFile::new()?;
-        let disk_image_path = temp_file.path().to_path_buf();
-
-        eprintln!("Disk image path: {:?}", disk_image_path);
-        // Create a raw disk image
-        let disk_image_size = 16 * 1024 * 1024usize; // 16MB
-        create_raw_img(&disk_image_path, disk_image_size)?;
-
-        // Call the function to create the MBR partitioned image
-        DiskPartitioner::create_mbr_partitioned_image(&disk_image_path)?;
-
-        // Verify the disk image has been correctly partitioned
-        let output = Command::new("fdisk")
-            .env("LANG", "C") // Set LANG to C to force English output
-            .env("LC_ALL", "C") // Set LC_ALL to C to force English output
-            .arg("-l")
-            .arg(&disk_image_path)
-            .output()
-            .expect("Failed to execute 'fdisk -l' command");
-
-        let output_str = String::from_utf8_lossy(&output.stdout);
-        assert!(
-            output_str.contains("Disklabel type: dos"),
-            "Disk image does not have an MBR partition table"
-        );
-        assert!(
-            output_str.contains("Start"),
-            "Disk image does not have a partition"
-        );
-
-        Ok(())
-    }
-}

+ 0 - 19
dadk/src/actions/rootfs/v2/mod.rs

@@ -1,19 +0,0 @@
-use crate::{console::rootfs::RootFSCommand, context::DADKExecContext};
-use anyhow::Result;
-
-mod disk_img;
-mod loopdev;
-mod sysroot;
-
-pub fn run(ctx: &DADKExecContext, rootfs_cmd: &RootFSCommand) -> Result<()> {
-    match rootfs_cmd {
-        RootFSCommand::Create(param) => disk_img::create(ctx, param.skip_if_exists),
-        RootFSCommand::Delete => disk_img::delete(ctx, false),
-        RootFSCommand::DeleteSysroot => sysroot::delete(ctx),
-        RootFSCommand::Mount => disk_img::mount(ctx),
-        RootFSCommand::Umount => disk_img::umount(ctx),
-        RootFSCommand::CheckDiskImageExists => disk_img::check_disk_image_exists(ctx),
-        RootFSCommand::ShowMountPoint => disk_img::show_mount_point(ctx),
-        RootFSCommand::ShowLoopDevice => disk_img::show_loop_device(ctx),
-    }
-}

+ 1 - 1
dadk/src/actions/user.rs

@@ -20,4 +20,4 @@ pub(super) fn run(ctx: &DADKExecContext, cmd: &UserCommand) -> Result<()> {
         .expect("Failed to build execute context");
     dadk_user_main(context);
     Ok(())
-}
+}

+ 1 - 1
dadk/src/console/mod.rs

@@ -51,6 +51,6 @@ impl Action {
         if matches!(self, Action::Profile(_)) {
             return false;
         }
-        return true;
+        true
     }
 }

+ 10 - 10
dadk/src/console/tests.rs

@@ -5,7 +5,7 @@ use super::*;
 
 #[test]
 fn test_command_line_args_default() {
-    let args = CommandLineArgs::parse_from(&["dadk", "kernel"]);
+    let args = CommandLineArgs::parse_from(["dadk", "kernel"]);
     assert_eq!(args.action, Action::Kernel);
     assert_eq!(args.manifest_path, "dadk-manifest.toml");
 }
@@ -13,19 +13,19 @@ fn test_command_line_args_default() {
 #[test]
 fn test_command_line_args_with_manifest() {
     // test short
-    let args = CommandLineArgs::parse_from(&["dadk", "-f", "custom-manifest.toml", "kernel"]);
+    let args = CommandLineArgs::parse_from(["dadk", "-f", "custom-manifest.toml", "kernel"]);
     assert_eq!(args.action, Action::Kernel);
     assert_eq!(args.manifest_path, "custom-manifest.toml");
     // test long
     let args =
-        CommandLineArgs::parse_from(&["dadk", "--manifest", "custom-manifest.toml", "kernel"]);
+        CommandLineArgs::parse_from(["dadk", "--manifest", "custom-manifest.toml", "kernel"]);
     assert_eq!(args.action, Action::Kernel);
     assert_eq!(args.manifest_path, "custom-manifest.toml");
 }
 
 #[test]
 fn test_command_line_args_rootfs_subcommand() {
-    let args = CommandLineArgs::parse_from(&["dadk", "rootfs", "create"]);
+    let args = CommandLineArgs::parse_from(["dadk", "rootfs", "create"]);
     assert!(matches!(
         args.action,
         Action::Rootfs(RootFSCommand::Create(CreateCommandParam {
@@ -33,7 +33,7 @@ fn test_command_line_args_rootfs_subcommand() {
         }))
     ));
 
-    let args = CommandLineArgs::parse_from(&["dadk", "rootfs", "create", "--skip-if-exists"]);
+    let args = CommandLineArgs::parse_from(["dadk", "rootfs", "create", "--skip-if-exists"]);
     assert!(matches!(
         args.action,
         Action::Rootfs(RootFSCommand::Create(CreateCommandParam {
@@ -44,7 +44,7 @@ fn test_command_line_args_rootfs_subcommand() {
 
 #[test]
 fn test_show_mountpoint() {
-    let args = CommandLineArgs::parse_from(&["dadk", "rootfs", "show-mountpoint"]);
+    let args = CommandLineArgs::parse_from(["dadk", "rootfs", "show-mountpoint"]);
     assert!(matches!(
         args.action,
         Action::Rootfs(RootFSCommand::ShowMountPoint)
@@ -53,7 +53,7 @@ fn test_show_mountpoint() {
 
 #[test]
 fn test_command_line_args_user() {
-    let args = CommandLineArgs::parse_from(&["dadk", "user", "build"]);
+    let args = CommandLineArgs::parse_from(["dadk", "user", "build"]);
 
     assert!(matches!(args.action, Action::User(UserCommand::Build)));
 }
@@ -61,7 +61,7 @@ fn test_command_line_args_user() {
 /// 该函数测试CommandLineArgs解析器是否正确解析`dadk user clean`命令
 #[test]
 fn test_command_line_args_user_clean() {
-    let args = CommandLineArgs::parse_from(&["dadk", "user", "clean"]);
+    let args = CommandLineArgs::parse_from(["dadk", "user", "clean"]);
     assert!(matches!(args.action, Action::User(UserCommand::Clean(_))));
     if let Action::User(UserCommand::Clean(args)) = args.action {
         assert_eq!(args.level, UserCleanLevel::All);
@@ -70,7 +70,7 @@ fn test_command_line_args_user_clean() {
     }
 
     // 检查 `--level` 参数
-    let args = CommandLineArgs::parse_from(&["dadk", "user", "clean", "--level", "in-src"]);
+    let args = CommandLineArgs::parse_from(["dadk", "user", "clean", "--level", "in-src"]);
     if let Action::User(UserCommand::Clean(args)) = args.action {
         assert_eq!(args.level, UserCleanLevel::InSrc);
     } else {
@@ -78,7 +78,7 @@ fn test_command_line_args_user_clean() {
     }
 
     // 检查 `--task` 参数
-    let args = CommandLineArgs::parse_from(&["dadk", "user", "clean", "--task", "a-0.1.0"]);
+    let args = CommandLineArgs::parse_from(["dadk", "user", "clean", "--task", "a-0.1.0"]);
     if let Action::User(UserCommand::Clean(args)) = args.action {
         assert_eq!(args.task, Some("a-0.1.0".to_string()));
     } else {

+ 6 - 6
dadk/src/console/user.rs

@@ -27,9 +27,9 @@ pub enum UserCleanLevel {
     Output,
 }
 
-impl Into<dadk_config::user::UserCleanLevel> for UserCleanLevel {
-    fn into(self) -> dadk_config::user::UserCleanLevel {
-        match self {
+impl From<UserCleanLevel> for dadk_config::user::UserCleanLevel {
+    fn from(val: UserCleanLevel) -> Self {
+        match val {
             UserCleanLevel::All => dadk_config::user::UserCleanLevel::All,
             UserCleanLevel::InSrc => dadk_config::user::UserCleanLevel::InSrc,
             UserCleanLevel::Output => dadk_config::user::UserCleanLevel::Output,
@@ -37,9 +37,9 @@ impl Into<dadk_config::user::UserCleanLevel> for UserCleanLevel {
     }
 }
 
-impl Into<dadk_user::context::Action> for UserCommand {
-    fn into(self) -> dadk_user::context::Action {
-        match self {
+impl From<UserCommand> for dadk_user::context::Action {
+    fn from(val: UserCommand) -> Self {
+        match val {
             UserCommand::Build => dadk_user::context::Action::Build,
             UserCommand::Install => dadk_user::context::Action::Install,
             UserCommand::Clean(args) => dadk_user::context::Action::Clean(args.level.into()),

+ 43 - 11
dadk/src/context/mod.rs

@@ -12,7 +12,8 @@ use crate::{
     console::CommandLineArgs,
     utils::{abs_path, check_dir_exists},
 };
-
+use crate::actions::rootfs::disk_img::get_builder_version;
+use crate::actions::rootfs::BuilderVersion;
 mod manifest;
 
 /// DADK的执行上下文
@@ -48,7 +49,7 @@ impl DADKExecContext {
 
     /// 设置进程的工作目录
     fn setup_workdir(&self) -> Result<()> {
-        std::env::set_current_dir(&self.workdir()).expect("Failed to set current directory");
+        std::env::set_current_dir(self.workdir()).expect("Failed to set current directory");
         Ok(())
     }
     /// Get rootfs configuration
@@ -67,8 +68,7 @@ impl DADKExecContext {
     ///
     /// If the directory does not exist, or the path is not a folder, an error is returned
     pub fn sysroot_dir(&self) -> Result<PathBuf> {
-        check_dir_exists(&self.manifest().metadata.sysroot_dir)
-            .map(|p| p.clone())
+        check_dir_exists(&self.manifest().metadata.sysroot_dir).cloned()
             .map_err(|e| anyhow::anyhow!("Failed to get sysroot dir: {}", e))
     }
 
@@ -76,15 +76,13 @@ impl DADKExecContext {
     ///
     /// If the directory does not exist, or the path is not a folder, an error is returned
     pub fn cache_root_dir(&self) -> Result<PathBuf> {
-        check_dir_exists(&self.manifest().metadata.cache_root_dir)
-            .map(|p| p.clone())
+        check_dir_exists(&self.manifest().metadata.cache_root_dir).cloned()
             .map_err(|e| anyhow::anyhow!("Failed to get cache root dir: {}", e))
     }
 
     #[deprecated]
     pub fn user_config_dir(&self) -> Result<PathBuf> {
-        check_dir_exists(&self.manifest().metadata.user_config_dir)
-            .map(|p| p.clone())
+        check_dir_exists(&self.manifest().metadata.user_config_dir).cloned()
             .map_err(|e| anyhow::anyhow!("Failed to get user config dir: {}", e))
     }
 
@@ -92,18 +90,52 @@ impl DADKExecContext {
         self.manifest().metadata.arch
     }
 
-    /// 获取磁盘镜像的路径,路径由工作目录、架构和固定文件名组成
     pub fn disk_image_path(&self) -> PathBuf {
+        match get_builder_version() {
+            BuilderVersion::V1 => self.disk_image_path_v1(),
+            BuilderVersion::V2 => self.disk_image_path_v2(),
+        }
+    }
+    /// 获取磁盘镜像的路径,路径由工作目录、架构和固定文件名组成
+    pub fn disk_image_path_v2(&self) -> PathBuf {
         self.workdir()
-            .join(format!("bin/{}/disk.img", self.target_arch()))
+            .join(format!("bin/{}/disk.img", self.target_arch()))//这个是新版本路径
     }
-
+    
     /// 获取磁盘挂载路径
+    
+    pub fn disk_image_path_v1(&self) -> PathBuf {
+        self.workdir()
+            .join(format!("bin/{}.img", self.disk_image_basename_v1()))//这个是旧版本路径
+    }
+
+
+
     pub fn disk_mount_path(&self) -> PathBuf {
+        
+        match get_builder_version() {
+            BuilderVersion::V1 => self.disk_mount_path_v1(),
+            BuilderVersion::V2 => self.disk_mount_path_v2(),            
+        }  
+    }
+    
+    pub fn disk_mount_path_v2(&self) -> PathBuf {
         self.workdir()
             .join(format!("bin/{}/mnt", self.target_arch()))
     }
 
+
+    /// 获取磁盘挂载路径
+    pub fn disk_mount_path_v1(&self) -> PathBuf {
+        self.workdir()
+            .join(format!("bin/mnt/{}", self.disk_image_basename_v1()))
+    }
+
+    fn disk_image_basename_v1(&self) -> String {
+        let arch: String = self.target_arch().into();
+        format!("disk-image-{}", arch)
+    }
+
     /// 获取磁盘镜像大小
     pub fn disk_image_size(&self) -> usize {
         self.rootfs().metadata.size

+ 2 - 2
dadk/src/utils.rs

@@ -3,7 +3,7 @@ use std::path::PathBuf;
 use anyhow::{anyhow, Result};
 
 /// 检查目录是否存在
-pub(super) fn check_dir_exists<'a>(path: &'a PathBuf) -> Result<&'a PathBuf> {
+pub(super) fn check_dir_exists(path: &PathBuf) -> Result<&PathBuf> {
     if !path.exists() {
         return Err(anyhow!("Path '{}' not exists", path.display()));
     }
@@ -11,7 +11,7 @@ pub(super) fn check_dir_exists<'a>(path: &'a PathBuf) -> Result<&'a PathBuf> {
         return Err(anyhow!("Path '{}' is not a directory", path.display()));
     }
 
-    return Ok(path);
+    Ok(path)
 }
 
 /// 获取给定路径的绝对路径

部分文件因文件數量過多而無法顯示