serve.rs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. use std::{collections::HashMap, path::PathBuf, sync::Arc};
  2. use failure::Fail;
  3. use rbx_dom_weak::RbxInstanceProperties;
  4. use crate::{
  5. imfs::new::{Imfs, RealFetcher, WatchMode},
  6. project::{Project, ProjectLoadError},
  7. serve_session::ServeSession,
  8. snapshot::{apply_patch_set, compute_patch_set, InstancePropertiesWithMeta, RojoTree},
  9. snapshot_middleware::snapshot_from_imfs,
  10. web::LiveServer,
  11. };
  12. const DEFAULT_PORT: u16 = 34872;
  13. #[derive(Debug)]
  14. pub struct ServeOptions {
  15. pub fuzzy_project_path: PathBuf,
  16. pub port: Option<u16>,
  17. }
  18. #[derive(Debug, Fail)]
  19. pub enum ServeError {
  20. #[fail(display = "Couldn't load project: {}", _0)]
  21. ProjectLoad(#[fail(cause)] ProjectLoadError),
  22. }
  23. impl_from!(ServeError {
  24. ProjectLoadError => ProjectLoad,
  25. });
  26. pub fn serve(options: &ServeOptions) -> Result<(), ServeError> {
  27. let maybe_project = match Project::load_fuzzy(&options.fuzzy_project_path) {
  28. Ok(project) => Some(project),
  29. Err(ProjectLoadError::NotFound) => None,
  30. Err(other) => return Err(other.into()),
  31. };
  32. let port = options
  33. .port
  34. .or_else(|| {
  35. maybe_project
  36. .as_ref()
  37. .and_then(|project| project.serve_port)
  38. })
  39. .unwrap_or(DEFAULT_PORT);
  40. println!("Rojo server listening on port {}", port);
  41. let mut tree = RojoTree::new(InstancePropertiesWithMeta {
  42. properties: RbxInstanceProperties {
  43. name: "ROOT".to_owned(),
  44. class_name: "Folder".to_owned(),
  45. properties: HashMap::new(),
  46. },
  47. metadata: Default::default(),
  48. });
  49. let root_id = tree.get_root_id();
  50. let mut imfs = Imfs::new(RealFetcher::new(WatchMode::Enabled));
  51. let entry = imfs
  52. .get(&options.fuzzy_project_path)
  53. .expect("could not get project path");
  54. let snapshot = snapshot_from_imfs(&mut imfs, &entry)
  55. .expect("snapshot failed")
  56. .expect("snapshot did not return an instance");
  57. let patch_set = compute_patch_set(&snapshot, &tree, root_id);
  58. apply_patch_set(&mut tree, &patch_set);
  59. let session = Arc::new(ServeSession::new(imfs, tree, maybe_project));
  60. let server = LiveServer::new(session);
  61. server.start(port);
  62. // let receiver = imfs.change_receiver();
  63. // while let Ok(change) = receiver.recv() {
  64. // imfs.commit_change(&change)
  65. // .expect("Failed to commit Imfs change");
  66. // use notify::DebouncedEvent;
  67. // if let DebouncedEvent::Write(path) = change {
  68. // let contents = imfs.get_contents(path)
  69. // .expect("Failed to read changed path");
  70. // println!("{:?}", std::str::from_utf8(contents));
  71. // }
  72. // }
  73. Ok(())
  74. }