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.

285 lines
10KB

  1. // Contains an embedded version of livereload-js
  2. //
  3. // Copyright (c) 2010-2012 Andrey Tarantsov
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. use std::env;
  24. use std::path::Path;
  25. use std::sync::mpsc::channel;
  26. use std::time::{Instant, Duration};
  27. use std::thread;
  28. use chrono::prelude::*;
  29. use iron::{Iron, Request, IronResult, Response, status};
  30. use mount::Mount;
  31. use staticfile::Static;
  32. use notify::{Watcher, RecursiveMode, watcher};
  33. use ws::{WebSocket, Sender, Message};
  34. use site::Site;
  35. use errors::{Result, ResultExt};
  36. use console;
  37. use rebuild;
  38. #[derive(Debug, PartialEq)]
  39. enum ChangeKind {
  40. Content,
  41. Templates,
  42. StaticFiles,
  43. }
  44. // Uglified using uglifyjs
  45. // Also, commenting out the lines 330-340 (containing `e instanceof ProtocolError`) was needed
  46. // as it seems their build didn't work well and didn't include ProtocolError so it would error on
  47. // errors
  48. const LIVE_RELOAD: &'static str = include_str!("livereload.js");
  49. fn livereload_handler(_: &mut Request) -> IronResult<Response> {
  50. Ok(Response::with((status::Ok, LIVE_RELOAD.to_string())))
  51. }
  52. fn rebuild_done_handling(broadcaster: &Sender, res: Result<()>, reload_path: &str) {
  53. match res {
  54. Ok(_) => {
  55. broadcaster.send(format!(r#"
  56. {{
  57. "command": "reload",
  58. "path": "{}",
  59. "originalPath": "",
  60. "liveCSS": true,
  61. "liveImg": true,
  62. "protocol": ["http://livereload.com/protocols/official-7"]
  63. }}"#, reload_path)
  64. ).unwrap();
  65. },
  66. Err(e) => console::unravel_errors("Failed to build the site", &e)
  67. }
  68. }
  69. pub fn serve(interface: &str, port: &str, config_file: &str) -> Result<()> {
  70. let start = Instant::now();
  71. let mut site = Site::new(env::current_dir().unwrap(), config_file)?;
  72. let address = format!("{}:{}", interface, port);
  73. // Override the base url so links work in localhost
  74. site.config.base_url = if site.config.base_url.ends_with('/') {
  75. format!("http://{}/", address)
  76. } else {
  77. format!("http://{}", address)
  78. };
  79. site.load()?;
  80. site.enable_live_reload();
  81. console::notify_site_size(&site);
  82. console::warn_about_ignored_pages(&site);
  83. site.build()?;
  84. console::report_elapsed_time(start);
  85. // Setup watchers
  86. let (tx, rx) = channel();
  87. let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
  88. watcher.watch("content/", RecursiveMode::Recursive)
  89. .chain_err(|| "Can't watch the `content` folder. Does it exist?")?;
  90. watcher.watch("static/", RecursiveMode::Recursive)
  91. .chain_err(|| "Can't watch the `static` folder. Does it exist?")?;
  92. watcher.watch("templates/", RecursiveMode::Recursive)
  93. .chain_err(|| "Can't watch the `templates` folder. Does it exist?")?;
  94. let ws_address = format!("{}:{}", interface, "1112");
  95. // Start a webserver that serves the `public` directory
  96. let mut mount = Mount::new();
  97. mount.mount("/", Static::new(Path::new("public/")));
  98. mount.mount("/livereload.js", livereload_handler);
  99. // Starts with a _ to not trigger the unused lint
  100. // we need to assign to a variable otherwise it will block
  101. let _iron = Iron::new(mount).http(address.as_str())
  102. .chain_err(|| "Can't start the webserver")?;
  103. // The websocket for livereload
  104. let ws_server = WebSocket::new(|output: Sender| {
  105. move |msg: Message| {
  106. if msg.into_text().unwrap().contains("\"hello\"") {
  107. return output.send(Message::text(r#"
  108. {
  109. "command": "hello",
  110. "protocols": [ "http://livereload.com/protocols/official-7" ],
  111. "serverName": "Gutenberg"
  112. }
  113. "#));
  114. }
  115. Ok(())
  116. }
  117. }).unwrap();
  118. let broadcaster = ws_server.broadcaster();
  119. thread::spawn(move || {
  120. ws_server.listen(&*ws_address).unwrap();
  121. });
  122. let pwd = format!("{}", env::current_dir().unwrap().display());
  123. println!("Listening for changes in {}/{{content, static, templates}}", pwd);
  124. println!("Web server is available at http://{}", address);
  125. println!("Press Ctrl+C to stop\n");
  126. use notify::DebouncedEvent::*;
  127. loop {
  128. match rx.recv() {
  129. Ok(event) => {
  130. match event {
  131. Create(path) |
  132. Write(path) |
  133. Remove(path) |
  134. Rename(_, path) => {
  135. if is_temp_file(&path) {
  136. continue;
  137. }
  138. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  139. let start = Instant::now();
  140. match detect_change_kind(&pwd, &path) {
  141. (ChangeKind::Content, _) => {
  142. console::info(&format!("-> Content changed {}", path.display()));
  143. // Force refresh
  144. rebuild_done_handling(&broadcaster, rebuild::after_content_change(&mut site, &path), "/x.js");
  145. },
  146. (ChangeKind::Templates, _) => {
  147. console::info(&format!("-> Template changed {}", path.display()));
  148. // Force refresh
  149. rebuild_done_handling(&broadcaster, rebuild::after_template_change(&mut site, &path), "/x.js");
  150. },
  151. (ChangeKind::StaticFiles, p) => {
  152. if path.is_file() {
  153. console::info(&format!("-> Static file changes detected {}", path.display()));
  154. rebuild_done_handling(&broadcaster, site.copy_static_file(&path), &p);
  155. }
  156. },
  157. };
  158. console::report_elapsed_time(start);
  159. }
  160. _ => {}
  161. }
  162. },
  163. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  164. };
  165. }
  166. }
  167. /// Returns whether the path we received corresponds to a temp file created
  168. /// by an editor or the OS
  169. fn is_temp_file(path: &Path) -> bool {
  170. let ext = path.extension();
  171. match ext {
  172. Some(ex) => match ex.to_str().unwrap() {
  173. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  174. // jetbrains IDE
  175. x if x.ends_with("jb_old___") => true,
  176. x if x.ends_with("jb_tmp___") => true,
  177. x if x.ends_with("jb_bak___") => true,
  178. // vim
  179. x if x.ends_with('~') => true,
  180. _ => {
  181. if let Some(filename) = path.file_stem() {
  182. // emacs
  183. filename.to_str().unwrap().starts_with('#')
  184. } else {
  185. false
  186. }
  187. }
  188. },
  189. None => {
  190. path.ends_with(".DS_STORE")
  191. },
  192. }
  193. }
  194. /// Detect what changed from the given path so we have an idea what needs
  195. /// to be reloaded
  196. fn detect_change_kind(pwd: &str, path: &Path) -> (ChangeKind, String) {
  197. let path_str = format!("{}", path.display())
  198. .replace(pwd, "")
  199. .replace("\\", "/");
  200. let change_kind = if path_str.starts_with("/templates") {
  201. ChangeKind::Templates
  202. } else if path_str.starts_with("/content") {
  203. ChangeKind::Content
  204. } else if path_str.starts_with("/static") {
  205. ChangeKind::StaticFiles
  206. } else {
  207. unreachable!("Got a change in an unexpected path: {}", path_str);
  208. };
  209. (change_kind, path_str)
  210. }
  211. #[cfg(test)]
  212. mod tests {
  213. use std::path::Path;
  214. use super::{is_temp_file, detect_change_kind, ChangeKind};
  215. #[test]
  216. fn can_recognize_temp_files() {
  217. let test_cases = vec![
  218. Path::new("hello.swp"),
  219. Path::new("hello.swx"),
  220. Path::new(".DS_STORE"),
  221. Path::new("hello.tmp"),
  222. Path::new("hello.html.__jb_old___"),
  223. Path::new("hello.html.__jb_tmp___"),
  224. Path::new("hello.html.__jb_bak___"),
  225. Path::new("hello.html~"),
  226. Path::new("#hello.html"),
  227. ];
  228. for t in test_cases {
  229. assert!(is_temp_file(&t));
  230. }
  231. }
  232. #[test]
  233. fn can_detect_kind_of_changes() {
  234. let test_cases = vec![
  235. (
  236. (ChangeKind::Templates, "/templates/hello.html".to_string()),
  237. "/home/vincent/site", Path::new("/home/vincent/site/templates/hello.html")
  238. ),
  239. (
  240. (ChangeKind::StaticFiles, "/static/site.css".to_string()),
  241. "/home/vincent/site", Path::new("/home/vincent/site/static/site.css")
  242. ),
  243. (
  244. (ChangeKind::Content, "/content/posts/hello.md".to_string()),
  245. "/home/vincent/site", Path::new("/home/vincent/site/content/posts/hello.md")
  246. ),
  247. ];
  248. for (expected, pwd, path) in test_cases {
  249. assert_eq!(expected, detect_change_kind(&pwd, &path));
  250. }
  251. }
  252. }