Эх сурвалжийг харах

feat: use `local_ip()` and fallback to prompt (#6290)

Amr Bashir 2 жил өмнө
parent
commit
ec007ef0d0

+ 5 - 0
.changes/cli-mobile-auto-ip.md

@@ -0,0 +1,5 @@
+---
+'cli.rs': 'patch'
+---
+
+Auto select an external IP for mobile development and fallback to prompting the user.

+ 32 - 25
tooling/cli/src/dev.rs

@@ -89,32 +89,39 @@ fn command_internal(mut options: Options) -> Result<()> {
 pub fn local_ip_address() -> &'static IpAddr {
   static LOCAL_IP: OnceCell<IpAddr> = OnceCell::new();
   LOCAL_IP.get_or_init(|| {
-    let addresses: Vec<IpAddr> = local_ip_address::list_afinet_netifas()
-      .expect("failed to list networks")
-      .into_iter()
-      .map(|(_, ipaddr)| ipaddr)
-      .filter(|ipaddr| match ipaddr {
-        IpAddr::V4(i) => i != &Ipv4Addr::LOCALHOST,
-        _ => false,
-      })
-      .collect();
-    match addresses.len() {
-      0 => panic!("No external IP detected."),
-      1 => {
-        let ipaddr = addresses.first().unwrap();
-        log::info!("Detected external IP {ipaddr}.");
-        *ipaddr
-      }
-      _ => {
-        let selected = dialoguer::Select::with_theme(&dialoguer::theme::ColorfulTheme::default())
-          .with_prompt("What external IP should we use for your development server?")
-          .items(&addresses)
-          .default(0)
-          .interact()
-          .expect("failed to select external IP");
-        *addresses.get(selected).unwrap()
+    let ip = local_ip_address::local_ip().unwrap_or_else(|_| {
+      let addresses: Vec<IpAddr> = local_ip_address::list_afinet_netifas()
+        .expect("failed to list networks")
+        .into_iter()
+        .map(|(_, ipaddr)| ipaddr)
+        .filter(|ipaddr| match ipaddr {
+          IpAddr::V4(i) => i != &Ipv4Addr::LOCALHOST,
+          _ => false,
+        })
+        .collect();
+      match addresses.len() {
+        0 => panic!("No external IP detected."),
+        1 => {
+          let ipaddr = addresses.first().unwrap();
+          *ipaddr
+        }
+        _ => {
+          let selected = dialoguer::Select::with_theme(&dialoguer::theme::ColorfulTheme::default())
+            .with_prompt(
+              "Failed to detect external IP, What IP should we use to access your development server?",
+            )
+            .items(&addresses)
+            .default(0)
+            .interact()
+            .expect("failed to select external IP");
+          *addresses.get(selected).unwrap()
+        }
       }
-    }
+    });
+
+    log::info!("Using {ip} to access the development server.");
+
+    ip
   })
 }