stackify_docker_api/opts/
config.rs

1use crate::models::{Driver, Labels};
2use crate::{Error, Result};
3use containers_api::opts::{Filter, FilterItem};
4use containers_api::{impl_filter_func, impl_opts_builder};
5use serde::{Deserialize, Serialize};
6
7impl_opts_builder!(url => ConfigList);
8
9pub enum ConfigFilter {
10    /// The ID of the config.
11    Id(String),
12    /// Label in the form of `label=key`
13    LabelKey(String),
14    /// Label in the form of `label=key=val`
15    Label(String, String),
16    /// The name of the config.
17    Name(String),
18    Names(String),
19}
20
21impl Filter for ConfigFilter {
22    fn query_item(&self) -> FilterItem {
23        use ConfigFilter::*;
24        match &self {
25            Id(id) => FilterItem::new("id", id.to_owned()),
26            LabelKey(label) => FilterItem::new("label", label.to_owned()),
27            Label(key, val) => FilterItem::new("label", format!("{key}={val}")),
28            Name(name) => FilterItem::new("name", name.to_owned()),
29            Names(names) => FilterItem::new("names", names.to_owned()),
30        }
31    }
32}
33
34impl ConfigListOptsBuilder {
35    impl_filter_func!(
36        /// Filter listed configs by variants of the enum.
37        ConfigFilter
38    );
39}
40
41#[derive(Clone, Debug, Serialize, Deserialize)]
42#[serde(rename_all = "PascalCase")]
43/// Structure used to create a new config with [`Configs::create`](crate::Configs::create).
44pub struct ConfigCreateOpts {
45    name: String,
46    labels: Labels,
47    data: String,
48    templating: Driver,
49}
50
51impl ConfigCreateOpts {
52    /// Create a new config with name and data. This function will take care of
53    /// encoding the config's data as base64.
54    pub fn new<N, D>(name: N, data: D) -> Self
55    where
56        N: Into<String>,
57        D: AsRef<str>,
58    {
59        Self {
60            name: name.into(),
61            labels: Labels::new(),
62            data: base64::encode(data.as_ref()),
63            templating: Driver {
64                name: "".into(),
65                options: None,
66            },
67        }
68    }
69
70    /// Set the templating driver of this config.
71    pub fn set_templating(mut self, driver: Driver) -> Self {
72        self.templating = driver;
73        self
74    }
75
76    /// Add a label to this config
77    pub fn add_label<K, V>(mut self, key: K, val: V) -> Self
78    where
79        K: Into<String>,
80        V: Into<String>,
81    {
82        self.labels.insert(key.into(), val.into());
83        self
84    }
85
86    pub fn serialize(&self) -> Result<String> {
87        serde_json::to_string(&self).map_err(Error::from)
88    }
89
90    pub fn serialize_vec(&self) -> Result<Vec<u8>> {
91        serde_json::to_vec(&self).map_err(Error::from)
92    }
93}