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.

222 lines
7.2KB

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