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.

299 lines
11KB

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