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.

487 lines
17KB

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