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