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.

371 lines
14KB

  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::io;
  26. use std::path::{Path, PathBuf};
  27. use std::sync::mpsc::channel;
  28. use std::time::{Instant, Duration};
  29. use std::thread;
  30. use chrono::prelude::*;
  31. use actix;
  32. use actix_web::{fs, server, App, HttpRequest, HttpResponse, Responder};
  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(_: HttpRequest) -> &'static str {
  55. LIVE_RELOAD
  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. /// Attempt to render `index.html` when a directory is requested.
  93. ///
  94. /// The default "batteries included" mechanisms for actix to handle directory
  95. /// listings rely on redirection which behaves oddly (the location headers
  96. /// seem to use relative paths for some reason).
  97. /// They also mean that the address in the browser will include the
  98. /// `index.html` on a successful redirect (rare), which is unsightly.
  99. ///
  100. /// Rather than deal with all of that, we can hijack a hook for presenting a
  101. /// custom directory listing response and serve it up using their
  102. /// `NamedFile` responder.
  103. fn handle_directory<'a, 'b>(dir: &'a fs::Directory, req: &'b HttpRequest) -> io::Result<HttpResponse> {
  104. let mut path = PathBuf::from(&dir.base);
  105. path.push(&dir.path);
  106. path.push("index.html");
  107. Ok(fs::NamedFile::open(path).respond_to(req).unwrap())
  108. }
  109. pub fn serve(interface: &str, port: &str, output_dir: &str, base_url: &str, config_file: &str) -> Result<()> {
  110. let start = Instant::now();
  111. let (mut site, address) = create_new_site(interface, port, output_dir, base_url, config_file)?;
  112. console::report_elapsed_time(start);
  113. // Setup watchers
  114. let mut watching_static = false;
  115. let (tx, rx) = channel();
  116. let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
  117. watcher.watch("content/", RecursiveMode::Recursive)
  118. .chain_err(|| "Can't watch the `content` folder. Does it exist?")?;
  119. watcher.watch("templates/", RecursiveMode::Recursive)
  120. .chain_err(|| "Can't watch the `templates` folder. Does it exist?")?;
  121. watcher.watch(config_file, RecursiveMode::Recursive)
  122. .chain_err(|| "Can't watch the `config` file. Does it exist?")?;
  123. if Path::new("static").exists() {
  124. watching_static = true;
  125. watcher.watch("static/", RecursiveMode::Recursive)
  126. .chain_err(|| "Can't watch the `static` folder. Does it exist?")?;
  127. }
  128. // Sass support is optional so don't make it an error to no have a sass folder
  129. let _ = watcher.watch("sass/", RecursiveMode::Recursive);
  130. let ws_address = format!("{}:{}", interface, site.live_reload.unwrap());
  131. let output_path = Path::new(output_dir).to_path_buf();
  132. // output path is going to need to be moved later on, so clone it for the
  133. // http closure to avoid contention.
  134. let static_root = output_path.clone();
  135. thread::spawn(move || {
  136. let sys = actix::System::new("http-server");
  137. server::new(move || {
  138. App::new()
  139. .resource(r"/livereload.js", |r| r.f(livereload_handler))
  140. // Start a webserver that serves the `output_dir` directory
  141. .handler(r"/", fs::StaticFiles::new(&static_root)
  142. .show_files_listing()
  143. .files_listing_renderer(handle_directory))
  144. })
  145. .bind(&address)
  146. .expect("Can't start the webserver")
  147. .shutdown_timeout(20)
  148. .start();
  149. println!("Web server is available at http://{}", &address);
  150. let _ = sys.run();
  151. });
  152. // The websocket for livereload
  153. let ws_server = WebSocket::new(|output: Sender| {
  154. move |msg: Message| {
  155. if msg.into_text().unwrap().contains("\"hello\"") {
  156. return output.send(Message::text(r#"
  157. {
  158. "command": "hello",
  159. "protocols": [ "http://livereload.com/protocols/official-7" ],
  160. "serverName": "Gutenberg"
  161. }
  162. "#));
  163. }
  164. Ok(())
  165. }
  166. }).unwrap();
  167. let broadcaster = ws_server.broadcaster();
  168. thread::spawn(move || {
  169. ws_server.listen(&*ws_address).unwrap();
  170. });
  171. let pwd = format!("{}", env::current_dir().unwrap().display());
  172. let mut watchers = vec!["content", "templates", "config.toml"];
  173. if watching_static {
  174. watchers.push("static");
  175. }
  176. if site.config.compile_sass {
  177. watchers.push("sass");
  178. }
  179. println!("Listening for changes in {}/{{{}}}", pwd, watchers.join(", "));
  180. println!("Press Ctrl+C to stop\n");
  181. // Delete the output folder on ctrl+C
  182. ctrlc::set_handler(move || {
  183. remove_dir_all(&output_path).expect("Failed to delete output directory");
  184. ::std::process::exit(0);
  185. }).expect("Error setting Ctrl-C handler");
  186. use notify::DebouncedEvent::*;
  187. loop {
  188. match rx.recv() {
  189. Ok(event) => {
  190. match event {
  191. Create(path) |
  192. Write(path) |
  193. Remove(path) |
  194. Rename(_, path) => {
  195. if is_temp_file(&path) || path.is_dir() {
  196. continue;
  197. }
  198. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  199. let start = Instant::now();
  200. match detect_change_kind(&pwd, &path) {
  201. (ChangeKind::Content, _) => {
  202. console::info(&format!("-> Content changed {}", path.display()));
  203. // Force refresh
  204. rebuild_done_handling(&broadcaster, rebuild::after_content_change(&mut site, &path), "/x.js");
  205. },
  206. (ChangeKind::Templates, _) => {
  207. console::info(&format!("-> Template changed {}", path.display()));
  208. // Force refresh
  209. rebuild_done_handling(&broadcaster, rebuild::after_template_change(&mut site, &path), "/x.js");
  210. },
  211. (ChangeKind::StaticFiles, p) => {
  212. if path.is_file() {
  213. console::info(&format!("-> Static file changes detected {}", path.display()));
  214. rebuild_done_handling(&broadcaster, copy_file(&path, &site.output_path, &site.static_path), &p);
  215. }
  216. },
  217. (ChangeKind::Sass, p) => {
  218. console::info(&format!("-> Sass file changed {}", path.display()));
  219. rebuild_done_handling(&broadcaster, site.compile_sass(&site.base_path), &p);
  220. },
  221. (ChangeKind::Config, _) => {
  222. console::info(&format!("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible."));
  223. site = create_new_site(interface, port, output_dir, base_url, config_file).unwrap().0;
  224. }
  225. };
  226. console::report_elapsed_time(start);
  227. }
  228. _ => {}
  229. }
  230. },
  231. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  232. };
  233. }
  234. }
  235. /// Returns whether the path we received corresponds to a temp file created
  236. /// by an editor or the OS
  237. fn is_temp_file(path: &Path) -> bool {
  238. let ext = path.extension();
  239. match ext {
  240. Some(ex) => match ex.to_str().unwrap() {
  241. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  242. // jetbrains IDE
  243. x if x.ends_with("jb_old___") => true,
  244. x if x.ends_with("jb_tmp___") => true,
  245. x if x.ends_with("jb_bak___") => true,
  246. // vim
  247. x if x.ends_with('~') => true,
  248. _ => {
  249. if let Some(filename) = path.file_stem() {
  250. // emacs
  251. filename.to_str().unwrap().starts_with('#')
  252. } else {
  253. false
  254. }
  255. }
  256. },
  257. None => {
  258. path.ends_with(".DS_STORE")
  259. },
  260. }
  261. }
  262. /// Detect what changed from the given path so we have an idea what needs
  263. /// to be reloaded
  264. fn detect_change_kind(pwd: &str, path: &Path) -> (ChangeKind, String) {
  265. let path_str = format!("{}", path.display())
  266. .replace(pwd, "")
  267. .replace("\\", "/");
  268. let change_kind = if path_str.starts_with("/templates") {
  269. ChangeKind::Templates
  270. } else if path_str.starts_with("/content") {
  271. ChangeKind::Content
  272. } else if path_str.starts_with("/static") {
  273. ChangeKind::StaticFiles
  274. } else if path_str.starts_with("/sass") {
  275. ChangeKind::Sass
  276. } else if path_str == "/config.toml" {
  277. ChangeKind::Config
  278. } else {
  279. unreachable!("Got a change in an unexpected path: {}", path_str)
  280. };
  281. (change_kind, path_str)
  282. }
  283. #[cfg(test)]
  284. mod tests {
  285. use std::path::Path;
  286. use super::{is_temp_file, detect_change_kind, ChangeKind};
  287. #[test]
  288. fn can_recognize_temp_files() {
  289. let test_cases = vec![
  290. Path::new("hello.swp"),
  291. Path::new("hello.swx"),
  292. Path::new(".DS_STORE"),
  293. Path::new("hello.tmp"),
  294. Path::new("hello.html.__jb_old___"),
  295. Path::new("hello.html.__jb_tmp___"),
  296. Path::new("hello.html.__jb_bak___"),
  297. Path::new("hello.html~"),
  298. Path::new("#hello.html"),
  299. ];
  300. for t in test_cases {
  301. assert!(is_temp_file(&t));
  302. }
  303. }
  304. #[test]
  305. fn can_detect_kind_of_changes() {
  306. let test_cases = vec![
  307. (
  308. (ChangeKind::Templates, "/templates/hello.html".to_string()),
  309. "/home/vincent/site", Path::new("/home/vincent/site/templates/hello.html")
  310. ),
  311. (
  312. (ChangeKind::StaticFiles, "/static/site.css".to_string()),
  313. "/home/vincent/site", Path::new("/home/vincent/site/static/site.css")
  314. ),
  315. (
  316. (ChangeKind::Content, "/content/posts/hello.md".to_string()),
  317. "/home/vincent/site", Path::new("/home/vincent/site/content/posts/hello.md")
  318. ),
  319. (
  320. (ChangeKind::Sass, "/sass/print.scss".to_string()),
  321. "/home/vincent/site", Path::new("/home/vincent/site/sass/print.scss")
  322. ),
  323. (
  324. (ChangeKind::Config, "/config.toml".to_string()),
  325. "/home/vincent/site", Path::new("/home/vincent/site/config.toml")
  326. ),
  327. ];
  328. for (expected, pwd, path) in test_cases {
  329. assert_eq!(expected, detect_change_kind(&pwd, &path));
  330. }
  331. }
  332. }