From 20cb0e8863beb0d709adc2f41905ce3f1f465447 Mon Sep 17 00:00:00 2001 From: Satya Rohith Date: Fri, 17 May 2024 11:08:50 +0530 Subject: feat(serve): support `--port 0` to use an open port (#23846) Closes https://github.com/denoland/deno/issues/23845 --- cli/args/flags.rs | 39 +++++++++++++++++++++++++++++++-------- cli/args/mod.rs | 3 +-- 2 files changed, 32 insertions(+), 10 deletions(-) (limited to 'cli/args') diff --git a/cli/args/flags.rs b/cli/args/flags.rs index dca9cfa49..9de1c6057 100644 --- a/cli/args/flags.rs +++ b/cli/args/flags.rs @@ -26,7 +26,6 @@ use serde::Serialize; use std::env; use std::ffi::OsString; use std::net::SocketAddr; -use std::num::NonZeroU16; use std::num::NonZeroU32; use std::num::NonZeroU8; use std::num::NonZeroUsize; @@ -283,7 +282,7 @@ impl RunFlags { pub struct ServeFlags { pub script: String, pub watch: Option, - pub port: NonZeroU16, + pub port: u16, pub host: String, } @@ -293,7 +292,7 @@ impl ServeFlags { Self { script, watch: None, - port: NonZeroU16::new(port).unwrap(), + port, host: host.to_owned(), } } @@ -2464,8 +2463,8 @@ fn serve_subcommand() -> Command { .arg( Arg::new("port") .long("port") - .help("The TCP port to serve on, defaulting to 8000.") - .value_parser(value_parser!(NonZeroU16)), + .help("The TCP port to serve on, defaulting to 8000. Pass 0 to pick a random free port.") + .value_parser(value_parser!(u16)), ) .arg( Arg::new("host") @@ -4127,9 +4126,7 @@ fn serve_parse( app: Command, ) -> clap::error::Result<()> { // deno serve implies --allow-net=host:port - let port = matches - .remove_one::("port") - .unwrap_or(NonZeroU16::new(8000).unwrap()); + let port = matches.remove_one::("port").unwrap_or(8000); let host = matches .remove_one::("host") .unwrap_or_else(|| "0.0.0.0".to_owned()); @@ -5322,6 +5319,32 @@ mod tests { ..Flags::default() } ); + + let r = flags_from_vec(svec![ + "deno", + "serve", + "--port", + "0", + "--host", + "example.com", + "main.ts" + ]); + assert_eq!( + r.unwrap(), + Flags { + subcommand: DenoSubcommand::Serve(ServeFlags::new_default( + "main.ts".to_string(), + 0, + "example.com" + )), + permissions: PermissionFlags { + allow_net: Some(vec!["example.com:0".to_owned()]), + ..Default::default() + }, + code_cache_enabled: true, + ..Flags::default() + } + ); } #[test] diff --git a/cli/args/mod.rs b/cli/args/mod.rs index 0a0f7d704..b3d508e18 100644 --- a/cli/args/mod.rs +++ b/cli/args/mod.rs @@ -62,7 +62,6 @@ use std::env; use std::io::BufReader; use std::io::Cursor; use std::net::SocketAddr; -use std::num::NonZeroU16; use std::num::NonZeroUsize; use std::path::Path; use std::path::PathBuf; @@ -1036,7 +1035,7 @@ impl CliOptions { } } - pub fn serve_port(&self) -> Option { + pub fn serve_port(&self) -> Option { if let DenoSubcommand::Serve(flags) = self.sub_command() { Some(flags.port) } else { -- cgit v1.2.3