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.

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