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.

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