Skip to main content

ephemeris_forge_forgejo/plan/
actions_variables.rs

1use std::collections::BTreeMap;
2
3use ephemeris_forge::{Collection, FieldDiff, Report};
4
5use crate::Live;
6use crate::api::request::{CreateVariableOption, UpdateVariableOption};
7use crate::config::ActionsVariables;
8use crate::operation::actions_variables::Operation;
9
10pub(super) fn plan(
11    config: Option<&ActionsVariables>,
12    live: &Live,
13    report: &mut Report,
14) -> Vec<Operation> {
15    let Some(config) = config else {
16        return Vec::new();
17    };
18    let wanted: BTreeMap<String, String> = config
19        .variables
20        .iter()
21        .map(|(name, value)| (name.to_ascii_uppercase(), value.replace("\r\n", "\n")))
22        .collect();
23    Collection {
24        noun: "actions variable",
25        mode: config.mode,
26    }
27    .plan(
28        &wanted,
29        &live.actions_variables,
30        report,
31        |variable, name| variable.name.as_deref() == Some(name),
32        |name, value, actual, _| {
33            let mut diff = FieldDiff::default();
34            let changed = diff.check(
35                "value",
36                actual.is_some_and(|variable| variable.data.as_deref() == Some(value.as_str())),
37                &actual.and_then(|variable| variable.data.as_deref()),
38                &value.as_str(),
39            );
40            let name = name.to_owned();
41            let value = value.clone();
42            let operations = match (changed, actual) {
43                (false, _) => Vec::new(),
44                (true, Some(_)) => vec![Operation::Update {
45                    name,
46                    body: UpdateVariableOption { value },
47                }],
48                (true, None) => vec![Operation::Create {
49                    name,
50                    body: CreateVariableOption { value },
51                }],
52            };
53            (diff, operations)
54        },
55        |variable, _| {
56            let name = variable.name.clone()?;
57            Some((name.clone(), Operation::Delete { name }))
58        },
59    )
60}