use std::time::Duration;
use crate::client::{GitFoxClient, Method, Query};
use crate::error::Result;
use crate::models::{Execution, LogLine, Pipeline, RepoRef};
pub struct PipelinesApi<'a> {
client: &'a GitFoxClient,
}
impl<'a> PipelinesApi<'a> {
pub(crate) fn new(client: &'a GitFoxClient) -> Self {
Self { client }
}
pub async fn list(
&self,
repo: &RepoRef,
latest: bool,
page: u32,
limit: u32,
) -> Result<Vec<Pipeline>> {
let mut q = Query::new();
q.push("page", page).push("limit", limit);
if latest {
q.push("latest", "true");
}
let path = format!("/api/v1/repos/{}/pipelines", repo.encoded());
self.client.get_json(&q.apply(&path)).await
}
pub async fn list_executions(
&self,
repo: &RepoRef,
pipeline: &str,
page: u32,
limit: u32,
) -> Result<Vec<Execution>> {
let mut q = Query::new();
q.push("page", page).push("limit", limit);
let path = format!(
"/api/v1/repos/{}/pipelines/{}/executions",
repo.encoded(),
urlencode(pipeline)
);
self.client.get_json(&q.apply(&path)).await
}
pub async fn get_execution(
&self,
repo: &RepoRef,
pipeline: &str,
number: u64,
) -> Result<Execution> {
self.client
.get_json(&self.execution_path(repo, pipeline, number))
.await
}
pub async fn step_logs(
&self,
repo: &RepoRef,
pipeline: &str,
number: u64,
stage: i64,
step: i64,
) -> Result<Vec<LogLine>> {
let path = format!(
"{}/logs/{stage}/{step}",
self.execution_path(repo, pipeline, number)
);
self.client.get_json(&path).await
}
pub async fn step_logs_live(
&self,
repo: &RepoRef,
pipeline: &str,
number: u64,
stage: i64,
step: i64,
idle: Duration,
) -> Result<Vec<LogLine>> {
let path = format!(
"{}/logs/{stage}/{step}/stream",
self.execution_path(repo, pipeline, number)
);
self.client.sse_lines(&path, idle).await
}
pub async fn retry(&self, repo: &RepoRef, pipeline: &str, number: u64) -> Result<Execution> {
self.post(&format!(
"{}/retry",
self.execution_path(repo, pipeline, number)
))
.await
}
pub async fn cancel(&self, repo: &RepoRef, pipeline: &str, number: u64) -> Result<Execution> {
self.post(&format!(
"{}/cancel",
self.execution_path(repo, pipeline, number)
))
.await
}
pub async fn delete_execution(
&self,
repo: &RepoRef,
pipeline: &str,
number: u64,
) -> Result<()> {
self.client
.request(
Method::DELETE,
&self.execution_path(repo, pipeline, number),
None,
&[],
)
.await
.map(|_| ())
}
pub async fn get(&self, repo: &RepoRef, pipeline: &str) -> Result<Pipeline> {
self.client
.get_json(&self.pipeline_path(repo, pipeline))
.await
}
pub async fn set_disabled(
&self,
repo: &RepoRef,
pipeline: &str,
disabled: bool,
) -> Result<Pipeline> {
self.client
.request(
Method::PATCH,
&self.pipeline_path(repo, pipeline),
Some(&serde_json::json!({ "disabled": disabled })),
&[],
)
.await?
.deserialize()
}
pub async fn content(&self, repo: &RepoRef, pipeline: &str) -> Result<String> {
let value: serde_json::Value = self
.client
.get_json(&format!("{}/content", self.pipeline_path(repo, pipeline)))
.await?;
let raw = value
.get("content")
.and_then(serde_json::Value::as_str)
.unwrap_or_default();
Ok(decode_definition(raw))
}
fn pipeline_path(&self, repo: &RepoRef, pipeline: &str) -> String {
format!(
"/api/v1/repos/{}/pipelines/{}",
repo.encoded(),
urlencode(pipeline)
)
}
pub async fn trigger(
&self,
repo: &RepoRef,
pipeline: &str,
branch: Option<&str>,
) -> Result<Execution> {
let mut q = Query::new();
q.push_opt("branch", branch);
let path = format!(
"/api/v1/repos/{}/pipelines/{}/executions",
repo.encoded(),
urlencode(pipeline)
);
self.post(&q.apply(&path)).await
}
async fn post(&self, path: &str) -> Result<Execution> {
self.client
.request(Method::POST, path, None, &[])
.await?
.deserialize()
}
fn execution_path(&self, repo: &RepoRef, pipeline: &str, number: u64) -> String {
format!(
"/api/v1/repos/{}/pipelines/{}/executions/{number}",
repo.encoded(),
urlencode(pipeline)
)
}
}
fn decode_definition(raw: &str) -> String {
crate::models::decode_base64(raw)
.and_then(|bytes| String::from_utf8(bytes).ok())
.unwrap_or_else(|| raw.to_string())
}
pub(crate) fn urlencode(segment: &str) -> String {
let mut out = String::with_capacity(segment.len());
for byte in segment.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(byte as char)
}
other => out.push_str(&format!("%{other:02X}")),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn api_paths(pipeline: &str) -> (String, String) {
let client = GitFoxClient::builder("https://git.example.com")
.build()
.unwrap();
let api = PipelinesApi::new(&client);
let repo = RepoRef::parse("ai/backend").unwrap();
let execution = api.execution_path(&repo, pipeline, 182);
(execution.clone(), format!("{execution}/logs/1/2"))
}
#[test]
fn execution_and_log_paths_are_built_from_the_documented_shape() {
let (execution, logs) = api_paths("default");
assert_eq!(
execution,
"/api/v1/repos/ai%2Fbackend/pipelines/default/executions/182"
);
assert_eq!(
logs,
"/api/v1/repos/ai%2Fbackend/pipelines/default/executions/182/logs/1/2"
);
}
#[test]
fn a_pipeline_name_with_a_slash_or_space_cannot_break_out_of_its_segment() {
let (execution, _) = api_paths("team/build pipeline");
assert_eq!(
execution,
"/api/v1/repos/ai%2Fbackend/pipelines/team%2Fbuild%20pipeline/executions/182"
);
let client = GitFoxClient::builder("https://git.example.com")
.build()
.unwrap();
assert!(
client
.resolve(&execution)
.unwrap()
.as_str()
.ends_with("/pipelines/team%2Fbuild%20pipeline/executions/182")
);
}
#[test]
fn a_definition_is_decoded_from_base64_and_plain_text_passes_through() {
assert_eq!(
decode_definition("dmVyc2lvbjogMQpraW5kOiBwaXBlbGluZQo="),
"version: 1\nkind: pipeline\n"
);
assert_eq!(decode_definition("version: 1\n"), "version: 1\n");
}
#[test]
fn urlencode_leaves_ordinary_identifiers_alone() {
assert_eq!(urlencode("build-and-test_v2.1~x"), "build-and-test_v2.1~x");
}
}