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.

402 lines
15KB

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