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.

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