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.

503 lines
18KB

  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. 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(2)).unwrap();
  163. watcher
  164. .watch("content/", RecursiveMode::Recursive)
  165. .chain_err(|| "Can't watch the `content` folder. Does it exist?")?;
  166. watcher
  167. .watch(config_file, RecursiveMode::Recursive)
  168. .chain_err(|| "Can't watch the `config` file. Does it exist?")?;
  169. if Path::new("static").exists() {
  170. watching_static = true;
  171. watcher
  172. .watch("static/", RecursiveMode::Recursive)
  173. .chain_err(|| "Can't watch the `static` folder.")?;
  174. }
  175. if Path::new("templates").exists() {
  176. watching_templates = true;
  177. watcher
  178. .watch("templates/", RecursiveMode::Recursive)
  179. .chain_err(|| "Can't watch the `templates` folder.")?;
  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://{}", &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. loop {
  262. match rx.recv() {
  263. Ok(event) => {
  264. match event {
  265. Create(path) | Write(path) | Remove(path) | Rename(_, path) => {
  266. if is_temp_file(&path) || path.is_dir() {
  267. continue;
  268. }
  269. println!(
  270. "Change detected @ {}",
  271. Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
  272. );
  273. let start = Instant::now();
  274. match detect_change_kind(&pwd, &path) {
  275. (ChangeKind::Content, _) => {
  276. console::info(&format!("-> Content changed {}", path.display()));
  277. if let Some(ref broadcaster) = broadcaster {
  278. // Force refresh
  279. rebuild_done_handling(
  280. broadcaster,
  281. rebuild::after_content_change(&mut site, &path),
  282. "/x.js",
  283. );
  284. }
  285. }
  286. (ChangeKind::Templates, _) => {
  287. console::info(&format!("-> Template changed {}", path.display()));
  288. if let Some(ref broadcaster) = broadcaster {
  289. // Force refresh
  290. rebuild_done_handling(
  291. broadcaster,
  292. rebuild::after_template_change(&mut site, &path),
  293. "/x.js",
  294. );
  295. }
  296. }
  297. (ChangeKind::StaticFiles, p) => {
  298. if path.is_file() {
  299. console::info(&format!(
  300. "-> Static file changes detected {}",
  301. path.display()
  302. ));
  303. if let Some(ref broadcaster) = broadcaster {
  304. rebuild_done_handling(
  305. broadcaster,
  306. copy_file(&path, &site.output_path, &site.static_path),
  307. &p.to_string_lossy(),
  308. );
  309. }
  310. }
  311. }
  312. (ChangeKind::Sass, p) => {
  313. console::info(&format!("-> Sass file changed {}", path.display()));
  314. if let Some(ref broadcaster) = broadcaster {
  315. rebuild_done_handling(
  316. &broadcaster,
  317. site.compile_sass(&site.base_path),
  318. &p.to_string_lossy(),
  319. );
  320. }
  321. }
  322. (ChangeKind::Config, _) => {
  323. console::info("-> Config changed. The whole site will be reloaded. The browser needs to be refreshed to make the changes visible.");
  324. site = create_new_site(
  325. interface,
  326. port,
  327. output_dir,
  328. base_url,
  329. config_file,
  330. )
  331. .unwrap()
  332. .0;
  333. }
  334. };
  335. console::report_elapsed_time(start);
  336. }
  337. _ => {}
  338. }
  339. }
  340. Err(e) => console::error(&format!("Watch error: {:?}", e)),
  341. };
  342. }
  343. }
  344. /// Returns whether the path we received corresponds to a temp file created
  345. /// by an editor or the OS
  346. fn is_temp_file(path: &Path) -> bool {
  347. let ext = path.extension();
  348. match ext {
  349. Some(ex) => match ex.to_str().unwrap() {
  350. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  351. // jetbrains IDE
  352. x if x.ends_with("jb_old___") => true,
  353. x if x.ends_with("jb_tmp___") => true,
  354. x if x.ends_with("jb_bak___") => true,
  355. // vim
  356. x if x.ends_with('~') => true,
  357. _ => {
  358. if let Some(filename) = path.file_stem() {
  359. // emacs
  360. let name = filename.to_str().unwrap();
  361. name.starts_with('#') || name.starts_with(".#")
  362. } else {
  363. false
  364. }
  365. }
  366. },
  367. None => true,
  368. }
  369. }
  370. /// Detect what changed from the given path so we have an idea what needs
  371. /// to be reloaded
  372. fn detect_change_kind(pwd: &Path, path: &Path) -> (ChangeKind, PathBuf) {
  373. let mut partial_path = PathBuf::from("/");
  374. partial_path.push(path.strip_prefix(pwd).unwrap_or(path));
  375. let change_kind = if partial_path.starts_with("/templates") {
  376. ChangeKind::Templates
  377. } else if partial_path.starts_with("/content") {
  378. ChangeKind::Content
  379. } else if partial_path.starts_with("/static") {
  380. ChangeKind::StaticFiles
  381. } else if partial_path.starts_with("/sass") {
  382. ChangeKind::Sass
  383. } else if partial_path == Path::new("/config.toml") {
  384. ChangeKind::Config
  385. } else {
  386. unreachable!("Got a change in an unexpected path: {}", partial_path.display());
  387. };
  388. (change_kind, partial_path)
  389. }
  390. #[cfg(test)]
  391. mod tests {
  392. use std::path::{Path, PathBuf};
  393. use super::{detect_change_kind, is_temp_file, ChangeKind};
  394. #[test]
  395. fn can_recognize_temp_files() {
  396. let test_cases = vec![
  397. Path::new("hello.swp"),
  398. Path::new("hello.swx"),
  399. Path::new(".DS_STORE"),
  400. Path::new("hello.tmp"),
  401. Path::new("hello.html.__jb_old___"),
  402. Path::new("hello.html.__jb_tmp___"),
  403. Path::new("hello.html.__jb_bak___"),
  404. Path::new("hello.html~"),
  405. Path::new("#hello.html"),
  406. ];
  407. for t in test_cases {
  408. assert!(is_temp_file(&t));
  409. }
  410. }
  411. #[test]
  412. fn can_detect_kind_of_changes() {
  413. let test_cases = vec![
  414. (
  415. (ChangeKind::Templates, PathBuf::from("/templates/hello.html")),
  416. Path::new("/home/vincent/site"),
  417. Path::new("/home/vincent/site/templates/hello.html"),
  418. ),
  419. (
  420. (ChangeKind::StaticFiles, PathBuf::from("/static/site.css")),
  421. Path::new("/home/vincent/site"),
  422. Path::new("/home/vincent/site/static/site.css"),
  423. ),
  424. (
  425. (ChangeKind::Content, PathBuf::from("/content/posts/hello.md")),
  426. Path::new("/home/vincent/site"),
  427. Path::new("/home/vincent/site/content/posts/hello.md"),
  428. ),
  429. (
  430. (ChangeKind::Sass, PathBuf::from("/sass/print.scss")),
  431. Path::new("/home/vincent/site"),
  432. Path::new("/home/vincent/site/sass/print.scss"),
  433. ),
  434. (
  435. (ChangeKind::Config, PathBuf::from("/config.toml")),
  436. Path::new("/home/vincent/site"),
  437. Path::new("/home/vincent/site/config.toml"),
  438. ),
  439. ];
  440. for (expected, pwd, path) in test_cases {
  441. assert_eq!(expected, detect_change_kind(&pwd, &path));
  442. }
  443. }
  444. #[test]
  445. #[cfg(windows)]
  446. fn windows_path_handling() {
  447. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  448. let pwd = Path::new(r#"C:\\Users\johan\site"#);
  449. let path = Path::new(r#"C:\\Users\johan\site\templates\hello.html"#);
  450. assert_eq!(expected, detect_change_kind(pwd, path));
  451. }
  452. #[test]
  453. fn relative_path() {
  454. let expected = (ChangeKind::Templates, PathBuf::from("/templates/hello.html"));
  455. let pwd = Path::new("/home/johan/site");
  456. let path = Path::new("templates/hello.html");
  457. assert_eq!(expected, detect_change_kind(pwd, path));
  458. }
  459. }