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.

133 lines
4.5KB

  1. use std::env;
  2. use std::path::Path;
  3. use std::sync::mpsc::channel;
  4. use std::time::Duration;
  5. use std::thread;
  6. use iron::{Iron, Request, IronResult, Response, status};
  7. use mount::Mount;
  8. use staticfile::Static;
  9. use notify::{Watcher, RecursiveMode, watcher};
  10. use ws::{WebSocket};
  11. use site::Site;
  12. use errors::{Result};
  13. const LIVE_RELOAD: &'static [u8; 37809] = include_bytes!("livereload.js");
  14. fn livereload_handler(_: &mut Request) -> IronResult<Response> {
  15. Ok(Response::with((status::Ok, String::from_utf8(LIVE_RELOAD.to_vec()).unwrap())))
  16. }
  17. // Most of it taken from mdbook
  18. pub fn serve(interface: &str, port: &str) -> Result<()> {
  19. let mut site = Site::new(true)?;
  20. site.build()?;
  21. let address = format!("{}:{}", interface, port);
  22. let ws_address = format!("{}:{}", interface, "1112");
  23. // Start a webserver that serves the `public` directory
  24. let mut mount = Mount::new();
  25. mount.mount("/", Static::new(Path::new("public/")));
  26. mount.mount("/livereload.js", livereload_handler);
  27. let server = Iron::new(mount).http(address.clone()).unwrap();
  28. println!("Web server is available at http://{}", address);
  29. println!("Press CTRL+C to stop");
  30. // The websocket for livereload
  31. let ws_server = WebSocket::new(|_| {
  32. |_| {
  33. Ok(())
  34. }
  35. }).unwrap();
  36. let broadcaster = ws_server.broadcaster();
  37. thread::spawn(move || {
  38. ws_server.listen(&*ws_address).unwrap();
  39. });
  40. // And finally watching/reacting on file changes
  41. let (tx, rx) = channel();
  42. let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
  43. watcher.watch("content/", RecursiveMode::Recursive).unwrap();
  44. watcher.watch("static/", RecursiveMode::Recursive).unwrap();
  45. watcher.watch("templates/", RecursiveMode::Recursive).unwrap();
  46. let pwd = env::current_dir().unwrap();
  47. println!("Listening for changes in {}/{{content, static, templates}}", pwd.display());
  48. use notify::DebouncedEvent::*;
  49. loop {
  50. // See https://github.com/spf13/hugo/blob/master/commands/hugo.go
  51. // for a more complete version of that
  52. match rx.recv() {
  53. Ok(event) => match event {
  54. NoticeWrite(path) |
  55. NoticeRemove(path) |
  56. Create(path) |
  57. Write(path) |
  58. Remove(path) |
  59. Rename(_, path) => {
  60. if !is_temp_file(&path) {
  61. println!("Change detected in {}", path.display());
  62. match site.rebuild() {
  63. Ok(_) => {
  64. println!("Site rebuilt");
  65. broadcaster.send(r#"
  66. {
  67. "command": "reload",
  68. "path": "",
  69. "originalPath": "",
  70. "liveCSS": true,
  71. "liveImg": true,
  72. "protocol": ["http://livereload.com/protocols/official-7"]
  73. }"#).unwrap();
  74. },
  75. Err(e) => {
  76. println!("Failed to build the site");
  77. println!("Error: {}", e);
  78. for e in e.iter().skip(1) {
  79. println!("Reason: {}", e)
  80. }
  81. }
  82. }
  83. }
  84. }
  85. _ => {}
  86. },
  87. Err(e) => println!("Watch error: {:?}", e),
  88. };
  89. }
  90. }
  91. /// Returns whether the path we received corresponds to a temp file create
  92. /// by an editor
  93. fn is_temp_file(path: &Path) -> bool {
  94. let ext = path.extension();
  95. match ext {
  96. Some(ex) => match ex.to_str().unwrap() {
  97. "swp" | "swx" | "tmp" | ".DS_STORE" => true,
  98. // jetbrains IDE
  99. x if x.ends_with("jb_old___") => true,
  100. x if x.ends_with("jb_tmp___") => true,
  101. x if x.ends_with("jb_bak___") => true,
  102. // byword
  103. x if x.starts_with("sb-") => true,
  104. // gnome
  105. x if x.starts_with(".gooutputstream") => true,
  106. _ => {
  107. if let Some(filename) = path.file_stem() {
  108. // emacs
  109. filename.to_str().unwrap().starts_with("#")
  110. } else {
  111. false
  112. }
  113. }
  114. },
  115. None => false,
  116. }
  117. }