Skip to content

Commit 0b3eed1

Browse files
committed
improve code
1 parent ced97f3 commit 0b3eed1

File tree

3 files changed

+33
-20
lines changed

3 files changed

+33
-20
lines changed

crates/vite_task/src/session/execute/mod.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
pub mod fingerprint;
22
pub mod spawn;
33

4-
use std::{process::ExitCode, sync::Arc};
4+
use std::sync::Arc;
55

66
use futures_util::FutureExt;
77
use petgraph::{algo::toposort, graph::DiGraph};
@@ -21,7 +21,7 @@ use super::{
2121
CacheDisabledReason, CacheStatus, ExecutionEvent, ExecutionEventKind, ExecutionId,
2222
ExecutionItemDisplay, OutputKind,
2323
},
24-
reporter::Reporter,
24+
reporter::{ExitStatus, Reporter},
2525
};
2626
use crate::{Session, session::execute::spawn::SpawnTrackResult};
2727

@@ -330,12 +330,15 @@ impl ExecutionContext<'_> {
330330
impl<'a, CustomSubcommand> Session<'a, CustomSubcommand> {
331331
/// Execute an execution plan, reporting events to the provided reporter.
332332
///
333-
/// Returns Ok(()) on success, or Err(ExitCode) on failure.
333+
/// Returns Err(ExitStatus) to suggest the caller to abort and exit the process with the given exit status.
334+
///
335+
/// The return type isn't just ExitStatus because we want to distinguish between normal successful execution,
336+
/// and execution that failed and needs to exit with a specific code which can be zero.
334337
pub async fn execute(
335338
&self,
336339
plan: ExecutionPlan,
337340
mut reporter: Box<dyn Reporter>,
338-
) -> Result<(), ExitCode> {
341+
) -> Result<(), ExitStatus> {
339342
let mut execution_context = ExecutionContext {
340343
event_handler: &mut *reporter,
341344
current_execution_id: ExecutionId::zero(),

crates/vite_task/src/session/reporter.rs

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
use std::{
44
collections::HashSet,
55
io::Write,
6-
process::ExitCode,
76
sync::{Arc, LazyLock},
87
time::Duration,
98
};
@@ -29,14 +28,23 @@ impl<T: owo_colors::OwoColorize> ColorizeExt for T {
2928
}
3029
}
3130

31+
/// Exit status code for task execution
32+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33+
pub struct ExitStatus(pub u8);
34+
35+
impl ExitStatus {
36+
pub const FAILURE: Self = Self(1);
37+
pub const SUCCESS: Self = Self(0);
38+
}
39+
3240
/// Trait for handling execution events and reporting results
3341
pub trait Reporter {
3442
/// Handle an execution event (start, output, error, finish)
3543
fn handle_event(&mut self, event: ExecutionEvent);
3644

3745
/// Called after execution completes (whether successful or not)
38-
/// Returns Ok(()) on success, or Err(ExitCode) on failure
39-
fn post_execution(self: Box<Self>) -> Result<(), ExitCode>;
46+
/// Returns Ok(()) on success, or Err(ExitStatus) on failure
47+
fn post_execution(self: Box<Self>) -> Result<(), ExitStatus>;
4048
}
4149

4250
const COMMAND_STYLE: Style = Style::new().cyan();
@@ -487,7 +495,7 @@ impl<W: Write> Reporter for LabeledReporter<W> {
487495
}
488496
}
489497

490-
fn post_execution(mut self: Box<Self>) -> Result<(), ExitCode> {
498+
fn post_execution(mut self: Box<Self>) -> Result<(), ExitStatus> {
491499
// Check if execution was aborted due to error
492500
if let Some(error_msg) = &self.first_error {
493501
// Print separator
@@ -514,7 +522,7 @@ impl<W: Write> Reporter for LabeledReporter<W> {
514522
.style(Style::new().bright_black())
515523
);
516524

517-
return Err(ExitCode::FAILURE);
525+
return Err(ExitStatus::FAILURE);
518526
}
519527

520528
// No errors - print summary if not hidden
@@ -538,14 +546,13 @@ impl<W: Write> Reporter for LabeledReporter<W> {
538546
.filter(|&status| status != 0)
539547
.collect();
540548

541-
match failed_exit_codes.len() {
542-
0 => Ok(()),
543-
1 => {
549+
match failed_exit_codes.as_slice() {
550+
[] => Ok(()),
551+
[code] => {
544552
// Return the single failed task's exit code (clamped to u8 range)
545-
let code = failed_exit_codes[0];
546-
Err(ExitCode::from(code.clamp(1, 255) as u8))
553+
Err(ExitStatus((*code).clamp(1, 255) as u8))
547554
}
548-
_ => Err(ExitCode::FAILURE),
555+
_ => Err(ExitStatus::FAILURE),
549556
}
550557
}
551558
}

crates/vite_task_bin/src/main.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
11
use std::{env, process::ExitCode, sync::Arc};
22

33
use vite_path::{AbsolutePath, current_dir};
4-
use vite_task::{CLIArgs, Session, session::reporter::LabeledReporter};
4+
use vite_task::{
5+
CLIArgs, Session,
6+
session::reporter::{ExitStatus, LabeledReporter},
7+
};
58
use vite_task_bin::{CustomTaskSubcommand, NonTaskSubcommand, OwnedSessionCallbacks};
69

710
#[tokio::main]
811
async fn main() -> ExitCode {
912
match run().await {
10-
Ok(exit_code) => exit_code,
13+
Ok(exit_status) => exit_status.0.into(),
1114
Err(err) => {
1215
eprintln!("Error: {err}");
1316
ExitCode::FAILURE
1417
}
1518
}
1619
}
1720

18-
async fn run() -> anyhow::Result<ExitCode> {
21+
async fn run() -> anyhow::Result<ExitStatus> {
1922
let cwd: Arc<AbsolutePath> = current_dir()?.into();
2023
// Parse the CLI arguments and see if they are for vite-task or not
2124
let args = match CLIArgs::<CustomTaskSubcommand, NonTaskSubcommand>::try_parse_from(env::args())
@@ -30,7 +33,7 @@ async fn run() -> anyhow::Result<ExitCode> {
3033
CLIArgs::NonTask(NonTaskSubcommand::Version) => {
3134
// Non-task subcommands are not handled by vite-task's session.
3235
println!("{}", env!("CARGO_PKG_VERSION"));
33-
return Ok(ExitCode::SUCCESS);
36+
return Ok(ExitStatus::SUCCESS);
3437
}
3538
};
3639

@@ -40,5 +43,5 @@ async fn run() -> anyhow::Result<ExitCode> {
4043

4144
// Create reporter and execute
4245
let reporter = LabeledReporter::new(std::io::stdout(), session.workspace_path());
43-
Ok(session.execute(plan, Box::new(reporter)).await.err().unwrap_or(ExitCode::SUCCESS))
46+
Ok(session.execute(plan, Box::new(reporter)).await.err().unwrap_or(ExitStatus::SUCCESS))
4447
}

0 commit comments

Comments
 (0)