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.

634 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.1.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. match remove_dir_all(&output_path) {
  253. Ok(()) => (),
  254. Err(e) => println!("Errored while deleting output folder: {}", e),
  255. }
  256. ::std::process::exit(0);
  257. })
  258. .expect("Error setting Ctrl-C handler");
  259. use notify::DebouncedEvent::*;
  260. let reload_templates = |site: &mut Site, path: &Path| {
  261. let msg = if path.is_dir() {
  262. format!("-> Directory in `templates` folder changed {}", path.display())
  263. } else {
  264. format!("-> Template changed {}", path.display())
  265. };
  266. console::info(&msg);
  267. // Force refresh
  268. rebuild_done_handling(&broadcaster, rebuild::after_template_change(site, &path), "/x.js");
  269. };
  270. let reload_sass = |site: &Site, path: &Path, partial_path: &Path| {
  271. let msg = if path.is_dir() {
  272. format!("-> Directory in `sass` folder changed {}", path.display())
  273. } else {
  274. format!("-> Sass file changed {}", path.display())
  275. };
  276. console::info(&msg);
  277. rebuild_done_handling(
  278. &broadcaster,
  279. site.compile_sass(&site.base_path),
  280. &partial_path.to_string_lossy(),
  281. );
  282. };
  283. let copy_static = |site: &Site, path: &Path, partial_path: &Path| {
  284. // Do nothing if the file/dir was deleted
  285. if !path.exists() {
  286. return;
  287. }
  288. let msg = if path.is_dir() {
  289. format!("-> Directory in `static` folder changed {}", path.display())
  290. } else {
  291. format!("-> Static file changed {}", path.display())
  292. };
  293. console::info(&msg);
  294. if path.is_dir() {
  295. rebuild_done_handling(
  296. &broadcaster,
  297. site.copy_static_directories(),
  298. &path.to_string_lossy(),
  299. );
  300. } else {
  301. rebuild_done_handling(
  302. &broadcaster,
  303. copy_file(
  304. &path,
  305. &site.output_path,
  306. &site.static_path,
  307. site.config.hard_link_static,
  308. ),
  309. &partial_path.to_string_lossy(),
  310. );
  311. }
  312. };
  313. loop {
  314. match rx.recv() {
  315. Ok(event) => {
  316. match event {
  317. Rename(old_path, path) => {
  318. if path.is_file() && is_temp_file(&path) {
  319. continue;
  320. }
  321. let (change_kind, partial_path) = detect_change_kind(&pwd, &path);
  322. // We only care about changes in non-empty folders
  323. if path.is_dir() && is_folder_empty(&path) {
  324. continue;
  325. }
  326. println!(
  327. "Change detected @ {}",
  328. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  329. );
  330. let start = Instant::now();
  331. match change_kind {
  332. ChangeKind::Content => {
  333. console::info(&format!("-> Content renamed {}", path.display()));
  334. // Force refresh
  335. rebuild_done_handling(
  336. &broadcaster,
  337. rebuild::after_content_rename(&mut site, &old_path, &path),
  338. "/x.js",
  339. );
  340. }
  341. ChangeKind::Templates => reload_templates(&mut site, &path),
  342. ChangeKind::StaticFiles => copy_static(&site, &path, &partial_path),
  343. ChangeKind::Sass => reload_sass(&site, &path, &partial_path),
  344. ChangeKind::Themes => {
  345. console::info(
  346. "-> Themes changed. The whole site will be reloaded.",
  347. );
  348. site = create_new_site(
  349. interface,
  350. port,
  351. output_dir,
  352. base_url,
  353. config_file,
  354. include_drafts,
  355. )
  356. .unwrap()
  357. .0;
  358. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  359. }
  360. ChangeKind::Config => {
  361. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  362. site = create_new_site(
  363. interface,
  364. port,
  365. output_dir,
  366. base_url,
  367. config_file,
  368. include_drafts,
  369. )
  370. .unwrap()
  371. .0;
  372. }
  373. }
  374. console::report_elapsed_time(start);
  375. }
  376. // Intellij does weird things on edit, chmod is there to count those changes
  377. // https://github.com/passcod/notify/issues/150#issuecomment-494912080
  378. Create(path) | Write(path) | Remove(path) | Chmod(path) => {
  379. if is_ignored_file(&site.config.ignored_content_globset, &path) {
  380. continue;
  381. }
  382. if is_temp_file(&path) || path.is_dir() {
  383. continue;
  384. }
  385. println!(
  386. "Change detected @ {}",
  387. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  388. );
  389. let start = Instant::now();
  390. match detect_change_kind(&pwd, &path) {
  391. (ChangeKind::Content, _) => {
  392. console::info(&format!("-> Content changed {}", path.display()));
  393. // Force refresh
  394. rebuild_done_handling(
  395. &broadcaster,
  396. rebuild::after_content_change(&mut site, &path),
  397. "/x.js",
  398. );
  399. }
  400. (ChangeKind::Templates, _) => reload_templates(&mut site, &path),
  401. (ChangeKind::StaticFiles, p) => copy_static(&site, &path, &p),
  402. (ChangeKind::Sass, p) => reload_sass(&site, &path, &p),
  403. (ChangeKind::Themes, _) => {
  404. console::info(
  405. "-> Themes changed. The whole site will be reloaded.",
  406. );
  407. site = create_new_site(
  408. interface,
  409. port,
  410. output_dir,
  411. base_url,
  412. config_file,
  413. include_drafts,
  414. )
  415. .unwrap()
  416. .0;
  417. rebuild_done_handling(&broadcaster, Ok(()), "/x.js");
  418. }
  419. (ChangeKind::Config, _) => {
  420. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  421. site = create_new_site(
  422. interface,
  423. port,
  424. output_dir,
  425. base_url,
  426. config_file,
  427. include_drafts,
  428. )
  429. .unwrap()
  430. .0;
  431. }
  432. };
  433. console::report_elapsed_time(start);
  434. }
  435. _ => {}
  436. }
  437. }
  438. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  439. };
  440. }
  441. }
  442. fn is_ignored_file(ignored_content_globset: &Option<GlobSet>, path: &Path) -> bool {
  443. match ignored_content_globset {
  444. Some(gs) => gs.is_match(path),
  445. None => false,
  446. }
  447. }
  448. /// Returns whether the path we received corresponds to a temp file created
  449. /// by an editor or the OS
  450. fn is_temp_file(path: &Path) -> bool {
  451. let ext = path.extension();
  452. match ext {
  453. Some(ex) => match ex.to_str().unwrap() {
  454. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  455. // jetbrains IDE
  456. x if x.ends_with("jb_old___") => true,
  457. x if x.ends_with("jb_tmp___") => true,
  458. x if x.ends_with("jb_bak___") => true,
  459. // vim
  460. x if x.ends_with('~') => true,
  461. _ => {
  462. if let Some(filename) = path.file_stem() {
  463. // emacs
  464. let name = filename.to_str().unwrap();
  465. name.starts_with('#') || name.starts_with(".#")
  466. } else {
  467. false
  468. }
  469. }
  470. },
  471. None => true,
  472. }
  473. }
  474. /// Detect what changed from the given path so we have an idea what needs
  475. /// to be reloaded
  476. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  477. let mut partial_path = PathBuf::from("/");
  478. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  479. let change_kind = if partial_path.starts_with("/templates") {
  480. ChangeKind::Templates
  481. } else if partial_path.starts_with("/themes") {
  482. ChangeKind::Themes
  483. } else if partial_path.starts_with("/content") {
  484. ChangeKind::Content
  485. } else if partial_path.starts_with("/static") {
  486. ChangeKind::StaticFiles
  487. } else if partial_path.starts_with("/sass") {
  488. ChangeKind::Sass
  489. } else if partial_path == Path::new("/config.toml") {
  490. ChangeKind::Config
  491. } else {
  492. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  493. };
  494. (change_kind, partial_path)
  495. }
  496. /// Check if the directory at path contains any file
  497. fn is_folder_empty(dir: &Path) -> bool {
  498. // Can panic if we don't have the rights I guess?
  499. let files: Vec<_> =
  500. read_dir(dir).expect("Failed to read a directory to see if it was empty").collect();
  501. files.is_empty()
  502. }
  503. #[cfg(test)]
  504. mod tests {
  505. use std::path::{Path, PathBuf};
  506. use super::{detect_change_kind, is_temp_file, ChangeKind};
  507. #[test]
  508. fn can_recognize_temp_files() {
  509. let test_cases = vec![
  510. Path::new("hello.swp"),
  511. Path::new("hello.swx"),
  512. Path::new(".DS_STORE"),
  513. Path::new("hello.tmp"),
  514. Path::new("hello.html.__jb_old___"),
  515. Path::new("hello.html.__jb_tmp___"),
  516. Path::new("hello.html.__jb_bak___"),
  517. Path::new("hello.html~"),
  518. Path::new("#hello.html"),
  519. ];
  520. for t in test_cases {
  521. assert!(is_temp_file(&t));
  522. }
  523. }
  524. #[test]
  525. fn can_detect_kind_of_changes() {
  526. let test_cases = vec![
  527. (
  528. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  529. Path::new("/home/vincent/site"),
  530. Path::new("/home/vincent/site/templates/hello.html"),
  531. ),
  532. (
  533. (ChangeKind::Themes, PathBuf::from("/themes/hello.html")),
  534. Path::new("/home/vincent/site"),
  535. Path::new("/home/vincent/site/themes/hello.html"),
  536. ),
  537. (
  538. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  539. Path::new("/home/vincent/site"),
  540. Path::new("/home/vincent/site/static/site.css"),
  541. ),
  542. (
  543. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  544. Path::new("/home/vincent/site"),
  545. Path::new("/home/vincent/site/content/posts/hello.md"),
  546. ),
  547. (
  548. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  549. Path::new("/home/vincent/site"),
  550. Path::new("/home/vincent/site/sass/print.scss"),
  551. ),
  552. (
  553. (ChangeKind::Config, PathBuf::from("/config.toml")),
  554. Path::new("/home/vincent/site"),
  555. Path::new("/home/vincent/site/config.toml"),
  556. ),
  557. ];
  558. for (expected, pwd, path) in test_cases {
  559. assert_eq!(expected, detect_change_kind(&pwd, &path));
  560. }
  561. }
  562. #[test]
  563. #[cfg(windows)]
  564. fn windows_path_handling() {
  565. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  566. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  567. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  568. assert_eq!(expected, detect_change_kind(pwd, path));
  569. }
  570. #[test]
  571. fn relative_path() {
  572. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  573. let pwd = Path::new("/home/johan/site");
  574. let path = Path::new("templates/hello.html");
  575. assert_eq!(expected, detect_change_kind(pwd, path));
  576. }
  577. }