1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use clap;
use notify::{RecursiveMode, Watcher};
use std::{path::Path, sync::mpsc, thread, time::Duration};
use crate::build;
use crate::build::BuildArgs;
use crate::config::SimiConfig;
use crate::error::*;
#[derive(Clone)]
pub struct ServeArgs {
pub build: BuildArgs,
pub port: u16,
pub serve_only: bool,
}
impl ServeArgs {
pub fn from_clap<'a>(matches: &clap::ArgMatches<'a>) -> Self {
let build = BuildArgs::from_clap(matches);
let port: u16 = match matches.value_of("port") {
Some(port) => port.parse().expect("Unable to parse port number"),
_ => crate::DEFAULT_SERVE_PORT,
};
Self {
build,
port,
serve_only: matches.is_present("only"),
}
}
}
pub fn run(arg: ServeArgs) -> Result<(), Error> {
let cwd = ::std::env::current_dir().expect("unable to get current working directory");
let config = SimiConfig::from_serve(arg.clone())?;
let (sfs, port) = if arg.serve_only {
let sfs = crate::simple_static_server::StaticFiles::new(&cwd)?;
(sfs, arg.port)
} else {
build::build(&config)?;
let sfs = crate::simple_static_server::StaticFiles::new(
&config.output_path().to_string_lossy().to_string(),
)?;
(sfs, config.serve_port())
};
let server_thread = thread::spawn(move || sfs.start(port));
watch(&cwd, &config);
server_thread.join().unwrap();
Ok(())
}
fn watch(cwd: &Path, config: &SimiConfig) {
let src_dir = cwd.join("src");
let static_dir = cwd.join("static");
let (tx, rx) = mpsc::channel();
let mut watcher = notify::watcher(tx, Duration::from_millis(500)).unwrap();
watcher.watch(src_dir, RecursiveMode::Recursive).unwrap();
if static_dir.exists() {
watcher.watch(static_dir, RecursiveMode::Recursive).unwrap();
}
loop {
match rx.recv() {
Ok(_event) => build::build(&config).unwrap(),
Err(err) => println!("watch error: {:?}", err),
}
}
}