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