Browse Source

bugfix: 更换仓库后无法通过编译 (#21)

* bugfix: 更换仓库后无法通过编译
裕依 1 year ago
parent
commit
c5dad5d052
6 changed files with 88 additions and 13 deletions
  1. 8 0
      .github/workflows/rust.yml
  2. 1 1
      Cargo.toml
  3. 1 1
      rust-toolchain.toml
  4. 6 6
      src/executor/cache.rs
  5. 1 2
      src/executor/mod.rs
  6. 71 3
      src/executor/source.rs

+ 8 - 0
.github/workflows/rust.yml

@@ -20,3 +20,11 @@ jobs:
       run: cargo build --verbose
     - name: Run tests
       run: cargo test --verbose
+  
+  fmt:
+    runs-on: ubuntu-latest
+    steps:
+    - uses: actions/checkout@v3
+
+    - name: Check formatting
+      run: cargo fmt --check

+ 1 - 1
Cargo.toml

@@ -16,7 +16,7 @@ doc = true
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
-clap = { version = "4.2.4", features = ["derive"] }
+clap = { version = "=4.2.4", features = ["derive"] }
 lazy_static = "1.4.0"
 log = "0.4.17"
 regex = "1.9.1"

+ 1 - 1
rust-toolchain.toml

@@ -1,3 +1,3 @@
 [toolchain]
 channel = "nightly-2023-08-15"
-components = ["rust-src"]
+components = ["rust-src", "rustfmt"]

+ 6 - 6
src/executor/cache.rs

@@ -75,6 +75,12 @@ pub fn cache_root_init(path: Option<PathBuf>) -> Result<(), ExecutorError> {
     return Ok(());
 }
 
+#[derive(Debug, Clone, Copy)]
+pub enum CacheDirType {
+    Build,
+    Source,
+}
+
 #[derive(Debug, Clone)]
 pub struct CacheDir {
     #[allow(dead_code)]
@@ -83,12 +89,6 @@ pub struct CacheDir {
     pub cache_type: CacheDirType,
 }
 
-#[derive(Debug, Clone, Copy)]
-pub enum CacheDirType {
-    Build,
-    Source,
-}
-
 impl CacheDir {
     pub const DADK_BUILD_CACHE_DIR_ENV_KEY_PREFIX: &'static str = "DADK_BUILD_CACHE_DIR";
     pub const DADK_SOURCE_CACHE_DIR_ENV_KEY_PREFIX: &'static str = "DADK_SOURCE_CACHE_DIR";

+ 1 - 2
src/executor/mod.rs

@@ -137,9 +137,8 @@ impl Executor {
         // 检查构建结果,如果为空,则抛出警告
         if self.build_dir.is_empty()? {
             warn!(
-                "Task {}: build result is empty, do you forget to copy the result to [${}]?",
+                "Task {}: build result is empty, do you forget to copy the result to [$DADK_CURRENT_BUILD_DIR]?",
                 self.entity.task().name_version(),
-                CacheDir::build_dir_env_key(&self.entity)?
             );
         }
         return Ok(());

+ 71 - 3
src/executor/source.rs

@@ -81,12 +81,12 @@ impl GitSource {
     ///
     /// ## 参数
     ///
-    /// * `target_dir` - 目标目录
+    /// - `target_dir` - 目标目录
     ///
     /// ## 返回
     ///
-    /// * `Ok(())` - 成功
-    /// * `Err(String)` - 失败,错误信息
+    /// - `Ok(())` - 成功
+    /// - `Err(String)` - 失败,错误信息
     pub fn prepare(&self, target_dir: &CacheDir) -> Result<(), String> {
         info!(
             "Preparing git repo: {}, branch: {:?}, revision: {:?}",
@@ -117,7 +117,75 @@ impl GitSource {
         return Ok(());
     }
 
+    fn check_repo(&self, target_dir: &CacheDir) -> Result<bool, String> {
+        let path: &PathBuf = &target_dir.path;
+        let mut cmd = Command::new("git");
+        cmd.arg("remote").arg("get-url").arg("origin");
+
+        // 设置工作目录
+        cmd.current_dir(path);
+
+        // 创建子进程,执行命令
+        let proc: std::process::Child = cmd
+            .stderr(Stdio::piped())
+            .stdout(Stdio::piped())
+            .spawn()
+            .map_err(|e| e.to_string())?;
+        let output = proc.wait_with_output().map_err(|e| e.to_string())?;
+
+        if output.status.success() {
+            let mut r = String::from_utf8(output.stdout).unwrap();
+            r.pop();
+            Ok(r == self.url)
+        } else {
+            return Err(format!(
+                "git remote get-url origin failed, status: {:?},  stderr: {:?}",
+                output.status,
+                StdioUtils::tail_n_str(StdioUtils::stderr_to_lines(&output.stderr), 5)
+            ));
+        }
+    }
+
+    fn set_url(&self, target_dir: &CacheDir) -> Result<(), String> {
+        let path: &PathBuf = &target_dir.path;
+        let mut cmd = Command::new("git");
+        cmd.arg("remote")
+            .arg("set-url")
+            .arg("origin")
+            .arg(self.url.as_str());
+
+        // 设置工作目录
+        cmd.current_dir(path);
+
+        // 创建子进程,执行命令
+        let proc: std::process::Child = cmd
+            .stderr(Stdio::piped())
+            .spawn()
+            .map_err(|e| e.to_string())?;
+        let output = proc.wait_with_output().map_err(|e| e.to_string())?;
+
+        if !output.status.success() {
+            return Err(format!(
+                "git remote set-url origin failed, status: {:?},  stderr: {:?}",
+                output.status,
+                StdioUtils::tail_n_str(StdioUtils::stderr_to_lines(&output.stderr), 5)
+            ));
+        }
+        Ok(())
+    }
+
     fn checkout(&self, target_dir: &CacheDir) -> Result<(), String> {
+        // 确保目标目录中的仓库为所指定仓库
+        if !self.check_repo(target_dir).map_err(|e| {
+            format!(
+                "Failed to check repo: {}, message: {e:?}",
+                target_dir.path.display()
+            )
+        })? {
+            info!("Target dir isn't specified repo, change remote url");
+            self.set_url(target_dir)?;
+        }
+
         let do_checkout = || -> Result<(), String> {
             let mut cmd = Command::new("git");
             cmd.current_dir(&target_dir.path);