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.9KB

  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. pub fn serve(interface: &str, port: &str, config_file: &str) -> Result<()> {
  48. let start = Instant::now();
  49. let mut site = Site::new(env::current_dir().unwrap(), config_file)?;
  50. let address = format!("{}:{}", interface, port);
  51. // Override the base url so links work in localhost
  52. site.config.base_url = if site.config.base_url.ends_with('/') {
  53. format!("http://{}/", address)
  54. } else {
  55. format!("http://{}", address)
  56. };
  57. site.load()?;
  58. site.enable_live_reload();
  59. console::notify_site_size(&site);
  60. console::warn_about_ignored_pages(&site);
  61. site.build()?;
  62. console::report_elapsed_time(start);
  63. // Setup watchers
  64. let (tx, rx) = channel();
  65. let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
  66. watcher.watch("content/", RecursiveMode::Recursive)
  67. .chain_err(|| "Can't watch the `content` folder. Does it exist?")?;
  68. watcher.watch("static/", RecursiveMode::Recursive)
  69. .chain_err(|| "Can't watch the `static` folder. Does it exist?")?;
  70. watcher.watch("templates/", RecursiveMode::Recursive)
  71. .chain_err(|| "Can't watch the `templates` folder. Does it exist?")?;
  72. let ws_address = format!("{}:{}", interface, "1112");
  73. // Start a webserver that serves the `public` directory
  74. let mut mount = Mount::new();
  75. mount.mount("/", Static::new(Path::new("public/")));
  76. mount.mount("/livereload.js", livereload_handler);
  77. // Starts with a _ to not trigger the unused lint
  78. // we need to assign to a variable otherwise it will block
  79. let _iron = Iron::new(mount).http(address.as_str())
  80. .chain_err(|| "Can't start the webserver")?;
  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. match rx.recv() {
  107. Ok(event) => {
  108. match event {
  109. Create(path) |
  110. Write(path) |
  111. Remove(path) |
  112. Rename(_, path) => {
  113. if is_temp_file(&path) {
  114. continue;
  115. }
  116. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  117. let start = Instant::now();
  118. match detect_change_kind(&pwd, &path) {
  119. (ChangeKind::Content, _) => {
  120. console::info(&format!("-> Content changed {}", path.display()));
  121. // Force refresh
  122. rebuild_done_handling(&broadcaster, rebuild::after_content_change(&mut site, &path), "/x.js");
  123. },
  124. (ChangeKind::Templates, _) => {
  125. console::info(&format!("-> Template changed {}", path.display()));
  126. // Force refresh
  127. rebuild_done_handling(&broadcaster, rebuild::after_template_change(&mut site, &path), "/x.js");
  128. },
  129. (ChangeKind::StaticFiles, p) => {
  130. if path.is_file() {
  131. console::info(&format!("-> Static file changes detected {}", path.display()));
  132. rebuild_done_handling(&broadcaster, site.copy_static_file(&path), &p);
  133. }
  134. },
  135. };
  136. console::report_elapsed_time(start);
  137. }
  138. _ => {}
  139. }
  140. },
  141. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  142. };
  143. }
  144. }
  145. /// Returns whether the path we received corresponds to a temp file created
  146. /// by an editor or the OS
  147. fn is_temp_file(path: &Path) -> bool {
  148. let ext = path.extension();
  149. match ext {
  150. Some(ex) => match ex.to_str().unwrap() {
  151. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  152. // jetbrains IDE
  153. x if x.ends_with("jb_old___") => true,
  154. x if x.ends_with("jb_tmp___") => true,
  155. x if x.ends_with("jb_bak___") => true,
  156. // vim
  157. x if x.ends_with('~') => true,
  158. _ => {
  159. if let Some(filename) = path.file_stem() {
  160. // emacs
  161. filename.to_str().unwrap().starts_with('#')
  162. } else {
  163. false
  164. }
  165. }
  166. },
  167. None => {
  168. path.ends_with(".DS_STORE")
  169. },
  170. }
  171. }
  172. /// Detect what changed from the given path so we have an idea what needs
  173. /// to be reloaded
  174. fn detect_change_kind(pwd: &str, path: &Path) -> (ChangeKind, String) {
  175. let path_str = format!("{}", path.display())
  176. .replace(pwd, "")
  177. .replace("\\", "/");
  178. let change_kind = if path_str.starts_with("/templates") {
  179. ChangeKind::Templates
  180. } else if path_str.starts_with("/content") {
  181. ChangeKind::Content
  182. } else if path_str.starts_with("/static") {
  183. ChangeKind::StaticFiles
  184. } else {
  185. unreachable!("Got a change in an unexpected path: {}", path_str);
  186. };
  187. (change_kind, path_str)
  188. }
  189. #[cfg(test)]
  190. mod tests {
  191. use std::path::Path;
  192. use super::{is_temp_file, detect_change_kind, ChangeKind};
  193. #[test]
  194. fn can_recognize_temp_files() {
  195. let test_cases = vec![
  196. Path::new("hello.swp"),
  197. Path::new("hello.swx"),
  198. Path::new(".DS_STORE"),
  199. Path::new("hello.tmp"),
  200. Path::new("hello.html.__jb_old___"),
  201. Path::new("hello.html.__jb_tmp___"),
  202. Path::new("hello.html.__jb_bak___"),
  203. Path::new("hello.html~"),
  204. Path::new("#hello.html"),
  205. ];
  206. for t in test_cases {
  207. assert!(is_temp_file(&t));
  208. }
  209. }
  210. #[test]
  211. fn can_detect_kind_of_changes() {
  212. let test_cases = vec![
  213. (
  214. (ChangeKind::Templates, "/templates/hello.html".to_string()),
  215. "/home/vincent/site", Path::new("/home/vincent/site/templates/hello.html")
  216. ),
  217. (
  218. (ChangeKind::StaticFiles, "/static/site.css".to_string()),
  219. "/home/vincent/site", Path::new("/home/vincent/site/static/site.css")
  220. ),
  221. (
  222. (ChangeKind::Content, "/content/posts/hello.md".to_string()),
  223. "/home/vincent/site", Path::new("/home/vincent/site/content/posts/hello.md")
  224. ),
  225. ];
  226. for (expected, pwd, path) in test_cases {
  227. assert_eq!(expected, detect_change_kind(&pwd, &path));
  228. }
  229. }
  230. }