use crate::Args;
use crate::ignore::IGNORE_FILE;
use crate::listen::DEFAULT_PORT;
use crate::serve::INDEX_FILE;
use crate::watch::POLL_INTERVAL;
use std::fmt::Display;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::path::Path;
const BLUE: &str = "\x1b[94m";
const RESET: &str = "\x1b[0m";
const LINK_START: &str = "\x1b]8;;";
const LINK_END: &str = "\x1b]8;;\x1b\\";
const LINK_MID: &str = "\x1b\\";
const RULE: &str = "-----------------------------------------------";
const LABEL_WIDTH: usize = 15;
pub(crate) fn print(
bound: SocketAddr,
args: &Args,
static_dir: &Path,
no_app_page: bool,
from_ignore_file: usize,
) {
let authority = authority(bound);
let url = url(bound);
println!("{RULE}");
row("Serving", static_dir.display());
if args.port.is_none() && bound.port() != DEFAULT_PORT {
row(
"Note",
format!("port {DEFAULT_PORT} was busy, using {}", bound.port()),
);
}
row("Live reload", live_reload(args));
if let Some(ignoring) = ignoring(&args.ignore, from_ignore_file) {
row("Ignoring", ignoring);
}
row("Single-page app", on_off(args.spa));
row(
"Caching",
if args.cache_assets {
"files under /assets/ for a year"
} else {
"off"
},
);
if no_app_page {
row(
"Warning",
format!("there is no {INDEX_FILE} here, so no page will load"),
);
}
row("Open", hyperlink(&url, &authority));
println!("{RULE}\n");
}
pub(crate) fn url(bound: SocketAddr) -> String {
format!("http://{}", authority(bound))
}
fn authority(bound: SocketAddr) -> String {
let ip = bound.ip();
let is_localhost = ip.is_unspecified()
|| ip == IpAddr::V4(Ipv4Addr::LOCALHOST)
|| ip == IpAddr::V6(Ipv6Addr::LOCALHOST);
if is_localhost {
format!("localhost:{}", bound.port())
} else {
bound.to_string()
}
}
fn row(label: &str, value: impl Display) {
println!(" {label:<LABEL_WIDTH$}: {BLUE}{value}{RESET}");
}
fn live_reload(args: &Args) -> String {
if args.no_reload {
return "off".to_string();
}
if args.poll {
return format!("on, looking at the files every {POLL_INTERVAL:?}");
}
"on".to_string()
}
fn ignoring(given: &[String], from_file: usize) -> Option<String> {
let mut parts: Vec<String> = given.to_vec();
match from_file {
0 => {}
1 => parts.push(format!("1 pattern in {IGNORE_FILE}")),
many => parts.push(format!("{many} patterns in {IGNORE_FILE}")),
}
(!parts.is_empty()).then(|| parts.join(", "))
}
fn on_off(enabled: bool) -> &'static str {
if enabled { "on" } else { "off" }
}
fn hyperlink(url: &str, text: impl Display) -> String {
format!("{LINK_START}{url}{LINK_MID}{text}{LINK_END}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn what_is_ignored_is_listed_and_the_file_is_counted() {
let given = ["*.map".to_string()];
assert_eq!(ignoring(&[], 0), None);
assert_eq!(ignoring(&given, 0).as_deref(), Some("*.map"));
assert_eq!(
ignoring(&given, 1).as_deref(),
Some("*.map, 1 pattern in .servioignore")
);
assert_eq!(
ignoring(&[], 2).as_deref(),
Some("2 patterns in .servioignore")
);
}
}