Skip to main content

euv_cli/mode/
fn.rs

1use super::*;
2
3/// Executes the build-only pipeline.
4///
5/// # Arguments
6///
7/// - `ModeArgs` - The CLI arguments.
8///
9/// # Returns
10///
11/// - `Result<(), EuvError>` - Indicates success or failure.
12pub async fn build_mode(mut args: ModeArgs) -> Result<(), EuvError> {
13    reconcile_args(&mut args);
14    args.set_crate_path(
15        sync_canonicalize(args.get_crate_path()).map_err(|error: io::Error| EuvError::IoPath {
16            message: ERROR_INVALID_CRATE_PATH.to_string(),
17            path: args.get_crate_path().clone(),
18            error,
19        })?,
20    );
21    let crate_path_str: String = args.get_crate_path().to_string_lossy().to_string();
22    if crate_path_str.starts_with(WINDOWS_UNC_PREFIX) {
23        args.set_crate_path(PathBuf::from(
24            crate_path_str
25                .strip_prefix(WINDOWS_UNC_PREFIX)
26                .unwrap_or(&crate_path_str),
27        ));
28    }
29    print_banner(Action::Build);
30    run_build_only_pipeline(&args).await?;
31    log::info!("Build completed. Exiting (build-only mode).");
32    Ok(())
33}
34
35/// Executes the format command.
36///
37/// # Arguments
38///
39/// - `FmtArgs` - The CLI arguments for the fmt command.
40///
41/// # Returns
42///
43/// - `Result<(), EuvError>` - Indicates success or failure.
44pub async fn fmt_mode(args: FmtArgs) -> Result<(), EuvError> {
45    let fmt_path: PathBuf = if args.get_path().is_absolute() {
46        args.get_path().clone()
47    } else {
48        current_dir()
49            .map_err(|error: io::Error| EuvError::Io {
50                message: ERROR_CURRENT_DIRECTORY.to_string(),
51                error,
52            })?
53            .join(args.get_path())
54    };
55    let mode: FmtMode = if args.get_check() {
56        FmtMode::Check
57    } else {
58        FmtMode::Write
59    };
60    format_dir(&fmt_path, mode).await
61}
62
63/// Executes the run mode (build + dev server + hot reload).
64///
65/// # Arguments
66///
67/// - `ModeArgs` - The CLI arguments.
68///
69/// # Returns
70///
71/// - `Result<(), EuvError>` - Indicates success or failure.
72#[hyperlane(server: Server)]
73pub async fn run_mode(mut args: ModeArgs) -> Result<(), EuvError> {
74    reconcile_args(&mut args);
75    args.set_crate_path(
76        sync_canonicalize(args.get_crate_path()).map_err(|error: io::Error| EuvError::IoPath {
77            message: ERROR_INVALID_CRATE_PATH.to_string(),
78            path: args.get_crate_path().clone(),
79            error,
80        })?,
81    );
82    let crate_path_str: String = args.get_crate_path().to_string_lossy().to_string();
83    if crate_path_str.starts_with(WINDOWS_UNC_PREFIX) {
84        args.set_crate_path(PathBuf::from(
85            crate_path_str
86                .strip_prefix(WINDOWS_UNC_PREFIX)
87                .unwrap_or(&crate_path_str),
88        ));
89    }
90    let serving_route_prefix: String = resolve_serving_route_prefix(&args);
91    let initial_html: String = run_build_pipeline(&args, None).await?;
92    print_banner(Action::Run);
93    let (reload_tx, _): (
94        broadcast::Sender<ReloadEvent>,
95        broadcast::Receiver<ReloadEvent>,
96    ) = broadcast::channel(16);
97    let state: Arc<AppState> = Arc::new(AppState::new(
98        RwLock::new(initial_html),
99        reload_tx.clone(),
100        RwLock::new(false),
101        args.clone(),
102    ));
103    let state_for_watch: Arc<AppState> = Arc::clone(&state);
104    tokio::spawn(async move {
105        if let Err(error) = watch_and_build(state_for_watch).await {
106            log::error!("Watch error: {error}");
107        }
108    });
109    let pkg_dir: PathBuf = resolve_pkg_dir(&args);
110    log::info!("Serving pkg from: {}", pkg_dir.display());
111    let mut server_config: ServerConfig = ServerConfig::default();
112    server_config.set_nodelay(Some(false));
113    server_config.set_address(Server::format_bind_address(DEFAULT_HOST, args.get_port()));
114    server.server_config(server_config);
115    server.route::<IndexRoute>(format!("{serving_route_prefix}/{{path:.*}}"));
116    if let Err(error) = set_global_state(Arc::clone(&state)) {
117        log::error!("Failed to set global state: {error}");
118    }
119    print_server_urls(&ServerUrlConfig::new(
120        args.get_port(),
121        serving_route_prefix.clone(),
122        INDEX_HTML_FILE_NAME.to_string(),
123    ));
124    let server_control_hook: ServerControlHook = server
125        .run()
126        .await
127        .map_err(|error: Box<ServerError>| EuvError::Server(error.to_string()))?;
128    server_control_hook.wait().await;
129    Ok(())
130}