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.

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