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.

697 lines
25KB

  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. loop {
  362. match rx.recv() {
  363. Ok(event) => {
  364. match event {
  365. Rename(old_path, path) => {
  366. if path.is_file() && is_temp_file(&path) {
  367. continue;
  368. }
  369. let (change_kind, partial_path) = detect_change_kind(&pwd, &path);
  370. // We only care about changes in non-empty folders
  371. if path.is_dir() && is_folder_empty(&path) {
  372. continue;
  373. }
  374. println!(
  375. "Change detected @ {}",
  376. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  377. );
  378. let start = Instant::now();
  379. match change_kind {
  380. ChangeKind::Content => {
  381. console::info(&format!("-> Content renamed {}", path.display()));
  382. // Force refresh
  383. rebuild_done_handling(
  384. &broadcaster,
  385. rebuild::after_content_rename(&mut site, &old_path, &path),
  386. "/x.js",
  387. );
  388. }
  389. ChangeKind::Templates => reload_templates(&mut site, &path),
  390. ChangeKind::StaticFiles => copy_static(&site, &path, &partial_path),
  391. ChangeKind::Sass => reload_sass(&site, &path, &partial_path),
  392. ChangeKind::Themes => {
  393. console::info(
  394. "-> Themes changed. The whole site will be reloaded.",
  395. );
  396. site = create_new_site(
  397. root_dir,
  398. interface,
  399. port,
  400. output_dir,
  401. base_url,
  402. config_file,
  403. include_drafts,
  404. )
  405. .unwrap()
  406. .0;
  407. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  408. }
  409. ChangeKind::Config => {
  410. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  411. site = create_new_site(
  412. root_dir,
  413. interface,
  414. port,
  415. output_dir,
  416. base_url,
  417. config_file,
  418. include_drafts,
  419. )
  420. .unwrap()
  421. .0;
  422. }
  423. }
  424. console::report_elapsed_time(start);
  425. }
  426. // Intellij does weird things on edit, chmod is there to count those changes
  427. // https://github.com/passcod/notify/issues/150#issuecomment-494912080
  428. Create(path) | Write(path) | Remove(path) | Chmod(path) => {
  429. if is_ignored_file(&site.config.ignored_content_globset, &path) {
  430. continue;
  431. }
  432. if is_temp_file(&path) || path.is_dir() {
  433. continue;
  434. }
  435. println!(
  436. "Change detected @ {}",
  437. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  438. );
  439. let start = Instant::now();
  440. match detect_change_kind(&pwd, &path) {
  441. (ChangeKind::Content, _) => {
  442. console::info(&format!("-> Content changed {}", path.display()));
  443. // Force refresh
  444. rebuild_done_handling(
  445. &broadcaster,
  446. rebuild::after_content_change(&mut site, &path),
  447. "/x.js",
  448. );
  449. }
  450. (ChangeKind::Templates, _) => reload_templates(&mut site, &path),
  451. (ChangeKind::StaticFiles, p) => copy_static(&site, &path, &p),
  452. (ChangeKind::Sass, p) => reload_sass(&site, &path, &p),
  453. (ChangeKind::Themes, _) => {
  454. console::info(
  455. "-> Themes changed. The whole site will be reloaded.",
  456. );
  457. site = create_new_site(
  458. root_dir,
  459. interface,
  460. port,
  461. output_dir,
  462. base_url,
  463. config_file,
  464. include_drafts,
  465. )
  466. .unwrap()
  467. .0;
  468. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  469. }
  470. (ChangeKind::Config, _) => {
  471. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  472. site = create_new_site(
  473. root_dir,
  474. interface,
  475. port,
  476. output_dir,
  477. base_url,
  478. config_file,
  479. include_drafts,
  480. )
  481. .unwrap()
  482. .0;
  483. }
  484. };
  485. console::report_elapsed_time(start);
  486. }
  487. _ => {}
  488. }
  489. }
  490. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  491. };
  492. }
  493. }
  494. fn is_ignored_file(ignored_content_globset: &Option<GlobSet>, path: &Path) -> bool {
  495. match ignored_content_globset {
  496. Some(gs) => gs.is_match(path),
  497. None => false,
  498. }
  499. }
  500. /// Returns whether the path we received corresponds to a temp file created
  501. /// by an editor or the OS
  502. fn is_temp_file(path: &Path) -> bool {
  503. let ext = path.extension();
  504. match ext {
  505. Some(ex) => match ex.to_str().unwrap() {
  506. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  507. // jetbrains IDE
  508. x if x.ends_with("jb_old___") => true,
  509. x if x.ends_with("jb_tmp___") => true,
  510. x if x.ends_with("jb_bak___") => true,
  511. // vim
  512. x if x.ends_with('~') => true,
  513. _ => {
  514. if let Some(filename) = path.file_stem() {
  515. // emacs
  516. let name = filename.to_str().unwrap();
  517. name.starts_with('#') || name.starts_with(".#")
  518. } else {
  519. false
  520. }
  521. }
  522. },
  523. None => true,
  524. }
  525. }
  526. /// Detect what changed from the given path so we have an idea what needs
  527. /// to be reloaded
  528. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  529. let mut partial_path = PathBuf::from("/");
  530. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  531. let change_kind = if partial_path.starts_with("/templates") {
  532. ChangeKind::Templates
  533. } else if partial_path.starts_with("/themes") {
  534. ChangeKind::Themes
  535. } else if partial_path.starts_with("/content") {
  536. ChangeKind::Content
  537. } else if partial_path.starts_with("/static") {
  538. ChangeKind::StaticFiles
  539. } else if partial_path.starts_with("/sass") {
  540. ChangeKind::Sass
  541. } else if partial_path == Path::new("/config.toml") {
  542. ChangeKind::Config
  543. } else {
  544. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  545. };
  546. (change_kind, partial_path)
  547. }
  548. /// Check if the directory at path contains any file
  549. fn is_folder_empty(dir: &Path) -> bool {
  550. // Can panic if we don't have the rights I guess?
  551. let files: Vec<_> =
  552. read_dir(dir).expect("Failed to read a directory to see if it was empty").collect();
  553. files.is_empty()
  554. }
  555. #[cfg(test)]
  556. mod tests {
  557. use std::path::{Path, PathBuf};
  558. use super::{detect_change_kind, is_temp_file, ChangeKind};
  559. #[test]
  560. fn can_recognize_temp_files() {
  561. let test_cases = vec![
  562. Path::new("hello.swp"),
  563. Path::new("hello.swx"),
  564. Path::new(".DS_STORE"),
  565. Path::new("hello.tmp"),
  566. Path::new("hello.html.__jb_old___"),
  567. Path::new("hello.html.__jb_tmp___"),
  568. Path::new("hello.html.__jb_bak___"),
  569. Path::new("hello.html~"),
  570. Path::new("#hello.html"),
  571. ];
  572. for t in test_cases {
  573. assert!(is_temp_file(&t));
  574. }
  575. }
  576. #[test]
  577. fn can_detect_kind_of_changes() {
  578. let test_cases = vec![
  579. (
  580. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  581. Path::new("/home/vincent/site"),
  582. Path::new("/home/vincent/site/templates/hello.html"),
  583. ),
  584. (
  585. (ChangeKind::Themes, PathBuf::from("/themes/hello.html")),
  586. Path::new("/home/vincent/site"),
  587. Path::new("/home/vincent/site/themes/hello.html"),
  588. ),
  589. (
  590. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  591. Path::new("/home/vincent/site"),
  592. Path::new("/home/vincent/site/static/site.css"),
  593. ),
  594. (
  595. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  596. Path::new("/home/vincent/site"),
  597. Path::new("/home/vincent/site/content/posts/hello.md"),
  598. ),
  599. (
  600. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  601. Path::new("/home/vincent/site"),
  602. Path::new("/home/vincent/site/sass/print.scss"),
  603. ),
  604. (
  605. (ChangeKind::Config, PathBuf::from("/config.toml")),
  606. Path::new("/home/vincent/site"),
  607. Path::new("/home/vincent/site/config.toml"),
  608. ),
  609. ];
  610. for (expected, pwd, path) in test_cases {
  611. assert_eq!(expected, detect_change_kind(&pwd, &path));
  612. }
  613. }
  614. #[test]
  615. #[cfg(windows)]
  616. fn windows_path_handling() {
  617. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  618. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  619. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  620. assert_eq!(expected, detect_change_kind(pwd, path));
  621. }
  622. #[test]
  623. fn relative_path() {
  624. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  625. let pwd = Path::new("/home/johan/site");
  626. let path = Path::new("templates/hello.html");
  627. assert_eq!(expected, detect_change_kind(pwd, path));
  628. }
  629. }