Selaa lähdekoodia

feat(cli): add --port, closes #6186 (#6283)

* feat(cli): add --dev-server-port, closes #6186

* add http:// prefix

* name it to `--port`

* rename in all places
Amr Bashir 2 vuotta sitten
vanhempi
sitoutus
b7a2ce2c63

+ 5 - 0
.changes/cli-dev-server-port.md

@@ -0,0 +1,5 @@
+---
+'cli.rs': 'patch'
+---
+
+Add `--port` to specify the port used for static files dev server. It can also be specified through `TAURI_DEV_SERVER_PORT` env var.

+ 9 - 4
tooling/cli/src/dev.rs

@@ -64,6 +64,10 @@ pub struct Options {
   /// Disable the dev server for static files.
   #[clap(long)]
   pub no_dev_server: bool,
+  /// Specify port for the dev server for static files. Defaults to 1430
+  /// Can also be set using `TAURI_DEV_SERVER_PORT` env var.
+  #[clap(long)]
+  pub port: Option<u16>,
 }
 
 pub fn command(options: Options) -> Result<()> {
@@ -223,11 +227,12 @@ fn command_internal(mut options: Options) -> Result<()> {
     .clone();
   if !options.no_dev_server {
     if let AppUrl::Url(WindowUrl::App(path)) = &dev_path {
-      use crate::helpers::web_dev_server::{start_dev_server, SERVER_URL};
+      use crate::helpers::web_dev_server::start_dev_server;
       if path.exists() {
         let path = path.canonicalize()?;
-        start_dev_server(path);
-        dev_path = AppUrl::Url(WindowUrl::External(SERVER_URL.parse().unwrap()));
+        let server_url = start_dev_server(path, options.port);
+        let server_url = format!("http://{server_url}");
+        dev_path = AppUrl::Url(WindowUrl::External(server_url.parse().unwrap()));
 
         // TODO: in v2, use an env var to pass the url to the app context
         // or better separate the config passed from the cli internally and
@@ -238,7 +243,7 @@ fn command_internal(mut options: Options) -> Result<()> {
           c.build.dev_path = dev_path.clone();
           options.config = Some(serde_json::to_string(&c).unwrap());
         } else {
-          options.config = Some(format!(r#"{{ "build": {{ "devPath": "{SERVER_URL}" }} }}"#))
+          options.config = Some(format!(r#"{{ "build": {{ "devPath": "{server_url}" }} }}"#))
         }
       }
     }

+ 14 - 5
tooling/cli/src/helpers/web_dev_server.rs

@@ -14,9 +14,8 @@ use kuchiki::{traits::TendrilSink, NodeRef};
 use notify::RecursiveMode;
 use notify_debouncer_mini::new_debouncer;
 use std::{
-  net::SocketAddr,
+  net::{Ipv4Addr, SocketAddr},
   path::{Path, PathBuf},
-  str::FromStr,
   sync::{mpsc::sync_channel, Arc},
   thread,
   time::Duration,
@@ -25,15 +24,23 @@ use tauri_utils::mime_type::MimeType;
 use tokio::sync::broadcast::{channel, Sender};
 
 const AUTO_RELOAD_SCRIPT: &str = include_str!("./auto-reload.js");
-pub const SERVER_URL: &str = "http://127.0.0.1:1430";
 
 struct State {
   serve_dir: PathBuf,
   tx: Sender<()>,
 }
 
-pub fn start_dev_server<P: AsRef<Path>>(path: P) {
+pub fn start_dev_server<P: AsRef<Path>>(path: P, port: Option<u16>) -> SocketAddr {
   let serve_dir = path.as_ref().to_path_buf();
+  let server_url = SocketAddr::new(
+    Ipv4Addr::new(127, 0, 0, 1).into(),
+    port.unwrap_or_else(|| {
+      std::env::var("TAURI_DEV_SERVER_PORT")
+        .unwrap_or_else(|_| "1430".to_string())
+        .parse()
+        .unwrap()
+    }),
+  );
 
   std::thread::spawn(move || {
     tokio::runtime::Builder::new_current_thread()
@@ -84,12 +91,14 @@ pub fn start_dev_server<P: AsRef<Path>>(path: P) {
               ws.on_upgrade(|socket| async move { ws_handler(socket, state).await })
             }),
           );
-        Server::bind(&SocketAddr::from_str(SERVER_URL.split('/').nth(2).unwrap()).unwrap())
+        Server::bind(&server_url)
           .serve(router.into_make_service())
           .await
           .unwrap();
       })
   });
+
+  server_url
 }
 
 async fn handler<T>(req: Request<T>, state: Arc<State>) -> impl IntoResponse {