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.

249 lines
8.0KB

  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. // Force refresh
  104. rebuild_done_handling(&broadcaster, site.rebuild_after_content_change(), "/x.js");
  105. },
  106. (ChangeKind::Templates, _) => {
  107. println!("-> Template changed {}", path.display());
  108. // Force refresh
  109. rebuild_done_handling(&broadcaster, site.rebuild_after_template_change(), "/x.js");
  110. },
  111. (ChangeKind::StaticFiles, p) => {
  112. println!("-> Static file changes detected {}", path.display());
  113. rebuild_done_handling(&broadcaster, site.copy_static_directory(), &p);
  114. },
  115. };
  116. report_elapsed_time(start);
  117. }
  118. _ => {}
  119. }
  120. },
  121. Err(e) => println!("Watch error: {:?}", e),
  122. };
  123. }
  124. }
  125. /// Returns whether the path we received corresponds to a temp file create
  126. /// by an editor
  127. fn is_temp_file(path: &Path) -> bool {
  128. let ext = path.extension();
  129. match ext {
  130. Some(ex) => match ex.to_str().unwrap() {
  131. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  132. // jetbrains IDE
  133. x if x.ends_with("jb_old___") => true,
  134. x if x.ends_with("jb_tmp___") => true,
  135. x if x.ends_with("jb_bak___") => true,
  136. // vim
  137. x if x.ends_with("~") => true,
  138. _ => {
  139. if let Some(filename) = path.file_stem() {
  140. // emacs
  141. filename.to_str().unwrap().starts_with("#")
  142. } else {
  143. false
  144. }
  145. }
  146. },
  147. None => {
  148. if path.ends_with(".DS_STORE") {
  149. true
  150. } else {
  151. false
  152. }
  153. },
  154. }
  155. }
  156. /// Detect what changed from the given path so we have an idea what needs
  157. /// to be reloaded
  158. fn detect_change_kind(pwd: &str, path: &Path) -> (ChangeKind, String) {
  159. let path_str = format!("{}", path.display())
  160. .replace(pwd, "")
  161. .replace("\\", "/");
  162. let change_kind = if path_str.starts_with("/templates") {
  163. ChangeKind::Templates
  164. } else if path_str.starts_with("/content") {
  165. ChangeKind::Content
  166. } else if path_str.starts_with("/static") {
  167. ChangeKind::StaticFiles
  168. } else {
  169. panic!("Got a change in an unexpected path: {}", path_str);
  170. };
  171. (change_kind, path_str)
  172. }
  173. #[cfg(test)]
  174. mod tests {
  175. use std::path::Path;
  176. use super::{is_temp_file, detect_change_kind, ChangeKind};
  177. #[test]
  178. fn test_can_recognize_temp_files() {
  179. let testcases = vec![
  180. Path::new("hello.swp"),
  181. Path::new("hello.swx"),
  182. Path::new(".DS_STORE"),
  183. Path::new("hello.tmp"),
  184. Path::new("hello.html.__jb_old___"),
  185. Path::new("hello.html.__jb_tmp___"),
  186. Path::new("hello.html.__jb_bak___"),
  187. Path::new("hello.html~"),
  188. Path::new("#hello.html"),
  189. ];
  190. for t in testcases {
  191. println!("{:?}", t.display());
  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. println!("{:?}", path.display());
  213. assert_eq!(expected, detect_change_kind(&pwd, &path));
  214. }
  215. }
  216. }