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.

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