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.

267 lines
9.1KB

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