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.

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