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.

247 lines
8.1KB

  1. use std::env;
  2. use std::path::Path;
  3. use std::sync::mpsc::channel;
  4. use std::time::{Instant, Duration};
  5. use std::thread;
  6. use chrono::prelude::*;
  7. use iron::{Iron, Request, IronResult, Response, status};
  8. use mount::Mount;
  9. use staticfile::Static;
  10. use notify::{Watcher, RecursiveMode, watcher};
  11. use ws::{WebSocket, Sender};
  12. use gutenberg::Site;
  13. use gutenberg::errors::{Result};
  14. use ::{report_elapsed_time, unravel_errors};
  15. use console;
  16. #[derive(Debug, PartialEq)]
  17. enum ChangeKind {
  18. Content,
  19. Templates,
  20. StaticFiles,
  21. }
  22. const LIVE_RELOAD: &'static str = include_str!("livereload.js");
  23. fn livereload_handler(_: &mut Request) -> IronResult<Response> {
  24. Ok(Response::with((status::Ok, LIVE_RELOAD.to_string())))
  25. }
  26. fn rebuild_done_handling(broadcaster: &Sender, res: Result<()>, reload_path: &str) {
  27. match res {
  28. Ok(_) => {
  29. broadcaster.send(format!(r#"
  30. {{
  31. "command": "reload",
  32. "path": "{}",
  33. "originalPath": "",
  34. "liveCSS": true,
  35. "liveImg": true,
  36. "protocol": ["http://livereload.com/protocols/official-7"]
  37. }}"#, reload_path)
  38. ).unwrap();
  39. },
  40. Err(e) => unravel_errors("Failed to build the site", e, false)
  41. }
  42. }
  43. // Most of it taken from mdbook
  44. pub fn serve(interface: &str, port: &str, config_file: &str) -> Result<()> {
  45. let start = Instant::now();
  46. let mut site = Site::new(env::current_dir().unwrap(), config_file)?;
  47. let address = format!("{}:{}", interface, port);
  48. // Override the base url so links work in localhost
  49. site.config.base_url = if site.config.base_url.ends_with('/') {
  50. format!("http://{}/", address)
  51. } else {
  52. format!("http://{}", address)
  53. };
  54. site.load()?;
  55. site.enable_live_reload();
  56. site.build()?;
  57. report_elapsed_time(start);
  58. let ws_address = format!("{}:{}", interface, "1112");
  59. // Start a webserver that serves the `public` directory
  60. let mut mount = Mount::new();
  61. mount.mount("/", Static::new(Path::new("public/")));
  62. mount.mount("/livereload.js", livereload_handler);
  63. // Starts with a _ to not trigger the unused lint
  64. // we need to assign to a variable otherwise it will block
  65. let _iron = Iron::new(mount).http(address.as_str()).unwrap();
  66. // The websocket for livereload
  67. let ws_server = WebSocket::new(|_| {
  68. |_| {
  69. Ok(())
  70. }
  71. }).unwrap();
  72. let broadcaster = ws_server.broadcaster();
  73. thread::spawn(move || {
  74. ws_server.listen(&*ws_address).unwrap();
  75. });
  76. // And finally watching/reacting on file changes
  77. let (tx, rx) = channel();
  78. let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
  79. watcher.watch("content/", RecursiveMode::Recursive).unwrap();
  80. watcher.watch("static/", RecursiveMode::Recursive).unwrap();
  81. watcher.watch("templates/", RecursiveMode::Recursive).unwrap();
  82. let pwd = format!("{}", env::current_dir().unwrap().display());
  83. println!("Listening for changes in {}/{{content, static, templates}}", pwd);
  84. println!("Web server is available at http://{}", address);
  85. println!("Press Ctrl+C to stop\n");
  86. use notify::DebouncedEvent::*;
  87. loop {
  88. // See https://github.com/spf13/hugo/blob/master/commands/hugo.go
  89. // for a more complete version of that
  90. match rx.recv() {
  91. Ok(event) => {
  92. match event {
  93. Create(path) |
  94. Write(path) |
  95. Remove(path) |
  96. Rename(_, path) => {
  97. if is_temp_file(&path) {
  98. continue;
  99. }
  100. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  101. let start = Instant::now();
  102. match detect_change_kind(&pwd, &path) {
  103. (ChangeKind::Content, _) => {
  104. console::info(&format!("-> Content changed {}", path.display()));
  105. // Force refresh
  106. rebuild_done_handling(&broadcaster, site.rebuild_after_content_change(&path), "/x.js");
  107. },
  108. (ChangeKind::Templates, _) => {
  109. console::info(&format!("-> Template changed {}", path.display()));
  110. // Force refresh
  111. rebuild_done_handling(&broadcaster, site.rebuild_after_template_change(), "/x.js");
  112. },
  113. (ChangeKind::StaticFiles, p) => {
  114. console::info(&format!("-> Static file changes detected {}", path.display()));
  115. rebuild_done_handling(&broadcaster, site.copy_static_directory(), &p);
  116. },
  117. };
  118. report_elapsed_time(start);
  119. }
  120. _ => {}
  121. }
  122. },
  123. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  124. };
  125. }
  126. }
  127. /// Returns whether the path we received corresponds to a temp file created
  128. /// by an editor or the OS
  129. fn is_temp_file(path: &Path) -> bool {
  130. let ext = path.extension();
  131. match ext {
  132. Some(ex) => match ex.to_str().unwrap() {
  133. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  134. // jetbrains IDE
  135. x if x.ends_with("jb_old___") => true,
  136. x if x.ends_with("jb_tmp___") => true,
  137. x if x.ends_with("jb_bak___") => true,
  138. // vim
  139. x if x.ends_with('~') => true,
  140. _ => {
  141. if let Some(filename) = path.file_stem() {
  142. // emacs
  143. filename.to_str().unwrap().starts_with('#')
  144. } else {
  145. false
  146. }
  147. }
  148. },
  149. None => {
  150. path.ends_with(".DS_STORE")
  151. },
  152. }
  153. }
  154. /// Detect what changed from the given path so we have an idea what needs
  155. /// to be reloaded
  156. fn detect_change_kind(pwd: &str, path: &Path) -> (ChangeKind, String) {
  157. let path_str = format!("{}", path.display())
  158. .replace(pwd, "")
  159. .replace("\\", "/");
  160. let change_kind = if path_str.starts_with("/templates") {
  161. ChangeKind::Templates
  162. } else if path_str.starts_with("/content") {
  163. ChangeKind::Content
  164. } else if path_str.starts_with("/static") {
  165. ChangeKind::StaticFiles
  166. } else {
  167. unreachable!("Got a change in an unexpected path: {}", path_str);
  168. };
  169. (change_kind, path_str)
  170. }
  171. #[cfg(test)]
  172. mod tests {
  173. use std::path::Path;
  174. use super::{is_temp_file, detect_change_kind, ChangeKind};
  175. #[test]
  176. fn test_can_recognize_temp_files() {
  177. let testcases = vec![
  178. Path::new("hello.swp"),
  179. Path::new("hello.swx"),
  180. Path::new(".DS_STORE"),
  181. Path::new("hello.tmp"),
  182. Path::new("hello.html.__jb_old___"),
  183. Path::new("hello.html.__jb_tmp___"),
  184. Path::new("hello.html.__jb_bak___"),
  185. Path::new("hello.html~"),
  186. Path::new("#hello.html"),
  187. ];
  188. for t in testcases {
  189. assert!(is_temp_file(&t));
  190. }
  191. }
  192. #[test]
  193. fn test_can_detect_kind_of_changes() {
  194. let testcases = vec![
  195. (
  196. (ChangeKind::Templates, "/templates/hello.html".to_string()),
  197. "/home/vincent/site", Path::new("/home/vincent/site/templates/hello.html")
  198. ),
  199. (
  200. (ChangeKind::StaticFiles, "/static/site.css".to_string()),
  201. "/home/vincent/site", Path::new("/home/vincent/site/static/site.css")
  202. ),
  203. (
  204. (ChangeKind::Content, "/content/posts/hello.md".to_string()),
  205. "/home/vincent/site", Path::new("/home/vincent/site/content/posts/hello.md")
  206. ),
  207. ];
  208. for (expected, pwd, path) in testcases {
  209. assert_eq!(expected, detect_change_kind(&pwd, &path));
  210. }
  211. }
  212. }