فهرست منبع

feat(dadk-config) (#72)

* 删除rust_target

* 解析用户程序配置文件:dadk-user -> dadk-config

* 添加用户程序配置文件模版

* patch
Jomo 5 ماه پیش
والد
کامیت
d2ade6ef03
29فایلهای تغییر یافته به همراه588 افزوده شده و 1651 حذف شده
  1. 0 75
      crates/test_base/src/dadk_user.rs
  2. 0 1
      crates/test_base/src/lib.rs
  3. 1 0
      dadk-config/src/common/mod.rs
  4. 195 0
      dadk-config/src/common/task.rs
  5. 72 0
      dadk-config/src/user/mod.rs
  6. 17 0
      dadk-config/templates/config/actions/mod.rs
  7. 23 0
      dadk-config/templates/config/actions/user.rs
  8. 76 0
      dadk-config/templates/config/userapp_config.toml
  9. 72 0
      dadk-config/tests/test_user_config.rs
  10. 3 37
      dadk-user/src/executor/mod.rs
  11. 21 13
      dadk-user/src/executor/source.rs
  12. 0 212
      dadk-user/src/executor/target.rs
  13. 1 1
      dadk-user/src/executor/tests.rs
  14. 0 478
      dadk-user/src/parser/config.rs
  15. 14 49
      dadk-user/src/parser/mod.rs
  16. 67 269
      dadk-user/src/parser/task.rs
  17. 1 44
      dadk-user/src/scheduler/mod.rs
  18. 5 5
      dadk-user/src/scheduler/tests.rs
  19. 0 28
      dadk-user/templates/config/build_from_source/test_archive.toml
  20. 0 30
      dadk-user/templates/config/build_from_source/test_git.toml
  21. 0 28
      dadk-user/templates/config/build_from_source/test_local.toml
  22. 0 29
      dadk-user/templates/config/install_from_prebuilt/test_archive.toml
  23. 0 29
      dadk-user/templates/config/install_from_prebuilt/test_local.toml
  24. 0 286
      dadk-user/tests/test_parse_dadk_user_config.rs
  25. 3 8
      tests/data/dadk_config_v2/app_all_target_arch_0_2_0.toml
  26. 5 6
      tests/data/dadk_config_v2/app_normal_with_env_0_2_0.toml
  27. 6 7
      tests/data/dadk_config_v2/app_normal_with_env_fail_0_2_0.toml
  28. 4 9
      tests/data/dadk_config_v2/app_target_arch_riscv64_only_0_2_0.toml
  29. 2 7
      tests/data/dadk_config_v2/app_target_arch_x86_64_only_0_2_0.toml

+ 0 - 75
crates/test_base/src/dadk_user.rs

@@ -1,75 +0,0 @@
-use std::path::PathBuf;
-
-use test_context::TestContext;
-
-#[derive(Debug, Clone)]
-pub struct DadkUserTestContext {
-    /// 项目的根目录
-    test_base_path: PathBuf,
-}
-
-impl DadkUserTestContext {
-    /// 获取项目的根目录
-    pub fn test_base_path(&self) -> &PathBuf {
-        &self.test_base_path
-    }
-
-    /// 获取项目目录下的文件的的绝对路径
-    pub fn abs_path(&self, relative_path: &str) -> PathBuf {
-        self.test_base_path.join(relative_path)
-    }
-
-    /// 获取 dadk配置模版的路径
-    pub fn templates_dir(&self) -> PathBuf {
-        const TEMPLATES_CONFIG_DIR: &str = "templates/config";
-        self.abs_path(TEMPLATES_CONFIG_DIR)
-    }
-}
-
-impl TestContext for DadkUserTestContext {
-    fn setup() -> Self {
-        env_logger::try_init_from_env(env_logger::Env::default().default_filter_or("info")).ok();
-
-        // 获取dadk-user包的根目录
-        let mut test_base_path: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
-        test_base_path.pop();
-        test_base_path.pop();
-        test_base_path.push("dadk-user");
-        log::debug!(
-            "DadkUserTestContext setup: project_base_path={:?}",
-            test_base_path
-        );
-        // 设置workdir
-        std::env::set_current_dir(&test_base_path).expect("Failed to setup test base path");
-
-        let r = DadkUserTestContext { test_base_path };
-
-        r
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use std::env;
-
-    #[test]
-    fn test_test_base_path() {
-        let test_context = DadkUserTestContext::setup();
-        let expected_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
-            .parent()
-            .unwrap()
-            .parent()
-            .unwrap()
-            .join("dadk-user");
-        assert_eq!(test_context.test_base_path(), &expected_path);
-    }
-
-    #[test]
-    fn test_abs_path() {
-        let test_context = DadkUserTestContext::setup();
-        let relative_path = "some_relative_path";
-        let expected_path = test_context.test_base_path().join(relative_path);
-        assert_eq!(test_context.abs_path(relative_path), expected_path);
-    }
-}

+ 0 - 1
crates/test_base/src/lib.rs

@@ -1,5 +1,4 @@
 pub extern crate test_context;
 
 pub mod dadk_config;
-pub mod dadk_user;
 pub mod global;

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

@@ -1 +1,2 @@
 pub mod target_arch;
+pub mod task;

+ 195 - 0
dadk-config/src/common/task.rs

@@ -0,0 +1,195 @@
+use anyhow::{Error, Result};
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+pub struct TaskSource {
+    #[serde(rename = "type")]
+    pub source_type: TaskSourceType,
+    pub source: Source,
+    #[serde(rename = "source-path")]
+    pub source_path: String,
+    /// 分支(可选,如果为空,则拉取master)branch和revision只能同时指定一个
+    pub branch: Option<String>,
+    /// 特定的提交的hash值(可选,如果为空,则拉取branch的最新提交)
+    pub revision: Option<String>,
+}
+
+/// # 任务类型
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub enum TaskSourceType {
+    /// 从源码构建
+    #[serde(rename = "build-from-source")]
+    BuildFromSource,
+    /// 从预编译包安装
+    #[serde(rename = "install-from-prebuilt")]
+    InstallFromPrebuilt,
+}
+
+/// # 来源类型
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+pub enum Source {
+    /// 从Git仓库获取
+    #[serde(rename = "git")]
+    Git,
+    /// 从本地目录获取
+    #[serde(rename = "local")]
+    Local,
+    /// 从在线压缩包获取
+    #[serde(rename = "archive")]
+    Archive,
+}
+
+/// @brief 构建配置
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct BuildConfig {
+    /// 构建命令
+    #[serde(rename = "build-command")]
+    pub build_command: Option<String>,
+}
+
+impl BuildConfig {
+    #[allow(dead_code)]
+    pub fn new(build_command: Option<String>) -> Self {
+        Self { build_command }
+    }
+
+    pub fn validate(&self) -> Result<()> {
+        return Ok(());
+    }
+
+    pub fn trim(&mut self) {
+        if let Some(build_command) = &mut self.build_command {
+            *build_command = build_command.trim().to_string();
+        }
+    }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct InstallConfig {
+    /// 安装到DragonOS内的目录
+    #[serde(rename = "in-dragonos-path")]
+    pub in_dragonos_path: Option<PathBuf>,
+}
+
+impl InstallConfig {
+    #[allow(dead_code)]
+    pub fn new(in_dragonos_path: Option<PathBuf>) -> Self {
+        Self { in_dragonos_path }
+    }
+
+    pub fn validate(&self) -> Result<()> {
+        if self.in_dragonos_path.is_none() {
+            return Ok(());
+        }
+        if self.in_dragonos_path.as_ref().unwrap().is_relative() {
+            return Err(Error::msg(
+                "InstallConfig: in_dragonos_path should be an Absolute path",
+            ));
+        }
+        return Ok(());
+    }
+
+    pub fn trim(&mut self) {}
+}
+/// # 清理配置
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct CleanConfig {
+    /// 清理命令
+    #[serde(rename = "clean-command")]
+    pub clean_command: Option<String>,
+}
+
+impl CleanConfig {
+    #[allow(dead_code)]
+    pub fn new(clean_command: Option<String>) -> Self {
+        Self { clean_command }
+    }
+
+    pub fn validate(&self) -> Result<()> {
+        return Ok(());
+    }
+
+    pub fn trim(&mut self) {
+        if let Some(clean_command) = &mut self.clean_command {
+            *clean_command = clean_command.trim().to_string();
+        }
+    }
+}
+
+/// @brief 依赖项
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
+pub struct Dependency {
+    #[serde(default = "default_empty_string")]
+    pub name: String,
+    #[serde(default = "default_empty_string")]
+    pub version: String,
+}
+
+impl Dependency {
+    #[allow(dead_code)]
+    pub fn new(name: String, version: String) -> Self {
+        Self { name, version }
+    }
+
+    pub fn validate(&self) -> Result<()> {
+        if self.name.is_empty() {
+            return Err(Error::msg("name is empty"));
+        }
+        if self.version.is_empty() {
+            return Err(Error::msg("version is empty"));
+        }
+        return Ok(());
+    }
+
+    pub fn trim(&mut self) {
+        self.name = self.name.trim().to_string();
+        self.version = self.version.trim().to_string();
+    }
+
+    pub fn name_version(&self) -> String {
+        return format!("{}-{}", self.name, self.version);
+    }
+}
+
+/// # 任务环境变量
+///
+/// 任务执行时的环境变量.这个环境变量是在当前任务执行时设置的,不会影响到其他任务
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
+pub struct TaskEnv {
+    #[serde(default = "default_empty_string")]
+    pub key: String,
+    #[serde(default = "default_empty_string")]
+    pub value: String,
+}
+
+impl TaskEnv {
+    #[allow(dead_code)]
+    pub fn new(key: String, value: String) -> Self {
+        Self { key, value }
+    }
+
+    pub fn key(&self) -> &str {
+        &self.key
+    }
+
+    pub fn value(&self) -> &str {
+        &self.value
+    }
+
+    pub fn trim(&mut self) {
+        self.key = self.key.trim().to_string();
+        self.value = self.value.trim().to_string();
+    }
+
+    pub fn validate(&self) -> Result<()> {
+        if self.key.is_empty() {
+            return Err(Error::msg("Env: key is empty"));
+        }
+        return Ok(());
+    }
+}
+
+fn default_empty_string() -> String {
+    "".to_string()
+}

+ 72 - 0
dadk-config/src/user/mod.rs

@@ -1,3 +1,14 @@
+use std::path::PathBuf;
+
+use serde::Deserialize;
+
+use crate::common::{
+    target_arch::TargetArch,
+    task::{BuildConfig, CleanConfig, Dependency, InstallConfig, TaskEnv, TaskSource},
+};
+
+use anyhow::Result;
+
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub enum UserCleanLevel {
     /// 清理所有用户程序构建缓存
@@ -7,3 +18,64 @@ pub enum UserCleanLevel {
     /// 只清理用户程序输出目录
     Output,
 }
+
+#[derive(Debug, Deserialize, PartialEq)]
+/// 用户程序配置文件
+pub struct UserConfigFile {
+    /// 包名
+    pub name: String,
+    /// 版本
+    pub version: String,
+    /// 包的描述
+    pub description: String,
+    /// 任务类型
+    #[serde(rename = "task-source")]
+    pub task_source: TaskSource,
+    /// 依赖的包
+    #[serde(default = "default_empty_dep")]
+    pub depends: Vec<Dependency>,
+    /// 构建配置
+    pub build: BuildConfig,
+    /// 安装配置
+    pub install: InstallConfig,
+    /// 清理配置
+    pub clean: CleanConfig,
+    /// 环境变量
+    #[serde(default = "default_empty_env")]
+    pub envs: Vec<TaskEnv>,
+
+    /// (可选) 是否只构建一次,如果为true,DADK会在构建成功后,将构建结果缓存起来,下次构建时,直接使用缓存的构建结果。
+    #[serde(rename = "build-once", default = "default_false")]
+    pub build_once: bool,
+
+    /// (可选) 是否只安装一次,如果为true,DADK会在安装成功后,不再重复安装。
+    #[serde(rename = "install-once", default = "default_false")]
+    pub install_once: bool,
+
+    #[serde(rename = "target-arch")]
+    pub target_arch: Vec<TargetArch>,
+}
+
+impl UserConfigFile {
+    pub fn load(path: &PathBuf) -> Result<Self> {
+        let content = std::fs::read_to_string(path)?;
+        Self::load_from_str(&content)
+    }
+
+    pub fn load_from_str(content: &str) -> Result<Self> {
+        let config: UserConfigFile = toml::from_str(content)?;
+        Ok(config)
+    }
+}
+
+fn default_empty_env() -> Vec<TaskEnv> {
+    vec![]
+}
+
+fn default_empty_dep() -> Vec<Dependency> {
+    vec![]
+}
+
+fn default_false() -> bool {
+    false
+}

+ 17 - 0
dadk-config/templates/config/actions/mod.rs

@@ -0,0 +1,17 @@
+use crate::context::DADKExecContext;
+
+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) => {
+            unimplemented!("rootfs command has not implemented for run yet.")
+        }
+        crate::console::Action::User(user_command) => {
+            user::run(&ctx, user_command).expect("Run user action error.")
+        }
+    }
+}

+ 23 - 0
dadk-config/templates/config/actions/user.rs

@@ -0,0 +1,23 @@
+use anyhow::Result;
+use dadk_user::dadk_user_main;
+
+use crate::{console::user::UserCommand, context::DADKExecContext};
+
+pub(super) fn run(ctx: &DADKExecContext, cmd: &UserCommand) -> Result<()> {
+    let config_dir = ctx.user_config_dir()?;
+    let cache_root_dir = ctx.cache_root_dir()?;
+    let sysroot_dir = ctx.sysroot_dir()?;
+    let dadk_user_action: dadk_user::context::Action = cmd.clone().into();
+
+    let context = dadk_user::context::DadkUserExecuteContextBuilder::default()
+        .sysroot_dir(sysroot_dir)
+        .config_dir(config_dir)
+        .action(dadk_user_action)
+        .thread_num(1)
+        .cache_dir(cache_root_dir)
+        .target_arch(ctx.target_arch())
+        .build()
+        .expect("Failed to build execute context");
+    dadk_user_main(context);
+    Ok(())
+}

+ 76 - 0
dadk-config/templates/config/userapp_config.toml

@@ -0,0 +1,76 @@
+# 用户程序名称
+name = "userapp_config"
+
+# 版本号
+version = "0.2.0"
+
+# 用户程序描述信息
+description = ""
+
+# (可选)是否只构建一次,如果为true,DADK会在构建成功后,将构建结果缓存起来,下次构建时,直接使用缓存的构建结果
+build-once = true
+
+#  (可选) 是否只安装一次,如果为true,DADK会在安装成功后,不再重复安装
+
+install-once = true
+
+# 目标架构
+# 可选值:"x86_64", "aarch64", "riscv64"
+target-arch = ["x86_64"]
+
+# 任务源
+[task-source]
+
+# 构建类型
+# 可选值:"build-from_source", "install-from-prebuilt"
+type = "build-from-source"
+
+# 构建来源
+# "build_from_source" 可选值:"git", "local", "archive"
+# "install_from_prebuilt" 可选值:"local", "archive"
+source = "git"
+
+# 路径或URL
+source-path = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/test_git.git"
+
+# git标签或分支
+# 注意: branch和revision只能二选一,且source要设置为"git"
+revision = "01cdc56863"
+# branch = "test"
+
+# 构建相关信息
+[build]
+
+# (可选)构建命令
+build-command = "make install"
+
+# 安装相关信息
+[install]
+
+# (可选)安装到DragonOS的路径
+in-dragonos-path = "/bin"
+
+# 清除相关信息
+[clean]
+
+# (可选)清除命令
+clean-command = "make clean"
+
+# (可选)依赖项
+# 注意:如果没有依赖项,忽略此项,不允许只留一个[[depends]]
+[[depends]]
+name = "depend1"
+version = "0.1.1"
+
+[[depends]]
+name = "depend2"
+version = "0.1.2"
+
+# (可选)环境变量
+[[envs]]
+key = "PATH"
+value = "/usr/bin"
+
+[[envs]]
+key = "LD_LIBRARY_PATH"
+value = "/usr/lib"

+ 72 - 0
dadk-config/tests/test_user_config.rs

@@ -0,0 +1,72 @@
+use std::path::PathBuf;
+
+use dadk_config::{
+    common::{
+        target_arch::TargetArch,
+        task::{
+            BuildConfig, CleanConfig, Dependency, InstallConfig, Source, TaskEnv, TaskSource,
+            TaskSourceType,
+        },
+    },
+    user::UserConfigFile,
+};
+use test_base::{
+    dadk_config::DadkConfigTestContext,
+    test_context::{self as test_context, test_context},
+};
+
+const USER_CONFIG_LOCAL_FILE: &str = "config/userapp_config.toml";
+
+/// 测试解析DADK用户配置文件
+#[test_context(DadkConfigTestContext)]
+#[test]
+fn test_parse_dadk_user_config(ctx: &mut DadkConfigTestContext) {
+    let config_file = ctx.templates_dir().join(USER_CONFIG_LOCAL_FILE);
+    assert!(config_file.exists());
+    assert!(config_file.is_file());
+    let r = UserConfigFile::load(&config_file);
+    assert!(r.is_ok());
+    let mut user_config = r.unwrap();
+    let mut expected_user_config = UserConfigFile {
+        name: "userapp_config".to_string(),
+        version: "0.2.0".to_string(),
+        description: "".to_string(),
+        build_once: true,
+        install_once: true,
+        task_source: TaskSource {
+            source_type: TaskSourceType::BuildFromSource,
+            source: Source::Git,
+            source_path: "https://git.mirrors.dragonos.org.cn/DragonOS-Community/test_git.git"
+                .to_string(),
+            branch: None,
+            revision: Some("01cdc56863".to_string()),
+        },
+        depends: vec![
+            Dependency {
+                name: "depend1".to_string(),
+                version: "0.1.1".to_string(),
+            },
+            Dependency {
+                name: "depend2".to_string(),
+                version: "0.1.2".to_string(),
+            },
+        ],
+        build: BuildConfig::new(Some("make install".to_string())),
+        install: InstallConfig::new(Some(PathBuf::from("/bin"))),
+        clean: CleanConfig::new(Some("make clean".to_string())),
+        envs: vec![
+            TaskEnv::new("PATH".to_string(), "/usr/bin".to_string()),
+            TaskEnv::new("LD_LIBRARY_PATH".to_string(), "/usr/lib".to_string()),
+        ],
+        target_arch: vec![TargetArch::try_from("x86_64").unwrap()],
+    };
+
+    user_config.target_arch.sort();
+    expected_user_config.target_arch.sort();
+    user_config.depends.sort();
+    expected_user_config.depends.sort();
+    user_config.envs.sort();
+    expected_user_config.envs.sort();
+
+    assert_eq!(user_config, expected_user_config)
+}

+ 3 - 37
dadk-user/src/executor/mod.rs

@@ -6,25 +6,25 @@ use std::{
     sync::{Arc, RwLock},
 };
 
-use dadk_config::user::UserCleanLevel;
 use log::{debug, error, info, warn};
 
 use crate::{
     context::{Action, DadkUserExecuteContext},
     executor::cache::CacheDir,
     parser::{
-        task::{CodeSource, PrebuiltSource, TaskEnv, TaskType},
+        task::{CodeSource, PrebuiltSource, TaskType},
         task_log::{BuildStatus, InstallStatus, TaskLog},
     },
     scheduler::{SchedEntities, SchedEntity},
     utils::{file::FileUtils, path::abs_path},
 };
 
+use dadk_config::{common::task::TaskEnv, user::UserCleanLevel};
+
 use self::cache::{CacheDirType, TaskDataDir};
 
 pub mod cache;
 pub mod source;
-pub mod target;
 #[cfg(test)]
 mod tests;
 
@@ -181,8 +181,6 @@ impl Executor {
             }
         }
 
-        self.mv_target_to_tmp()?;
-
         // 确认源文件就绪
         self.prepare_input()?;
 
@@ -242,11 +240,6 @@ impl Executor {
             .map_err(|e| ExecutorError::InstallError(e))?;
         info!("Task {} installed.", self.entity.task().name_version());
 
-        // 安装完后,删除临时target文件
-        if let Some(target) = self.entity.target() {
-            target.clean_tmpdadk()?;
-        }
-
         return Ok(());
     }
 
@@ -406,9 +399,6 @@ impl Executor {
 
     /// # 准备工作线程本地环境变量
     fn prepare_local_env(&mut self) -> Result<(), ExecutorError> {
-        // 设置本地环境变量
-        self.prepare_target_env()?;
-
         let binding = self.entity.task();
         let task_envs: Option<&Vec<TaskEnv>> = binding.envs.as_ref();
 
@@ -528,30 +518,6 @@ impl Executor {
             return Err(ExecutorError::TaskFailed(errmsg));
         }
     }
-
-    pub fn mv_target_to_tmp(&mut self) -> Result<(), ExecutorError> {
-        if let Some(rust_target) = self.entity.task().rust_target.clone() {
-            // 将target文件拷贝至 /tmp 下对应的dadk文件的临时target文件中
-            self.entity
-                .target()
-                .as_ref()
-                .unwrap()
-                .cp_to_tmp(&rust_target)?;
-        }
-        return Ok(());
-    }
-
-    pub fn prepare_target_env(&mut self) -> Result<(), ExecutorError> {
-        if self.entity.task().rust_target.is_some() {
-            // 如果有dadk任务有rust_target字段,需要设置DADK_RUST_TARGET_FILE环境变量,值为临时target文件路径
-            self.entity
-                .target()
-                .as_ref()
-                .unwrap()
-                .prepare_env(&mut self.local_envs);
-        }
-        return Ok(());
-    }
 }
 
 #[derive(Debug, Clone)]

+ 21 - 13
dadk-user/src/executor/source.rs

@@ -14,6 +14,8 @@ use crate::utils::{file::FileUtils, stdio::StdioUtils};
 
 use super::cache::CacheDir;
 
+use anyhow::{Error, Result};
+
 /// # Git源
 ///
 /// 从Git仓库获取源码
@@ -38,9 +40,9 @@ impl GitSource {
     /// # 验证参数合法性
     ///
     /// 仅进行形式校验,不会检查Git仓库是否存在,以及分支是否存在、是否有权限访问等
-    pub fn validate(&mut self) -> Result<(), String> {
+    pub fn validate(&mut self) -> Result<()> {
         if self.url.is_empty() {
-            return Err("url is empty".to_string());
+            return Err(Error::msg("url is empty"));
         }
         // branch和revision不能同时为空
         if self.branch.is_none() && self.revision.is_none() {
@@ -48,17 +50,17 @@ impl GitSource {
         }
         // branch和revision只能同时指定一个
         if self.branch.is_some() && self.revision.is_some() {
-            return Err("branch and revision are both specified".to_string());
+            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("branch is empty".to_string());
+                return Err(Error::msg("branch is empty"));
             }
         }
         if self.revision.is_some() {
             if self.revision.as_ref().unwrap().is_empty() {
-                return Err("revision is empty".to_string());
+                return Err(Error::msg("revision is empty"));
             }
         }
         return Ok(());
@@ -460,18 +462,21 @@ impl LocalSource {
         Self { path }
     }
 
-    pub fn validate(&self, expect_file: Option<bool>) -> Result<(), String> {
+    pub fn validate(&self, expect_file: Option<bool>) -> Result<()> {
         if !self.path.exists() {
-            return Err(format!("path {:?} not exists", self.path));
+            return Err(Error::msg(format!("path {:?} not exists", self.path)));
         }
 
         if let Some(expect_file) = expect_file {
             if expect_file && !self.path.is_file() {
-                return Err(format!("path {:?} is not a file", self.path));
+                return Err(Error::msg(format!("path {:?} is not a file", self.path)));
             }
 
             if !expect_file && !self.path.is_dir() {
-                return Err(format!("path {:?} is not a directory", self.path));
+                return Err(Error::msg(format!(
+                    "path {:?} is not a directory",
+                    self.path
+                )));
             }
         }
 
@@ -497,18 +502,21 @@ impl ArchiveSource {
     pub fn new(url: String) -> Self {
         Self { url }
     }
-    pub fn validate(&self) -> Result<(), String> {
+    pub fn validate(&self) -> Result<()> {
         if self.url.is_empty() {
-            return Err("url is empty".to_string());
+            return Err(Error::msg("url is empty"));
         }
 
         // 判断是一个网址
         if let Ok(url) = Url::parse(&self.url) {
             if url.scheme() != "http" && url.scheme() != "https" {
-                return Err(format!("url {:?} is not a http/https url", self.url));
+                return Err(Error::msg(format!(
+                    "url {:?} is not a http/https url",
+                    self.url
+                )));
             }
         } else {
-            return Err(format!("url {:?} is not a valid url", self.url));
+            return Err(Error::msg(format!("url {:?} is not a valid url", self.url)));
         }
         return Ok(());
     }

+ 0 - 212
dadk-user/src/executor/target.rs

@@ -1,212 +0,0 @@
-use ::std::{
-    collections::hash_map::DefaultHasher,
-    fs,
-    hash::{Hash, Hasher},
-    path::PathBuf,
-};
-use log::error;
-use std::io::Write;
-
-use crate::{
-    executor::{EnvMap, EnvVar},
-    static_resources::INLINE_TARGETS,
-};
-
-use crate::executor::ExecutorError;
-
-/// Target用于管理target文件
-#[derive(Debug, Clone)]
-pub struct Target {
-    /// 临时target文件路径
-    tmp_target_path: PathBuf,
-}
-
-impl Target {
-    /// 创建target管理器
-    ///
-    /// ## 参数
-    ///
-    /// - `path` : 临时target文件路径
-    ///
-    /// ## 返回值
-    ///
-    /// target管理器
-    pub fn new(path: PathBuf) -> Target {
-        Target {
-            tmp_target_path: path,
-        }
-    }
-
-    /// 将用户的target文件或用户使用的内置target文件拷贝到临时target文件
-    ///
-    /// ## 参数
-    ///
-    /// - `rust_target` : dadk任务的rust_target字段值
-    ///
-    /// ## 返回值
-    ///
-    /// Ok(()) 拷贝成功
-    /// Err(ExecutorError) 拷贝失败
-    pub fn cp_to_tmp(&self, rust_target: &str) -> Result<(), ExecutorError> {
-        // 创建临时target文件
-        if Self::is_user_target(rust_target) {
-            // 如果是用户的target文件,则从源target文件路径from拷贝
-            let from = Self::user_target_path(&rust_target).unwrap();
-            self.copy_to_tmp(&from)?;
-        } else {
-            // 如果使用的是内置target文件,则将默认的target文件写入临时target文件中
-            self.write_to_tmp(rust_target)?;
-        }
-        return Ok(());
-    }
-
-    pub fn copy_to_tmp(&self, from: &PathBuf) -> Result<(), ExecutorError> {
-        //创建临时target文件
-        self.create_tmp_target()?;
-        if let Err(e) = fs::copy(from, &self.tmp_target_path) {
-            return Err(ExecutorError::PrepareEnvError(format!("{}", e)));
-        }
-        return Ok(());
-    }
-
-    pub fn write_to_tmp(&self, rust_target: &str) -> Result<(), ExecutorError> {
-        // 创建临时target文件
-        let file = self.create_tmp_target()?;
-        let data = INLINE_TARGETS.lock().unwrap().get(rust_target)?;
-        // 将target文件的二进制变量写入临时target文件中
-        if file.is_some() {
-            if let Err(e) = file.unwrap().write_all(&data) {
-                return Err(ExecutorError::PrepareEnvError(format!("{}", e)));
-            }
-        }
-        return Ok(());
-    }
-
-    /// 获取用户的target文件路径
-    ///
-    /// ## 参数
-    ///
-    /// - `rust_target` : dadk任务的rust_target字段值
-    ///
-    /// ## 返回值
-    ///
-    /// Ok(PathBuf) 用户target文件路径
-    /// Err(ExecutorError) 用户target文件路径无效
-    pub fn user_target_path(rust_target: &str) -> Result<PathBuf, ExecutorError> {
-        // 如果是个路径,说明是用户自己的编译target文件,就判断文件是否有效
-        let path = PathBuf::from(rust_target);
-        if path.exists() {
-            return Ok(path);
-        } else {
-            let path = path.as_path().to_str().unwrap();
-            let errmsg = format!("Can not find the rust_target file: {}", path);
-            error!("{errmsg}");
-            return Err(ExecutorError::PrepareEnvError(errmsg));
-        }
-    }
-
-    /// 通过dadk任务的路径生成相应的临时dadk目录路径
-    ///
-    /// ## 参数
-    ///
-    /// - `file_str` : dadk任务文件路径的字符串值
-    ///
-    /// ## 返回值
-    ///
-    /// 临时dadk目录路径
-    pub fn tmp_dadk(file_str: &str) -> PathBuf {
-        let mut hasher = DefaultHasher::new();
-        file_str.hash(&mut hasher);
-        let hash_string = format!("{:x}", hasher.finish());
-        // 在/tmp文件夹下,创建当前DADK任务文件夹用于临时存放target
-        let tmp_dadk = format!("/tmp/dadk{}/", hash_string);
-        return PathBuf::from(tmp_dadk);
-    }
-
-    /// 创建临时target文件
-    ///
-    /// ## 参数
-    ///
-    /// - `tmp_target_path` : 临时target文件路径
-    ///
-    /// ## 返回值
-    ///
-    /// Ok(Some(fs::File)) 创建成功后的文件
-    /// Ok(None) 临时target文件已经存在,不需要再创建
-    /// Err(ExecutorError) 创建失败
-    pub fn create_tmp_target(&self) -> Result<Option<fs::File>, ExecutorError> {
-        // 先创建用于存放临时target文件的临时dadk目录
-        let dir = Self::dir(&self.tmp_target_path);
-        if fs::metadata(dir.clone()).is_err() {
-            if let Err(e) = fs::create_dir(dir.clone()) {
-                return Err(ExecutorError::PrepareEnvError(format!(
-                    "{}{}",
-                    dir.display(),
-                    e
-                )));
-            }
-        }
-
-        // 如果临时target文件已经存在,则不需要返回文件,返回None即可
-        if fs::metadata(&self.tmp_target_path).is_err() {
-            if let Ok(file) = fs::File::create(&self.tmp_target_path) {
-                return Ok(Some(file));
-            }
-        }
-
-        return Ok(None);
-    }
-
-    /// 设置DADK_RUST_TARGET_FILE环境变量
-    ///
-    /// ## 参数
-    ///
-    /// - `local_envs` : 当前任务的环境变量列表
-    ///
-    /// ## 返回值
-    ///
-    /// 无
-    pub fn prepare_env(&self, local_envs: &mut EnvMap) {
-        let path = self
-            .tmp_target_path()
-            .as_path()
-            .to_str()
-            .unwrap()
-            .to_string();
-        local_envs.add(EnvVar::new("DADK_RUST_TARGET_FILE".to_string(), path));
-    }
-
-    /// 清理生成的临时dadk目录
-    pub fn clean_tmpdadk(&self) -> Result<(), ExecutorError> {
-        if self.tmp_target_path.exists() {
-            let dir = Self::dir(&self.tmp_target_path);
-            std::fs::remove_dir_all(&dir)
-                .map_err(|e| ExecutorError::CleanError(format!("{}{}", dir.display(), e)))?;
-        }
-        return Ok(());
-    }
-
-    /// 获取文件所在的目录路径
-    ///
-    /// ## 参数
-    ///
-    /// - `path` : 文件路径
-    ///
-    /// ## 返回值
-    ///
-    /// 文件所在目录路径
-    pub fn dir(path: &PathBuf) -> PathBuf {
-        let path_str = path.as_path().to_str().unwrap();
-        let index = path_str.rfind('/').unwrap();
-        return PathBuf::from(path_str[..index + 1].to_string());
-    }
-
-    pub fn is_user_target(rust_target: &str) -> bool {
-        // 如果包含.的话,说明用户使用的是自己的target文件,因为带有.json这样的字符
-        return rust_target.contains('.');
-    }
-
-    pub fn tmp_target_path(&self) -> &PathBuf {
-        return &self.tmp_target_path;
-    }
-}

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

@@ -13,7 +13,7 @@ use crate::{
 use super::create_global_env_list;
 
 fn setup_executor<T: TestContextExt>(config_file: PathBuf, ctx: &T) -> Executor {
-    let task = Parser::new(ctx.base_context().config_v1_dir()).parse_config_file(&config_file);
+    let task = Parser::new(ctx.base_context().config_v2_dir()).parse_config_file(&config_file);
     assert!(task.is_ok(), "parse error: {:?}", task);
     let scheduler = Scheduler::new(
         ctx.execute_context().self_ref().unwrap(),

+ 0 - 478
dadk-user/src/parser/config.rs

@@ -1,478 +0,0 @@
-use std::path::PathBuf;
-
-use dadk_config::common::target_arch::TargetArch;
-use serde::de::Error;
-use toml::Value;
-
-use super::{
-    task::{Dependency, TaskEnv},
-    InnerParserError, ParserError,
-};
-
-// DADK用户配置关键字
-pub(super) enum DADKUserConfigKey {
-    Name,
-    Version,
-    Description,
-    BuildOnce,
-    InstallOnce,
-    RustTarget,
-    TargetArch,
-    TaskType,
-    Type,
-    Source,
-    SourcePath,
-    Revision,
-    Branch,
-    Build,
-    BuildCommand,
-    Install,
-    InDragonosPath,
-    Clean,
-    CleanCommand,
-    Depends,
-    Envs,
-    BuildFromSource,
-    InstallFromPrebuilt,
-    Git,
-    Local,
-    Archive,
-}
-
-impl Into<&str> for DADKUserConfigKey {
-    fn into(self) -> &'static str {
-        match self {
-            DADKUserConfigKey::Name => "name",
-            DADKUserConfigKey::Version => "version",
-            DADKUserConfigKey::Description => "description",
-            DADKUserConfigKey::BuildOnce => "build-once",
-            DADKUserConfigKey::InstallOnce => "install-once",
-            DADKUserConfigKey::RustTarget => "rust-target",
-            DADKUserConfigKey::TargetArch => "target-arch",
-            DADKUserConfigKey::TaskType => "task-type",
-            DADKUserConfigKey::Type => "type",
-            DADKUserConfigKey::Source => "source",
-            DADKUserConfigKey::SourcePath => "source-path",
-            DADKUserConfigKey::Revision => "revison",
-            DADKUserConfigKey::Branch => "branch",
-            DADKUserConfigKey::Build => "build",
-            DADKUserConfigKey::BuildCommand => "build-command",
-            DADKUserConfigKey::Install => "install",
-            DADKUserConfigKey::InDragonosPath => "in-dragonos-path",
-            DADKUserConfigKey::Clean => "clean",
-            DADKUserConfigKey::CleanCommand => "clean-command",
-            DADKUserConfigKey::Depends => "depends",
-            DADKUserConfigKey::Envs => "envs",
-            DADKUserConfigKey::BuildFromSource => "build_from_source",
-            DADKUserConfigKey::InstallFromPrebuilt => "install_from_prebuilt",
-            DADKUserConfigKey::Archive => "archive",
-            DADKUserConfigKey::Git => "git",
-            DADKUserConfigKey::Local => "local",
-        }
-    }
-}
-
-impl TryFrom<&str> for DADKUserConfigKey {
-    type Error = ParserError;
-    fn try_from(value: &str) -> Result<Self, Self::Error> {
-        match value {
-            "name" => Ok(DADKUserConfigKey::Name),
-            "version" => Ok(DADKUserConfigKey::Version),
-            "description" => Ok(DADKUserConfigKey::Description),
-            "build-once" => Ok(DADKUserConfigKey::BuildOnce),
-            "install-once" => Ok(DADKUserConfigKey::InstallOnce),
-            "rust-target" => Ok(DADKUserConfigKey::RustTarget),
-            "target-arch" => Ok(DADKUserConfigKey::TargetArch),
-            "task-type" => Ok(DADKUserConfigKey::TaskType),
-            "type" => Ok(DADKUserConfigKey::Type),
-            "source" => Ok(DADKUserConfigKey::Source),
-            "source-path" => Ok(DADKUserConfigKey::SourcePath),
-            "revison" => Ok(DADKUserConfigKey::Revision),
-            "branch" => Ok(DADKUserConfigKey::Branch),
-            "build" => Ok(DADKUserConfigKey::Build),
-            "build-command" => Ok(DADKUserConfigKey::BuildCommand),
-            "install" => Ok(DADKUserConfigKey::Install),
-            "in-dragonos-path" => Ok(DADKUserConfigKey::InDragonosPath),
-            "clean" => Ok(DADKUserConfigKey::Clean),
-            "clean-command" => Ok(DADKUserConfigKey::CleanCommand),
-            "depends" => Ok(DADKUserConfigKey::Depends),
-            "envs" => Ok(DADKUserConfigKey::Envs),
-            "build_from_source" => Ok(DADKUserConfigKey::BuildFromSource),
-            "install_from_prebuilt" => Ok(DADKUserConfigKey::InstallFromPrebuilt),
-            "archive" => Ok(DADKUserConfigKey::Archive),
-            "git" => Ok(DADKUserConfigKey::Git),
-            "local" => Ok(DADKUserConfigKey::Local),
-            _ => Err(ParserError {
-                config_file: None,
-                error: InnerParserError::TomlError(toml::de::Error::custom(format!(
-                    "Unknown dadk_user_config_key: {}",
-                    value
-                ))),
-            }),
-        }
-    }
-}
-
-pub(super) struct DADKUserConfig {
-    pub(super) standard_config: DADKUserStandardConfig,
-    pub(super) task_type_config: DADKUserTaskType,
-    pub(super) build_config: DADKUserBuildConfig,
-    pub(super) install_config: DADKUserInstallConfig,
-    pub(super) clean_config: DADKUserCleanConfig,
-    pub(super) depends_config: DADKUserDependsConfig,
-    pub(super) envs_config: DADKUserEnvsConfig,
-}
-
-impl DADKUserConfig {
-    pub(super) fn parse(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-    ) -> Result<DADKUserConfig, ParserError> {
-        Ok(Self {
-            standard_config: DADKUserStandardConfig::parse(config_file, table)?,
-            task_type_config: DADKUserTaskType::parse(config_file, table)?,
-            build_config: DADKUserBuildConfig::parse(config_file, table)?,
-            install_config: DADKUserInstallConfig::parse(config_file, table)?,
-            clean_config: DADKUserCleanConfig::parse(config_file, table)?,
-            depends_config: DADKUserDependsConfig::parse(config_file, table)?,
-            envs_config: DADKUserEnvsConfig::parse(config_file, table)?,
-        })
-    }
-}
-
-/// 标准信息配置
-#[derive(Debug)]
-pub(super) struct DADKUserStandardConfig {
-    pub(super) name: String,
-    pub(super) version: String,
-    pub(super) description: String,
-    pub(super) build_once: bool,
-    pub(super) install_once: bool,
-    pub(super) rust_target: Option<String>,
-    pub(super) target_arch: Vec<TargetArch>,
-}
-
-impl DADKUserStandardConfig {
-    fn parse(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-    ) -> Result<DADKUserStandardConfig, ParserError> {
-        let name: String =
-            TomlValueParser::parse_string(config_file, table, DADKUserConfigKey::Name.into())?;
-        let version =
-            TomlValueParser::parse_string(config_file, table, DADKUserConfigKey::Version.into())?;
-        let description = TomlValueParser::parse_string(
-            config_file,
-            table,
-            DADKUserConfigKey::Description.into(),
-        )?;
-        let build_once =
-            TomlValueParser::parse_bool(config_file, table, DADKUserConfigKey::BuildOnce.into())?;
-        let install_once =
-            TomlValueParser::parse_bool(config_file, table, DADKUserConfigKey::InstallOnce.into())?;
-        let rust_target =
-            TomlValueParser::parse_option_string(table, DADKUserConfigKey::RustTarget.into());
-        let target_arch: Vec<TargetArch> = match TomlValueParser::parse_option_array(
-            table,
-            DADKUserConfigKey::TargetArch.into(),
-        ) {
-            Some(value_vec) => {
-                let mut target_arch_vec = Vec::new();
-                for value in value_vec {
-                    let target_arch =
-                        TargetArch::try_from(value.as_str().unwrap()).map_err(|e| ParserError {
-                            config_file: Some(config_file.clone()),
-                            error: InnerParserError::TomlError(toml::de::Error::custom(e)),
-                        })?;
-                    target_arch_vec.push(target_arch);
-                }
-                target_arch_vec
-            }
-            None => vec![TargetArch::X86_64],
-        };
-
-        Ok(Self {
-            name,
-            version,
-            description,
-            build_once,
-            install_once,
-            rust_target,
-            target_arch,
-        })
-    }
-}
-
-/// task-type配置
-#[derive(Debug)]
-pub(super) struct DADKUserTaskType {
-    pub(super) config_file: PathBuf,
-    pub(super) task_type: String,
-    pub(super) source: String,
-    pub(super) source_path: String,
-    // git独有
-    pub(super) revision: Option<String>,
-    pub(super) branch: Option<String>,
-}
-
-impl DADKUserTaskType {
-    fn parse(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-    ) -> Result<DADKUserTaskType, ParserError> {
-        let task_type_table =
-            TomlValueParser::parse_table(config_file, table, DADKUserConfigKey::TaskType.into())?;
-        let task_type = TomlValueParser::parse_string(
-            config_file,
-            &task_type_table,
-            DADKUserConfigKey::Type.into(),
-        )?;
-        let source = TomlValueParser::parse_string(
-            config_file,
-            &task_type_table,
-            DADKUserConfigKey::Source.into(),
-        )?;
-
-        let source_path = TomlValueParser::parse_string(
-            config_file,
-            &task_type_table,
-            DADKUserConfigKey::SourcePath.into(),
-        )?;
-
-        let (branch, revision) =
-            if source.to_lowercase().trim() == Into::<&str>::into(DADKUserConfigKey::Git) {
-                let branch = TomlValueParser::parse_option_string(
-                    &task_type_table,
-                    DADKUserConfigKey::Branch.into(),
-                );
-                let revision = TomlValueParser::parse_option_string(
-                    &task_type_table,
-                    DADKUserConfigKey::Revision.into(),
-                );
-                (branch, revision)
-            } else {
-                (None, None)
-            };
-
-        Ok(Self {
-            config_file: config_file.clone(),
-            task_type,
-            source,
-            source_path,
-            revision,
-            branch,
-        })
-    }
-}
-
-/// build配置
-#[derive(Debug)]
-pub(super) struct DADKUserBuildConfig {
-    pub(super) build_command: Option<String>,
-}
-
-impl DADKUserBuildConfig {
-    fn parse(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-    ) -> Result<DADKUserBuildConfig, ParserError> {
-        let build_table =
-            TomlValueParser::parse_table(config_file, table, DADKUserConfigKey::Build.into())?;
-        let build_command = TomlValueParser::parse_option_string(
-            &build_table,
-            DADKUserConfigKey::BuildCommand.into(),
-        );
-        Ok(Self { build_command })
-    }
-}
-
-/// install配置
-#[derive(Debug)]
-pub(super) struct DADKUserInstallConfig {
-    pub(super) in_dragonos_path: Option<PathBuf>,
-}
-
-impl DADKUserInstallConfig {
-    fn parse(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-    ) -> Result<DADKUserInstallConfig, ParserError> {
-        let install_table =
-            TomlValueParser::parse_table(config_file, table, DADKUserConfigKey::Install.into())?;
-        let in_dragonos_path = TomlValueParser::parse_option_string(
-            &install_table,
-            DADKUserConfigKey::InDragonosPath.into(),
-        )
-        .map(|path| PathBuf::from(path));
-
-        Ok(Self { in_dragonos_path })
-    }
-}
-
-/// clean配置
-#[derive(Debug)]
-pub(super) struct DADKUserCleanConfig {
-    pub(super) clean_command: Option<String>,
-}
-
-impl DADKUserCleanConfig {
-    fn parse(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-    ) -> Result<DADKUserCleanConfig, ParserError> {
-        let clean_table =
-            TomlValueParser::parse_table(config_file, table, DADKUserConfigKey::Clean.into())?;
-        let clean_command = TomlValueParser::parse_option_string(
-            &clean_table,
-            DADKUserConfigKey::CleanCommand.into(),
-        );
-        Ok(Self { clean_command })
-    }
-}
-
-/// depends配置
-#[derive(Debug)]
-pub(super) struct DADKUserDependsConfig {
-    pub(super) depends: Vec<Dependency>,
-}
-
-impl DADKUserDependsConfig {
-    fn parse(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-    ) -> Result<DADKUserDependsConfig, ParserError> {
-        let depends_table =
-            TomlValueParser::parse_table(config_file, table, DADKUserConfigKey::Depends.into())?;
-        let depends = depends_table
-            .iter()
-            .map(|(key, value)| Dependency {
-                name: key.clone(),
-                version: value.as_str().unwrap().to_string(),
-            })
-            .collect::<Vec<Dependency>>();
-        Ok(Self { depends })
-    }
-}
-/// envs配置
-#[derive(Debug)]
-pub(super) struct DADKUserEnvsConfig {
-    pub(super) envs: Option<Vec<TaskEnv>>,
-}
-
-impl DADKUserEnvsConfig {
-    fn parse(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-    ) -> Result<DADKUserEnvsConfig, ParserError> {
-        let envs_table: toml::map::Map<String, Value> =
-            TomlValueParser::parse_table(config_file, table, DADKUserConfigKey::Envs.into())?;
-        let envs_vec = if !envs_table.is_empty() {
-            Some(
-                envs_table
-                    .iter()
-                    .map(|(key, value)| TaskEnv {
-                        key: key.clone(),
-                        value: value.as_str().unwrap().to_string(),
-                    })
-                    .collect::<Vec<TaskEnv>>(),
-            )
-        } else {
-            None
-        };
-
-        Ok(DADKUserEnvsConfig { envs: envs_vec })
-    }
-}
-
-struct TomlValueParser;
-
-impl TomlValueParser {
-    // 解析String类型的值
-    fn parse_string(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-        key: &'static str,
-    ) -> Result<String, ParserError> {
-        let value = table.get(key).ok_or(ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TomlError(toml::de::Error::missing_field(key)),
-        })?;
-        Ok(value.as_str().unwrap().to_string())
-    }
-
-    // 解析Option<String>类型的值
-    fn parse_option_string(table: &toml::value::Table, key: &'static str) -> Option<String> {
-        let value = table.get(key);
-        value.map(|v| v.as_str().unwrap().to_string())
-    }
-
-    // 解析Table类型的值
-    fn parse_table(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-        key: &'static str,
-    ) -> Result<toml::value::Table, ParserError> {
-        let value = table.get(key).ok_or(ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TomlError(toml::de::Error::missing_field(key)),
-        })?;
-        let table = value.as_table().ok_or(ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TomlError(toml::de::Error::custom(format!(
-                "{} is not a table",
-                key
-            ))),
-        })?;
-        Ok(table.clone())
-    }
-
-    #[allow(dead_code)]
-    // 解析Array类型的值
-    fn parse_array(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-        key: &'static str,
-    ) -> Result<Vec<toml::Value>, ParserError> {
-        let value = table.get(key).ok_or(ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TomlError(toml::de::Error::missing_field(key)),
-        })?;
-        let array = value.as_array().ok_or(ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TomlError(toml::de::Error::custom(format!(
-                "{} is not an array",
-                key
-            ))),
-        })?;
-        Ok(array.clone())
-    }
-
-    // 解析Option<Array>类型的值
-    fn parse_option_array(
-        table: &toml::value::Table,
-        key: &'static str,
-    ) -> Option<Vec<toml::Value>> {
-        let value = table.get(key);
-        value.map(|v| v.as_array().unwrap().clone())
-    }
-
-    // 解析Boolean类型的值
-    fn parse_bool(
-        config_file: &PathBuf,
-        table: &toml::value::Table,
-        key: &'static str,
-    ) -> Result<bool, ParserError> {
-        let value = table.get(key).ok_or(ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TomlError(toml::de::Error::missing_field(key)),
-        })?;
-        let boolean = value.as_bool().ok_or(ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TomlError(toml::de::Error::custom(format!(
-                "{} is not a boolean",
-                key
-            ))),
-        })?;
-        Ok(boolean)
-    }
-}

+ 14 - 49
dadk-user/src/parser/mod.rs

@@ -50,11 +50,10 @@ use std::{
 };
 
 use self::task::DADKTask;
-use config::DADKUserConfig;
+use anyhow::Result;
+use dadk_config::user::UserConfigFile;
 use log::{debug, error, info};
-use task::{BuildConfig, CleanConfig, InstallConfig, TaskType};
-use toml::Table;
-mod config;
+
 pub mod task;
 pub mod task_log;
 
@@ -141,10 +140,10 @@ impl Parser {
     ///
     /// * `Ok(Vec<(PathBuf, DADKTask)>)` - 任务列表(配置文件路径, 任务)
     /// * `Err(ParserError)` - 解析错误
-    pub fn parse(&mut self) -> Result<Vec<(PathBuf, DADKTask)>, ParserError> {
+    pub fn parse(&mut self) -> Result<Vec<(PathBuf, DADKTask)>> {
         self.scan_config_files()?;
         info!("Found {} config files", self.config_files.len());
-        let r: Result<Vec<(PathBuf, DADKTask)>, ParserError> = self.gen_tasks();
+        let r: Result<Vec<(PathBuf, DADKTask)>> = self.gen_tasks();
         if r.is_err() {
             error!("Error while parsing config files: {:?}", r);
         }
@@ -152,7 +151,7 @@ impl Parser {
     }
 
     /// # 扫描配置文件目录,找到所有配置文件
-    fn scan_config_files(&mut self) -> Result<(), ParserError> {
+    fn scan_config_files(&mut self) -> Result<()> {
         info!("Scanning config files in {}", self.config_dir.display());
 
         let mut dir_queue: Vec<PathBuf> = Vec::new();
@@ -162,16 +161,10 @@ impl Parser {
         while !dir_queue.is_empty() {
             // 扫描目录,找到所有*.dadk文件
             let dir = dir_queue.pop().unwrap();
-            let entries: ReadDir = std::fs::read_dir(&dir).map_err(|e| ParserError {
-                config_file: None,
-                error: InnerParserError::IoError(e),
-            })?;
+            let entries: ReadDir = std::fs::read_dir(&dir)?;
 
             for entry in entries {
-                let entry: DirEntry = entry.map_err(|e| ParserError {
-                    config_file: None,
-                    error: InnerParserError::IoError(e),
-                })?;
+                let entry: DirEntry = entry?;
 
                 let path: PathBuf = entry.path();
                 if path.is_dir() {
@@ -202,7 +195,7 @@ impl Parser {
     ///
     /// * `Ok(Vec<DADKTask>)` - 任务列表
     /// * `Err(ParserError)` - 解析错误
-    fn gen_tasks(&self) -> Result<Vec<(PathBuf, DADKTask)>, ParserError> {
+    fn gen_tasks(&self) -> Result<Vec<(PathBuf, DADKTask)>> {
         let mut result_vec = Vec::new();
         for config_file in &self.config_files {
             let task: DADKTask = self.parse_config_file(config_file)?;
@@ -223,7 +216,7 @@ impl Parser {
     ///
     /// * `Ok(DADKTask)` - 生成好的任务
     /// * `Err(ParserError)` - 解析错误
-    pub(super) fn parse_config_file(&self, config_file: &PathBuf) -> Result<DADKTask, ParserError> {
+    pub(super) fn parse_config_file(&self, config_file: &PathBuf) -> Result<DADKTask> {
         // 从toml文件中解析出DADKTask
         let mut task: DADKTask = Self::parse_toml_file(config_file)?;
 
@@ -233,42 +226,14 @@ impl Parser {
         task.trim();
 
         // 校验DADKTask的参数是否合法
-        task.validate().map_err(|e| ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TaskError(e),
-        })?;
+        task.validate()?;
 
         return Ok(task);
     }
 
     /// 解析toml文件,生成DADKTask
-    pub fn parse_toml_file(config_file: &PathBuf) -> Result<DADKTask, ParserError> {
-        let content = std::fs::read_to_string(config_file).map_err(|e| ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::IoError(e),
-        })?;
-
-        let table = content.parse::<Table>().map_err(|e| ParserError {
-            config_file: Some(config_file.clone()),
-            error: InnerParserError::TomlError(e),
-        })?;
-
-        let dadk_user_config = DADKUserConfig::parse(config_file, &table)?;
-
-        Ok(DADKTask {
-            name: dadk_user_config.standard_config.name,
-            version: dadk_user_config.standard_config.version,
-            description: dadk_user_config.standard_config.description,
-            rust_target: dadk_user_config.standard_config.rust_target,
-            task_type: TaskType::try_from(dadk_user_config.task_type_config)?,
-            depends: dadk_user_config.depends_config.depends,
-            build: BuildConfig::from(dadk_user_config.build_config),
-            install: InstallConfig::from(dadk_user_config.install_config),
-            clean: CleanConfig::from(dadk_user_config.clean_config),
-            envs: dadk_user_config.envs_config.envs,
-            build_once: dadk_user_config.standard_config.build_once,
-            install_once: dadk_user_config.standard_config.install_once,
-            target_arch: dadk_user_config.standard_config.target_arch,
-        })
+    pub fn parse_toml_file(config_file: &PathBuf) -> Result<DADKTask> {
+        let dadk_user_config = UserConfigFile::load(config_file)?;
+        DADKTask::try_from(dadk_user_config)
     }
 }

+ 67 - 269
dadk-user/src/parser/task.rs

@@ -1,17 +1,19 @@
 use std::path::PathBuf;
 
-use dadk_config::common::target_arch::TargetArch;
-use serde::{de::Error, Deserialize, Serialize};
-
 use crate::executor::source::{ArchiveSource, GitSource, LocalSource};
-
-use super::{
-    config::{
-        DADKUserBuildConfig, DADKUserCleanConfig, DADKUserConfigKey, DADKUserInstallConfig,
-        DADKUserTaskType,
+use dadk_config::{
+    common::{
+        target_arch::TargetArch,
+        task::{
+            BuildConfig, CleanConfig, Dependency, InstallConfig, Source, TaskEnv, TaskSource,
+            TaskSourceType,
+        },
     },
-    InnerParserError, ParserError,
+    user::UserConfigFile,
 };
+use serde::{Deserialize, Serialize};
+
+use anyhow::{Ok, Result};
 
 // 对于生成的包名和版本号,需要进行替换的字符。
 pub static NAME_VERSION_REPLACE_TABLE: [(&str, &str); 6] = [
@@ -31,8 +33,6 @@ pub struct DADKTask {
     pub version: String,
     /// 包的描述
     pub description: String,
-    /// 编译target
-    pub rust_target: Option<String>,
     /// 任务类型
     pub task_type: TaskType,
     /// 依赖的包
@@ -64,7 +64,6 @@ impl DADKTask {
         name: String,
         version: String,
         description: String,
-        rust_target: Option<String>,
         task_type: TaskType,
         depends: Vec<Dependency>,
         build: BuildConfig,
@@ -79,7 +78,6 @@ impl DADKTask {
             name,
             version,
             description,
-            rust_target,
             task_type,
             depends,
             build,
@@ -104,12 +102,12 @@ impl DADKTask {
         vec![Self::default_target_arch()]
     }
 
-    pub fn validate(&mut self) -> Result<(), String> {
+    pub fn validate(&mut self) -> Result<()> {
         if self.name.is_empty() {
-            return Err("name is empty".to_string());
+            return Err(anyhow::Error::msg("name is empty"));
         }
         if self.version.is_empty() {
-            return Err("version is empty".to_string());
+            return Err(anyhow::Error::msg("version is empty"));
         }
         self.task_type.validate()?;
         self.build.validate()?;
@@ -127,9 +125,6 @@ impl DADKTask {
         self.name = self.name.trim().to_string();
         self.version = self.version.trim().to_string();
         self.description = self.description.trim().to_string();
-        if let Some(target) = &self.rust_target {
-            self.rust_target = Some(target.trim().to_string());
-        };
         self.task_type.trim();
         self.build.trim();
         self.install.trim();
@@ -138,7 +133,7 @@ impl DADKTask {
         self.trim_envs();
     }
 
-    fn validate_depends(&self) -> Result<(), String> {
+    fn validate_depends(&self) -> Result<()> {
         for depend in &self.depends {
             depend.validate()?;
         }
@@ -151,7 +146,7 @@ impl DADKTask {
         }
     }
 
-    fn validate_envs(&self) -> Result<(), String> {
+    fn validate_envs(&self) -> Result<()> {
         if let Some(envs) = &self.envs {
             for env in envs {
                 env.validate()?;
@@ -160,9 +155,9 @@ impl DADKTask {
         return Ok(());
     }
 
-    fn validate_target_arch(&self) -> Result<(), String> {
+    fn validate_target_arch(&self) -> Result<()> {
         if self.target_arch.is_empty() {
-            return Err("target_arch is empty".to_string());
+            return Err(anyhow::Error::msg("target_arch is empty"));
         }
         return Ok(());
     }
@@ -176,18 +171,18 @@ impl DADKTask {
     }
 
     /// 验证任务类型与构建配置是否匹配
-    fn validate_build_type(&self) -> Result<(), String> {
+    fn validate_build_type(&self) -> Result<()> {
         match &self.task_type {
             TaskType::BuildFromSource(_) => {
                 if self.build.build_command.is_none() {
-                    return Err("build command is empty".to_string());
+                    return Err(anyhow::Error::msg("build command is empty"));
                 }
             }
             TaskType::InstallFromPrebuilt(_) => {
                 if self.build.build_command.is_some() {
-                    return Err(
-                        "build command should be empty when install from prebuilt".to_string()
-                    );
+                    return Err(anyhow::Error::msg(
+                        "build command should be empty when install from prebuilt",
+                    ));
                 }
             }
         }
@@ -239,151 +234,24 @@ impl DADKTask {
     }
 }
 
-impl PartialEq for DADKTask {
-    fn eq(&self, other: &Self) -> bool {
-        self.name == other.name
-            && self.version == other.version
-            && self.description == other.description
-            && self.rust_target == other.rust_target
-            && self.build_once == other.build_once
-            && self.install_once == other.install_once
-            && self.target_arch == other.target_arch
-            && self.task_type == other.task_type
-            && self.build == other.build
-            && self.install == other.install
-            && self.clean == other.clean
-            && self.depends == other.depends
-            && self.envs == other.envs
-    }
-}
-
-/// @brief 构建配置
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct BuildConfig {
-    /// 构建命令
-    pub build_command: Option<String>,
-}
-
-impl BuildConfig {
-    #[allow(dead_code)]
-    pub fn new(build_command: Option<String>) -> Self {
-        Self { build_command }
-    }
-
-    pub fn validate(&self) -> Result<(), String> {
-        return Ok(());
-    }
-
-    pub fn trim(&mut self) {
-        if let Some(build_command) = &mut self.build_command {
-            *build_command = build_command.trim().to_string();
-        }
-    }
-}
-
-impl From<DADKUserBuildConfig> for BuildConfig {
-    fn from(value: DADKUserBuildConfig) -> Self {
-        return BuildConfig {
-            build_command: value.build_command,
-        };
-    }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct InstallConfig {
-    /// 安装到DragonOS内的目录
-    pub in_dragonos_path: Option<PathBuf>,
-}
-
-impl InstallConfig {
-    #[allow(dead_code)]
-    pub fn new(in_dragonos_path: Option<PathBuf>) -> Self {
-        Self { in_dragonos_path }
-    }
-
-    pub fn validate(&self) -> Result<(), String> {
-        if self.in_dragonos_path.is_none() {
-            return Ok(());
-        }
-        if self.in_dragonos_path.as_ref().unwrap().is_relative() {
-            return Err("InstallConfig: in_dragonos_path should be an Absolute path".to_string());
-        }
-        return Ok(());
-    }
-
-    pub fn trim(&mut self) {}
-}
-
-impl From<DADKUserInstallConfig> for InstallConfig {
-    fn from(value: DADKUserInstallConfig) -> Self {
-        return InstallConfig {
-            in_dragonos_path: (value.in_dragonos_path),
-        };
-    }
-}
-
-/// # 清理配置
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct CleanConfig {
-    /// 清理命令
-    pub clean_command: Option<String>,
-}
-
-impl CleanConfig {
-    #[allow(dead_code)]
-    pub fn new(clean_command: Option<String>) -> Self {
-        Self { clean_command }
-    }
-
-    pub fn validate(&self) -> Result<(), String> {
-        return Ok(());
-    }
-
-    pub fn trim(&mut self) {
-        if let Some(clean_command) = &mut self.clean_command {
-            *clean_command = clean_command.trim().to_string();
-        }
-    }
-}
-
-impl From<DADKUserCleanConfig> for CleanConfig {
-    fn from(value: DADKUserCleanConfig) -> Self {
-        return CleanConfig {
-            clean_command: value.clean_command,
-        };
-    }
-}
-
-/// @brief 依赖项
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
-pub struct Dependency {
-    pub name: String,
-    pub version: String,
-}
-
-impl Dependency {
-    #[allow(dead_code)]
-    pub fn new(name: String, version: String) -> Self {
-        Self { name, version }
-    }
-
-    pub fn validate(&self) -> Result<(), String> {
-        if self.name.is_empty() {
-            return Err("name is empty".to_string());
-        }
-        if self.version.is_empty() {
-            return Err("version is empty".to_string());
-        }
-        return Ok(());
-    }
-
-    pub fn trim(&mut self) {
-        self.name = self.name.trim().to_string();
-        self.version = self.version.trim().to_string();
-    }
-
-    pub fn name_version(&self) -> String {
-        return format!("{}-{}", self.name, self.version);
+impl TryFrom<UserConfigFile> for DADKTask {
+    type Error = anyhow::Error;
+
+    fn try_from(user_config: UserConfigFile) -> Result<Self> {
+        Ok(DADKTask {
+            name: user_config.name,
+            version: user_config.version,
+            description: user_config.description,
+            task_type: TaskType::try_from(user_config.task_source)?,
+            depends: user_config.depends,
+            build: user_config.build,
+            install: user_config.install,
+            clean: user_config.clean,
+            envs: Some(user_config.envs),
+            build_once: user_config.build_once,
+            install_once: user_config.install_once,
+            target_arch: user_config.target_arch,
+        })
     }
 }
 
@@ -397,7 +265,7 @@ pub enum TaskType {
 }
 
 impl TaskType {
-    pub fn validate(&mut self) -> Result<(), String> {
+    pub fn validate(&mut self) -> Result<()> {
         match self {
             TaskType::BuildFromSource(source) => source.validate(),
             TaskType::InstallFromPrebuilt(source) => source.validate(),
@@ -412,68 +280,34 @@ impl TaskType {
     }
 }
 
-impl TryFrom<DADKUserTaskType> for TaskType {
-    type Error = ParserError;
-    fn try_from(dadk_user_task_type: DADKUserTaskType) -> Result<Self, Self::Error> {
-        let task_type = DADKUserConfigKey::try_from(dadk_user_task_type.task_type.as_str())
-            .map_err(|mut e| {
-                e.config_file = Some(dadk_user_task_type.config_file.clone());
-                e
-            })?;
-
-        let source =
-            DADKUserConfigKey::try_from(dadk_user_task_type.source.as_str()).map_err(|mut e| {
-                e.config_file = Some(dadk_user_task_type.config_file.clone());
-                e
-            })?;
-
-        match task_type {
-            DADKUserConfigKey::BuildFromSource => match source {
-                DADKUserConfigKey::Git => {
-                    Ok(TaskType::BuildFromSource(CodeSource::Git(GitSource::new(
-                        dadk_user_task_type.source_path,
-                        dadk_user_task_type.branch,
-                        dadk_user_task_type.revision,
-                    ))))
-                }
-                DADKUserConfigKey::Local => Ok(TaskType::BuildFromSource(CodeSource::Local(
-                    LocalSource::new(PathBuf::from(dadk_user_task_type.source_path)),
+impl TryFrom<TaskSource> for TaskType {
+    type Error = anyhow::Error;
+    fn try_from(task_source: TaskSource) -> Result<Self> {
+        match task_source.source_type {
+            TaskSourceType::BuildFromSource => match task_source.source {
+                Source::Git => Ok(TaskType::BuildFromSource(CodeSource::Git(GitSource::new(
+                    task_source.source_path,
+                    task_source.branch,
+                    task_source.revision,
+                )))),
+                Source::Local => Ok(TaskType::BuildFromSource(CodeSource::Local(
+                    LocalSource::new(PathBuf::from(task_source.source_path)),
                 ))),
-                DADKUserConfigKey::Archive => Ok(TaskType::BuildFromSource(CodeSource::Archive(
-                    ArchiveSource::new(dadk_user_task_type.source_path),
+                Source::Archive => Ok(TaskType::BuildFromSource(CodeSource::Archive(
+                    ArchiveSource::new(task_source.source_path),
                 ))),
-                _ => Err(ParserError {
-                    config_file: Some(dadk_user_task_type.config_file),
-                    error: InnerParserError::TomlError(toml::de::Error::custom(format!(
-                        "Unknown source: {}",
-                        dadk_user_task_type.source
-                    ))),
-                }),
             },
-            DADKUserConfigKey::InstallFromPrebuilt => match source {
-                DADKUserConfigKey::Local => {
-                    Ok(TaskType::InstallFromPrebuilt(PrebuiltSource::Local(
-                        LocalSource::new(PathBuf::from(dadk_user_task_type.source_path)),
-                    )))
-                }
-                DADKUserConfigKey::Archive => Ok(TaskType::InstallFromPrebuilt(
-                    PrebuiltSource::Archive(ArchiveSource::new(dadk_user_task_type.source_path)),
+            TaskSourceType::InstallFromPrebuilt => match task_source.source {
+                Source::Git => Err(anyhow::Error::msg(
+                    "InstallFromPrebuild doesn't support Git",
                 )),
-                _ => Err(ParserError {
-                    config_file: Some(dadk_user_task_type.config_file),
-                    error: InnerParserError::TomlError(toml::de::Error::custom(format!(
-                        "Unknown source: {}",
-                        dadk_user_task_type.source
-                    ))),
-                }),
-            },
-            _ => Err(ParserError {
-                config_file: Some(dadk_user_task_type.config_file),
-                error: InnerParserError::TomlError(toml::de::Error::custom(format!(
-                    "Unknown task type: {}",
-                    dadk_user_task_type.task_type
+                Source::Local => Ok(TaskType::InstallFromPrebuilt(PrebuiltSource::Local(
+                    LocalSource::new(PathBuf::from(task_source.source_path)),
+                ))),
+                Source::Archive => Ok(TaskType::InstallFromPrebuilt(PrebuiltSource::Archive(
+                    ArchiveSource::new(task_source.source_path),
                 ))),
-            }),
+            },
         }
     }
 }
@@ -490,7 +324,7 @@ pub enum CodeSource {
 }
 
 impl CodeSource {
-    pub fn validate(&mut self) -> Result<(), String> {
+    pub fn validate(&mut self) -> Result<()> {
         match self {
             CodeSource::Git(source) => source.validate(),
             CodeSource::Local(source) => source.validate(Some(false)),
@@ -516,7 +350,7 @@ pub enum PrebuiltSource {
 }
 
 impl PrebuiltSource {
-    pub fn validate(&self) -> Result<(), String> {
+    pub fn validate(&self) -> Result<()> {
         match self {
             PrebuiltSource::Archive(source) => source.validate(),
             PrebuiltSource::Local(source) => source.validate(None),
@@ -530,39 +364,3 @@ impl PrebuiltSource {
         }
     }
 }
-
-/// # 任务环境变量
-///
-/// 任务执行时的环境变量.这个环境变量是在当前任务执行时设置的,不会影响到其他任务
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
-pub struct TaskEnv {
-    pub key: String,
-    pub value: String,
-}
-
-impl TaskEnv {
-    #[allow(dead_code)]
-    pub fn new(key: String, value: String) -> Self {
-        Self { key, value }
-    }
-
-    pub fn key(&self) -> &str {
-        &self.key
-    }
-
-    pub fn value(&self) -> &str {
-        &self.value
-    }
-
-    pub fn trim(&mut self) {
-        self.key = self.key.trim().to_string();
-        self.value = self.value.trim().to_string();
-    }
-
-    pub fn validate(&self) -> Result<(), String> {
-        if self.key.is_empty() {
-            return Err("Env: key is empty".to_string());
-        }
-        return Ok(());
-    }
-}

+ 1 - 44
dadk-user/src/scheduler/mod.rs

@@ -14,7 +14,7 @@ use log::{error, info};
 
 use crate::{
     context::{Action, DadkUserExecuteContext},
-    executor::{target::Target, Executor},
+    executor::Executor,
     parser::task::DADKTask,
 };
 
@@ -41,8 +41,6 @@ pub struct InnerEntity {
     indegree: usize,
     /// 子节点
     children: Vec<Arc<SchedEntity>>,
-    /// target管理
-    target: Option<Target>,
 }
 
 /// # 调度实体
@@ -94,11 +92,6 @@ impl SchedEntity {
         self.inner.lock().unwrap().indegree
     }
 
-    /// 获取target
-    pub fn target(&self) -> Option<Target> {
-        self.inner.lock().unwrap().target.clone()
-    }
-
     /// 当前任务完成后,所有子节点入度减1
     ///
     /// ## 参数
@@ -367,7 +360,6 @@ impl Scheduler {
         let id: i32 = self.generate_task_id();
         let indegree: usize = 0;
         let children = Vec::new();
-        let target = self.generate_task_target(&path, &task.rust_target)?;
         let entity = Arc::new(SchedEntity {
             inner: Mutex::new(InnerEntity {
                 id,
@@ -375,7 +367,6 @@ impl Scheduler {
                 file_path: path.clone(),
                 indegree,
                 children,
-                target,
             }),
         });
         let name_version = (entity.task().name.clone(), entity.task().version.clone());
@@ -404,40 +395,6 @@ impl Scheduler {
         return TASK_ID.fetch_add(1, Ordering::SeqCst);
     }
 
-    fn generate_task_target(
-        &self,
-        path: &PathBuf,
-        rust_target: &Option<String>,
-    ) -> Result<Option<Target>, SchedulerError> {
-        if let Some(rust_target) = rust_target {
-            // 如果rust_target字段不为none,说明需要target管理
-            // 获取dadk任务路径,用于生成临时dadk文件名
-            let file_str = path.as_path().to_str().unwrap();
-            let tmp_dadk_path = Target::tmp_dadk(file_str);
-            let tmp_dadk_str = tmp_dadk_path.as_path().to_str().unwrap();
-
-            if Target::is_user_target(rust_target) {
-                // 如果target文件是用户自己的
-                if let Ok(target_path) = Target::user_target_path(rust_target) {
-                    let target_path_str = target_path.as_path().to_str().unwrap();
-                    let index = target_path_str.rfind('/').unwrap();
-                    let target_name = target_path_str[index + 1..].to_string();
-                    let tmp_target = PathBuf::from(format!("{}{}", tmp_dadk_str, target_name));
-                    return Ok(Some(Target::new(tmp_target)));
-                } else {
-                    return Err(SchedulerError::TaskError(
-                        "The path of target file is invalid.".to_string(),
-                    ));
-                }
-            } else {
-                // 如果target文件是内置的
-                let tmp_target = PathBuf::from(format!("{}{}.json", tmp_dadk_str, rust_target));
-                return Ok(Some(Target::new(tmp_target)));
-            }
-        }
-        return Ok(None);
-    }
-
     /// # 执行调度器中的所有任务
     pub fn run(&self) -> Result<(), SchedulerError> {
         // 准备全局环境变量

+ 5 - 5
dadk-user/src/scheduler/tests.rs

@@ -21,7 +21,7 @@ fn should_not_run_task_only_riscv64_on_x86_64(ctx: &DadkExecuteContextTestBuildX
         .base_context()
         .config_v2_dir()
         .join("app_target_arch_riscv64_only_0_2_0.toml");
-    let task = Parser::new(ctx.base_context().config_v1_dir()).parse_config_file(&config_file);
+    let task = Parser::new(ctx.base_context().config_v2_dir()).parse_config_file(&config_file);
     assert!(task.is_ok(), "parse error: {:?}", task);
     let task = task.unwrap();
     assert!(
@@ -62,7 +62,7 @@ fn should_not_run_task_only_x86_64_on_riscv64(ctx: &DadkExecuteContextTestBuildR
         .base_context()
         .config_v2_dir()
         .join("app_target_arch_x86_64_only_0_2_0.toml");
-    let task = Parser::new(ctx.base_context().config_v1_dir()).parse_config_file(&config_file);
+    let task = Parser::new(ctx.base_context().config_v2_dir()).parse_config_file(&config_file);
     assert!(task.is_ok(), "parse error: {:?}", task);
     let task = task.unwrap();
     assert!(
@@ -103,7 +103,7 @@ fn should_run_task_include_x86_64_on_x86_64(ctx: &DadkExecuteContextTestBuildX86
         .base_context()
         .config_v2_dir()
         .join("app_all_target_arch_0_2_0.toml");
-    let task = Parser::new(ctx.base_context().config_v1_dir()).parse_config_file(&config_file);
+    let task = Parser::new(ctx.base_context().config_v2_dir()).parse_config_file(&config_file);
     assert!(task.is_ok(), "parse error: {:?}", task);
     let task = task.unwrap();
 
@@ -136,7 +136,7 @@ fn should_run_task_include_riscv64_on_riscv64(ctx: &DadkExecuteContextTestBuildR
         .base_context()
         .config_v2_dir()
         .join("app_all_target_arch_0_2_0.toml");
-    let task = Parser::new(ctx.base_context().config_v1_dir()).parse_config_file(&config_file);
+    let task = Parser::new(ctx.base_context().config_v2_dir()).parse_config_file(&config_file);
     assert!(task.is_ok(), "parse error: {:?}", task);
     let task = task.unwrap();
 
@@ -166,7 +166,7 @@ fn should_run_task_include_riscv64_on_riscv64(ctx: &DadkExecuteContextTestBuildR
 #[test]
 fn ensure_all_target_arch_testcase_v1(ctx: &BaseGlobalTestContext) {
     let config_file = ctx.config_v2_dir().join("app_all_target_arch_0_2_0.toml");
-    let task = Parser::new(ctx.config_v1_dir()).parse_config_file(&config_file);
+    let task = Parser::new(ctx.config_v2_dir()).parse_config_file(&config_file);
     assert!(task.is_ok(), "parse error: {:?}", task);
     let task = task.unwrap();
 

+ 0 - 28
dadk-user/templates/config/build_from_source/test_archive.toml

@@ -1,28 +0,0 @@
-name = "test_archive"
-version = "0.2.0"
-description = ""
-build-once = true
-install-once = true
-target-arch = ["x86_64"]
-
-[task-type]
-type = "build_from_source"
-source = "archive"
-source-path = "https://url"
-
-[build]
-build-command = "make install"
-
-[install]
-in-dragonos-path = "/bin"
-
-[clean]
-clean-command = "make clean"
-
-[depends]
-depend1 = "0.1.1"
-depend2 = "0.1.2"
-
-[envs]
-PATH = "/usr/bin"
-LD_LIBRARY_PATH = "/usr/lib"

+ 0 - 30
dadk-user/templates/config/build_from_source/test_git.toml

@@ -1,30 +0,0 @@
-name = "test_git"
-version = "0.2.0"
-description = ""
-build-once = true
-install-once = true
-target-arch = ["x86_64"]
-
-[task-type]
-type = "build_from_source"
-source = "git"
-source-path = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/test_git.git"
-revison = "01cdc56863"
-branch = "test"
-
-[build]
-build-command = "make install"
-
-[install]
-in-dragonos-path = "/bin"
-
-[clean]
-clean-command = "make clean"
-
-[depends]
-depend1 = "0.1.1"
-depend2 = "0.1.2"
-
-[envs]
-PATH = "/usr/bin"
-LD_LIBRARY_PATH = "/usr/lib"

+ 0 - 28
dadk-user/templates/config/build_from_source/test_local.toml

@@ -1,28 +0,0 @@
-name = "test_local"
-version = "0.2.0"
-description = ""
-build-once = true
-install-once = true
-target-arch = ["x86_64"]
-
-[task-type]
-type = "build_from_source"
-source = "local"
-source-path = "apps/test"
-
-[build]
-build-command = "make install"
-
-[install]
-in-dragonos-path = "/bin"
-
-[clean]
-clean-command = "make clean"
-
-[depends]
-depend1 = "0.1.1"
-depend2 = "0.1.2"
-
-[envs]
-PATH = "/usr/bin"
-LD_LIBRARY_PATH = "/usr/lib"

+ 0 - 29
dadk-user/templates/config/install_from_prebuilt/test_archive.toml

@@ -1,29 +0,0 @@
-name = "test_archive"
-version = "0.2.0"
-description = ""
-build-once = true
-install-once = true
-target-arch = ["x86_64"]
-
-[task-type]
-type = "install_from_prebuilt"
-source = "archive"
-source-path = "https://url"
-
-
-[build]
-build-command = "make install"
-
-[install]
-in-dragonos-path = "/bin"
-
-[clean]
-clean-command = "make clean"
-
-[depends]
-depend1 = "0.1.1"
-depend2 = "0.1.2"
-
-[envs]
-PATH = "/usr/bin"
-LD_LIBRARY_PATH = "/usr/lib"

+ 0 - 29
dadk-user/templates/config/install_from_prebuilt/test_local.toml

@@ -1,29 +0,0 @@
-name = "test_local"
-version = "0.2.0"
-description = ""
-build-once = true
-install-once = true
-target-arch = ["x86_64"]
-
-[task-type]
-type = "install_from_prebuilt"
-source = "local"
-source-path = "/home/dev/demo"
-
-
-[build]
-build-command = "make install"
-
-[install]
-in-dragonos-path = "/bin"
-
-[clean]
-clean-command = "make clean"
-
-[depends]
-depend1 = "0.1.1"
-depend2 = "0.1.2"
-
-[envs]
-PATH = "/usr/bin"
-LD_LIBRARY_PATH = "/usr/lib"

+ 0 - 286
dadk-user/tests/test_parse_dadk_user_config.rs

@@ -1,286 +0,0 @@
-use std::path::PathBuf;
-
-use dadk_config::common::target_arch::TargetArch;
-use dadk_user::{
-    executor::source::{ArchiveSource, GitSource, LocalSource},
-    parser::{
-        task::{
-            BuildConfig, CleanConfig, CodeSource, DADKTask, Dependency, InstallConfig,
-            PrebuiltSource, TaskEnv, TaskType,
-        },
-        Parser,
-    },
-};
-use test_base::{
-    dadk_user::DadkUserTestContext,
-    test_context::{self as test_context, test_context},
-};
-
-const DADK_USER_TEST_BUILD_LOCAL: &str = "build_from_source/test_local.toml";
-const DADK_USER_TEST_BUILD_GIT: &str = "build_from_source/test_git.toml";
-const DADK_USER_TEST_BUILD_ARCHIVE: &str = "build_from_source/test_archive.toml";
-const DADK_USER_TEST_INSTALL_LOCAL: &str = "install_from_prebuilt/test_local.toml";
-const DADK_USER_TEST_INSTALL_ARCHIVE: &str = "install_from_prebuilt/test_archive.toml";
-
-/// 测试解析DADK用户配置文件
-#[test_context(DadkUserTestContext)]
-#[test]
-fn test_parse_dadk_user_config_build_local(ctx: &mut DadkUserTestContext) {
-    let config_file = ctx.templates_dir().join(DADK_USER_TEST_BUILD_LOCAL);
-    assert!(config_file.exists());
-    assert!(config_file.is_file());
-    let r = Parser::parse_toml_file(&config_file);
-    assert!(r.is_ok());
-    let mut parsed_dadk_task = r.unwrap();
-    let mut expected_dadk_task = DADKTask {
-        name: "test_local".to_string(),
-        version: "0.2.0".to_string(),
-        description: "".to_string(),
-        build_once: true,
-        install_once: true,
-        task_type: TaskType::BuildFromSource(CodeSource::Local(LocalSource::new(PathBuf::from(
-            "apps/test",
-        )))),
-        rust_target: None,
-        depends: vec![
-            Dependency {
-                name: "depend1".to_string(),
-                version: "0.1.1".to_string(),
-            },
-            Dependency {
-                name: "depend2".to_string(),
-                version: "0.1.2".to_string(),
-            },
-        ],
-        build: BuildConfig::new(Some("make install".to_string())),
-        install: InstallConfig::new(Some(PathBuf::from("/bin"))),
-        clean: CleanConfig::new(Some("make clean".to_string())),
-        envs: Some(vec![
-            TaskEnv::new("PATH".to_string(), "/usr/bin".to_string()),
-            TaskEnv::new("LD_LIBRARY_PATH".to_string(), "/usr/lib".to_string()),
-        ]),
-        target_arch: vec![TargetArch::try_from("x86_64").unwrap()],
-    };
-
-    parsed_dadk_task.target_arch.sort();
-    expected_dadk_task.target_arch.sort();
-    parsed_dadk_task.depends.sort();
-    expected_dadk_task.depends.sort();
-    if let Some(envs) = &mut parsed_dadk_task.envs {
-        envs.sort();
-    }
-    if let Some(envs) = &mut expected_dadk_task.envs {
-        envs.sort();
-    }
-    assert_eq!(parsed_dadk_task, expected_dadk_task)
-}
-
-#[test_context(DadkUserTestContext)]
-#[test]
-fn test_parse_dadk_user_config_build_git(ctx: &mut DadkUserTestContext) {
-    let config_file = ctx.templates_dir().join(DADK_USER_TEST_BUILD_GIT);
-    assert!(config_file.exists());
-    assert!(config_file.is_file());
-    let r = Parser::parse_toml_file(&config_file);
-    assert!(r.is_ok());
-    let mut parsed_dadk_task = r.unwrap();
-    let mut expected_dadk_task = DADKTask {
-        name: "test_git".to_string(),
-        version: "0.2.0".to_string(),
-        description: "".to_string(),
-        build_once: true,
-        install_once: true,
-        task_type: TaskType::BuildFromSource(CodeSource::Git(GitSource::new(
-            "https://git.mirrors.dragonos.org.cn/DragonOS-Community/test_git.git".to_string(),
-            Some("test".to_string()),
-            Some("01cdc56863".to_string()),
-        ))),
-        rust_target: None,
-        depends: vec![
-            Dependency {
-                name: "depend1".to_string(),
-                version: "0.1.1".to_string(),
-            },
-            Dependency {
-                name: "depend2".to_string(),
-                version: "0.1.2".to_string(),
-            },
-        ],
-        build: BuildConfig::new(Some("make install".to_string())),
-        install: InstallConfig::new(Some(PathBuf::from("/bin"))),
-        clean: CleanConfig::new(Some("make clean".to_string())),
-        envs: Some(vec![
-            TaskEnv::new("PATH".to_string(), "/usr/bin".to_string()),
-            TaskEnv::new("LD_LIBRARY_PATH".to_string(), "/usr/lib".to_string()),
-        ]),
-        target_arch: vec![TargetArch::try_from("x86_64").unwrap()],
-    };
-
-    parsed_dadk_task.target_arch.sort();
-    expected_dadk_task.target_arch.sort();
-    parsed_dadk_task.depends.sort();
-    expected_dadk_task.depends.sort();
-    if let Some(envs) = &mut parsed_dadk_task.envs {
-        envs.sort();
-    }
-    if let Some(envs) = &mut expected_dadk_task.envs {
-        envs.sort();
-    }
-    assert_eq!(parsed_dadk_task, expected_dadk_task)
-}
-
-#[test_context(DadkUserTestContext)]
-#[test]
-fn test_parse_dadk_user_config_build_archive(ctx: &mut DadkUserTestContext) {
-    let config_file = ctx.templates_dir().join(DADK_USER_TEST_BUILD_ARCHIVE);
-    assert!(config_file.exists());
-    assert!(config_file.is_file());
-    let r = Parser::parse_toml_file(&config_file);
-    assert!(r.is_ok());
-    let mut parsed_dadk_task = r.unwrap();
-    let mut expected_dadk_task = DADKTask {
-        name: "test_archive".to_string(),
-        version: "0.2.0".to_string(),
-        description: "".to_string(),
-        build_once: true,
-        install_once: true,
-        task_type: TaskType::BuildFromSource(CodeSource::Archive(ArchiveSource::new(
-            "https://url".to_string(),
-        ))),
-        rust_target: None,
-        depends: vec![
-            Dependency {
-                name: "depend1".to_string(),
-                version: "0.1.1".to_string(),
-            },
-            Dependency {
-                name: "depend2".to_string(),
-                version: "0.1.2".to_string(),
-            },
-        ],
-        build: BuildConfig::new(Some("make install".to_string())),
-        install: InstallConfig::new(Some(PathBuf::from("/bin"))),
-        clean: CleanConfig::new(Some("make clean".to_string())),
-        envs: Some(vec![
-            TaskEnv::new("PATH".to_string(), "/usr/bin".to_string()),
-            TaskEnv::new("LD_LIBRARY_PATH".to_string(), "/usr/lib".to_string()),
-        ]),
-        target_arch: vec![TargetArch::try_from("x86_64").unwrap()],
-    };
-
-    parsed_dadk_task.target_arch.sort();
-    expected_dadk_task.target_arch.sort();
-    parsed_dadk_task.depends.sort();
-    expected_dadk_task.depends.sort();
-    if let Some(envs) = &mut parsed_dadk_task.envs {
-        envs.sort();
-    }
-    if let Some(envs) = &mut expected_dadk_task.envs {
-        envs.sort();
-    }
-    assert_eq!(parsed_dadk_task, expected_dadk_task)
-}
-
-#[test_context(DadkUserTestContext)]
-#[test]
-fn test_parse_dadk_user_config_install_local(ctx: &mut DadkUserTestContext) {
-    let config_file = ctx.templates_dir().join(DADK_USER_TEST_INSTALL_LOCAL);
-    assert!(config_file.exists());
-    assert!(config_file.is_file());
-    let r = Parser::parse_toml_file(&config_file);
-    assert!(r.is_ok());
-    let mut parsed_dadk_task = r.unwrap();
-    let mut expected_dadk_task = DADKTask {
-        name: "test_local".to_string(),
-        version: "0.2.0".to_string(),
-        description: "".to_string(),
-        build_once: true,
-        install_once: true,
-        task_type: TaskType::InstallFromPrebuilt(PrebuiltSource::Local(LocalSource::new(
-            PathBuf::from("/home/dev/demo"),
-        ))),
-        rust_target: None,
-        depends: vec![
-            Dependency {
-                name: "depend1".to_string(),
-                version: "0.1.1".to_string(),
-            },
-            Dependency {
-                name: "depend2".to_string(),
-                version: "0.1.2".to_string(),
-            },
-        ],
-        build: BuildConfig::new(Some("make install".to_string())),
-        install: InstallConfig::new(Some(PathBuf::from("/bin"))),
-        clean: CleanConfig::new(Some("make clean".to_string())),
-        envs: Some(vec![
-            TaskEnv::new("PATH".to_string(), "/usr/bin".to_string()),
-            TaskEnv::new("LD_LIBRARY_PATH".to_string(), "/usr/lib".to_string()),
-        ]),
-        target_arch: vec![TargetArch::try_from("x86_64").unwrap()],
-    };
-
-    parsed_dadk_task.target_arch.sort();
-    expected_dadk_task.target_arch.sort();
-    parsed_dadk_task.depends.sort();
-    expected_dadk_task.depends.sort();
-    if let Some(envs) = &mut parsed_dadk_task.envs {
-        envs.sort();
-    }
-    if let Some(envs) = &mut expected_dadk_task.envs {
-        envs.sort();
-    }
-    assert_eq!(parsed_dadk_task, expected_dadk_task)
-}
-
-#[test_context(DadkUserTestContext)]
-#[test]
-fn test_parse_dadk_user_config_install_archive(ctx: &mut DadkUserTestContext) {
-    let config_file = ctx.templates_dir().join(DADK_USER_TEST_INSTALL_ARCHIVE);
-    assert!(config_file.exists());
-    assert!(config_file.is_file());
-    let r = Parser::parse_toml_file(&config_file);
-    assert!(r.is_ok());
-    let mut parsed_dadk_task = r.unwrap();
-    let mut expected_dadk_task = DADKTask {
-        name: "test_archive".to_string(),
-        version: "0.2.0".to_string(),
-        description: "".to_string(),
-        build_once: true,
-        install_once: true,
-        task_type: TaskType::InstallFromPrebuilt(PrebuiltSource::Archive(ArchiveSource::new(
-            "https://url".to_string(),
-        ))),
-        rust_target: None,
-        depends: vec![
-            Dependency {
-                name: "depend1".to_string(),
-                version: "0.1.1".to_string(),
-            },
-            Dependency {
-                name: "depend2".to_string(),
-                version: "0.1.2".to_string(),
-            },
-        ],
-        build: BuildConfig::new(Some("make install".to_string())),
-        install: InstallConfig::new(Some(PathBuf::from("/bin"))),
-        clean: CleanConfig::new(Some("make clean".to_string())),
-        envs: Some(vec![
-            TaskEnv::new("PATH".to_string(), "/usr/bin".to_string()),
-            TaskEnv::new("LD_LIBRARY_PATH".to_string(), "/usr/lib".to_string()),
-        ]),
-        target_arch: vec![TargetArch::try_from("x86_64").unwrap()],
-    };
-
-    parsed_dadk_task.target_arch.sort();
-    expected_dadk_task.target_arch.sort();
-    parsed_dadk_task.depends.sort();
-    expected_dadk_task.depends.sort();
-    if let Some(envs) = &mut parsed_dadk_task.envs {
-        envs.sort();
-    }
-    if let Some(envs) = &mut expected_dadk_task.envs {
-        envs.sort();
-    }
-    assert_eq!(parsed_dadk_task, expected_dadk_task)
-}

+ 3 - 8
tests/data/dadk_config_v2/app_all_target_arch_0_2_0.toml

@@ -5,12 +5,11 @@ build-once = false
 install-once = false
 target-arch = ["riscv64", "x86_64", "aarch64"]
 
-[task-type]
-type = "build_from_source"
+[task-source]
+type = "build-from-source"
 source = "git"
 source-path = "1"
 branch = "1"
-revision = ""
 
 [build]
 build-command = "1"
@@ -19,8 +18,4 @@ build-command = "1"
 in-dragonos-path = "/"
 
 [clean]
-clean-command = "1"
-
-[depends]
-
-[envs]
+clean-command = "1"

+ 5 - 6
tests/data/dadk_config_v2/app_normal_with_env_0_2_0.toml

@@ -5,8 +5,8 @@ build-once = false
 install-once = false
 target-arch = ["x86_64"]              # Assuming this is the default target architecture
 
-[task-type]
-type = "build_from_source"
+[task-source]
+type = "build-from-source"
 source = "local"
 source-path = "tests/data/apps/app_normal_with_env"
 
@@ -19,7 +19,6 @@ in-dragonos-path = "/"
 [clean]
 clean-command = ""
 
-[depends]
-
-[envs]
-CC = "abc-gcc"
+[[envs]]
+key = "CC"
+value = "abc-gcc"

+ 6 - 7
tests/data/dadk_config_v2/app_normal_with_env_fail_0_2_0.toml

@@ -3,10 +3,10 @@ version = "0.2.0"
 description = "A normal app with env which should failed"
 build-once = false
 install-once = false
-target-arch = ["x86_64"]              # Assuming this is the default target architecture
+target-arch = ["x86_64"]                                  # Assuming this is the default target architecture
 
-[task-type]
-type = "build_from_source"
+[task-source]
+type = "build-from-source"
 source = "local"
 source-path = "tests/data/apps/app_normal_with_env_fail"
 
@@ -19,7 +19,6 @@ in-dragonos-path = "/"
 [clean]
 clean-command = ""
 
-[depends]
-
-[envs]
-CC = "abc-gcc1"
+[[envs]]
+key = "CC"
+value = "abc-gcc1"

+ 4 - 9
tests/data/dadk_config_v2/app_target_arch_riscv64_only_0_2_0.toml

@@ -5,12 +5,11 @@ build-once = false
 install-once = false
 target-arch = ["riscv64"]
 
-[task-type]
-type = "build_from_source"
+[task-source]
+type = "build-from-source"
 source = "git"
 source-path = "1"
-branch = "1"
-revision = ""
+revision = "01cdc56863"
 
 [build]
 build-command = "1"
@@ -19,8 +18,4 @@ build-command = "1"
 in-dragonos-path = "/"
 
 [clean]
-clean-command = "1"
-
-[depends]
-
-[envs]
+clean-command = "1"

+ 2 - 7
tests/data/dadk_config_v2/app_target_arch_x86_64_only_0_2_0.toml

@@ -5,12 +5,11 @@ build-once = false
 install-once = false
 target-arch = ["x86_64"]
 
-[task-type]
-type = "build_from_source"
+[task-source]
+type = "build-from-source"
 source = "git"
 source-path = "1"
 branch = "1"
-revision = ""
 
 [build]
 build-command = "1"
@@ -20,7 +19,3 @@ in-dragonos-path = "/"
 
 [clean]
 clean-command = "1"
-
-[depends]
-
-[envs]