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.

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