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.

341 lines
13KB

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