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.

631 lines
23KB

  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, File};
  25. use std::io::Read;
  26. use std::path::{Path, PathBuf, MAIN_SEPARATOR};
  27. use std::sync::mpsc::channel;
  28. use std::thread;
  29. use std::time::{Duration, Instant};
  30. use actix_files as fs;
  31. use actix_web::middleware::errhandlers::{ErrorHandlerResponse, ErrorHandlers};
  32. use actix_web::{dev, http, web, App, HttpResponse, HttpServer};
  33. use chrono::prelude::*;
  34. use ctrlc;
  35. use notify::{watcher, RecursiveMode, Watcher};
  36. use ws::{Message, Sender, WebSocket};
  37. use errors::{Error as ZolaError, Result};
  38. use globset::GlobSet;
  39. use site::Site;
  40. use utils::fs::copy_file;
  41. use crate::console;
  42. use open;
  43. use rebuild;
  44. #[derive(Debug, PartialEq)]
  45. enum ChangeKind {
  46. Content,
  47. Templates,
  48. Themes,
  49. StaticFiles,
  50. Sass,
  51. Config,
  52. }
  53. // This is dist/livereload.min.js from the LiveReload.js v3.0.0 release
  54. const LIVE_RELOAD: &str = include_str!("livereload.js");
  55. struct ErrorFilePaths {
  56. not_found: PathBuf,
  57. }
  58. fn not_found<B>(
  59. res: dev::ServiceResponse<B>,
  60. ) -> std::result::Result<ErrorHandlerResponse<B>, actix_web::Error> {
  61. let buf: Vec<u8> = {
  62. let error_files: &ErrorFilePaths = res.request().app_data().unwrap();
  63. let mut fh = File::open(&error_files.not_found)?;
  64. let mut buf: Vec<u8> = vec![];
  65. let _ = fh.read_to_end(&mut buf)?;
  66. buf
  67. };
  68. let new_resp = HttpResponse::build(http::StatusCode::NOT_FOUND)
  69. .header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static("text/html"))
  70. .body(buf);
  71. Ok(ErrorHandlerResponse::Response(res.into_response(new_resp.into_body())))
  72. }
  73. fn livereload_handler() -> HttpResponse {
  74. HttpResponse::Ok().content_type("text/javascript").body(LIVE_RELOAD)
  75. }
  76. fn rebuild_done_handling(broadcaster: &Option<Sender>, res: Result<()>, reload_path: &str) {
  77. match res {
  78. Ok(_) => {
  79. if let Some(broadcaster) = broadcaster.as_ref() {
  80. broadcaster
  81. .send(format!(
  82. r#"
  83. {{
  84. "command": "reload",
  85. "path": "{}",
  86. "originalPath": "",
  87. "liveCSS": true,
  88. "liveImg": true,
  89. "protocol": ["http://livereload.com/protocols/official-7"]
  90. }}"#,
  91. reload_path
  92. ))
  93. .unwrap();
  94. }
  95. }
  96. Err(e) => console::unravel_errors("Failed to build the site", &e),
  97. }
  98. }
  99. fn create_new_site(
  100. interface: &str,
  101. port: u16,
  102. output_dir: &str,
  103. base_url: &str,
  104. config_file: &str,
  105. include_drafts: bool,
  106. ) -> Result<(Site, String)> {
  107. let mut site = Site::new(env::current_dir().unwrap(), config_file)?;
  108. let base_address = format!("{}:{}", base_url, port);
  109. let address = format!("{}:{}", interface, port);
  110. let base_url = if site.config.base_url.ends_with('/') {
  111. format!("http://{}/", base_address)
  112. } else {
  113. format!("http://{}", base_address)
  114. };
  115. site.config.enable_serve_mode();
  116. site.set_base_url(base_url);
  117. site.set_output_path(output_dir);
  118. if include_drafts {
  119. site.include_drafts();
  120. }
  121. site.load()?;
  122. site.enable_live_reload(port);
  123. console::notify_site_size(&site);
  124. console::warn_about_ignored_pages(&site);
  125. site.build()?;
  126. Ok((site, address))
  127. }
  128. pub fn serve(
  129. interface: &str,
  130. port: u16,
  131. output_dir: &str,
  132. base_url: &str,
  133. config_file: &str,
  134. watch_only: bool,
  135. open: bool,
  136. include_drafts: bool,
  137. ) -> Result<()> {
  138. let start = Instant::now();
  139. let (mut site, address) =
  140. create_new_site(interface, port, output_dir, base_url, config_file, include_drafts)?;
  141. console::report_elapsed_time(start);
  142. // Setup watchers
  143. let mut watching_static = false;
  144. let mut watching_templates = false;
  145. let mut watching_themes = false;
  146. let (tx, rx) = channel();
  147. let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap();
  148. watcher
  149. .watch("content/", RecursiveMode::Recursive)
  150. .map_err(|e| ZolaError::chain("Can't watch the `content` folder. Does it exist?", e))?;
  151. watcher
  152. .watch(config_file, RecursiveMode::Recursive)
  153. .map_err(|e| ZolaError::chain("Can't watch the `config` file. Does it exist?", e))?;
  154. if Path::new("static").exists() {
  155. watching_static = true;
  156. watcher
  157. .watch("static/", RecursiveMode::Recursive)
  158. .map_err(|e| ZolaError::chain("Can't watch the `static` folder.", e))?;
  159. }
  160. if Path::new("templates").exists() {
  161. watching_templates = true;
  162. watcher
  163. .watch("templates/", RecursiveMode::Recursive)
  164. .map_err(|e| ZolaError::chain("Can't watch the `templates` folder.", e))?;
  165. }
  166. if Path::new("themes").exists() {
  167. watching_themes = true;
  168. watcher
  169. .watch("themes/", RecursiveMode::Recursive)
  170. .map_err(|e| ZolaError::chain("Can't watch the `themes` folder.", e))?;
  171. }
  172. // Sass support is optional so don't make it an error to no have a sass folder
  173. let _ = watcher.watch("sass/", RecursiveMode::Recursive);
  174. let ws_address = format!("{}:{}", interface, site.live_reload.unwrap());
  175. let output_path = Path::new(output_dir).to_path_buf();
  176. // output path is going to need to be moved later on, so clone it for the
  177. // http closure to avoid contention.
  178. let static_root = output_path.clone();
  179. let broadcaster = if !watch_only {
  180. thread::spawn(move || {
  181. let s = HttpServer::new(move || {
  182. let error_handlers =
  183. ErrorHandlers::new().handler(http::StatusCode::NOT_FOUND, not_found);
  184. App::new()
  185. .data(ErrorFilePaths { not_found: static_root.join("404.html") })
  186. .wrap(error_handlers)
  187. .route("/livereload.js", web::get().to(livereload_handler))
  188. // Start a webserver that serves the `output_dir` directory
  189. .service(fs::Files::new("/", &static_root).index_file("index.html"))
  190. })
  191. .bind(&address)
  192. .expect("Can't start the webserver")
  193. .shutdown_timeout(20);
  194. println!("Web server is available at http://{}\n", &address);
  195. if open {
  196. if let Err(err) = open::that(format!("http://{}", &address)) {
  197. eprintln!("Failed to open URL in your browser: {}", err);
  198. }
  199. }
  200. s.run()
  201. });
  202. // The websocket for livereload
  203. let ws_server = WebSocket::new(|output: Sender| {
  204. move |msg: Message| {
  205. if msg.into_text().unwrap().contains("\"hello\"") {
  206. return output.send(Message::text(
  207. r#"
  208. {
  209. "command": "hello",
  210. "protocols": [ "http://livereload.com/protocols/official-7" ],
  211. "serverName": "Zola"
  212. }
  213. "#,
  214. ));
  215. }
  216. Ok(())
  217. }
  218. })
  219. .unwrap();
  220. let broadcaster = ws_server.broadcaster();
  221. thread::spawn(move || {
  222. ws_server.listen(&*ws_address).unwrap();
  223. });
  224. Some(broadcaster)
  225. } else {
  226. println!("Watching in watch only mode, no web server will be started");
  227. None
  228. };
  229. let pwd = env::current_dir().unwrap();
  230. let mut watchers = vec!["content", "config.toml"];
  231. if watching_static {
  232. watchers.push("static");
  233. }
  234. if watching_templates {
  235. watchers.push("templates");
  236. }
  237. if watching_themes {
  238. watchers.push("themes");
  239. }
  240. if site.config.compile_sass {
  241. watchers.push("sass");
  242. }
  243. println!(
  244. "Listening for changes in {}{}{{{}}}",
  245. pwd.display(),
  246. MAIN_SEPARATOR,
  247. watchers.join(", ")
  248. );
  249. println!("Press Ctrl+C to stop\n");
  250. // Delete the output folder on ctrl+C
  251. ctrlc::set_handler(move || {
  252. let _ = remove_dir_all(&output_path);
  253. ::std::process::exit(0);
  254. })
  255. .expect("Error setting Ctrl-C handler");
  256. use notify::DebouncedEvent::*;
  257. let reload_templates = |site: &mut Site, path: &Path| {
  258. let msg = if path.is_dir() {
  259. format!("-> Directory in `templates` folder changed {}", path.display())
  260. } else {
  261. format!("-> Template changed {}", path.display())
  262. };
  263. console::info(&msg);
  264. // Force refresh
  265. rebuild_done_handling(&broadcaster, rebuild::after_template_change(site, &path), "/x.js");
  266. };
  267. let reload_sass = |site: &Site, path: &Path, partial_path: &Path| {
  268. let msg = if path.is_dir() {
  269. format!("-> Directory in `sass` folder changed {}", path.display())
  270. } else {
  271. format!("-> Sass file changed {}", path.display())
  272. };
  273. console::info(&msg);
  274. rebuild_done_handling(
  275. &broadcaster,
  276. site.compile_sass(&site.base_path),
  277. &partial_path.to_string_lossy(),
  278. );
  279. };
  280. let copy_static = |site: &Site, path: &Path, partial_path: &Path| {
  281. // Do nothing if the file/dir was deleted
  282. if !path.exists() {
  283. return;
  284. }
  285. let msg = if path.is_dir() {
  286. format!("-> Directory in `static` folder changed {}", path.display())
  287. } else {
  288. format!("-> Static file changed {}", path.display())
  289. };
  290. console::info(&msg);
  291. if path.is_dir() {
  292. rebuild_done_handling(
  293. &broadcaster,
  294. site.copy_static_directories(),
  295. &path.to_string_lossy(),
  296. );
  297. } else {
  298. rebuild_done_handling(
  299. &broadcaster,
  300. copy_file(
  301. &path,
  302. &site.output_path,
  303. &site.static_path,
  304. site.config.hard_link_static,
  305. ),
  306. &partial_path.to_string_lossy(),
  307. );
  308. }
  309. };
  310. loop {
  311. match rx.recv() {
  312. Ok(event) => {
  313. match event {
  314. Rename(old_path, path) => {
  315. if path.is_file() && is_temp_file(&path) {
  316. continue;
  317. }
  318. let (change_kind, partial_path) = detect_change_kind(&pwd, &path);
  319. // We only care about changes in non-empty folders
  320. if path.is_dir() && is_folder_empty(&path) {
  321. continue;
  322. }
  323. println!(
  324. "Change detected @ {}",
  325. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  326. );
  327. let start = Instant::now();
  328. match change_kind {
  329. ChangeKind::Content => {
  330. console::info(&format!("-> Content renamed {}", path.display()));
  331. // Force refresh
  332. rebuild_done_handling(
  333. &broadcaster,
  334. rebuild::after_content_rename(&mut site, &old_path, &path),
  335. "/x.js",
  336. );
  337. }
  338. ChangeKind::Templates => reload_templates(&mut site, &path),
  339. ChangeKind::StaticFiles => copy_static(&site, &path, &partial_path),
  340. ChangeKind::Sass => reload_sass(&site, &path, &partial_path),
  341. ChangeKind::Themes => {
  342. console::info(
  343. "-> Themes changed. The whole site will be reloaded.",
  344. );
  345. site = create_new_site(
  346. interface,
  347. port,
  348. output_dir,
  349. base_url,
  350. config_file,
  351. include_drafts,
  352. )
  353. .unwrap()
  354. .0;
  355. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  356. }
  357. ChangeKind::Config => {
  358. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  359. site = create_new_site(
  360. interface,
  361. port,
  362. output_dir,
  363. base_url,
  364. config_file,
  365. include_drafts,
  366. )
  367. .unwrap()
  368. .0;
  369. }
  370. }
  371. console::report_elapsed_time(start);
  372. }
  373. // Intellij does weird things on edit, chmod is there to count those changes
  374. // https://github.com/passcod/notify/issues/150#issuecomment-494912080
  375. Create(path) | Write(path) | Remove(path) | Chmod(path) => {
  376. if is_ignored_file(&site.config.ignored_content_globset, &path) {
  377. continue;
  378. }
  379. if is_temp_file(&path) || path.is_dir() {
  380. continue;
  381. }
  382. println!(
  383. "Change detected @ {}",
  384. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  385. );
  386. let start = Instant::now();
  387. match detect_change_kind(&pwd, &path) {
  388. (ChangeKind::Content, _) => {
  389. console::info(&format!("-> Content changed {}", path.display()));
  390. // Force refresh
  391. rebuild_done_handling(
  392. &broadcaster,
  393. rebuild::after_content_change(&mut site, &path),
  394. "/x.js",
  395. );
  396. }
  397. (ChangeKind::Templates, _) => reload_templates(&mut site, &path),
  398. (ChangeKind::StaticFiles, p) => copy_static(&site, &path, &p),
  399. (ChangeKind::Sass, p) => reload_sass(&site, &path, &p),
  400. (ChangeKind::Themes, _) => {
  401. console::info(
  402. "-> Themes changed. The whole site will be reloaded.",
  403. );
  404. site = create_new_site(
  405. interface,
  406. port,
  407. output_dir,
  408. base_url,
  409. config_file,
  410. include_drafts,
  411. )
  412. .unwrap()
  413. .0;
  414. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  415. }
  416. (ChangeKind::Config, _) => {
  417. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  418. site = create_new_site(
  419. interface,
  420. port,
  421. output_dir,
  422. base_url,
  423. config_file,
  424. include_drafts,
  425. )
  426. .unwrap()
  427. .0;
  428. }
  429. };
  430. console::report_elapsed_time(start);
  431. }
  432. _ => {}
  433. }
  434. }
  435. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  436. };
  437. }
  438. }
  439. fn is_ignored_file(ignored_content_globset: &Option<GlobSet>, path: &Path) -> bool {
  440. match ignored_content_globset {
  441. Some(gs) => gs.is_match(path),
  442. None => false,
  443. }
  444. }
  445. /// Returns whether the path we received corresponds to a temp file created
  446. /// by an editor or the OS
  447. fn is_temp_file(path: &Path) -> bool {
  448. let ext = path.extension();
  449. match ext {
  450. Some(ex) => match ex.to_str().unwrap() {
  451. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  452. // jetbrains IDE
  453. x if x.ends_with("jb_old___") => true,
  454. x if x.ends_with("jb_tmp___") => true,
  455. x if x.ends_with("jb_bak___") => true,
  456. // vim
  457. x if x.ends_with('~') => true,
  458. _ => {
  459. if let Some(filename) = path.file_stem() {
  460. // emacs
  461. let name = filename.to_str().unwrap();
  462. name.starts_with('#') || name.starts_with(".#")
  463. } else {
  464. false
  465. }
  466. }
  467. },
  468. None => true,
  469. }
  470. }
  471. /// Detect what changed from the given path so we have an idea what needs
  472. /// to be reloaded
  473. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  474. let mut partial_path = PathBuf::from("/");
  475. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  476. let change_kind = if partial_path.starts_with("/templates") {
  477. ChangeKind::Templates
  478. } else if partial_path.starts_with("/themes") {
  479. ChangeKind::Themes
  480. } else if partial_path.starts_with("/content") {
  481. ChangeKind::Content
  482. } else if partial_path.starts_with("/static") {
  483. ChangeKind::StaticFiles
  484. } else if partial_path.starts_with("/sass") {
  485. ChangeKind::Sass
  486. } else if partial_path == Path::new("/config.toml") {
  487. ChangeKind::Config
  488. } else {
  489. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  490. };
  491. (change_kind, partial_path)
  492. }
  493. /// Check if the directory at path contains any file
  494. fn is_folder_empty(dir: &Path) -> bool {
  495. // Can panic if we don't have the rights I guess?
  496. let files: Vec<_> =
  497. read_dir(dir).expect("Failed to read a directory to see if it was empty").collect();
  498. files.is_empty()
  499. }
  500. #[cfg(test)]
  501. mod tests {
  502. use std::path::{Path, PathBuf};
  503. use super::{detect_change_kind, is_temp_file, ChangeKind};
  504. #[test]
  505. fn can_recognize_temp_files() {
  506. let test_cases = vec![
  507. Path::new("hello.swp"),
  508. Path::new("hello.swx"),
  509. Path::new(".DS_STORE"),
  510. Path::new("hello.tmp"),
  511. Path::new("hello.html.__jb_old___"),
  512. Path::new("hello.html.__jb_tmp___"),
  513. Path::new("hello.html.__jb_bak___"),
  514. Path::new("hello.html~"),
  515. Path::new("#hello.html"),
  516. ];
  517. for t in test_cases {
  518. assert!(is_temp_file(&t));
  519. }
  520. }
  521. #[test]
  522. fn can_detect_kind_of_changes() {
  523. let test_cases = vec![
  524. (
  525. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  526. Path::new("/home/vincent/site"),
  527. Path::new("/home/vincent/site/templates/hello.html"),
  528. ),
  529. (
  530. (ChangeKind::Themes, PathBuf::from("/themes/hello.html")),
  531. Path::new("/home/vincent/site"),
  532. Path::new("/home/vincent/site/themes/hello.html"),
  533. ),
  534. (
  535. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  536. Path::new("/home/vincent/site"),
  537. Path::new("/home/vincent/site/static/site.css"),
  538. ),
  539. (
  540. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  541. Path::new("/home/vincent/site"),
  542. Path::new("/home/vincent/site/content/posts/hello.md"),
  543. ),
  544. (
  545. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  546. Path::new("/home/vincent/site"),
  547. Path::new("/home/vincent/site/sass/print.scss"),
  548. ),
  549. (
  550. (ChangeKind::Config, PathBuf::from("/config.toml")),
  551. Path::new("/home/vincent/site"),
  552. Path::new("/home/vincent/site/config.toml"),
  553. ),
  554. ];
  555. for (expected, pwd, path) in test_cases {
  556. assert_eq!(expected, detect_change_kind(&pwd, &path));
  557. }
  558. }
  559. #[test]
  560. #[cfg(windows)]
  561. fn windows_path_handling() {
  562. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  563. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  564. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  565. assert_eq!(expected, detect_change_kind(pwd, path));
  566. }
  567. #[test]
  568. fn relative_path() {
  569. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  570. let pwd = Path::new("/home/johan/site");
  571. let path = Path::new("templates/hello.html");
  572. assert_eq!(expected, detect_change_kind(pwd, path));
  573. }
  574. }