use artifactize_core::types::RunId;
use clap::{ArgMatches, Args, Command, Error, FromArgMatches, Subcommand, error::ErrorKind};
use super::{Context, INTERRUPTED_EXIT, print_json};
use std::{
io::{self, Write},
path::PathBuf,
};
use super::{outcome_code, render::WAIT_TIMEOUT_EXIT};
use std::time::Duration;
const DEFAULT_RUN_WAIT: Duration = Duration::from_secs(600);
pub(super) async fn list(
context: Context,
scope: ListScope,
limit: u32,
offset: u32,
) -> Result<u8, String> {
let state = artifactize_core::state_dir(context.state_dir.as_deref())?;
let repo = match scope {
ListScope::Repo => Some(context.repo.unwrap_or_else(|| PathBuf::from("."))),
ListScope::All => None,
};
let runs = artifactize_core::runs::list(&state, repo.as_deref(), limit, offset).await?;
if context.json {
print_json(&runs)?;
} else {
let mut out = io::stdout().lock();
writeln!(
out,
"ID\tREPO\tCREATED\tCOMPLETED\tSTATUS\tREQUEST COUNTS\tCOMMENT"
)
.map_err(|e| e.to_string())?;
for run in runs {
let counts = run
.counts
.iter()
.map(|(state, count)| format!("{state}={count}"))
.collect::<Vec<_>>()
.join(" ");
writeln!(
out,
"{}\t{}\t{}\t{}\t{}\t{}\t{}",
run.id,
artifactize_core::platform::path_text(&run.repo_path),
run.created_at,
run.completed_at
.map_or_else(|| "-".to_owned(), |time| time.to_string()),
run.status,
counts,
run.comment.as_deref().unwrap_or("-")
)
.map_err(|e| e.to_string())?;
}
}
Ok(0)
}
#[derive(Debug, PartialEq, Eq)]
pub enum ShowMode {
Snapshot,
Wait { timeout: Duration },
}
#[derive(Args)]
#[group(skip)]
struct ShowFlags {
#[arg(long)]
wait: bool,
#[arg(
long,
value_name = "MS",
requires = "wait",
value_parser = timeout_duration,
help = format!("Wait timeout; never cancels the Run (default {}).", DEFAULT_RUN_WAIT.as_millis())
)]
timeout_ms: Option<Duration>,
}
impl ShowFlags {
fn mode(self) -> Result<Option<ShowMode>, Error> {
match (self.wait, self.timeout_ms) {
(true, timeout) => Ok(Some(ShowMode::Wait {
timeout: timeout.unwrap_or(DEFAULT_RUN_WAIT),
})),
(false, None) => Ok(None),
(false, Some(_)) => Err(Error::raw(
ErrorKind::MissingRequiredArgument,
"--timeout-ms requires --wait.",
)),
}
}
}
impl FromArgMatches for ShowMode {
fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
Ok(ShowFlags::from_arg_matches(matches)?
.mode()?
.unwrap_or(Self::Snapshot))
}
fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
if let Some(mode) = ShowFlags::from_arg_matches(matches)?.mode()? {
*self = mode;
}
Ok(())
}
}
impl Args for ShowMode {
fn augment_args(command: Command) -> Command {
ShowFlags::augment_args(command)
}
fn augment_args_for_update(command: Command) -> Command {
ShowFlags::augment_args_for_update(command)
}
}
pub(super) async fn show(
context: Context,
run_id: artifactize_core::types::RunId,
mode: ShowMode,
) -> Result<u8, String> {
let runs = artifactize_core::runs::Context::for_run(
context.state_dir.as_deref(),
&run_id,
&artifactize_core::platform::current_executable().map_err(|e| e.to_string())?,
)
.await?;
if let ShowMode::Wait { timeout } = mode {
let (cancellation, listener) = super::cancellation_listener()?;
let result =
artifactize_core::runs::wait(&runs, &run_id, Some(timeout), cancellation.clone()).await;
listener.abort();
if cancellation.is_cancelled() {
return Ok(INTERRUPTED_EXIT);
}
result?;
}
let view = artifactize_core::runs::view(&runs, &run_id).await?;
print_json(&artifactize_core::query::run_output(
&view,
time::OffsetDateTime::now_utc(),
))?;
let code = show_outcome(mode, &view.run);
if code == WAIT_TIMEOUT_EXIT {
writeln!(
io::stderr().lock(),
"Waiting timed out; Run {run_id} is still RUNNING."
)
.map_err(|e| e.to_string())?;
}
Ok(code)
}
fn show_outcome(mode: ShowMode, run: &artifactize_core::store::Run) -> u8 {
match mode {
ShowMode::Snapshot => 0,
ShowMode::Wait { .. } if run.status().is_open() => WAIT_TIMEOUT_EXIT,
ShowMode::Wait { .. } => outcome_code(run),
}
}
pub(super) async fn cancel(
context: Context,
id: artifactize_core::types::RunId,
) -> Result<u8, String> {
let runs = artifactize_core::runs::Context::for_run(
context.state_dir.as_deref(),
&id,
&artifactize_core::platform::current_executable().map_err(|e| e.to_string())?,
)
.await?;
print_json(&artifactize_core::runs::cancel(&runs, &id).await?)?;
Ok(0)
}
pub(super) async fn watch(
context: Context,
id: artifactize_core::types::RunId,
) -> Result<u8, String> {
let runs = artifactize_core::runs::Context::for_run(
context.state_dir.as_deref(),
&id,
&artifactize_core::platform::current_executable().map_err(|e| e.to_string())?,
)
.await?;
watch_run(&runs, id).await
}
pub(super) async fn watch_run(
runs: &artifactize_core::runs::Context,
id: RunId,
) -> Result<u8, String> {
let (cancellation, listener) = super::cancellation_listener()?;
let result =
artifactize_core::runs::watch(runs, &id, None, cancellation.clone(), |event| async move {
let mut out = io::stdout().lock();
serde_json::to_writer(&mut out, &event).map_err(|e| e.to_string())?;
writeln!(out)
.and_then(|()| out.flush())
.map_err(|e| e.to_string())
})
.await;
listener.abort();
if cancellation.is_cancelled() {
return Ok(INTERRUPTED_EXIT);
}
result?;
Ok(outcome_code(
&artifactize_core::runs::view(runs, &id).await?.run,
))
}
const DEFAULT_RUN_LIST_LIMIT: u32 = 50;
const MIN_WAIT_MILLIS: u64 = 1;
fn timeout_duration(text: &str) -> Result<std::time::Duration, String> {
let millis: u64 = text
.parse()
.map_err(|_| "timeout must be milliseconds".to_owned())?;
if !(MIN_WAIT_MILLIS..=artifactize_core::config::MAX_TIMEOUT_MS).contains(&millis) {
return Err(format!(
"timeoutMs must be between {MIN_WAIT_MILLIS} and {}",
artifactize_core::config::MAX_TIMEOUT_MS
));
}
Ok(std::time::Duration::from_millis(millis))
}
#[derive(Debug)]
pub enum ListScope {
Repo,
All,
}
#[derive(Args)]
#[group(skip)]
struct ListScopeFlags {
#[arg(long, conflicts_with = "all")]
repo_only: bool,
#[arg(long)]
all: bool,
}
impl ListScopeFlags {
fn selected(self) -> Result<Option<ListScope>, Error> {
match (self.repo_only, self.all) {
(false, false) => Ok(None),
(true, false) => Ok(Some(ListScope::Repo)),
(false, true) => Ok(Some(ListScope::All)),
(true, true) => Err(Error::raw(
ErrorKind::ArgumentConflict,
"Use --repo-only or --all, not both.",
)),
}
}
}
impl FromArgMatches for ListScope {
fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
Ok(ListScopeFlags::from_arg_matches(matches)?
.selected()?
.unwrap_or(Self::Repo))
}
fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
if let Some(scope) = ListScopeFlags::from_arg_matches(matches)?.selected()? {
*self = scope;
}
Ok(())
}
}
impl Args for ListScope {
fn augment_args(command: Command) -> Command {
ListScopeFlags::augment_args(command)
}
fn augment_args_for_update(command: Command) -> Command {
ListScopeFlags::augment_args_for_update(command)
}
}
#[derive(Debug, Subcommand)]
pub enum RunCommand {
Cancel { run_id: RunId },
List {
#[command(flatten)]
scope: ListScope,
#[arg(long, value_name = "N", default_value_t = DEFAULT_RUN_LIST_LIMIT)]
limit: u32,
#[arg(long, value_name = "N", default_value = "0")]
offset: u32,
},
Watch { run_id: RunId },
Show {
run_id: RunId,
#[command(flatten)]
mode: ShowMode,
},
}
#[cfg(test)]
mod tests;