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.

246 lines
7.9KB

  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(env::current_dir().unwrap())?;
  53. site.enable_live_reload();
  54. site.build()?;
  55. report_elapsed_time(start);
  56. let address = format!("{}:{}", interface, port);
  57. let ws_address = format!("{}:{}", interface, "1112");
  58. // Start a webserver that serves the `public` directory
  59. let mut mount = Mount::new();
  60. mount.mount("/", Static::new(Path::new("public/")));
  61. mount.mount("/livereload.js", livereload_handler);
  62. // Starts with a _ to not trigger the unused lint
  63. // we need to assign to a variable otherwise it will block
  64. let _iron = Iron::new(mount).http(address.as_str()).unwrap();
  65. println!("Web server is available at http://{}", address);
  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!("Press CTRL+C to stop\n");
  85. use notify::DebouncedEvent::*;
  86. loop {
  87. // See https://github.com/spf13/hugo/blob/master/commands/hugo.go
  88. // for a more complete version of that
  89. match rx.recv() {
  90. Ok(event) => {
  91. match event {
  92. Create(path) |
  93. Write(path) |
  94. Remove(path) |
  95. Rename(_, path) => {
  96. if is_temp_file(&path) {
  97. continue;
  98. }
  99. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  100. let start = Instant::now();
  101. match detect_change_kind(&pwd, &path) {
  102. (ChangeKind::Content, _) => {
  103. println!("-> Content changed {}", path.display());
  104. // Force refresh
  105. rebuild_done_handling(&broadcaster, site.rebuild_after_content_change(), "/x.js");
  106. },
  107. (ChangeKind::Templates, _) => {
  108. println!("-> Template changed {}", path.display());
  109. // Force refresh
  110. rebuild_done_handling(&broadcaster, site.rebuild_after_template_change(), "/x.js");
  111. },
  112. (ChangeKind::StaticFiles, p) => {
  113. println!("-> Static file changes detected {}", path.display());
  114. rebuild_done_handling(&broadcaster, site.copy_static_directory(), &p);
  115. },
  116. };
  117. report_elapsed_time(start);
  118. }
  119. _ => {}
  120. }
  121. },
  122. Err(e) => println!("Watch error: {:?}", e),
  123. };
  124. }
  125. }
  126. /// Returns whether the path we received corresponds to a temp file create
  127. /// by an editor
  128. fn is_temp_file(path: &Path) -> bool {
  129. let ext = path.extension();
  130. match ext {
  131. Some(ex) => match ex.to_str().unwrap() {
  132. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  133. // jetbrains IDE
  134. x if x.ends_with("jb_old___") => true,
  135. x if x.ends_with("jb_tmp___") => true,
  136. x if x.ends_with("jb_bak___") => true,
  137. // vim
  138. x if x.ends_with('~') => true,
  139. _ => {
  140. if let Some(filename) = path.file_stem() {
  141. // emacs
  142. filename.to_str().unwrap().starts_with('#')
  143. } else {
  144. false
  145. }
  146. }
  147. },
  148. None => {
  149. path.ends_with(".DS_STORE")
  150. },
  151. }
  152. }
  153. /// Detect what changed from the given path so we have an idea what needs
  154. /// to be reloaded
  155. fn detect_change_kind(pwd: &str, path: &Path) -> (ChangeKind, String) {
  156. let path_str = format!("{}", path.display())
  157. .replace(pwd, "")
  158. .replace("\\", "/");
  159. let change_kind = if path_str.starts_with("/templates") {
  160. ChangeKind::Templates
  161. } else if path_str.starts_with("/content") {
  162. ChangeKind::Content
  163. } else if path_str.starts_with("/static") {
  164. ChangeKind::StaticFiles
  165. } else {
  166. panic!("Got a change in an unexpected path: {}", path_str);
  167. };
  168. (change_kind, path_str)
  169. }
  170. #[cfg(test)]
  171. mod tests {
  172. use std::path::Path;
  173. use super::{is_temp_file, detect_change_kind, ChangeKind};
  174. #[test]
  175. fn test_can_recognize_temp_files() {
  176. let testcases = vec![
  177. Path::new("hello.swp"),
  178. Path::new("hello.swx"),
  179. Path::new(".DS_STORE"),
  180. Path::new("hello.tmp"),
  181. Path::new("hello.html.__jb_old___"),
  182. Path::new("hello.html.__jb_tmp___"),
  183. Path::new("hello.html.__jb_bak___"),
  184. Path::new("hello.html~"),
  185. Path::new("#hello.html"),
  186. ];
  187. for t in testcases {
  188. println!("{:?}", t.display());
  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. println!("{:?}", path.display());
  210. assert_eq!(expected, detect_change_kind(&pwd, &path));
  211. }
  212. }
  213. }