1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use crate::{
    build_request,
    error::{surf_to_tool_error, ToolError},
    set_page_number,
    settings::Core,
    variable::{Variable, VariablesOuter},
    workspace::Workspace,
    Meta, BASE_URL,
};
use async_scoped::AsyncScope;
use log::{error, info};
use serde::{Deserialize, Serialize};
use serde_json::json;
use surf::{http::Method, Client};
use url::Url;

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Attributes {
    pub name: String,
    pub description: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global: Option<bool>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Workspaces {
    #[serde(rename = "type")]
    pub relationship_type: String,
    pub id: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct WorkspacesOuter {
    pub data: Vec<Workspaces>,
}

impl From<Vec<Workspace>> for WorkspacesOuter {
    fn from(workspaces: Vec<Workspace>) -> Self {
        Self {
            data: workspaces
                .into_iter()
                .map(|ws| Workspaces {
                    relationship_type: "workspaces".to_string(),
                    id: ws.id,
                })
                .collect(),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Projects {
    #[serde(rename = "type")]
    pub relationship_type: String,
    pub id: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ProjectsOuter {
    pub data: Vec<Projects>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Relationships {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspaces: Option<WorkspacesOuter>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub projects: Option<ProjectsOuter>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vars: Option<VariablesOuter>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct VarSet {
    #[serde(rename = "type")]
    pub relationship_type: String,
    pub attributes: Attributes,
    pub relationships: Relationships,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct VarSets {
    pub data: Vec<VarSet>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
}

impl VarSets {
    pub fn new(var_sets: Vec<VarSet>) -> Self {
        VarSets { data: var_sets, meta: None }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct VarSetOuter {
    pub data: VarSet,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct VarSetOptions {
    pub name: String,
    pub description: String,
    pub global: Option<bool>,
    pub workspaces: Option<Vec<Workspace>>,
    pub projects: Option<Vec<String>>,
    pub vars: Option<Vec<Variable>>,
}

impl VarSetOuter {
    pub fn new(options: VarSetOptions) -> Self {
        Self {
            data: VarSet {
                relationship_type: "vars".to_string(),
                attributes: Attributes {
                    name: options.name.to_string(),
                    description: options.description.to_string(),
                    global: options.global,
                },
                relationships: Relationships {
                    workspaces: options.workspaces.map(|ws| WorkspacesOuter {
                        data: ws
                            .into_iter()
                            .map(|ws| Workspaces {
                                relationship_type: "workspaces".to_string(),
                                id: ws.id,
                            })
                            .collect(),
                    }),
                    projects: options.projects.map(|p| ProjectsOuter {
                        data: p
                            .into_iter()
                            .map(|p| Projects {
                                relationship_type: "projects".to_string(),
                                id: p,
                            })
                            .collect(),
                    }),
                    vars: options.vars.map(|v| VariablesOuter { data: v }),
                },
            },
        }
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct ApplyVarSet {
    #[serde(rename = "type")]
    pub relationship_type: String,
    pub id: String,
}

#[derive(Clone, Debug, Serialize)]
struct ApplyVarSetOuter {
    pub data: Vec<ApplyVarSet>,
}

impl From<Vec<Workspace>> for ApplyVarSetOuter {
    fn from(workspaces: Vec<Workspace>) -> Self {
        Self {
            data: workspaces
                .into_iter()
                .map(|ws| ApplyVarSet {
                    relationship_type: "workspaces".to_string(),
                    id: ws.id,
                })
                .collect(),
        }
    }
}

async fn check_pagination(
    meta: Meta,
    var_set_list: &mut VarSets,
    url: Url,
    config: &Core,
    client: Client,
) -> Result<(), ToolError> {
    let max_depth = config.pagination.max_depth.parse::<u32>()?;
    if max_depth > 1 || max_depth == 0 {
        let current_depth: u32 = 1;
        if let Some(next_page) = meta.pagination.next_page {
            if max_depth == 0 || current_depth < max_depth {
                let num_pages: u32 = if max_depth >= meta.pagination.total_pages
                    || max_depth == 0
                {
                    meta.pagination.total_pages
                } else {
                    max_depth
                };

                // Get the next page and merge the result
                let (_, var_set_pages) = AsyncScope::scope_and_block(|s| {
                    for n in next_page..=num_pages {
                        let c = client.clone();
                        let u = url.clone();
                        let proc = || async move {
                            info!("Retrieving variable set page {}.", &n);
                            let u = match set_page_number(n, u) {
                                Some(u) => u,
                                None => {
                                    error!("Failed to set page number.");
                                    return None;
                                }
                            };
                            let req = build_request(
                                Method::Get,
                                u.clone(),
                                config,
                                None,
                            );
                            match c.send(req).await {
                                Ok(mut s) => {
                                    info!(
                                                "Successfully retrieved variable set page {}!",
                                                &n
                                            );
                                    let res =
                                        match s.body_json::<VarSets>().await {
                                            Ok(r) => r,
                                            Err(e) => {
                                                error!("{:#?}", e);
                                                return None;
                                            }
                                        };
                                    Some(res.data)
                                }
                                Err(e) => {
                                    error!(
                                                "Failed to retrieve variable set page {} :(",
                                                &n
                                            );
                                    error!("{:#?}", e);
                                    None
                                }
                            }
                        };
                        s.spawn(proc());
                    }
                });
                for mut t in var_set_pages.into_iter().flatten() {
                    var_set_list.data.append(&mut t);
                }
            }
        }
    }
    Ok(())
}

pub async fn show(
    variable_set_id: &str,
    config: &Core,
    client: Client,
) -> Result<VarSet, ToolError> {
    let url = Url::parse(&format!("{}/varsets/{}", BASE_URL, variable_set_id))?;
    let req = build_request(Method::Get, url, config, None);
    let mut res = client.send(req).await.map_err(surf_to_tool_error)?;
    if res.status().is_success() {
        let var_set: VarSetOuter =
            res.body_json().await.map_err(surf_to_tool_error)?;
        Ok(var_set.data)
    } else {
        error!("Failed to show variable set");
        let error = res.body_string().await.map_err(surf_to_tool_error)?;
        Err(ToolError::General(anyhow::anyhow!(error)))
    }
}

pub async fn list_by_org(
    config: &Core,
    client: Client,
) -> Result<VarSets, ToolError> {
    info!(
        "Retrieving the initial list of variable sets for org {}.",
        config.org
    );
    let params = vec![
        ("page[size]", config.pagination.page_size.clone()),
        ("page[number]", config.pagination.start_page.clone()),
    ];
    let url = Url::parse_with_params(
        &format!("{}/organizations/{}/varsets", BASE_URL, config.org),
        &params,
    )?;
    let req = build_request(Method::Get, url.clone(), config, None);
    let mut var_set_list: VarSets = match client.send(req).await {
        Ok(mut res) => {
            info!("Variable sets for org {} retrieved.", config.org);
            match res.body_json().await {
                Ok(t) => t,
                Err(e) => {
                    error!("{:#?}", e);
                    return Err(ToolError::General(anyhow::anyhow!(e)));
                }
            }
        }
        Err(e) => {
            error!("Failed to fetch variable sets for org {}.", config.org);
            return Err(ToolError::General(anyhow::anyhow!(e)));
        }
    };
    // Need to check pagination
    if let Some(meta) = var_set_list.meta.clone() {
        check_pagination(meta, &mut var_set_list, url, config, client).await?;
    }
    info!("Finished retrieving variable sets.");
    Ok(var_set_list)
}

pub async fn list_by_project(
    config: &Core,
    client: Client,
) -> Result<VarSets, ToolError> {
    if config.project.clone().is_none() {
        return Err(ToolError::General(anyhow::anyhow!(
            "No project specified in config"
        )));
    }
    let project_id = config.project.clone().unwrap();
    info!(
        "Retrieving the initial list of variable sets for project {}.",
        project_id
    );
    let params = vec![
        ("page[size]", config.pagination.page_size.clone()),
        ("page[number]", config.pagination.start_page.clone()),
    ];
    let url = Url::parse_with_params(
        &format!("{}/projects/{}/varsets", BASE_URL, project_id),
        &params,
    )?;
    let req = build_request(Method::Get, url.clone(), config, None);
    let mut var_set_list: VarSets = match client.send(req).await {
        Ok(mut res) => {
            info!("Variable sets for project {} retrieved.", project_id);
            match res.body_json().await {
                Ok(t) => t,
                Err(e) => {
                    error!("{:#?}", e);
                    return Err(ToolError::General(anyhow::anyhow!(e)));
                }
            }
        }
        Err(e) => {
            error!("Failed to fetch variable sets for project {}.", project_id);
            return Err(ToolError::General(anyhow::anyhow!(e)));
        }
    };
    // Need to check pagination
    if let Some(meta) = var_set_list.meta.clone() {
        check_pagination(meta, &mut var_set_list, url, config, client).await?;
    }
    info!("Finished retrieving variable sets.");
    Ok(var_set_list)
}

pub async fn create(
    options: VarSetOptions,
    config: &Core,
    client: Client,
) -> Result<(), ToolError> {
    let url = Url::parse(&format!(
        "{}/organizations/{}/varsets",
        BASE_URL, config.org
    ))?;
    let req = build_request(
        Method::Post,
        url,
        config,
        Some(json!(VarSetOuter::new(options))),
    );
    let mut res = client.send(req).await.map_err(surf_to_tool_error)?;
    if res.status().is_success() {
        info!("Successfully created variable set");
    } else {
        error!("Failed to create variable set");
        let error = res.body_string().await.map_err(surf_to_tool_error)?;
        return Err(ToolError::General(anyhow::anyhow!(error)));
    }
    Ok(())
}

pub async fn apply_workspace(
    variable_set_id: &str,
    workspaces: Vec<Workspace>,
    config: &Core,
    client: Client,
) -> Result<(), ToolError> {
    let url = Url::parse(&format!(
        "{}/varsets/{}/relationships/workspaces",
        BASE_URL, variable_set_id
    ))?;
    let req = build_request(
        Method::Post,
        url,
        config,
        Some(json!(ApplyVarSetOuter::from(workspaces))),
    );
    let mut res = client.send(req).await.map_err(surf_to_tool_error)?;
    if res.status().is_success() {
        info!("Successfully applied workspaces to variable set");
    } else {
        error!("Failed to apply workspaces to variable set");
        let error = res.body_string().await.map_err(surf_to_tool_error)?;
        return Err(ToolError::General(anyhow::anyhow!(error)));
    }
    Ok(())
}

pub async fn remove_workspace(
    variable_set_id: &str,
    workspaces: Vec<Workspace>,
    config: &Core,
    client: Client,
) -> Result<(), ToolError> {
    let url = Url::parse(&format!(
        "{}/varsets/{}/relationships/workspaces",
        BASE_URL, variable_set_id
    ))?;
    let req = build_request(
        Method::Delete,
        url,
        config,
        Some(json!(WorkspacesOuter::from(workspaces))),
    );
    let mut res = client.send(req).await.map_err(surf_to_tool_error)?;
    if res.status().is_success() {
        info!("Successfully removed workspace from variable set");
    } else {
        error!("Failed to remove workspace from variable set");
        let error = res.body_string().await.map_err(surf_to_tool_error)?;
        return Err(ToolError::General(anyhow::anyhow!(error)));
    }
    Ok(())
}