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.

686 lines
24KB

  1. // Contains an embedded version of livereload-js 3.2.1
  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. root_dir: &Path,
  143. interface: &str,
  144. port: u16,
  145. output_dir: &str,
  146. base_url: &str,
  147. config_file: &str,
  148. include_drafts: bool,
  149. ) -> Result<(Site, String)> {
  150. let mut site = Site::new(root_dir, config_file)?;
  151. let base_address = format!("{}:{}", base_url, port);
  152. let address = format!("{}:{}", interface, port);
  153. let base_url = if site.config.base_url.ends_with('/') {
  154. format!("http://{}/", base_address)
  155. } else {
  156. format!("http://{}", base_address)
  157. };
  158. site.config.enable_serve_mode();
  159. site.set_base_url(base_url);
  160. site.set_output_path(output_dir);
  161. if include_drafts {
  162. site.include_drafts();
  163. }
  164. site.load()?;
  165. site.enable_live_reload(port);
  166. console::notify_site_size(&site);
  167. console::warn_about_ignored_pages(&site);
  168. site.build()?;
  169. Ok((site, address))
  170. }
  171. pub fn serve(
  172. root_dir: &Path,
  173. interface: &str,
  174. port: u16,
  175. output_dir: &str,
  176. base_url: &str,
  177. config_file: &str,
  178. watch_only: bool,
  179. open: bool,
  180. include_drafts: bool,
  181. ) -> Result<()> {
  182. let start = Instant::now();
  183. let (mut site, address) =
  184. create_new_site(root_dir, interface, port, output_dir, base_url, config_file, include_drafts)?;
  185. console::report_elapsed_time(start);
  186. // Setup watchers
  187. let mut watching_static = false;
  188. let mut watching_templates = false;
  189. let mut watching_themes = false;
  190. let (tx, rx) = channel();
  191. let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap();
  192. watcher
  193. .watch("content/", RecursiveMode::Recursive)
  194. .map_err(|e| ZolaError::chain("Can't watch the `content` folder. Does it exist?", e))?;
  195. watcher
  196. .watch(config_file, RecursiveMode::Recursive)
  197. .map_err(|e| ZolaError::chain("Can't watch the `config` file. Does it exist?", e))?;
  198. if Path::new("static").exists() {
  199. watching_static = true;
  200. watcher
  201. .watch("static/", RecursiveMode::Recursive)
  202. .map_err(|e| ZolaError::chain("Can't watch the `static` folder.", e))?;
  203. }
  204. if Path::new("templates").exists() {
  205. watching_templates = true;
  206. watcher
  207. .watch("templates/", RecursiveMode::Recursive)
  208. .map_err(|e| ZolaError::chain("Can't watch the `templates` folder.", e))?;
  209. }
  210. if Path::new("themes").exists() {
  211. watching_themes = true;
  212. watcher
  213. .watch("themes/", RecursiveMode::Recursive)
  214. .map_err(|e| ZolaError::chain("Can't watch the `themes` folder.", e))?;
  215. }
  216. // Sass support is optional so don't make it an error to no have a sass folder
  217. let _ = watcher.watch("sass/", RecursiveMode::Recursive);
  218. let ws_address = format!("{}:{}", interface, site.live_reload.unwrap());
  219. let output_path = Path::new(output_dir).to_path_buf();
  220. // output path is going to need to be moved later on, so clone it for the
  221. // http closure to avoid contention.
  222. let static_root = output_path.clone();
  223. let broadcaster = if !watch_only {
  224. thread::spawn(move || {
  225. let addr = address.parse().unwrap();
  226. let mut rt = tokio::runtime::Builder::new()
  227. .enable_all()
  228. .basic_scheduler()
  229. .build()
  230. .expect("Could not build tokio runtime");
  231. rt.block_on(async {
  232. let make_service = make_service_fn(move |_| {
  233. let static_root = static_root.clone();
  234. async {
  235. Ok::<_, hyper::Error>(service_fn(move |req| {
  236. handle_request(req, static_root.clone())
  237. }))
  238. }
  239. });
  240. let server = Server::bind(&addr).serve(make_service);
  241. println!("Web server is available at http://{}\n", &address);
  242. if open {
  243. if let Err(err) = open::that(format!("http://{}", &address)) {
  244. eprintln!("Failed to open URL in your browser: {}", err);
  245. }
  246. }
  247. server.await.expect("Could not start web server");
  248. });
  249. });
  250. // The websocket for livereload
  251. let ws_server = WebSocket::new(|output: Sender| {
  252. move |msg: Message| {
  253. if msg.into_text().unwrap().contains("\"hello\"") {
  254. return output.send(Message::text(
  255. r#"
  256. {
  257. "command": "hello",
  258. "protocols": [ "http://livereload.com/protocols/official-7" ],
  259. "serverName": "Zola"
  260. }
  261. "#,
  262. ));
  263. }
  264. Ok(())
  265. }
  266. })
  267. .unwrap();
  268. let broadcaster = ws_server.broadcaster();
  269. thread::spawn(move || {
  270. ws_server.listen(&*ws_address).unwrap();
  271. });
  272. Some(broadcaster)
  273. } else {
  274. println!("Watching in watch only mode, no web server will be started");
  275. None
  276. };
  277. let pwd = env::current_dir().unwrap();
  278. let mut watchers = vec!["content", "config.toml"];
  279. if watching_static {
  280. watchers.push("static");
  281. }
  282. if watching_templates {
  283. watchers.push("templates");
  284. }
  285. if watching_themes {
  286. watchers.push("themes");
  287. }
  288. if site.config.compile_sass {
  289. watchers.push("sass");
  290. }
  291. println!(
  292. "Listening for changes in {}{}{{{}}}",
  293. pwd.display(),
  294. MAIN_SEPARATOR,
  295. watchers.join(", ")
  296. );
  297. println!("Press Ctrl+C to stop\n");
  298. // Delete the output folder on ctrl+C
  299. ctrlc::set_handler(move || {
  300. match remove_dir_all(&output_path) {
  301. Ok(()) => (),
  302. Err(e) => println!("Errored while deleting output folder: {}", e),
  303. }
  304. ::std::process::exit(0);
  305. })
  306. .expect("Error setting Ctrl-C handler");
  307. use notify::DebouncedEvent::*;
  308. let reload_templates = |site: &mut Site, path: &Path| {
  309. let msg = if path.is_dir() {
  310. format!("-> Directory in `templates` folder changed {}", path.display())
  311. } else {
  312. format!("-> Template changed {}", path.display())
  313. };
  314. console::info(&msg);
  315. // Force refresh
  316. rebuild_done_handling(&broadcaster, rebuild::after_template_change(site, &path), "/x.js");
  317. };
  318. let reload_sass = |site: &Site, path: &Path, partial_path: &Path| {
  319. let msg = if path.is_dir() {
  320. format!("-> Directory in `sass` folder changed {}", path.display())
  321. } else {
  322. format!("-> Sass file changed {}", path.display())
  323. };
  324. console::info(&msg);
  325. rebuild_done_handling(
  326. &broadcaster,
  327. site.compile_sass(&site.base_path),
  328. &partial_path.to_string_lossy(),
  329. );
  330. };
  331. let copy_static = |site: &Site, path: &Path, partial_path: &Path| {
  332. // Do nothing if the file/dir was deleted
  333. if !path.exists() {
  334. return;
  335. }
  336. let msg = if path.is_dir() {
  337. format!("-> Directory in `static` folder changed {}", path.display())
  338. } else {
  339. format!("-> Static file changed {}", path.display())
  340. };
  341. console::info(&msg);
  342. if path.is_dir() {
  343. rebuild_done_handling(
  344. &broadcaster,
  345. site.copy_static_directories(),
  346. &path.to_string_lossy(),
  347. );
  348. } else {
  349. rebuild_done_handling(
  350. &broadcaster,
  351. copy_file(
  352. &path,
  353. &site.output_path,
  354. &site.static_path,
  355. site.config.hard_link_static,
  356. ),
  357. &partial_path.to_string_lossy(),
  358. );
  359. }
  360. };
  361. let recreate_site = || match create_new_site(
  362. root_dir,
  363. interface,
  364. port,
  365. output_dir,
  366. base_url,
  367. config_file,
  368. include_drafts,
  369. ) {
  370. Ok((s, _)) => {
  371. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  372. Some(s)
  373. }
  374. Err(e) => {
  375. console::error(&format!("{}", e));
  376. None
  377. }
  378. };
  379. loop {
  380. match rx.recv() {
  381. Ok(event) => {
  382. match event {
  383. Rename(old_path, path) => {
  384. if path.is_file() && is_temp_file(&path) {
  385. continue;
  386. }
  387. let (change_kind, partial_path) = detect_change_kind(&pwd, &path);
  388. // We only care about changes in non-empty folders
  389. if path.is_dir() && is_folder_empty(&path) {
  390. continue;
  391. }
  392. println!(
  393. "Change detected @ {}",
  394. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  395. );
  396. let start = Instant::now();
  397. match change_kind {
  398. ChangeKind::Content => {
  399. console::info(&format!("-> Content renamed {}", path.display()));
  400. // Force refresh
  401. rebuild_done_handling(
  402. &broadcaster,
  403. rebuild::after_content_rename(&mut site, &old_path, &path),
  404. "/x.js",
  405. );
  406. }
  407. ChangeKind::Templates => reload_templates(&mut site, &path),
  408. ChangeKind::StaticFiles => copy_static(&site, &path, &partial_path),
  409. ChangeKind::Sass => reload_sass(&site, &path, &partial_path),
  410. ChangeKind::Themes => {
  411. console::info(
  412. "-> Themes changed. The whole site will be reloaded.",
  413. );
  414. if let Some(s) = recreate_site() {
  415. site = s;
  416. }
  417. }
  418. ChangeKind::Config => {
  419. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  420. if let Some(s) = recreate_site() {
  421. site = s;
  422. }
  423. }
  424. }
  425. console::report_elapsed_time(start);
  426. }
  427. // Intellij does weird things on edit, chmod is there to count those changes
  428. // https://github.com/passcod/notify/issues/150#issuecomment-494912080
  429. Create(path) | Write(path) | Remove(path) | Chmod(path) => {
  430. if is_ignored_file(&site.config.ignored_content_globset, &path) {
  431. continue;
  432. }
  433. if is_temp_file(&path) || path.is_dir() {
  434. continue;
  435. }
  436. println!(
  437. "Change detected @ {}",
  438. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  439. );
  440. let start = Instant::now();
  441. match detect_change_kind(&pwd, &path) {
  442. (ChangeKind::Content, _) => {
  443. console::info(&format!("-> Content changed {}", path.display()));
  444. // Force refresh
  445. rebuild_done_handling(
  446. &broadcaster,
  447. rebuild::after_content_change(&mut site, &path),
  448. "/x.js",
  449. );
  450. }
  451. (ChangeKind::Templates, _) => reload_templates(&mut site, &path),
  452. (ChangeKind::StaticFiles, p) => copy_static(&site, &path, &p),
  453. (ChangeKind::Sass, p) => reload_sass(&site, &path, &p),
  454. (ChangeKind::Themes, _) => {
  455. console::info(
  456. "-> Themes changed. The whole site will be reloaded.",
  457. );
  458. if let Some(s) = recreate_site() {
  459. site = s;
  460. }
  461. }
  462. (ChangeKind::Config, _) => {
  463. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  464. if let Some(s) = recreate_site() {
  465. site = s;
  466. }
  467. }
  468. };
  469. console::report_elapsed_time(start);
  470. }
  471. _ => {}
  472. }
  473. }
  474. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  475. };
  476. }
  477. }
  478. fn is_ignored_file(ignored_content_globset: &Option<GlobSet>, path: &Path) -> bool {
  479. match ignored_content_globset {
  480. Some(gs) => gs.is_match(path),
  481. None => false,
  482. }
  483. }
  484. /// Returns whether the path we received corresponds to a temp file created
  485. /// by an editor or the OS
  486. fn is_temp_file(path: &Path) -> bool {
  487. let ext = path.extension();
  488. match ext {
  489. Some(ex) => match ex.to_str().unwrap() {
  490. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  491. // jetbrains IDE
  492. x if x.ends_with("jb_old___") => true,
  493. x if x.ends_with("jb_tmp___") => true,
  494. x if x.ends_with("jb_bak___") => true,
  495. // vim
  496. x if x.ends_with('~') => true,
  497. _ => {
  498. if let Some(filename) = path.file_stem() {
  499. // emacs
  500. let name = filename.to_str().unwrap();
  501. name.starts_with('#') || name.starts_with(".#")
  502. } else {
  503. false
  504. }
  505. }
  506. },
  507. None => true,
  508. }
  509. }
  510. /// Detect what changed from the given path so we have an idea what needs
  511. /// to be reloaded
  512. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  513. let mut partial_path = PathBuf::from("/");
  514. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  515. let change_kind = if partial_path.starts_with("/templates") {
  516. ChangeKind::Templates
  517. } else if partial_path.starts_with("/themes") {
  518. ChangeKind::Themes
  519. } else if partial_path.starts_with("/content") {
  520. ChangeKind::Content
  521. } else if partial_path.starts_with("/static") {
  522. ChangeKind::StaticFiles
  523. } else if partial_path.starts_with("/sass") {
  524. ChangeKind::Sass
  525. } else if partial_path == Path::new("/config.toml") {
  526. ChangeKind::Config
  527. } else {
  528. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  529. };
  530. (change_kind, partial_path)
  531. }
  532. /// Check if the directory at path contains any file
  533. fn is_folder_empty(dir: &Path) -> bool {
  534. // Can panic if we don't have the rights I guess?
  535. let files: Vec<_> =
  536. read_dir(dir).expect("Failed to read a directory to see if it was empty").collect();
  537. files.is_empty()
  538. }
  539. #[cfg(test)]
  540. mod tests {
  541. use std::path::{Path, PathBuf};
  542. use super::{detect_change_kind, is_temp_file, ChangeKind};
  543. #[test]
  544. fn can_recognize_temp_files() {
  545. let test_cases = vec![
  546. Path::new("hello.swp"),
  547. Path::new("hello.swx"),
  548. Path::new(".DS_STORE"),
  549. Path::new("hello.tmp"),
  550. Path::new("hello.html.__jb_old___"),
  551. Path::new("hello.html.__jb_tmp___"),
  552. Path::new("hello.html.__jb_bak___"),
  553. Path::new("hello.html~"),
  554. Path::new("#hello.html"),
  555. ];
  556. for t in test_cases {
  557. assert!(is_temp_file(&t));
  558. }
  559. }
  560. #[test]
  561. fn can_detect_kind_of_changes() {
  562. let test_cases = vec![
  563. (
  564. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  565. Path::new("/home/vincent/site"),
  566. Path::new("/home/vincent/site/templates/hello.html"),
  567. ),
  568. (
  569. (ChangeKind::Themes, PathBuf::from("/themes/hello.html")),
  570. Path::new("/home/vincent/site"),
  571. Path::new("/home/vincent/site/themes/hello.html"),
  572. ),
  573. (
  574. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  575. Path::new("/home/vincent/site"),
  576. Path::new("/home/vincent/site/static/site.css"),
  577. ),
  578. (
  579. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  580. Path::new("/home/vincent/site"),
  581. Path::new("/home/vincent/site/content/posts/hello.md"),
  582. ),
  583. (
  584. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  585. Path::new("/home/vincent/site"),
  586. Path::new("/home/vincent/site/sass/print.scss"),
  587. ),
  588. (
  589. (ChangeKind::Config, PathBuf::from("/config.toml")),
  590. Path::new("/home/vincent/site"),
  591. Path::new("/home/vincent/site/config.toml"),
  592. ),
  593. ];
  594. for (expected, pwd, path) in test_cases {
  595. assert_eq!(expected, detect_change_kind(&pwd, &path));
  596. }
  597. }
  598. #[test]
  599. #[cfg(windows)]
  600. fn windows_path_handling() {
  601. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  602. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  603. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  604. assert_eq!(expected, detect_change_kind(pwd, path));
  605. }
  606. #[test]
  607. fn relative_path() {
  608. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  609. let pwd = Path::new("/home/johan/site");
  610. let path = Path::new("templates/hello.html");
  611. assert_eq!(expected, detect_change_kind(pwd, path));
  612. }
  613. }