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.

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