use crate::error::{GitLabError, Result};
use crate::models::Pipeline;
use gitlab::Gitlab;
use gitlab::api::{
Query,
projects::pipelines::{self, PipelineVariable},
};
use std::collections::HashMap;
pub struct ProjectBuilder<'a> {
client: &'a Gitlab,
project: String,
}
impl<'a> ProjectBuilder<'a> {
pub(crate) fn new(client: &'a Gitlab, project: impl Into<String>) -> Self {
Self {
client,
project: project.into(),
}
}
pub fn create_pipeline(self) -> CreatePipelineBuilder<'a> {
CreatePipelineBuilder::new(self.client, self.project)
}
}
pub struct CreatePipelineBuilder<'a> {
client: &'a Gitlab,
project: String,
ref_name: Option<String>,
variables: HashMap<String, String>,
}
impl<'a> CreatePipelineBuilder<'a> {
pub(crate) fn new(client: &'a Gitlab, project: impl Into<String>) -> Self {
Self {
client,
project: project.into(),
ref_name: None,
variables: HashMap::new(),
}
}
pub fn ref_name(mut self, ref_name: impl Into<String>) -> Self {
self.ref_name = Some(ref_name.into());
self
}
pub fn variables(mut self, variables: HashMap<String, String>) -> Self {
self.variables = variables;
self
}
pub fn variable(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.variables.insert(key.into(), value.into());
self
}
pub async fn trigger(self) -> Result<Pipeline> {
let ref_name = self
.ref_name
.ok_or_else(|| GitLabError::invalid_input("ref", "ref_name is required"))?;
let mut endpoint_builder = pipelines::CreatePipeline::builder();
endpoint_builder.project(&self.project).ref_(&ref_name);
for (key, value) in self.variables {
let var = PipelineVariable::builder()
.key(key)
.value(value)
.build()
.map_err(|e| {
GitLabError::api(format!("Failed to build pipeline variable: {}", e))
})?;
endpoint_builder.variable(var);
}
let endpoint = endpoint_builder.build().map_err(|e| {
GitLabError::api(format!("Failed to build create pipeline endpoint: {}", e))
})?;
endpoint
.query(self.client)
.map_err(|e| GitLabError::api(format!("Failed to create pipeline: {}", e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_project_builder() {
fn _compile_test(client: &Gitlab) {
let _builder = ProjectBuilder::new(client, "project");
}
}
#[test]
fn test_create_pipeline_builder() {
fn _compile_test(client: &Gitlab) {
let _builder = CreatePipelineBuilder::new(client, "project")
.ref_name("main")
.variable("KEY", "value");
}
}
}