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.

255 lines
8.4KB

  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, ResultExt};
  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. // Setup watchers
  60. let (tx, rx) = channel();
  61. let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
  62. watcher.watch("content/", RecursiveMode::Recursive)
  63. .chain_err(|| "Can't watch the `content` folder. Does it exist?")?;
  64. watcher.watch("static/", RecursiveMode::Recursive)
  65. .chain_err(|| "Can't watch the `static` folder. Does it exist?")?;
  66. watcher.watch("templates/", RecursiveMode::Recursive)
  67. .chain_err(|| "Can't watch the `templates` folder. Does it exist?")?;
  68. let ws_address = format!("{}:{}", interface, "1112");
  69. // Start a webserver that serves the `public` directory
  70. let mut mount = Mount::new();
  71. mount.mount("/", Static::new(Path::new("public/")));
  72. mount.mount("/livereload.js", livereload_handler);
  73. // Starts with a _ to not trigger the unused lint
  74. // we need to assign to a variable otherwise it will block
  75. let _iron = Iron::new(mount).http(address.as_str()).unwrap();
  76. // The websocket for livereload
  77. let ws_server = WebSocket::new(|_| {
  78. |_| {
  79. Ok(())
  80. }
  81. }).unwrap();
  82. let broadcaster = ws_server.broadcaster();
  83. thread::spawn(move || {
  84. ws_server.listen(&*ws_address).unwrap();
  85. });
  86. let pwd = format!("{}", env::current_dir().unwrap().display());
  87. println!("Listening for changes in {}/{{content, static, templates}}", pwd);
  88. println!("Web server is available at http://{}", address);
  89. println!("Press Ctrl+C to stop\n");
  90. use notify::DebouncedEvent::*;
  91. loop {
  92. // See https://github.com/spf13/hugo/blob/master/commands/hugo.go
  93. // for a more complete version of that
  94. match rx.recv() {
  95. Ok(event) => {
  96. match event {
  97. Create(path) |
  98. Write(path) |
  99. Remove(path) |
  100. Rename(_, path) => {
  101. if is_temp_file(&path) {
  102. continue;
  103. }
  104. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  105. let start = Instant::now();
  106. match detect_change_kind(&pwd, &path) {
  107. (ChangeKind::Content, _) => {
  108. console::info(&format!("-> Content changed {}", path.display()));
  109. // Force refresh
  110. rebuild_done_handling(&broadcaster, site.rebuild_after_content_change(&path), "/x.js");
  111. },
  112. (ChangeKind::Templates, _) => {
  113. console::info(&format!("-> Template changed {}", path.display()));
  114. // Force refresh
  115. rebuild_done_handling(&broadcaster, site.rebuild_after_template_change(&path), "/x.js");
  116. },
  117. (ChangeKind::StaticFiles, p) => {
  118. if path.is_file() {
  119. console::info(&format!("-> Static file changes detected {}", path.display()));
  120. rebuild_done_handling(&broadcaster, site.copy_static_file(&path), &p);
  121. }
  122. },
  123. };
  124. report_elapsed_time(start);
  125. }
  126. _ => {}
  127. }
  128. },
  129. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  130. };
  131. }
  132. }
  133. /// Returns whether the path we received corresponds to a temp file created
  134. /// by an editor or the OS
  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. unreachable!("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. assert!(is_temp_file(&t));
  196. }
  197. }
  198. #[test]
  199. fn test_can_detect_kind_of_changes() {
  200. let testcases = vec![
  201. (
  202. (ChangeKind::Templates, "/templates/hello.html".to_string()),
  203. "/home/vincent/site", Path::new("/home/vincent/site/templates/hello.html")
  204. ),
  205. (
  206. (ChangeKind::StaticFiles, "/static/site.css".to_string()),
  207. "/home/vincent/site", Path::new("/home/vincent/site/static/site.css")
  208. ),
  209. (
  210. (ChangeKind::Content, "/content/posts/hello.md".to_string()),
  211. "/home/vincent/site", Path::new("/home/vincent/site/content/posts/hello.md")
  212. ),
  213. ];
  214. for (expected, pwd, path) in testcases {
  215. assert_eq!(expected, detect_change_kind(&pwd, &path));
  216. }
  217. }
  218. }