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.

568 lines
20KB

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