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.

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