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.

262 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. #[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) => console::unravel_errors("Failed to build the site", &e)
  40. }
  41. }
  42. // Most of it taken from mdbook
  43. pub fn serve(interface: &str, port: &str, config_file: &str) -> Result<()> {
  44. let start = Instant::now();
  45. let mut site = Site::new(env::current_dir().unwrap(), config_file)?;
  46. let address = format!("{}:{}", interface, port);
  47. // Override the base url so links work in localhost
  48. site.config.base_url = if site.config.base_url.ends_with('/') {
  49. format!("http://{}/", address)
  50. } else {
  51. format!("http://{}", address)
  52. };
  53. site.load()?;
  54. site.enable_live_reload();
  55. console::notify_site_size(&site);
  56. console::warn_about_ignored_pages(&site);
  57. site.build()?;
  58. console::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(|output: Sender| {
  78. move |msg: Message| {
  79. if msg.into_text().unwrap().contains("\"hello\"") {
  80. return output.send(Message::text(r#"
  81. {
  82. "command": "hello",
  83. "protocols": [ "http://livereload.com/protocols/official-7" ],
  84. "serverName": "Gutenberg"
  85. }
  86. "#));
  87. }
  88. Ok(())
  89. }
  90. }).unwrap();
  91. let broadcaster = ws_server.broadcaster();
  92. thread::spawn(move || {
  93. ws_server.listen(&*ws_address).unwrap();
  94. });
  95. let pwd = format!("{}", env::current_dir().unwrap().display());
  96. println!("Listening for changes in {}/{{content, static, templates}}", pwd);
  97. println!("Web server is available at http://{}", address);
  98. println!("Press Ctrl+C to stop\n");
  99. use notify::DebouncedEvent::*;
  100. loop {
  101. // See https://github.com/spf13/hugo/blob/master/commands/hugo.go
  102. // for a more complete version of that
  103. match rx.recv() {
  104. Ok(event) => {
  105. match event {
  106. Create(path) |
  107. Write(path) |
  108. Remove(path) |
  109. Rename(_, path) => {
  110. if is_temp_file(&path) {
  111. continue;
  112. }
  113. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  114. let start = Instant::now();
  115. match detect_change_kind(&pwd, &path) {
  116. (ChangeKind::Content, _) => {
  117. console::info(&format!("-> Content changed {}", path.display()));
  118. // Force refresh
  119. rebuild_done_handling(&broadcaster, site.rebuild_after_content_change(&path), "/x.js");
  120. },
  121. (ChangeKind::Templates, _) => {
  122. console::info(&format!("-> Template changed {}", path.display()));
  123. // Force refresh
  124. rebuild_done_handling(&broadcaster, site.rebuild_after_template_change(&path), "/x.js");
  125. },
  126. (ChangeKind::StaticFiles, p) => {
  127. if path.is_file() {
  128. console::info(&format!("-> Static file changes detected {}", path.display()));
  129. rebuild_done_handling(&broadcaster, site.copy_static_file(&path), &p);
  130. }
  131. },
  132. };
  133. console::report_elapsed_time(start);
  134. }
  135. _ => {}
  136. }
  137. },
  138. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  139. };
  140. }
  141. }
  142. /// Returns whether the path we received corresponds to a temp file created
  143. /// by an editor or the OS
  144. fn is_temp_file(path: &Path) -> bool {
  145. let ext = path.extension();
  146. match ext {
  147. Some(ex) => match ex.to_str().unwrap() {
  148. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  149. // jetbrains IDE
  150. x if x.ends_with("jb_old___") => true,
  151. x if x.ends_with("jb_tmp___") => true,
  152. x if x.ends_with("jb_bak___") => true,
  153. // vim
  154. x if x.ends_with('~') => true,
  155. _ => {
  156. if let Some(filename) = path.file_stem() {
  157. // emacs
  158. filename.to_str().unwrap().starts_with('#')
  159. } else {
  160. false
  161. }
  162. }
  163. },
  164. None => {
  165. path.ends_with(".DS_STORE")
  166. },
  167. }
  168. }
  169. /// Detect what changed from the given path so we have an idea what needs
  170. /// to be reloaded
  171. fn detect_change_kind(pwd: &str, path: &Path) -> (ChangeKind, String) {
  172. let path_str = format!("{}", path.display())
  173. .replace(pwd, "")
  174. .replace("\\", "/");
  175. let change_kind = if path_str.starts_with("/templates") {
  176. ChangeKind::Templates
  177. } else if path_str.starts_with("/content") {
  178. ChangeKind::Content
  179. } else if path_str.starts_with("/static") {
  180. ChangeKind::StaticFiles
  181. } else {
  182. unreachable!("Got a change in an unexpected path: {}", path_str);
  183. };
  184. (change_kind, path_str)
  185. }
  186. #[cfg(test)]
  187. mod tests {
  188. use std::path::Path;
  189. use super::{is_temp_file, detect_change_kind, ChangeKind};
  190. #[test]
  191. fn test_can_recognize_temp_files() {
  192. let testcases = vec![
  193. Path::new("hello.swp"),
  194. Path::new("hello.swx"),
  195. Path::new(".DS_STORE"),
  196. Path::new("hello.tmp"),
  197. Path::new("hello.html.__jb_old___"),
  198. Path::new("hello.html.__jb_tmp___"),
  199. Path::new("hello.html.__jb_bak___"),
  200. Path::new("hello.html~"),
  201. Path::new("#hello.html"),
  202. ];
  203. for t in testcases {
  204. assert!(is_temp_file(&t));
  205. }
  206. }
  207. #[test]
  208. fn test_can_detect_kind_of_changes() {
  209. let testcases = vec![
  210. (
  211. (ChangeKind::Templates, "/templates/hello.html".to_string()),
  212. "/home/vincent/site", Path::new("/home/vincent/site/templates/hello.html")
  213. ),
  214. (
  215. (ChangeKind::StaticFiles, "/static/site.css".to_string()),
  216. "/home/vincent/site", Path::new("/home/vincent/site/static/site.css")
  217. ),
  218. (
  219. (ChangeKind::Content, "/content/posts/hello.md".to_string()),
  220. "/home/vincent/site", Path::new("/home/vincent/site/content/posts/hello.md")
  221. ),
  222. ];
  223. for (expected, pwd, path) in testcases {
  224. assert_eq!(expected, detect_change_kind(&pwd, &path));
  225. }
  226. }
  227. }