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.

263 lines
8.8KB

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