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 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(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static("text/html"))
  68. .body(buf);
  69. Ok(ErrorHandlerResponse::Response(res.into_response(new_resp.into_body())))
  70. }
  71. fn livereload_handler() -> HttpResponse {
  72. HttpResponse::Ok().content_type("text/javascript").body(LIVE_RELOAD)
  73. }
  74. fn rebuild_done_handling(broadcaster: &Option<Sender>, res: Result<()>, reload_path: &str) {
  75. match res {
  76. Ok(_) => {
  77. if let Some(broadcaster) = broadcaster.as_ref() {
  78. broadcaster
  79. .send(format!(
  80. r#"
  81. {{
  82. "command": "reload",
  83. "path": "{}",
  84. "originalPath": "",
  85. "liveCSS": true,
  86. "liveImg": true,
  87. "protocol": ["http://livereload.com/protocols/official-7"]
  88. }}"#,
  89. reload_path
  90. ))
  91. .unwrap();
  92. }
  93. }
  94. Err(e) => console::unravel_errors("Failed to build the site", &e),
  95. }
  96. }
  97. fn create_new_site(
  98. interface: &str,
  99. port: u16,
  100. output_dir: &str,
  101. base_url: &str,
  102. config_file: &str,
  103. ) -> Result<(Site, String)> {
  104. let mut site = Site::new(env::current_dir().unwrap(), config_file)?;
  105. let base_address = format!("{}:{}", base_url, port);
  106. let address = format!("{}:{}", interface, port);
  107. let base_url = if site.config.base_url.ends_with('/') {
  108. format!("http://{}/", base_address)
  109. } else {
  110. format!("http://{}", base_address)
  111. };
  112. site.config.enable_serve_mode();
  113. site.set_base_url(base_url);
  114. site.set_output_path(output_dir);
  115. site.load()?;
  116. site.enable_live_reload(port);
  117. console::notify_site_size(&site);
  118. console::warn_about_ignored_pages(&site);
  119. site.build()?;
  120. Ok((site, address))
  121. }
  122. pub fn serve(
  123. interface: &str,
  124. port: u16,
  125. output_dir: &str,
  126. base_url: &str,
  127. config_file: &str,
  128. watch_only: bool,
  129. open: bool,
  130. ) -> Result<()> {
  131. let start = Instant::now();
  132. let (mut site, address) = create_new_site(interface, port, output_dir, base_url, config_file)?;
  133. console::report_elapsed_time(start);
  134. // Setup watchers
  135. let mut watching_static = false;
  136. let mut watching_templates = false;
  137. let (tx, rx) = channel();
  138. let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap();
  139. watcher
  140. .watch("content/", RecursiveMode::Recursive)
  141. .map_err(|e| ZolaError::chain("Can't watch the `content` folder. Does it exist?", e))?;
  142. watcher
  143. .watch(config_file, RecursiveMode::Recursive)
  144. .map_err(|e| ZolaError::chain("Can't watch the `config` file. Does it exist?", e))?;
  145. if Path::new("static").exists() {
  146. watching_static = true;
  147. watcher
  148. .watch("static/", RecursiveMode::Recursive)
  149. .map_err(|e| ZolaError::chain("Can't watch the `static` folder.", e))?;
  150. }
  151. if Path::new("templates").exists() {
  152. watching_templates = true;
  153. watcher
  154. .watch("templates/", RecursiveMode::Recursive)
  155. .map_err(|e| ZolaError::chain("Can't watch the `templates` folder.", e))?;
  156. }
  157. // Sass support is optional so don't make it an error to no have a sass folder
  158. let _ = watcher.watch("sass/", RecursiveMode::Recursive);
  159. let ws_address = format!("{}:{}", interface, site.live_reload.unwrap());
  160. let output_path = Path::new(output_dir).to_path_buf();
  161. // output path is going to need to be moved later on, so clone it for the
  162. // http closure to avoid contention.
  163. let static_root = output_path.clone();
  164. let broadcaster = if !watch_only {
  165. thread::spawn(move || {
  166. let s = HttpServer::new(move || {
  167. let error_handlers =
  168. ErrorHandlers::new().handler(http::StatusCode::NOT_FOUND, not_found);
  169. App::new()
  170. .data(ErrorFilePaths { not_found: static_root.join("404.html") })
  171. .wrap(error_handlers)
  172. .route("/livereload.js", web::get().to(livereload_handler))
  173. // Start a webserver that serves the `output_dir` directory
  174. .service(fs::Files::new("/", &static_root).index_file("index.html"))
  175. })
  176. .bind(&address)
  177. .expect("Can't start the webserver")
  178. .shutdown_timeout(20);
  179. println!("Web server is available at http://{}\n", &address);
  180. if open {
  181. if let Err(err) = open::that(format!("http://{}", &address)) {
  182. eprintln!("Failed to open URL in your browser: {}", err);
  183. }
  184. }
  185. s.run()
  186. });
  187. // The websocket for livereload
  188. let ws_server = WebSocket::new(|output: Sender| {
  189. move |msg: Message| {
  190. if msg.into_text().unwrap().contains("\"hello\"") {
  191. return output.send(Message::text(
  192. r#"
  193. {
  194. "command": "hello",
  195. "protocols": [ "http://livereload.com/protocols/official-7" ],
  196. "serverName": "Zola"
  197. }
  198. "#,
  199. ));
  200. }
  201. Ok(())
  202. }
  203. })
  204. .unwrap();
  205. let broadcaster = ws_server.broadcaster();
  206. thread::spawn(move || {
  207. ws_server.listen(&*ws_address).unwrap();
  208. });
  209. Some(broadcaster)
  210. } else {
  211. println!("Watching in watch only mode, no web server will be started");
  212. None
  213. };
  214. let pwd = env::current_dir().unwrap();
  215. let mut watchers = vec!["content", "config.toml"];
  216. if watching_static {
  217. watchers.push("static");
  218. }
  219. if watching_templates {
  220. watchers.push("templates");
  221. }
  222. if site.config.compile_sass {
  223. watchers.push("sass");
  224. }
  225. println!(
  226. "Listening for changes in {}{}{{{}}}",
  227. pwd.display(),
  228. MAIN_SEPARATOR,
  229. watchers.join(", ")
  230. );
  231. println!("Press Ctrl+C to stop\n");
  232. // Delete the output folder on ctrl+C
  233. ctrlc::set_handler(move || {
  234. let _ = remove_dir_all(&output_path);
  235. ::std::process::exit(0);
  236. })
  237. .expect("Error setting Ctrl-C handler");
  238. use notify::DebouncedEvent::*;
  239. let reload_templates = |site: &mut Site, path: &Path| {
  240. let msg = if path.is_dir() {
  241. format!("-> Directory in `templates` folder changed {}", path.display())
  242. } else {
  243. format!("-> Template changed {}", path.display())
  244. };
  245. console::info(&msg);
  246. // Force refresh
  247. rebuild_done_handling(&broadcaster, rebuild::after_template_change(site, &path), "/x.js");
  248. };
  249. let reload_sass = |site: &Site, path: &Path, partial_path: &Path| {
  250. let msg = if path.is_dir() {
  251. format!("-> Directory in `sass` folder changed {}", path.display())
  252. } else {
  253. format!("-> Sass file changed {}", path.display())
  254. };
  255. console::info(&msg);
  256. rebuild_done_handling(
  257. &broadcaster,
  258. site.compile_sass(&site.base_path),
  259. &partial_path.to_string_lossy(),
  260. );
  261. };
  262. let copy_static = |site: &Site, path: &Path, partial_path: &Path| {
  263. // Do nothing if the file/dir was deleted
  264. if !path.exists() {
  265. return;
  266. }
  267. let msg = if path.is_dir() {
  268. format!("-> Directory in `static` folder changed {}", path.display())
  269. } else {
  270. format!("-> Static file changed {}", path.display())
  271. };
  272. console::info(&msg);
  273. if path.is_dir() {
  274. rebuild_done_handling(
  275. &broadcaster,
  276. site.copy_static_directories(),
  277. &path.to_string_lossy(),
  278. );
  279. } else {
  280. rebuild_done_handling(
  281. &broadcaster,
  282. copy_file(
  283. &path,
  284. &site.output_path,
  285. &site.static_path,
  286. site.config.hard_link_static,
  287. ),
  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. }