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.

619 lines
22KB

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