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.

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