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.

251 lines
8.3KB

  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. println!("-> Creating {} pages and {} sections", site.pages.len(), site.sections.len());
  57. site.build()?;
  58. report_elapsed_time(start);
  59. let ws_address = format!("{}:{}", interface, "1112");
  60. // Start a webserver that serves the `public` directory
  61. let mut mount = Mount::new();
  62. mount.mount("/", Static::new(Path::new("public/")));
  63. mount.mount("/livereload.js", livereload_handler);
  64. // Starts with a _ to not trigger the unused lint
  65. // we need to assign to a variable otherwise it will block
  66. let _iron = Iron::new(mount).http(address.as_str()).unwrap();
  67. // The websocket for livereload
  68. let ws_server = WebSocket::new(|_| {
  69. |_| {
  70. Ok(())
  71. }
  72. }).unwrap();
  73. let broadcaster = ws_server.broadcaster();
  74. thread::spawn(move || {
  75. ws_server.listen(&*ws_address).unwrap();
  76. });
  77. // And finally watching/reacting on file changes
  78. let (tx, rx) = channel();
  79. let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
  80. watcher.watch("content/", RecursiveMode::Recursive).unwrap();
  81. watcher.watch("static/", RecursiveMode::Recursive).unwrap();
  82. watcher.watch("templates/", RecursiveMode::Recursive).unwrap();
  83. let pwd = format!("{}", env::current_dir().unwrap().display());
  84. println!("Listening for changes in {}/{{content, static, templates}}", pwd);
  85. println!("Web server is available at http://{}", address);
  86. println!("Press Ctrl+C to stop\n");
  87. use notify::DebouncedEvent::*;
  88. loop {
  89. // See https://github.com/spf13/hugo/blob/master/commands/hugo.go
  90. // for a more complete version of that
  91. match rx.recv() {
  92. Ok(event) => {
  93. match event {
  94. Create(path) |
  95. Write(path) |
  96. Remove(path) |
  97. Rename(_, path) => {
  98. if is_temp_file(&path) {
  99. continue;
  100. }
  101. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  102. let start = Instant::now();
  103. match detect_change_kind(&pwd, &path) {
  104. (ChangeKind::Content, _) => {
  105. console::info(&format!("-> Content changed {}", path.display()));
  106. // Force refresh
  107. rebuild_done_handling(&broadcaster, site.rebuild_after_content_change(&path), "/x.js");
  108. },
  109. (ChangeKind::Templates, _) => {
  110. console::info(&format!("-> Template changed {}", path.display()));
  111. // Force refresh
  112. rebuild_done_handling(&broadcaster, site.rebuild_after_template_change(), "/x.js");
  113. },
  114. (ChangeKind::StaticFiles, p) => {
  115. if path.is_file() {
  116. console::info(&format!("-> Static file changes detected {}", path.display()));
  117. rebuild_done_handling(&broadcaster, site.copy_static_file(&path), &p);
  118. }
  119. },
  120. };
  121. report_elapsed_time(start);
  122. }
  123. _ => {}
  124. }
  125. },
  126. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  127. };
  128. }
  129. }
  130. /// Returns whether the path we received corresponds to a temp file created
  131. /// by an editor or the OS
  132. fn is_temp_file(path: &Path) -> bool {
  133. let ext = path.extension();
  134. match ext {
  135. Some(ex) => match ex.to_str().unwrap() {
  136. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  137. // jetbrains IDE
  138. x if x.ends_with("jb_old___") => true,
  139. x if x.ends_with("jb_tmp___") => true,
  140. x if x.ends_with("jb_bak___") => true,
  141. // vim
  142. x if x.ends_with('~') => true,
  143. _ => {
  144. if let Some(filename) = path.file_stem() {
  145. // emacs
  146. filename.to_str().unwrap().starts_with('#')
  147. } else {
  148. false
  149. }
  150. }
  151. },
  152. None => {
  153. path.ends_with(".DS_STORE")
  154. },
  155. }
  156. }
  157. /// Detect what changed from the given path so we have an idea what needs
  158. /// to be reloaded
  159. fn detect_change_kind(pwd: &str, path: &Path) -> (ChangeKind, String) {
  160. let path_str = format!("{}", path.display())
  161. .replace(pwd, "")
  162. .replace("\\", "/");
  163. let change_kind = if path_str.starts_with("/templates") {
  164. ChangeKind::Templates
  165. } else if path_str.starts_with("/content") {
  166. ChangeKind::Content
  167. } else if path_str.starts_with("/static") {
  168. ChangeKind::StaticFiles
  169. } else {
  170. unreachable!("Got a change in an unexpected path: {}", path_str);
  171. };
  172. (change_kind, path_str)
  173. }
  174. #[cfg(test)]
  175. mod tests {
  176. use std::path::Path;
  177. use super::{is_temp_file, detect_change_kind, ChangeKind};
  178. #[test]
  179. fn test_can_recognize_temp_files() {
  180. let testcases = vec![
  181. Path::new("hello.swp"),
  182. Path::new("hello.swx"),
  183. Path::new(".DS_STORE"),
  184. Path::new("hello.tmp"),
  185. Path::new("hello.html.__jb_old___"),
  186. Path::new("hello.html.__jb_tmp___"),
  187. Path::new("hello.html.__jb_bak___"),
  188. Path::new("hello.html~"),
  189. Path::new("#hello.html"),
  190. ];
  191. for t in testcases {
  192. assert!(is_temp_file(&t));
  193. }
  194. }
  195. #[test]
  196. fn test_can_detect_kind_of_changes() {
  197. let testcases = vec![
  198. (
  199. (ChangeKind::Templates, "/templates/hello.html".to_string()),
  200. "/home/vincent/site", Path::new("/home/vincent/site/templates/hello.html")
  201. ),
  202. (
  203. (ChangeKind::StaticFiles, "/static/site.css".to_string()),
  204. "/home/vincent/site", Path::new("/home/vincent/site/static/site.css")
  205. ),
  206. (
  207. (ChangeKind::Content, "/content/posts/hello.md".to_string()),
  208. "/home/vincent/site", Path::new("/home/vincent/site/content/posts/hello.md")
  209. ),
  210. ];
  211. for (expected, pwd, path) in testcases {
  212. assert_eq!(expected, detect_change_kind(&pwd, &path));
  213. }
  214. }
  215. }