From a22cb3a332624bb35eabb66143314d946851fe9f Mon Sep 17 00:00:00 2001
From: Jiahao XU <Jiahao_XU@outlook.com>
Date: Fri, 10 Mar 2023 22:09:16 +1100
Subject: [PATCH] Fix x86_64 fallback for aarch64 MacOS (#875)

---
 crates/detect-targets/src/detect.rs       |  2 +-
 crates/detect-targets/src/detect/macos.rs | 24 +++++++++++++++++++++--
 2 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/crates/detect-targets/src/detect.rs b/crates/detect-targets/src/detect.rs
index 62af9f20..a7863e6c 100644
--- a/crates/detect-targets/src/detect.rs
+++ b/crates/detect-targets/src/detect.rs
@@ -61,7 +61,7 @@ pub async fn detect_targets() -> Vec<String> {
 
         cfg_if! {
             if #[cfg(target_os = "macos")] {
-                targets.extend(macos::detect_alternative_targets(&targets[0]));
+                targets.extend(macos::detect_alternative_targets(&targets[0]).await);
             } else if #[cfg(target_os = "windows")] {
                 targets.extend(windows::detect_alternative_targets(&targets[0]));
             }
diff --git a/crates/detect-targets/src/detect/macos.rs b/crates/detect-targets/src/detect/macos.rs
index 0c216981..58fc7fe8 100644
--- a/crates/detect-targets/src/detect/macos.rs
+++ b/crates/detect-targets/src/detect/macos.rs
@@ -1,10 +1,30 @@
+use std::{io, process::Stdio};
+
+use tokio::process::Command;
+
 const AARCH64: &str = "aarch64-apple-darwin";
 const X86: &str = "x86_64-apple-darwin";
 const UNIVERSAL: &str = "universal-apple-darwin";
 
-pub(super) fn detect_alternative_targets(target: &str) -> impl Iterator<Item = String> {
+async fn is_x86_64_supported() -> io::Result<bool> {
+    let exit_status = Command::new("arch")
+        .args(["-arch", "x86_64", "/usr/bin/true"])
+        .stdin(Stdio::null())
+        .stdout(Stdio::null())
+        .stderr(Stdio::null())
+        .spawn()?
+        .wait()
+        .await?;
+
+    Ok(exit_status.success())
+}
+
+pub(super) async fn detect_alternative_targets(target: &str) -> impl Iterator<Item = String> {
     match target {
-        AARCH64 => [Some(X86), Some(UNIVERSAL)],
+        AARCH64 => [
+            is_x86_64_supported().await.unwrap_or(false).then_some(X86),
+            Some(UNIVERSAL),
+        ],
         X86 => [Some(UNIVERSAL), None],
         _ => [None, None],
     }