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.

425 lines
16KB

  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, MAIN_SEPARATOR};
  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: &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 mut watching_templates = 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(config_file, RecursiveMode::Recursive)
  146. .chain_err(|| "Can't watch the `config` file. Does it exist?")?;
  147. if Path::new("static").exists() {
  148. watching_static = true;
  149. watcher.watch("static/", RecursiveMode::Recursive)
  150. .chain_err(|| "Can't watch the `static` folder.")?;
  151. }
  152. if Path::new("templates").exists() {
  153. watching_templates = true;
  154. watcher.watch("templates/", RecursiveMode::Recursive)
  155. .chain_err(|| "Can't watch the `templates` folder.")?;
  156. }
  157. // Sass support is optional so don't make it an error to no have a sass folder
  158. let _ = watcher.watch("sass/", RecursiveMode::Recursive);
  159. let ws_address = format!("{}:{}", interface, site.live_reload.unwrap());
  160. let output_path = Path::new(output_dir).to_path_buf();
  161. // output path is going to need to be moved later on, so clone it for the
  162. // http closure to avoid contention.
  163. let static_root = output_path.clone();
  164. thread::spawn(move || {
  165. let s = server::new(move || {
  166. App::new()
  167. .middleware(NotFoundHandler { rendered_template: static_root.join("404.html") })
  168. .resource(r"/livereload.js", |r| r.f(livereload_handler))
  169. // Start a webserver that serves the `output_dir` directory
  170. .handler(
  171. r"/",
  172. fs::StaticFiles::new(&static_root)
  173. .unwrap()
  174. .show_files_listing()
  175. .files_listing_renderer(handle_directory)
  176. )
  177. })
  178. .bind(&address)
  179. .expect("Can't start the webserver")
  180. .shutdown_timeout(20);
  181. println!("Web server is available at http://{}", &address);
  182. s.run();
  183. });
  184. // The websocket for livereload
  185. let ws_server = WebSocket::new(|output: Sender| {
  186. move |msg: Message| {
  187. if msg.into_text().unwrap().contains("\"hello\"") {
  188. return output.send(Message::text(r#"
  189. {
  190. "command": "hello",
  191. "protocols": [ "http://livereload.com/protocols/official-7" ],
  192. "serverName": "Zola"
  193. }
  194. "#));
  195. }
  196. Ok(())
  197. }
  198. }).unwrap();
  199. let broadcaster = ws_server.broadcaster();
  200. thread::spawn(move || {
  201. ws_server.listen(&*ws_address).unwrap();
  202. });
  203. let pwd = env::current_dir().unwrap();
  204. let mut watchers = vec!["content", "config.toml"];
  205. if watching_static {
  206. watchers.push("static");
  207. }
  208. if watching_templates {
  209. watchers.push("templates");
  210. }
  211. if site.config.compile_sass {
  212. watchers.push("sass");
  213. }
  214. println!("Listening for changes in {}{}{{{}}}", pwd.display(), MAIN_SEPARATOR, watchers.join(", "));
  215. println!("Press Ctrl+C to stop\n");
  216. // Delete the output folder on ctrl+C
  217. ctrlc::set_handler(move || {
  218. remove_dir_all(&output_path).expect("Failed to delete output directory");
  219. ::std::process::exit(0);
  220. }).expect("Error setting Ctrl-C handler");
  221. use notify::DebouncedEvent::*;
  222. loop {
  223. match rx.recv() {
  224. Ok(event) => {
  225. match event {
  226. Create(path) |
  227. Write(path) |
  228. Remove(path) |
  229. Rename(_, path) => {
  230. if is_temp_file(&path) || path.is_dir() {
  231. continue;
  232. }
  233. println!("Change detected @ {}", Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
  234. let start = Instant::now();
  235. match detect_change_kind(&pwd, &path) {
  236. (ChangeKind::Content, _) => {
  237. console::info(&format!("-> Content changed {}", path.display()));
  238. // Force refresh
  239. rebuild_done_handling(&broadcaster, rebuild::after_content_change(&mut site, &path), "/x.js");
  240. },
  241. (ChangeKind::Templates, _) => {
  242. console::info(&format!("-> Template changed {}", path.display()));
  243. // Force refresh
  244. rebuild_done_handling(&broadcaster, rebuild::after_template_change(&mut site, &path), "/x.js");
  245. },
  246. (ChangeKind::StaticFiles, p) => {
  247. if path.is_file() {
  248. console::info(&format!("-> Static file changes detected {}", path.display()));
  249. rebuild_done_handling(&broadcaster, copy_file(&path, &site.output_path, &site.static_path), &p.to_string_lossy());
  250. }
  251. },
  252. (ChangeKind::Sass, p) => {
  253. console::info(&format!("-> Sass file changed {}", path.display()));
  254. rebuild_done_handling(&broadcaster, site.compile_sass(&site.base_path), &p.to_string_lossy());
  255. },
  256. (ChangeKind::Config, _) => {
  257. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  258. site = create_new_site(interface, port, output_dir, base_url, config_file).unwrap().0;
  259. }
  260. };
  261. console::report_elapsed_time(start);
  262. }
  263. _ => {}
  264. }
  265. },
  266. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  267. };
  268. }
  269. }
  270. /// Returns whether the path we received corresponds to a temp file created
  271. /// by an editor or the OS
  272. fn is_temp_file(path: &Path) -> bool {
  273. let ext = path.extension();
  274. match ext {
  275. Some(ex) => match ex.to_str().unwrap() {
  276. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  277. // jetbrains IDE
  278. x if x.ends_with("jb_old___") => true,
  279. x if x.ends_with("jb_tmp___") => true,
  280. x if x.ends_with("jb_bak___") => true,
  281. // vim
  282. x if x.ends_with('~') => true,
  283. _ => {
  284. if let Some(filename) = path.file_stem() {
  285. // emacs
  286. let name = filename.to_str().unwrap();
  287. name.starts_with('#') || name.starts_with(".#")
  288. } else {
  289. false
  290. }
  291. }
  292. },
  293. None => {
  294. true
  295. },
  296. }
  297. }
  298. /// Detect what changed from the given path so we have an idea what needs
  299. /// to be reloaded
  300. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  301. let mut partial_path = PathBuf::from("/");
  302. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  303. let change_kind = if partial_path.starts_with("/templates") {
  304. ChangeKind::Templates
  305. } else if partial_path.starts_with("/content") {
  306. ChangeKind::Content
  307. } else if partial_path.starts_with("/static") {
  308. ChangeKind::StaticFiles
  309. } else if partial_path.starts_with("/sass") {
  310. ChangeKind::Sass
  311. } else if partial_path == Path::new("/config.toml") {
  312. ChangeKind::Config
  313. } else {
  314. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  315. };
  316. (change_kind, partial_path)
  317. }
  318. #[cfg(test)]
  319. mod tests {
  320. use std::path::{Path, PathBuf};
  321. use super::{is_temp_file, detect_change_kind, ChangeKind};
  322. #[test]
  323. fn can_recognize_temp_files() {
  324. let test_cases = vec![
  325. Path::new("hello.swp"),
  326. Path::new("hello.swx"),
  327. Path::new(".DS_STORE"),
  328. Path::new("hello.tmp"),
  329. Path::new("hello.html.__jb_old___"),
  330. Path::new("hello.html.__jb_tmp___"),
  331. Path::new("hello.html.__jb_bak___"),
  332. Path::new("hello.html~"),
  333. Path::new("#hello.html"),
  334. ];
  335. for t in test_cases {
  336. assert!(is_temp_file(&t));
  337. }
  338. }
  339. #[test]
  340. fn can_detect_kind_of_changes() {
  341. let test_cases = vec![
  342. (
  343. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  344. Path::new("/home/vincent/site"), Path::new("/home/vincent/site/templates/hello.html")
  345. ),
  346. (
  347. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  348. Path::new("/home/vincent/site"), Path::new("/home/vincent/site/static/site.css")
  349. ),
  350. (
  351. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  352. Path::new("/home/vincent/site"), Path::new("/home/vincent/site/content/posts/hello.md")
  353. ),
  354. (
  355. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  356. Path::new("/home/vincent/site"), Path::new("/home/vincent/site/sass/print.scss")
  357. ),
  358. (
  359. (ChangeKind::Config, PathBuf::from("/config.toml")),
  360. Path::new("/home/vincent/site"), Path::new("/home/vincent/site/config.toml")
  361. ),
  362. ];
  363. for (expected, pwd, path) in test_cases {
  364. assert_eq!(expected, detect_change_kind(&pwd, &path));
  365. }
  366. }
  367. #[test]
  368. #[cfg(windows)]
  369. fn windows_path_handling() {
  370. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  371. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  372. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  373. assert_eq!(expected, detect_change_kind(pwd, path));
  374. }
  375. #[test]
  376. fn relative_path() {
  377. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  378. let pwd = Path::new("/home/johan/site");
  379. let path = Path::new("templates/hello.html");
  380. assert_eq!(expected, detect_change_kind(pwd, path));
  381. }
  382. }