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.

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