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.

579 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: &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(
  272. &broadcaster,
  273. rebuild::after_template_change(site, &path),
  274. "/x.js",
  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. rebuild_done_handling(
  285. &broadcaster,
  286. site.compile_sass(&site.base_path),
  287. &partial_path.to_string_lossy(),
  288. );
  289. };
  290. let copy_static = |site: &Site, path: &Path, partial_path: &Path| {
  291. // Do nothing if the file/dir was deleted
  292. if !path.exists() {
  293. return;
  294. }
  295. let msg = if path.is_dir() {
  296. format!("-> Directory in `static` folder changed {}", path.display())
  297. } else {
  298. format!("-> Static file changed {}", path.display())
  299. };
  300. console::info(&msg);
  301. if path.is_dir() {
  302. rebuild_done_handling(
  303. &broadcaster,
  304. site.copy_static_directories(),
  305. &path.to_string_lossy(),
  306. );
  307. } else {
  308. rebuild_done_handling(
  309. &broadcaster,
  310. copy_file(&path, &site.output_path, &site.static_path),
  311. &partial_path.to_string_lossy(),
  312. );
  313. }
  314. };
  315. loop {
  316. match rx.recv() {
  317. Ok(event) => {
  318. match event {
  319. Rename(old_path, path) => {
  320. if path.is_file() && is_temp_file(&path) {
  321. continue;
  322. }
  323. let (change_kind, partial_path) = detect_change_kind(&pwd, &path);
  324. // We only care about changes in non-empty folders
  325. if path.is_dir() && is_folder_empty(&path) {
  326. continue;
  327. }
  328. println!(
  329. "Change detected @ {}",
  330. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  331. );
  332. let start = Instant::now();
  333. match change_kind {
  334. ChangeKind::Content => {
  335. console::info(&format!("-> Content renamed {}", path.display()));
  336. // Force refresh
  337. rebuild_done_handling(
  338. &broadcaster,
  339. rebuild::after_content_rename(&mut site, &old_path, &path),
  340. "/x.js",
  341. );
  342. }
  343. ChangeKind::Templates => reload_templates(&mut site, &path),
  344. ChangeKind::StaticFiles => copy_static(&site, &path, &partial_path),
  345. ChangeKind::Sass => reload_sass(&site, &path, &partial_path),
  346. ChangeKind::Config => {
  347. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  348. site = create_new_site(
  349. interface,
  350. port,
  351. output_dir,
  352. base_url,
  353. config_file,
  354. )
  355. .unwrap()
  356. .0;
  357. }
  358. }
  359. console::report_elapsed_time(start);
  360. }
  361. Create(path) | Write(path) | Remove(path) => {
  362. if is_temp_file(&path) || path.is_dir() {
  363. continue;
  364. }
  365. println!(
  366. "Change detected @ {}",
  367. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  368. );
  369. let start = Instant::now();
  370. match detect_change_kind(&pwd, &path) {
  371. (ChangeKind::Content, _) => {
  372. console::info(&format!("-> Content changed {}", path.display()));
  373. // Force refresh
  374. rebuild_done_handling(
  375. &broadcaster,
  376. rebuild::after_content_change(&mut site, &path),
  377. "/x.js",
  378. );
  379. }
  380. (ChangeKind::Templates, _) => reload_templates(&mut site, &path),
  381. (ChangeKind::StaticFiles, p) => copy_static(&site, &path, &p),
  382. (ChangeKind::Sass, p) => reload_sass(&site, &path, &p),
  383. (ChangeKind::Config, _) => {
  384. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  385. site = create_new_site(
  386. interface,
  387. port,
  388. output_dir,
  389. base_url,
  390. config_file,
  391. )
  392. .unwrap()
  393. .0;
  394. }
  395. };
  396. console::report_elapsed_time(start);
  397. }
  398. _ => {}
  399. }
  400. }
  401. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  402. };
  403. }
  404. }
  405. /// Returns whether the path we received corresponds to a temp file created
  406. /// by an editor or the OS
  407. fn is_temp_file(path: &Path) -> bool {
  408. let ext = path.extension();
  409. match ext {
  410. Some(ex) => match ex.to_str().unwrap() {
  411. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  412. // jetbrains IDE
  413. x if x.ends_with("jb_old___") => true,
  414. x if x.ends_with("jb_tmp___") => true,
  415. x if x.ends_with("jb_bak___") => true,
  416. // vim
  417. x if x.ends_with('~') => true,
  418. _ => {
  419. if let Some(filename) = path.file_stem() {
  420. // emacs
  421. let name = filename.to_str().unwrap();
  422. name.starts_with('#') || name.starts_with(".#")
  423. } else {
  424. false
  425. }
  426. }
  427. },
  428. None => true,
  429. }
  430. }
  431. /// Detect what changed from the given path so we have an idea what needs
  432. /// to be reloaded
  433. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  434. let mut partial_path = PathBuf::from("/");
  435. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  436. let change_kind = if partial_path.starts_with("/templates") {
  437. ChangeKind::Templates
  438. } else if partial_path.starts_with("/content") {
  439. ChangeKind::Content
  440. } else if partial_path.starts_with("/static") {
  441. ChangeKind::StaticFiles
  442. } else if partial_path.starts_with("/sass") {
  443. ChangeKind::Sass
  444. } else if partial_path == Path::new("/config.toml") {
  445. ChangeKind::Config
  446. } else {
  447. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  448. };
  449. (change_kind, partial_path)
  450. }
  451. /// Check if the directory at path contains any file
  452. fn is_folder_empty(dir: &Path) -> bool {
  453. // Can panic if we don't have the rights I guess?
  454. let files: Vec<_> =
  455. read_dir(dir).expect("Failed to read a directory to see if it was empty").collect();
  456. files.is_empty()
  457. }
  458. #[cfg(test)]
  459. mod tests {
  460. use std::path::{Path, PathBuf};
  461. use super::{detect_change_kind, is_temp_file, ChangeKind};
  462. #[test]
  463. fn can_recognize_temp_files() {
  464. let test_cases = vec![
  465. Path::new("hello.swp"),
  466. Path::new("hello.swx"),
  467. Path::new(".DS_STORE"),
  468. Path::new("hello.tmp"),
  469. Path::new("hello.html.__jb_old___"),
  470. Path::new("hello.html.__jb_tmp___"),
  471. Path::new("hello.html.__jb_bak___"),
  472. Path::new("hello.html~"),
  473. Path::new("#hello.html"),
  474. ];
  475. for t in test_cases {
  476. assert!(is_temp_file(&t));
  477. }
  478. }
  479. #[test]
  480. fn can_detect_kind_of_changes() {
  481. let test_cases = vec![
  482. (
  483. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  484. Path::new("/home/vincent/site"),
  485. Path::new("/home/vincent/site/templates/hello.html"),
  486. ),
  487. (
  488. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  489. Path::new("/home/vincent/site"),
  490. Path::new("/home/vincent/site/static/site.css"),
  491. ),
  492. (
  493. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  494. Path::new("/home/vincent/site"),
  495. Path::new("/home/vincent/site/content/posts/hello.md"),
  496. ),
  497. (
  498. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  499. Path::new("/home/vincent/site"),
  500. Path::new("/home/vincent/site/sass/print.scss"),
  501. ),
  502. (
  503. (ChangeKind::Config, PathBuf::from("/config.toml")),
  504. Path::new("/home/vincent/site"),
  505. Path::new("/home/vincent/site/config.toml"),
  506. ),
  507. ];
  508. for (expected, pwd, path) in test_cases {
  509. assert_eq!(expected, detect_change_kind(&pwd, &path));
  510. }
  511. }
  512. #[test]
  513. #[cfg(windows)]
  514. fn windows_path_handling() {
  515. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  516. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  517. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  518. assert_eq!(expected, detect_change_kind(pwd, path));
  519. }
  520. #[test]
  521. fn relative_path() {
  522. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  523. let pwd = Path::new("/home/johan/site");
  524. let path = Path::new("templates/hello.html");
  525. assert_eq!(expected, detect_change_kind(pwd, path));
  526. }
  527. }