Преглед на файлове

fix(rootfs-ish): clippy and format

Samuka007 преди 9 часа
родител
ревизия
89daaca507

+ 1 - 3
dadk/src/actions/mod.rs

@@ -5,9 +5,7 @@ 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.")
         }
@@ -21,4 +19,4 @@ pub fn run(ctx: DADKExecContext) {
             profile::run(&ctx, profile_command).expect("Run profile action error.")
         }
     }
-}
+}

+ 3 - 1
dadk/src/actions/profile/mod.rs

@@ -109,7 +109,9 @@ impl Sample {
                     .unwrap(),
             );
 
-            if let std::collections::btree_map::Entry::Vacant(e) = self.data.entry(self.current_cpu.unwrap()) {
+            if let std::collections::btree_map::Entry::Vacant(e) =
+                self.data.entry(self.current_cpu.unwrap())
+            {
                 e.insert(Vec::new());
             } else {
                 log::error!(

+ 49 - 50
dadk/src/actions/rootfs/disk_img.rs

@@ -1,5 +1,6 @@
+use std::path::Path;
 use std::sync::OnceLock;
-use std::{fs::File, io::Write, mem::ManuallyDrop, path::PathBuf, process::Command};
+use std::{fs::File, io::Write, mem::ManuallyDrop, process::Command};
 
 use crate::context::DADKExecContext;
 use anyhow::{anyhow, Result};
@@ -12,18 +13,17 @@ 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");
+    BUILDER_VERSION
+        .set(version)
+        .expect("Failed to set builder version");
     log::info!("Current builder version: {:?}", get_builder_version());
 }
-pub fn get_builder_version() -> BuilderVersion{
+pub fn get_builder_version() -> BuilderVersion {
     log::info!("Current builder version: {:?}", BUILDER_VERSION.get());
 
-    BUILDER_VERSION.get()
-                    .cloned()
-                    .unwrap_or(BuilderVersion::V1) 
-}  
+    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() {
@@ -98,8 +98,8 @@ pub fn mount(ctx: &DADKExecContext) -> Result<()> {
 }
 fn mount_unpartitioned_image(
     _ctx: &DADKExecContext,
-    disk_image_path: &PathBuf,
-    disk_mount_path: &PathBuf,
+    disk_image_path: &Path,
+    disk_mount_path: &Path,
 ) -> Result<()> {
     let cmd = Command::new("mount")
         .arg(disk_image_path)
@@ -115,7 +115,7 @@ fn mount_unpartitioned_image(
     Ok(())
 }
 /// Ensures the provided disk image path is not a device node.
-fn disk_path_safety_check(disk_image_path: &PathBuf) -> Result<()> {
+fn disk_path_safety_check(disk_image_path: &Path) -> 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!(
@@ -130,13 +130,13 @@ fn disk_path_safety_check(disk_image_path: &PathBuf) -> Result<()> {
     Ok(())
 }
 
-fn create_unpartitioned_image(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
+fn create_unpartitioned_image(ctx: &DADKExecContext, disk_image_path: &Path) -> 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<()> {
+fn create_raw_img(disk_image_path: &Path, image_size: usize) -> Result<()> {
     log::trace!("Creating raw disk image: {}", disk_image_path.display());
     // 创建父目录
     if let Some(parent) = disk_image_path.parent() {
@@ -179,7 +179,7 @@ pub fn show_mount_point(ctx: &DADKExecContext) -> Result<()> {
 struct DiskPartitioner;
 
 impl DiskPartitioner {
-    fn create_partitioned_image(disk_image_path: &PathBuf, part_type: PartitionType) -> Result<()> {
+    fn create_partitioned_image(disk_image_path: &Path, part_type: PartitionType) -> Result<()> {
         match part_type {
             PartitionType::None => {
                 // This case should not be reached as we are in the partitioned image creation function
@@ -197,7 +197,7 @@ impl DiskPartitioner {
         Ok(())
     }
 
-    fn create_mbr_partitioned_image(disk_image_path: &PathBuf) -> Result<()> {
+    fn create_mbr_partitioned_image(disk_image_path: &Path) -> Result<()> {
         let disk_image_path_str = disk_image_path.to_str().expect("Invalid path");
 
         // 检查 fdisk 是否存在
@@ -229,7 +229,7 @@ impl DiskPartitioner {
         Ok(())
     }
 
-    fn create_gpt_partitioned_image(_disk_image_path: &PathBuf) -> Result<()> {
+    fn create_gpt_partitioned_image(_disk_image_path: &Path) -> 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");
@@ -239,13 +239,13 @@ impl DiskPartitioner {
 struct DiskFormatter;
 
 impl DiskFormatter {
-    fn format_disk(disk_image_path: &PathBuf, fs_type: &FsType) -> Result<()> {
+    fn format_disk(disk_image_path: &Path, fs_type: &FsType) -> Result<()> {
         match fs_type {
             FsType::Fat32 => Self::format_fat32(disk_image_path),
         }
     }
 
-    fn format_fat32(disk_image_path: &PathBuf) -> Result<()> {
+    fn format_fat32(disk_image_path: &Path) -> Result<()> {
         // Use the `mkfs.fat` command to format the disk image as FAT32
         let status = Command::new("mkfs.fat")
             .arg("-F32")
@@ -260,43 +260,42 @@ impl DiskFormatter {
     }
 }
 
-
 fn mount_partitioned_image(
     ctx: &DADKExecContext,
-    disk_image_path: &PathBuf,
-    disk_mount_path: &PathBuf,
+    disk_image_path: &Path,
+    disk_mount_path: &Path,
 ) -> 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<()> {
+fn create_partitioned_image(ctx: &DADKExecContext, disk_image_path: &Path) -> 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),   
-    } 
+        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() {
+    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),   
-        } 
+        BuilderVersion::V1 => show_loop_device_v1(ctx),
+    }
 }
 
 fn mount_partitioned_image_v1(
     ctx: &DADKExecContext,
-    disk_image_path: &PathBuf,
-    disk_mount_path: &PathBuf,
+    disk_image_path: &Path,
+    disk_mount_path: &Path,
 ) -> Result<()> {
     let mut loop_device = ManuallyDrop::new(
         LoopDeviceBuilderV1::new()
-            .img_path(disk_image_path.clone())
+            .img_path(disk_image_path)
             .detach_on_drop(false)
             .build()
             .map_err(|e| anyhow!("Failed to create loop device: {}", e))?,
@@ -313,12 +312,12 @@ fn mount_partitioned_image_v1(
 }
 fn mount_partitioned_image_v2(
     ctx: &DADKExecContext,
-    disk_image_path: &PathBuf,
-    disk_mount_path: &PathBuf,
+    disk_image_path: &Path,
+    disk_mount_path: &Path,
 ) -> Result<()> {
     let loop_device = ManuallyDrop::new(
         LoopDeviceBuilderV2::new()
-            .img_path(disk_image_path.clone())
+            .img_path(disk_image_path)
             .detach_on_drop(false)
             .build()
             .map_err(|e| anyhow!("Failed to create loop device: {}", e))?,
@@ -331,16 +330,16 @@ fn mount_partitioned_image_v2(
 }
 pub fn umount(ctx: &DADKExecContext) -> Result<()> {
     match get_builder_version() {
-    BuilderVersion::V2 => umount_v2(ctx),
-    BuilderVersion::V1 => umount_v1(ctx),   
-    }   
+        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 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 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);
         }
@@ -404,7 +403,7 @@ pub fn umount_v2(ctx: &DADKExecContext) -> Result<()> {
         }
 
         let loop_device = LoopDeviceBuilderV2::new()
-            .img_path(disk_img_path)
+            .img_path(&disk_img_path)
             .detach_on_drop(true)
             .build()?;
         // the loop device will be detached automatically when _loop_device is dropped
@@ -417,12 +416,12 @@ pub fn umount_v2(ctx: &DADKExecContext) -> Result<()> {
         ))
     }
 }
-fn create_partitioned_image_v1(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
+fn create_partitioned_image_v1(ctx: &DADKExecContext, disk_image_path: &Path) -> 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())
+        .img_path(disk_image_path)
         .build()
         .map_err(|e| anyhow!("Failed to create loop device: {}", e))?;
     loop_device
@@ -434,12 +433,12 @@ fn create_partitioned_image_v1(ctx: &DADKExecContext, disk_image_path: &PathBuf)
     DiskFormatter::format_disk(&partition_path, &fs_type)?;
     Ok(())
 }
-fn create_partitioned_image_v2(ctx: &DADKExecContext, disk_image_path: &PathBuf) -> Result<()> {
+fn create_partitioned_image_v2(ctx: &DADKExecContext, disk_image_path: &Path) -> 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())
+        .img_path(disk_image_path)
         .detach_on_drop(false)
         .build()?;
 
@@ -452,7 +451,7 @@ 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)
+        .img_path(&disk_image_path)
         .build()?;
     if let Err(e) = loop_device.attach_by_exists() {
         log::error!("Failed to attach loop device: {}", e);
@@ -464,7 +463,7 @@ pub fn show_loop_device_v1(ctx: &DADKExecContext) -> Result<()> {
 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)
+        .img_path(&disk_image_path)
         .detach_on_drop(false)
         .build()?;
     println!("{}", loop_device.dev_path());
@@ -574,4 +573,4 @@ mod tests {
 
         Ok(())
     }
-}
+}

+ 8 - 3
dadk/src/actions/rootfs/loopdev_v1.rs

@@ -1,5 +1,10 @@
 use core::str;
-use std::{path::PathBuf, process::Command, thread::sleep, time::Duration};
+use std::{
+    path::{Path, PathBuf},
+    process::Command,
+    thread::sleep,
+    time::Duration,
+};
 
 use anyhow::{anyhow, Result};
 use regex::Regex;
@@ -246,8 +251,8 @@ impl LoopDeviceBuilder {
         }
     }
 
-    pub fn img_path(mut self, img_path: PathBuf) -> Self {
-        self.img_path = Some(abs_path(&img_path));
+    pub fn img_path(mut self, img_path: &Path) -> Self {
+        self.img_path = Some(abs_path(img_path));
         self
     }
 

+ 21 - 33
dadk/src/actions/rootfs/loopdev_v2.rs

@@ -1,5 +1,10 @@
 use core::str;
-use std::{path::PathBuf, process::Command, thread::sleep, time::Duration};
+use std::{
+    path::{Path, PathBuf},
+    process::Command,
+    thread::sleep,
+    time::Duration,
+};
 
 use regex::Regex;
 
@@ -7,7 +12,6 @@ use crate::utils::abs_path;
 
 const LOOP_DEVICE_LOSETUP_A_REGEX: &str = r"^/dev/loop(\d+)";
 
-
 pub struct LoopDevice {
     path: PathBuf,
     detach_on_drop: bool,
@@ -105,8 +109,8 @@ impl LoopDeviceBuilder {
         }
     }
 
-    pub fn img_path(mut self, img_path: PathBuf) -> Self {
-        self.img_path = Some(abs_path(&img_path));
+    pub fn img_path(mut self, img_path: &Path) -> Self {
+        self.img_path = Some(abs_path(img_path));
         self
     }
 
@@ -133,7 +137,6 @@ impl LoopDeviceBuilder {
     }
 }
 
-
 fn __loop_device_path_by_disk_image_path(
     disk_img_path: &str,
     losetup_a_output: &str,
@@ -153,7 +156,7 @@ fn __loop_device_path_by_disk_image_path(
         return Ok(loop_device);
     }
     Err(LoopError::LoopDeviceNotFound)
-} 
+}
 #[derive(Debug)]
 pub enum LoopError {
     InvalidUtf8,
@@ -190,9 +193,6 @@ impl std::fmt::Display for LoopError {
 
 impl std::error::Error for LoopError {}
 
-
-
-
 fn attach_loop_by_image(img_path: &str) -> Result<String, LoopError> {
     LosetupCmd::new()
         .arg("-f")
@@ -210,12 +210,6 @@ fn attach_exists_loop_by_image(img_path: &str) -> Result<String, LoopError> {
     __loop_device_path_by_disk_image_path(img_path, &output)
 }
 
-
-
-
-
-
-
 struct LosetupCmd {
     inner: Command,
 }
@@ -263,12 +257,10 @@ impl Mapper {
         let partition_name_prefix = format!("{}p", path.file_name().unwrap().to_str().unwrap());
         let device_dir = path.parent().unwrap();
 
-        for entry in device_dir.read_dir().unwrap() {
-            if let Ok(entry) = entry {
-                let entry = entry.file_name().into_string().unwrap();
-                if entry.starts_with(&partition_name_prefix) {
-                    parts.push(entry);
-                }
+        for entry in device_dir.read_dir().unwrap().flatten() {
+            let entry = entry.file_name().into_string().unwrap();
+            if entry.starts_with(&partition_name_prefix) {
+                parts.push(entry);
             }
         }
 
@@ -285,12 +277,10 @@ impl Mapper {
         // check if mapper is created, found if {device_dir}/mapper/loopX
         let mapper_path = device_dir.join("mapper");
 
-        for entry in mapper_path.read_dir().unwrap() {
-            if let Ok(entry) = entry {
-                let entry = entry.file_name().into_string().unwrap();
-                if entry.starts_with(&partition_name_prefix) {
-                    parts.push(entry);
-                }
+        for entry in mapper_path.read_dir().unwrap().flatten() {
+            let entry = entry.file_name().into_string().unwrap();
+            if entry.starts_with(&partition_name_prefix) {
+                parts.push(entry);
             }
         }
 
@@ -308,12 +298,10 @@ impl Mapper {
             .arg("-a")
             .arg(path.to_str().unwrap())
             .output()?;
-        for entry in mapper_path.read_dir().unwrap() {
-            if let Ok(entry) = entry {
-                let entry = entry.file_name().into_string().unwrap();
-                if entry.starts_with(&partition_name_prefix) {
-                    parts.push(entry);
-                }
+        for entry in mapper_path.read_dir().unwrap().flatten() {
+            let entry = entry.file_name().into_string().unwrap();
+            if entry.starts_with(&partition_name_prefix) {
+                parts.push(entry);
             }
         }
 

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

@@ -16,7 +16,6 @@ impl BuilderVersion {
         match version {
             "v2" => BuilderVersion::V2,
             "v1" | _ => BuilderVersion::V1,
-            
         }
     }
 }
@@ -32,4 +31,4 @@ pub fn run(ctx: &DADKExecContext, rootfs_cmd: &RootFSCommand) -> Result<()> {
         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(())
-}
+}

+ 16 - 17
dadk/src/context/mod.rs

@@ -1,3 +1,4 @@
+use std::path::Path;
 use std::{cell::OnceCell, path::PathBuf};
 
 use anyhow::Result;
@@ -8,12 +9,12 @@ use dadk_config::{
 use derive_builder::Builder;
 use manifest::parse_manifest;
 
+use crate::actions::rootfs::disk_img::get_builder_version;
+use crate::actions::rootfs::BuilderVersion;
 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的执行上下文
@@ -44,7 +45,7 @@ pub fn build_exec_context() -> Result<DADKExecContext> {
 impl DADKExecContext {
     /// 获取工作目录的绝对路径
     pub fn workdir(&self) -> PathBuf {
-        abs_path(&PathBuf::from(&self.command.workdir))
+        abs_path(Path::new(&self.command.workdir))
     }
 
     /// 设置进程的工作目录
@@ -68,7 +69,8 @@ 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).cloned()
+        check_dir_exists(&self.manifest().metadata.sysroot_dir)
+            .cloned()
             .map_err(|e| anyhow::anyhow!("Failed to get sysroot dir: {}", e))
     }
 
@@ -76,13 +78,15 @@ 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).cloned()
+        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).cloned()
+        check_dir_exists(&self.manifest().metadata.user_config_dir)
+            .cloned()
             .map_err(|e| anyhow::anyhow!("Failed to get user config dir: {}", e))
     }
 
@@ -99,32 +103,27 @@ impl DADKExecContext {
     /// 获取磁盘镜像的路径,路径由工作目录、架构和固定文件名组成
     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()))//这个是旧版本路径
+            .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(),            
-        }  
+            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()

+ 2 - 2
dadk/src/utils.rs

@@ -1,4 +1,4 @@
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
 
 use anyhow::{anyhow, Result};
 
@@ -15,7 +15,7 @@ pub(super) fn check_dir_exists(path: &PathBuf) -> Result<&PathBuf> {
 }
 
 /// 获取给定路径的绝对路径
-pub fn abs_path(path: &PathBuf) -> PathBuf {
+pub fn abs_path(path: &Path) -> PathBuf {
     if path.is_absolute() {
         path.to_path_buf()
     } else {