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.

575 lines
21KB

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