Skip to content

Commit

Permalink
feat(serve): add --open option to open the development server page …
Browse files Browse the repository at this point in the history
…in the default system web browser
  • Loading branch information
NTBBloodbath committed Aug 13, 2024
1 parent 0d6c1b0 commit fa79165
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
24 changes: 19 additions & 5 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,23 @@ enum Commands {
Serve {
#[arg(short = 'p', long, default_value_t = 3030, help = "Port to be used")]
port: u16,

#[arg(short = 'o', long, default_value_t = false, help = "Open the development server in your browser")]
open: bool,
},
/// Create a new asset in the site (e.g. 'new -k content post1.norg' -> 'content/post1.norg') and open it using your preferred system editor
New {
#[arg(short = 'k', long, default_value = "content", help = "type of asset", value_parser = [PossibleValue::new("content").help("New norg file"), PossibleValue::new("css").help("New CSS stylesheet"), PossibleValue::new("js").help("New JS script")])]
#[arg(
short = 'k',
long,
default_value = "content",
help = "type of asset",
value_parser = [
PossibleValue::new("content").help("New norg file"),
PossibleValue::new("css").help("New CSS stylesheet"),
PossibleValue::new("js").help("New JS script")
]
)]
kind: Option<String>,

/// Asset name, e.g. 'post1.norg' or 'hello.js'
Expand All @@ -58,7 +71,7 @@ pub async fn start() -> Result<()> {

match &cli.command {
Commands::Init { name } => init_site(name.as_ref()).await?,
Commands::Serve { port } => check_and_serve(*port).await?,
Commands::Serve { port, open } => check_and_serve(*port, *open).await?,
Commands::New { kind, name } => new_asset(kind.as_ref(), name.as_ref()).await?,
_ => bail!("Unsupported command"),
}
Expand Down Expand Up @@ -86,10 +99,11 @@ async fn init_site(name: Option<&String>) -> Result<()> {
///
/// # Arguments:
/// * port: The port number to use for the server.
/// * open: Whether to open the development server in the system web browser.
///
/// # Returns:
/// A `Result<()>` indicating success or error. On error, the context message will provide information on why the development server could not be initialized.
async fn check_and_serve(port: u16) -> Result<()> {
async fn check_and_serve(port: u16, open: bool) -> Result<()> {
if !net::is_port_available(port) {
let port_msg = if port == 3030 {
"default Norgolith port (3030)".to_string()
Expand All @@ -100,7 +114,7 @@ async fn check_and_serve(port: u16) -> Result<()> {
bail!("Could not initialize the development server: failed to open listener, perhaps the {} is busy?", port_msg);
}

cmd::serve(port).await?;
cmd::serve(port, open).await?;
Ok(())
}

Expand Down Expand Up @@ -206,7 +220,7 @@ mod tests {
// Enter the test directory
std::env::set_current_dir(canonicalize(test_site_dir.clone()).await?)?;

let result = check_and_serve(port).await;
let result = check_and_serve(port, false).await;
assert!(result.is_err());
assert!(result
.unwrap_err()
Expand Down
11 changes: 9 additions & 2 deletions src/cmd/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async fn convert_document() -> Result<()> {
Ok(())
}

pub async fn serve(port: u16) -> Result<()> {
pub async fn serve(port: u16, open: bool) -> Result<()> {
// Try to find a 'norgolith.toml' file in the current working directory and its parents
let found_site_root = fs::find_in_previous_dirs("file", "norgolith.toml").await?;

Expand All @@ -88,12 +88,19 @@ pub async fn serve(port: u16) -> Result<()> {
make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handle_request)) });
let addr = ([127, 0, 0, 1], port).into();
let server = Server::bind(&addr).serve(make_svc);
let uri = format!("http://localhost:{}/", port);

// Convert the norg documents to html
convert_document().await?;

println!("Serving site ...");
println!("Web server is available at http://localhost:{:?}/", port);
println!("Web server is available at {}", uri);
if open {
match open::that_detached(uri) {
Ok(()) => println!("Opening the development server page using your browser ..."),
Err(e) => bail!("Could not open the development server page: {}", e)
}
}
if let Err(err) = server.await {
bail!("Server error: {}", err)
}
Expand Down

0 comments on commit fa79165

Please sign in to comment.