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
7.8KB

  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;
  15. #[derive(Debug, PartialEq)]
  16. enum ChangeKind {
  17. Content,
  18. Templates,
  19. StaticFiles,
  20. }
  21. const LIVE_RELOAD: &'static str = include_str!("livereload.js");
  22. fn livereload_handler(_: &mut Request) -> IronResult<Response> {
  23. Ok(Response::with((status::Ok, LIVE_RELOAD.to_string())))
  24. }
  25. fn rebuild_done_handling(broadcaster: &Sender, res: Result<()>, reload_path: &str) {
  26. match res {
  27. Ok(_) => {
  28. broadcaster.send(format!(r#"
  29. {{
  30. "command": "reload",
  31. "path": "{}",
  32. "originalPath": "",
  33. "liveCSS": true,
  34. "liveImg": true,
  35. "protocol": ["http://livereload.com/protocols/official-7"]
  36. }}"#, reload_path)
  37. ).unwrap();
  38. },
  39. Err(e) => {
  40. println!("Failed to build the site");
  41. println!("Error: {}", e);
  42. for e in e.iter().skip(1) {
  43. println!("Reason: {}", e)
  44. }
  45. }
  46. }
  47. }
  48. // Most of it taken from mdbook
  49. pub fn serve(interface: &str, port: &str) -> Result<()> {
  50. println!("Building site...");
  51. let start = Instant::now();
  52. let mut site = Site::new(true)?;
  53. site.build()?;
  54. report_elapsed_time(start);
  55. let address = format!("{}:{}", interface, port);
  56. let ws_address = format!("{}:{}", interface, "1112");
  57. // Start a webserver that serves the `public` directory
  58. let mut mount = Mount::new();
  59. mount.mount("/", Static::new(Path::new("public/")));
  60. mount.mount("/livereload.js", livereload_handler);
  61. // Starts with a _ to not trigger the unused lint
  62. // we need to assign to a variable otherwise it will block
  63. let _iron = Iron::new(mount).http(address.clone()).unwrap();
  64. println!("Web server is available at http://{}", address);
  65. // The websocket for livereload
  66. let ws_server = WebSocket::new(|_| {
  67. |_| {
  68. Ok(())
  69. }
  70. }).unwrap();
  71. let broadcaster = ws_server.broadcaster();
  72. thread::spawn(move || {
  73. ws_server.listen(&*ws_address).unwrap();
  74. });
  75. // And finally watching/reacting on file changes
  76. let (tx, rx) = channel();
  77. let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
  78. watcher.watch("content/", RecursiveMode::Recursive).unwrap();
  79. watcher.watch("static/", RecursiveMode::Recursive).unwrap();
  80. watcher.watch("templates/", RecursiveMode::Recursive).unwrap();
  81. let pwd = format!("{}", env::current_dir().unwrap().display());
  82. println!("Listening for changes in {}/{{content, static, templates}}", pwd);
  83. println!("Press CTRL+C to stop\n");
  84. use notify::DebouncedEvent::*;
  85. loop {
  86. // See https://github.com/spf13/hugo/blob/master/commands/hugo.go
  87. // for a more complete version of that
  88. match rx.recv() {
  89. Ok(event) => {
  90. match event {
  91. Create(path) |
  92. Write(path) |
  93. Remove(path) |
  94. Rename(_, path) => {
  95. if is_temp_file(&path) {
  96. continue;
  97. }
  98. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  99. let start = Instant::now();
  100. match detect_change_kind(&pwd, &path) {
  101. (ChangeKind::Content, _) => {
  102. println!("-> Content changed {}", path.display());
  103. rebuild_done_handling(&broadcaster, site.rebuild(), "");
  104. },
  105. (ChangeKind::Templates, _) => {
  106. println!("-> Template changed {}", path.display());
  107. rebuild_done_handling(&broadcaster, site.rebuild_after_template_change(), "");
  108. },
  109. (ChangeKind::StaticFiles, p) => {
  110. println!("-> Static file changes detected {}", path.display());
  111. rebuild_done_handling(&broadcaster, site.copy_static_directory(), &p);
  112. },
  113. };
  114. report_elapsed_time(start);
  115. }
  116. _ => {}
  117. }
  118. },
  119. Err(e) => println!("Watch error: {:?}", e),
  120. };
  121. }
  122. }
  123. /// Returns whether the path we received corresponds to a temp file create
  124. /// by an editor
  125. fn is_temp_file(path: &Path) -> bool {
  126. let ext = path.extension();
  127. match ext {
  128. Some(ex) => match ex.to_str().unwrap() {
  129. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  130. // jetbrains IDE
  131. x if x.ends_with("jb_old___") => true,
  132. x if x.ends_with("jb_tmp___") => true,
  133. x if x.ends_with("jb_bak___") => true,
  134. // vim
  135. x if x.ends_with("~") => true,
  136. _ => {
  137. if let Some(filename) = path.file_stem() {
  138. // emacs
  139. filename.to_str().unwrap().starts_with("#")
  140. } else {
  141. false
  142. }
  143. }
  144. },
  145. None => {
  146. if path.ends_with(".DS_STORE") {
  147. true
  148. } else {
  149. false
  150. }
  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. panic!("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. println!("{:?}", t.display());
  190. assert!(is_temp_file(&t));
  191. }
  192. }
  193. #[test]
  194. fn test_can_detect_kind_of_changes() {
  195. let testcases = vec![
  196. (
  197. (ChangeKind::Templates, "/templates/hello.html".to_string()),
  198. "/home/vincent/site", Path::new("/home/vincent/site/templates/hello.html")
  199. ),
  200. (
  201. (ChangeKind::StaticFiles, "/static/site.css".to_string()),
  202. "/home/vincent/site", Path::new("/home/vincent/site/static/site.css")
  203. ),
  204. (
  205. (ChangeKind::Content, "/content/posts/hello.md".to_string()),
  206. "/home/vincent/site", Path::new("/home/vincent/site/content/posts/hello.md")
  207. ),
  208. ];
  209. for (expected, pwd, path) in testcases {
  210. println!("{:?}", path.display());
  211. assert_eq!(expected, detect_change_kind(&pwd, &path));
  212. }
  213. }
  214. }