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.

563 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 rebuild;
  42. #[derive(Debug, PartialEq)]
  43. enum ChangeKind {
  44. Content,
  45. Templates,
  46. StaticFiles,
  47. Sass,
  48. Config,
  49. }
  50. // Uglified using uglifyjs
  51. // Also, commenting out the lines 330-340 (containing `e instanceof ProtocolError`) was needed
  52. // as it seems their build didn't work well and didn't include ProtocolError so it would error on
  53. // errors
  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(
  70. http::header::CONTENT_TYPE,
  71. http::header::HeaderValue::from_static("text/html"),
  72. )
  73. .body(buf);
  74. Ok(ErrorHandlerResponse::Response(
  75. res.into_response(new_resp.into_body()),
  76. ))
  77. }
  78. fn livereload_handler() -> HttpResponse {
  79. HttpResponse::Ok().content_type("text/javascript").body(LIVE_RELOAD)
  80. }
  81. fn rebuild_done_handling(broadcaster: &Option<Sender>, res: Result<()>, reload_path: &str) {
  82. match res {
  83. Ok(_) => {
  84. if let Some(broadcaster) = broadcaster.as_ref() {
  85. broadcaster
  86. .send(format!(
  87. r#"
  88. {{
  89. "command": "reload",
  90. "path": "{}",
  91. "originalPath": "",
  92. "liveCSS": true,
  93. "liveImg": true,
  94. "protocol": ["http://livereload.com/protocols/official-7"]
  95. }}"#,
  96. reload_path
  97. ))
  98. .unwrap();
  99. }
  100. }
  101. Err(e) => console::unravel_errors("Failed to build the site", &e),
  102. }
  103. }
  104. fn create_new_site(
  105. interface: &str,
  106. port: u16,
  107. output_dir: &str,
  108. base_url: &str,
  109. config_file: &str,
  110. ) -> Result<(Site, String)> {
  111. let mut site = Site::new(env::current_dir().unwrap(), config_file)?;
  112. let base_address = format!("{}:{}", base_url, port);
  113. let address = format!("{}:{}", interface, port);
  114. let base_url = if site.config.base_url.ends_with('/') {
  115. format!("http://{}/", base_address)
  116. } else {
  117. format!("http://{}", base_address)
  118. };
  119. site.set_base_url(base_url);
  120. site.set_output_path(output_dir);
  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. ) -> 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. s.run()
  194. });
  195. // The websocket for livereload
  196. let ws_server = WebSocket::new(|output: Sender| {
  197. move |msg: Message| {
  198. if msg.into_text().unwrap().contains("\"hello\"") {
  199. return output.send(Message::text(
  200. r#"
  201. {
  202. "command": "hello",
  203. "protocols": [ "http://livereload.com/protocols/official-7" ],
  204. "serverName": "Zola"
  205. }
  206. "#,
  207. ));
  208. }
  209. Ok(())
  210. }
  211. })
  212. .unwrap();
  213. let broadcaster = ws_server.broadcaster();
  214. thread::spawn(move || {
  215. ws_server.listen(&*ws_address).unwrap();
  216. });
  217. Some(broadcaster)
  218. } else {
  219. println!("Watching in watch only mode, no web server will be started");
  220. None
  221. };
  222. let pwd = env::current_dir().unwrap();
  223. let mut watchers = vec!["content", "config.toml"];
  224. if watching_static {
  225. watchers.push("static");
  226. }
  227. if watching_templates {
  228. watchers.push("templates");
  229. }
  230. if site.config.compile_sass {
  231. watchers.push("sass");
  232. }
  233. println!(
  234. "Listening for changes in {}{}{{{}}}",
  235. pwd.display(),
  236. MAIN_SEPARATOR,
  237. watchers.join(", ")
  238. );
  239. println!("Press Ctrl+C to stop\n");
  240. // Delete the output folder on ctrl+C
  241. ctrlc::set_handler(move || {
  242. remove_dir_all(&output_path).expect("Failed to delete output directory");
  243. ::std::process::exit(0);
  244. })
  245. .expect("Error setting Ctrl-C handler");
  246. use notify::DebouncedEvent::*;
  247. let reload_templates = |site: &mut Site, path: &Path| {
  248. let msg = if path.is_dir() {
  249. format!("-> Directory in `templates` folder changed {}", path.display())
  250. } else {
  251. format!("-> Template changed {}", path.display())
  252. };
  253. console::info(&msg);
  254. // Force refresh
  255. rebuild_done_handling(&broadcaster, rebuild::after_template_change(site, &path), "/x.js");
  256. };
  257. let reload_sass = |site: &Site, path: &Path, partial_path: &Path| {
  258. let msg = if path.is_dir() {
  259. format!("-> Directory in `sass` folder changed {}", path.display())
  260. } else {
  261. format!("-> Sass file changed {}", path.display())
  262. };
  263. console::info(&msg);
  264. rebuild_done_handling(
  265. &broadcaster,
  266. site.compile_sass(&site.base_path),
  267. &partial_path.to_string_lossy(),
  268. );
  269. };
  270. let copy_static = |site: &Site, path: &Path, partial_path: &Path| {
  271. // Do nothing if the file/dir was deleted
  272. if !path.exists() {
  273. return;
  274. }
  275. let msg = if path.is_dir() {
  276. format!("-> Directory in `static` folder changed {}", path.display())
  277. } else {
  278. format!("-> Static file changed {}", path.display())
  279. };
  280. console::info(&msg);
  281. if path.is_dir() {
  282. rebuild_done_handling(
  283. &broadcaster,
  284. site.copy_static_directories(),
  285. &path.to_string_lossy(),
  286. );
  287. } else {
  288. rebuild_done_handling(
  289. &broadcaster,
  290. copy_file(&path, &site.output_path, &site.static_path),
  291. &partial_path.to_string_lossy(),
  292. );
  293. }
  294. };
  295. loop {
  296. match rx.recv() {
  297. Ok(event) => {
  298. match event {
  299. Rename(old_path, path) => {
  300. if path.is_file() && is_temp_file(&path) {
  301. continue;
  302. }
  303. let (change_kind, partial_path) = detect_change_kind(&pwd, &path);
  304. // We only care about changes in non-empty folders
  305. if path.is_dir() && is_folder_empty(&path) {
  306. continue;
  307. }
  308. println!(
  309. "Change detected @ {}",
  310. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  311. );
  312. let start = Instant::now();
  313. match change_kind {
  314. ChangeKind::Content => {
  315. console::info(&format!("-> Content renamed {}", path.display()));
  316. // Force refresh
  317. rebuild_done_handling(
  318. &broadcaster,
  319. rebuild::after_content_rename(&mut site, &old_path, &path),
  320. "/x.js",
  321. );
  322. }
  323. ChangeKind::Templates => reload_templates(&mut site, &path),
  324. ChangeKind::StaticFiles => copy_static(&site, &path, &partial_path),
  325. ChangeKind::Sass => reload_sass(&site, &path, &partial_path),
  326. ChangeKind::Config => {
  327. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  328. site = create_new_site(
  329. interface,
  330. port,
  331. output_dir,
  332. base_url,
  333. config_file,
  334. )
  335. .unwrap()
  336. .0;
  337. }
  338. }
  339. console::report_elapsed_time(start);
  340. }
  341. // Intellij does weird things on edit, chmod is there to count those changes
  342. // https://github.com/passcod/notify/issues/150#issuecomment-494912080
  343. Create(path) | Write(path) | Remove(path) | Chmod(path) => {
  344. if is_temp_file(&path) || path.is_dir() {
  345. continue;
  346. }
  347. println!(
  348. "Change detected @ {}",
  349. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  350. );
  351. let start = Instant::now();
  352. match detect_change_kind(&pwd, &path) {
  353. (ChangeKind::Content, _) => {
  354. console::info(&format!("-> Content changed {}", path.display()));
  355. // Force refresh
  356. rebuild_done_handling(
  357. &broadcaster,
  358. rebuild::after_content_change(&mut site, &path),
  359. "/x.js",
  360. );
  361. }
  362. (ChangeKind::Templates, _) => reload_templates(&mut site, &path),
  363. (ChangeKind::StaticFiles, p) => copy_static(&site, &path, &p),
  364. (ChangeKind::Sass, p) => reload_sass(&site, &path, &p),
  365. (ChangeKind::Config, _) => {
  366. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  367. site = create_new_site(
  368. interface,
  369. port,
  370. output_dir,
  371. base_url,
  372. config_file,
  373. )
  374. .unwrap()
  375. .0;
  376. }
  377. };
  378. console::report_elapsed_time(start);
  379. }
  380. _ => {}
  381. }
  382. }
  383. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  384. };
  385. }
  386. }
  387. /// Returns whether the path we received corresponds to a temp file created
  388. /// by an editor or the OS
  389. fn is_temp_file(path: &Path) -> bool {
  390. let ext = path.extension();
  391. match ext {
  392. Some(ex) => match ex.to_str().unwrap() {
  393. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  394. // jetbrains IDE
  395. x if x.ends_with("jb_old___") => true,
  396. x if x.ends_with("jb_tmp___") => true,
  397. x if x.ends_with("jb_bak___") => true,
  398. // vim
  399. x if x.ends_with('~') => true,
  400. _ => {
  401. if let Some(filename) = path.file_stem() {
  402. // emacs
  403. let name = filename.to_str().unwrap();
  404. name.starts_with('#') || name.starts_with(".#")
  405. } else {
  406. false
  407. }
  408. }
  409. },
  410. None => true,
  411. }
  412. }
  413. /// Detect what changed from the given path so we have an idea what needs
  414. /// to be reloaded
  415. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  416. let mut partial_path = PathBuf::from("/");
  417. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  418. let change_kind = if partial_path.starts_with("/templates") {
  419. ChangeKind::Templates
  420. } else if partial_path.starts_with("/content") {
  421. ChangeKind::Content
  422. } else if partial_path.starts_with("/static") {
  423. ChangeKind::StaticFiles
  424. } else if partial_path.starts_with("/sass") {
  425. ChangeKind::Sass
  426. } else if partial_path == Path::new("/config.toml") {
  427. ChangeKind::Config
  428. } else {
  429. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  430. };
  431. (change_kind, partial_path)
  432. }
  433. /// Check if the directory at path contains any file
  434. fn is_folder_empty(dir: &Path) -> bool {
  435. // Can panic if we don't have the rights I guess?
  436. let files: Vec<_> =
  437. read_dir(dir).expect("Failed to read a directory to see if it was empty").collect();
  438. files.is_empty()
  439. }
  440. #[cfg(test)]
  441. mod tests {
  442. use std::path::{Path, PathBuf};
  443. use super::{detect_change_kind, is_temp_file, ChangeKind};
  444. #[test]
  445. fn can_recognize_temp_files() {
  446. let test_cases = vec![
  447. Path::new("hello.swp"),
  448. Path::new("hello.swx"),
  449. Path::new(".DS_STORE"),
  450. Path::new("hello.tmp"),
  451. Path::new("hello.html.__jb_old___"),
  452. Path::new("hello.html.__jb_tmp___"),
  453. Path::new("hello.html.__jb_bak___"),
  454. Path::new("hello.html~"),
  455. Path::new("#hello.html"),
  456. ];
  457. for t in test_cases {
  458. assert!(is_temp_file(&t));
  459. }
  460. }
  461. #[test]
  462. fn can_detect_kind_of_changes() {
  463. let test_cases = vec![
  464. (
  465. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  466. Path::new("/home/vincent/site"),
  467. Path::new("/home/vincent/site/templates/hello.html"),
  468. ),
  469. (
  470. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  471. Path::new("/home/vincent/site"),
  472. Path::new("/home/vincent/site/static/site.css"),
  473. ),
  474. (
  475. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  476. Path::new("/home/vincent/site"),
  477. Path::new("/home/vincent/site/content/posts/hello.md"),
  478. ),
  479. (
  480. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  481. Path::new("/home/vincent/site"),
  482. Path::new("/home/vincent/site/sass/print.scss"),
  483. ),
  484. (
  485. (ChangeKind::Config, PathBuf::from("/config.toml")),
  486. Path::new("/home/vincent/site"),
  487. Path::new("/home/vincent/site/config.toml"),
  488. ),
  489. ];
  490. for (expected, pwd, path) in test_cases {
  491. assert_eq!(expected, detect_change_kind(&pwd, &path));
  492. }
  493. }
  494. #[test]
  495. #[cfg(windows)]
  496. fn windows_path_handling() {
  497. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  498. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  499. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  500. assert_eq!(expected, detect_change_kind(pwd, path));
  501. }
  502. #[test]
  503. fn relative_path() {
  504. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  505. let pwd = Path::new("/home/johan/site");
  506. let path = Path::new("templates/hello.html");
  507. assert_eq!(expected, detect_change_kind(pwd, path));
  508. }
  509. }