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.

serve.rs 11KB

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