You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

691 lines
25KB

  1. // Contains an embedded version of livereload-js
  2. //
  3. // Copyright (c) 2010-2012 Andrey Tarantsov
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. use std::env;
  24. use std::fs::{read_dir, remove_dir_all};
  25. use std::path::{Path, PathBuf, MAIN_SEPARATOR};
  26. use std::sync::mpsc::channel;
  27. use std::thread;
  28. use std::time::{Duration, Instant};
  29. use hyper::header;
  30. use hyper::service::{make_service_fn, service_fn};
  31. use hyper::{Body, Method, Request, Response, Server, StatusCode};
  32. use hyper_staticfile::ResolveResult;
  33. use tokio::io::AsyncReadExt;
  34. use chrono::prelude::*;
  35. use ctrlc;
  36. use notify::{watcher, RecursiveMode, Watcher};
  37. use ws::{Message, Sender, WebSocket};
  38. use errors::{Error as ZolaError, Result};
  39. use globset::GlobSet;
  40. use site::Site;
  41. use utils::fs::copy_file;
  42. use crate::console;
  43. use open;
  44. use rebuild;
  45. #[derive(Debug, PartialEq)]
  46. enum ChangeKind {
  47. Content,
  48. Templates,
  49. Themes,
  50. StaticFiles,
  51. Sass,
  52. Config,
  53. }
  54. static INTERNAL_SERVER_ERROR_TEXT: &[u8] = b"Internal Server Error";
  55. static METHOD_NOT_ALLOWED_TEXT: &[u8] = b"Method Not Allowed";
  56. static NOT_FOUND_TEXT: &[u8] = b"Not Found";
  57. // This is dist/livereload.min.js from the LiveReload.js v3.1.0 release
  58. const LIVE_RELOAD: &str = include_str!("livereload.js");
  59. async fn handle_request(req: Request<Body>, root: PathBuf) -> Result<Response<Body>> {
  60. // livereload.js is served using the LIVE_RELOAD str, not a file
  61. if req.uri().path() == "/livereload.js" {
  62. if req.method() == Method::GET {
  63. return Ok(livereload_js());
  64. } else {
  65. return Ok(method_not_allowed());
  66. }
  67. }
  68. let result = hyper_staticfile::resolve(&root, &req).await.unwrap();
  69. match result {
  70. ResolveResult::MethodNotMatched => return Ok(method_not_allowed()),
  71. ResolveResult::NotFound | ResolveResult::UriNotMatched => {
  72. return Ok(not_found(Path::new(&root.join("404.html"))).await)
  73. }
  74. _ => (),
  75. };
  76. Ok(hyper_staticfile::ResponseBuilder::new().request(&req).build(result).unwrap())
  77. }
  78. fn livereload_js() -> Response<Body> {
  79. Response::builder()
  80. .header(header::CONTENT_TYPE, "text/javascript")
  81. .status(StatusCode::OK)
  82. .body(LIVE_RELOAD.into())
  83. .expect("Could not build livereload.js response")
  84. }
  85. fn internal_server_error() -> Response<Body> {
  86. Response::builder()
  87. .header(header::CONTENT_TYPE, "text/plain")
  88. .status(StatusCode::INTERNAL_SERVER_ERROR)
  89. .body(INTERNAL_SERVER_ERROR_TEXT.into())
  90. .expect("Could not build Internal Server Error response")
  91. }
  92. fn method_not_allowed() -> Response<Body> {
  93. Response::builder()
  94. .header(header::CONTENT_TYPE, "text/plain")
  95. .status(StatusCode::METHOD_NOT_ALLOWED)
  96. .body(METHOD_NOT_ALLOWED_TEXT.into())
  97. .expect("Could not build Method Not Allowed response")
  98. }
  99. async fn not_found(page_path: &Path) -> Response<Body> {
  100. if let Ok(mut file) = tokio::fs::File::open(page_path).await {
  101. let mut buf = Vec::new();
  102. if file.read_to_end(&mut buf).await.is_ok() {
  103. return Response::builder()
  104. .header(header::CONTENT_TYPE, "text/html")
  105. .status(StatusCode::NOT_FOUND)
  106. .body(buf.into())
  107. .expect("Could not build Not Found response");
  108. }
  109. return internal_server_error();
  110. }
  111. // Use a plain text response when page_path isn't available
  112. Response::builder()
  113. .header(header::CONTENT_TYPE, "text/plain")
  114. .status(StatusCode::NOT_FOUND)
  115. .body(NOT_FOUND_TEXT.into())
  116. .expect("Could not build Not Found response")
  117. }
  118. fn rebuild_done_handling(broadcaster: &Option<Sender>, res: Result<()>, reload_path: &str) {
  119. match res {
  120. Ok(_) => {
  121. if let Some(broadcaster) = broadcaster.as_ref() {
  122. broadcaster
  123. .send(format!(
  124. r#"
  125. {{
  126. "command": "reload",
  127. "path": "{}",
  128. "originalPath": "",
  129. "liveCSS": true,
  130. "liveImg": true,
  131. "protocol": ["http://livereload.com/protocols/official-7"]
  132. }}"#,
  133. reload_path
  134. ))
  135. .unwrap();
  136. }
  137. }
  138. Err(e) => console::unravel_errors("Failed to build the site", &e),
  139. }
  140. }
  141. fn create_new_site(
  142. interface: &str,
  143. port: u16,
  144. output_dir: &str,
  145. base_url: &str,
  146. config_file: &str,
  147. include_drafts: bool,
  148. ) -> Result<(Site, String)> {
  149. let mut site = Site::new(env::current_dir().unwrap(), config_file)?;
  150. let base_address = format!("{}:{}", base_url, port);
  151. let address = format!("{}:{}", interface, port);
  152. let base_url = if site.config.base_url.ends_with('/') {
  153. format!("http://{}/", base_address)
  154. } else {
  155. format!("http://{}", base_address)
  156. };
  157. site.config.enable_serve_mode();
  158. site.set_base_url(base_url);
  159. site.set_output_path(output_dir);
  160. if include_drafts {
  161. site.include_drafts();
  162. }
  163. site.load()?;
  164. site.enable_live_reload(port);
  165. console::notify_site_size(&site);
  166. console::warn_about_ignored_pages(&site);
  167. site.build()?;
  168. Ok((site, address))
  169. }
  170. pub fn serve(
  171. interface: &str,
  172. port: u16,
  173. output_dir: &str,
  174. base_url: &str,
  175. config_file: &str,
  176. watch_only: bool,
  177. open: bool,
  178. include_drafts: bool,
  179. ) -> Result<()> {
  180. let start = Instant::now();
  181. let (mut site, address) =
  182. create_new_site(interface, port, output_dir, base_url, config_file, include_drafts)?;
  183. console::report_elapsed_time(start);
  184. // Setup watchers
  185. let mut watching_static = false;
  186. let mut watching_templates = false;
  187. let mut watching_themes = false;
  188. let (tx, rx) = channel();
  189. let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap();
  190. watcher
  191. .watch("content/", RecursiveMode::Recursive)
  192. .map_err(|e| ZolaError::chain("Can't watch the `content` folder. Does it exist?", e))?;
  193. watcher
  194. .watch(config_file, RecursiveMode::Recursive)
  195. .map_err(|e| ZolaError::chain("Can't watch the `config` file. Does it exist?", e))?;
  196. if Path::new("static").exists() {
  197. watching_static = true;
  198. watcher
  199. .watch("static/", RecursiveMode::Recursive)
  200. .map_err(|e| ZolaError::chain("Can't watch the `static` folder.", e))?;
  201. }
  202. if Path::new("templates").exists() {
  203. watching_templates = true;
  204. watcher
  205. .watch("templates/", RecursiveMode::Recursive)
  206. .map_err(|e| ZolaError::chain("Can't watch the `templates` folder.", e))?;
  207. }
  208. if Path::new("themes").exists() {
  209. watching_themes = true;
  210. watcher
  211. .watch("themes/", RecursiveMode::Recursive)
  212. .map_err(|e| ZolaError::chain("Can't watch the `themes` folder.", e))?;
  213. }
  214. // Sass support is optional so don't make it an error to no have a sass folder
  215. let _ = watcher.watch("sass/", RecursiveMode::Recursive);
  216. let ws_address = format!("{}:{}", interface, site.live_reload.unwrap());
  217. let output_path = Path::new(output_dir).to_path_buf();
  218. // output path is going to need to be moved later on, so clone it for the
  219. // http closure to avoid contention.
  220. let static_root = output_path.clone();
  221. let broadcaster = if !watch_only {
  222. thread::spawn(move || {
  223. let addr = address.parse().unwrap();
  224. let mut rt = tokio::runtime::Builder::new()
  225. .enable_all()
  226. .basic_scheduler()
  227. .build()
  228. .expect("Could not build tokio runtime");
  229. rt.block_on(async {
  230. let make_service = make_service_fn(move |_| {
  231. let static_root = static_root.clone();
  232. async {
  233. Ok::<_, hyper::Error>(service_fn(move |req| {
  234. handle_request(req, static_root.clone())
  235. }))
  236. }
  237. });
  238. let server = Server::bind(&addr).serve(make_service);
  239. println!("Web server is available at http://{}\n", &address);
  240. if open {
  241. if let Err(err) = open::that(format!("http://{}", &address)) {
  242. eprintln!("Failed to open URL in your browser: {}", err);
  243. }
  244. }
  245. server.await.expect("Could not start web server");
  246. });
  247. });
  248. // The websocket for livereload
  249. let ws_server = WebSocket::new(|output: Sender| {
  250. move |msg: Message| {
  251. if msg.into_text().unwrap().contains("\"hello\"") {
  252. return output.send(Message::text(
  253. r#"
  254. {
  255. "command": "hello",
  256. "protocols": [ "http://livereload.com/protocols/official-7" ],
  257. "serverName": "Zola"
  258. }
  259. "#,
  260. ));
  261. }
  262. Ok(())
  263. }
  264. })
  265. .unwrap();
  266. let broadcaster = ws_server.broadcaster();
  267. thread::spawn(move || {
  268. ws_server.listen(&*ws_address).unwrap();
  269. });
  270. Some(broadcaster)
  271. } else {
  272. println!("Watching in watch only mode, no web server will be started");
  273. None
  274. };
  275. let pwd = env::current_dir().unwrap();
  276. let mut watchers = vec!["content", "config.toml"];
  277. if watching_static {
  278. watchers.push("static");
  279. }
  280. if watching_templates {
  281. watchers.push("templates");
  282. }
  283. if watching_themes {
  284. watchers.push("themes");
  285. }
  286. if site.config.compile_sass {
  287. watchers.push("sass");
  288. }
  289. println!(
  290. "Listening for changes in {}{}{{{}}}",
  291. pwd.display(),
  292. MAIN_SEPARATOR,
  293. watchers.join(", ")
  294. );
  295. println!("Press Ctrl+C to stop\n");
  296. // Delete the output folder on ctrl+C
  297. ctrlc::set_handler(move || {
  298. match remove_dir_all(&output_path) {
  299. Ok(()) => (),
  300. Err(e) => println!("Errored while deleting output folder: {}", e),
  301. }
  302. ::std::process::exit(0);
  303. })
  304. .expect("Error setting Ctrl-C handler");
  305. use notify::DebouncedEvent::*;
  306. let reload_templates = |site: &mut Site, path: &Path| {
  307. let msg = if path.is_dir() {
  308. format!("-> Directory in `templates` folder changed {}", path.display())
  309. } else {
  310. format!("-> Template changed {}", path.display())
  311. };
  312. console::info(&msg);
  313. // Force refresh
  314. rebuild_done_handling(&broadcaster, rebuild::after_template_change(site, &path), "/x.js");
  315. };
  316. let reload_sass = |site: &Site, path: &Path, partial_path: &Path| {
  317. let msg = if path.is_dir() {
  318. format!("-> Directory in `sass` folder changed {}", path.display())
  319. } else {
  320. format!("-> Sass file changed {}", path.display())
  321. };
  322. console::info(&msg);
  323. rebuild_done_handling(
  324. &broadcaster,
  325. site.compile_sass(&site.base_path),
  326. &partial_path.to_string_lossy(),
  327. );
  328. };
  329. let copy_static = |site: &Site, path: &Path, partial_path: &Path| {
  330. // Do nothing if the file/dir was deleted
  331. if !path.exists() {
  332. return;
  333. }
  334. let msg = if path.is_dir() {
  335. format!("-> Directory in `static` folder changed {}", path.display())
  336. } else {
  337. format!("-> Static file changed {}", path.display())
  338. };
  339. console::info(&msg);
  340. if path.is_dir() {
  341. rebuild_done_handling(
  342. &broadcaster,
  343. site.copy_static_directories(),
  344. &path.to_string_lossy(),
  345. );
  346. } else {
  347. rebuild_done_handling(
  348. &broadcaster,
  349. copy_file(
  350. &path,
  351. &site.output_path,
  352. &site.static_path,
  353. site.config.hard_link_static,
  354. ),
  355. &partial_path.to_string_lossy(),
  356. );
  357. }
  358. };
  359. loop {
  360. match rx.recv() {
  361. Ok(event) => {
  362. match event {
  363. Rename(old_path, path) => {
  364. if path.is_file() && is_temp_file(&path) {
  365. continue;
  366. }
  367. let (change_kind, partial_path) = detect_change_kind(&pwd, &path);
  368. // We only care about changes in non-empty folders
  369. if path.is_dir() && is_folder_empty(&path) {
  370. continue;
  371. }
  372. println!(
  373. "Change detected @ {}",
  374. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  375. );
  376. let start = Instant::now();
  377. match change_kind {
  378. ChangeKind::Content => {
  379. console::info(&format!("-> Content renamed {}", path.display()));
  380. // Force refresh
  381. rebuild_done_handling(
  382. &broadcaster,
  383. rebuild::after_content_rename(&mut site, &old_path, &path),
  384. "/x.js",
  385. );
  386. }
  387. ChangeKind::Templates => reload_templates(&mut site, &path),
  388. ChangeKind::StaticFiles => copy_static(&site, &path, &partial_path),
  389. ChangeKind::Sass => reload_sass(&site, &path, &partial_path),
  390. ChangeKind::Themes => {
  391. console::info(
  392. "-> Themes changed. The whole site will be reloaded.",
  393. );
  394. site = create_new_site(
  395. interface,
  396. port,
  397. output_dir,
  398. base_url,
  399. config_file,
  400. include_drafts,
  401. )
  402. .unwrap()
  403. .0;
  404. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  405. }
  406. ChangeKind::Config => {
  407. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  408. site = create_new_site(
  409. interface,
  410. port,
  411. output_dir,
  412. base_url,
  413. config_file,
  414. include_drafts,
  415. )
  416. .unwrap()
  417. .0;
  418. }
  419. }
  420. console::report_elapsed_time(start);
  421. }
  422. // Intellij does weird things on edit, chmod is there to count those changes
  423. // https://github.com/passcod/notify/issues/150#issuecomment-494912080
  424. Create(path) | Write(path) | Remove(path) | Chmod(path) => {
  425. if is_ignored_file(&site.config.ignored_content_globset, &path) {
  426. continue;
  427. }
  428. if is_temp_file(&path) || path.is_dir() {
  429. continue;
  430. }
  431. println!(
  432. "Change detected @ {}",
  433. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  434. );
  435. let start = Instant::now();
  436. match detect_change_kind(&pwd, &path) {
  437. (ChangeKind::Content, _) => {
  438. console::info(&format!("-> Content changed {}", path.display()));
  439. // Force refresh
  440. rebuild_done_handling(
  441. &broadcaster,
  442. rebuild::after_content_change(&mut site, &path),
  443. "/x.js",
  444. );
  445. }
  446. (ChangeKind::Templates, _) => reload_templates(&mut site, &path),
  447. (ChangeKind::StaticFiles, p) => copy_static(&site, &path, &p),
  448. (ChangeKind::Sass, p) => reload_sass(&site, &path, &p),
  449. (ChangeKind::Themes, _) => {
  450. console::info(
  451. "-> Themes changed. The whole site will be reloaded.",
  452. );
  453. site = create_new_site(
  454. interface,
  455. port,
  456. output_dir,
  457. base_url,
  458. config_file,
  459. include_drafts,
  460. )
  461. .unwrap()
  462. .0;
  463. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  464. }
  465. (ChangeKind::Config, _) => {
  466. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  467. site = create_new_site(
  468. interface,
  469. port,
  470. output_dir,
  471. base_url,
  472. config_file,
  473. include_drafts,
  474. )
  475. .unwrap()
  476. .0;
  477. }
  478. };
  479. console::report_elapsed_time(start);
  480. }
  481. _ => {}
  482. }
  483. }
  484. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  485. };
  486. }
  487. }
  488. fn is_ignored_file(ignored_content_globset: &Option<GlobSet>, path: &Path) -> bool {
  489. match ignored_content_globset {
  490. Some(gs) => gs.is_match(path),
  491. None => false,
  492. }
  493. }
  494. /// Returns whether the path we received corresponds to a temp file created
  495. /// by an editor or the OS
  496. fn is_temp_file(path: &Path) -> bool {
  497. let ext = path.extension();
  498. match ext {
  499. Some(ex) => match ex.to_str().unwrap() {
  500. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  501. // jetbrains IDE
  502. x if x.ends_with("jb_old___") => true,
  503. x if x.ends_with("jb_tmp___") => true,
  504. x if x.ends_with("jb_bak___") => true,
  505. // vim
  506. x if x.ends_with('~') => true,
  507. _ => {
  508. if let Some(filename) = path.file_stem() {
  509. // emacs
  510. let name = filename.to_str().unwrap();
  511. name.starts_with('#') || name.starts_with(".#")
  512. } else {
  513. false
  514. }
  515. }
  516. },
  517. None => true,
  518. }
  519. }
  520. /// Detect what changed from the given path so we have an idea what needs
  521. /// to be reloaded
  522. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  523. let mut partial_path = PathBuf::from("/");
  524. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  525. let change_kind = if partial_path.starts_with("/templates") {
  526. ChangeKind::Templates
  527. } else if partial_path.starts_with("/themes") {
  528. ChangeKind::Themes
  529. } else if partial_path.starts_with("/content") {
  530. ChangeKind::Content
  531. } else if partial_path.starts_with("/static") {
  532. ChangeKind::StaticFiles
  533. } else if partial_path.starts_with("/sass") {
  534. ChangeKind::Sass
  535. } else if partial_path == Path::new("/config.toml") {
  536. ChangeKind::Config
  537. } else {
  538. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  539. };
  540. (change_kind, partial_path)
  541. }
  542. /// Check if the directory at path contains any file
  543. fn is_folder_empty(dir: &Path) -> bool {
  544. // Can panic if we don't have the rights I guess?
  545. let files: Vec<_> =
  546. read_dir(dir).expect("Failed to read a directory to see if it was empty").collect();
  547. files.is_empty()
  548. }
  549. #[cfg(test)]
  550. mod tests {
  551. use std::path::{Path, PathBuf};
  552. use super::{detect_change_kind, is_temp_file, ChangeKind};
  553. #[test]
  554. fn can_recognize_temp_files() {
  555. let test_cases = vec![
  556. Path::new("hello.swp"),
  557. Path::new("hello.swx"),
  558. Path::new(".DS_STORE"),
  559. Path::new("hello.tmp"),
  560. Path::new("hello.html.__jb_old___"),
  561. Path::new("hello.html.__jb_tmp___"),
  562. Path::new("hello.html.__jb_bak___"),
  563. Path::new("hello.html~"),
  564. Path::new("#hello.html"),
  565. ];
  566. for t in test_cases {
  567. assert!(is_temp_file(&t));
  568. }
  569. }
  570. #[test]
  571. fn can_detect_kind_of_changes() {
  572. let test_cases = vec![
  573. (
  574. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  575. Path::new("/home/vincent/site"),
  576. Path::new("/home/vincent/site/templates/hello.html"),
  577. ),
  578. (
  579. (ChangeKind::Themes, PathBuf::from("/themes/hello.html")),
  580. Path::new("/home/vincent/site"),
  581. Path::new("/home/vincent/site/themes/hello.html"),
  582. ),
  583. (
  584. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  585. Path::new("/home/vincent/site"),
  586. Path::new("/home/vincent/site/static/site.css"),
  587. ),
  588. (
  589. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  590. Path::new("/home/vincent/site"),
  591. Path::new("/home/vincent/site/content/posts/hello.md"),
  592. ),
  593. (
  594. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  595. Path::new("/home/vincent/site"),
  596. Path::new("/home/vincent/site/sass/print.scss"),
  597. ),
  598. (
  599. (ChangeKind::Config, PathBuf::from("/config.toml")),
  600. Path::new("/home/vincent/site"),
  601. Path::new("/home/vincent/site/config.toml"),
  602. ),
  603. ];
  604. for (expected, pwd, path) in test_cases {
  605. assert_eq!(expected, detect_change_kind(&pwd, &path));
  606. }
  607. }
  608. #[test]
  609. #[cfg(windows)]
  610. fn windows_path_handling() {
  611. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  612. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  613. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  614. assert_eq!(expected, detect_change_kind(pwd, path));
  615. }
  616. #[test]
  617. fn relative_path() {
  618. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  619. let pwd = Path::new("/home/johan/site");
  620. let path = Path::new("templates/hello.html");
  621. assert_eq!(expected, detect_change_kind(pwd, path));
  622. }
  623. }