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
use clap::{ArgMatches, Command};
use const_format::concatcp;

use crate::{
    cli::{
        cmds::{
            flight::SeaplaneFlightPlan,
            formation::{common, SeaplaneFormationFetch, SeaplaneFormationLaunch},
        },
        specs::{FLIGHT_SPEC, REGION_SPEC},
        CliCommand,
    },
    context::{Ctx, FlightCtx},
    error::{CliErrorKind, Context, Result},
    ops::formation::{Formation, FormationConfiguration},
    printer::Color,
};

static LONG_ABOUT: &str =
    "Make a new local Formation Plan (and optionally launch an instance of it)

Include local Flight Plans by using `--include-flight-plan`. Multiple Flights may be included in a
Formation Plan using a SEMICOLON separated list, or using the argument multiple times.

You can also create a new Flight Plan using the INLINE-SPEC option of `--include-flight-plan`.

Flight Plans created using INLINE-SPEC are automatically included in the Formation Plan.";

/// A newtype wrapper to enforce where the ArgMatches came from which reduces errors in checking if
/// values of arguments were used or not. i.e. `seaplane formation plan` may not have the same
/// arguments as `seaplane account token` even though both produce an `ArgMatches`.
#[allow(missing_debug_implementations)]
pub struct SeaplaneFormationPlanArgMatches<'a>(pub &'a ArgMatches);

#[derive(Copy, Clone, Debug)]
pub struct SeaplaneFormationPlan;

impl SeaplaneFormationPlan {
    pub fn command() -> Command<'static> {
        Command::new("plan")
            .after_help(concatcp!(FLIGHT_SPEC, "\n\n", REGION_SPEC))
            .visible_aliases(&["create", "add"])
            .override_usage("seaplane formation plan --include-flight-plan=SPEC... [OPTIONS]")
            .about("Create a Seaplane Formation")
            .long_about(LONG_ABOUT)
            .args(common::args())
            .arg(arg!(--force).help("Override any existing Formation with the same NAME"))
            .arg(arg!(--fetch|sync|synchronize - ('F')).help("Fetch remote instances prior to creating this plan to check for conflicts (by default only local references are considered)"))
    }
}

impl CliCommand for SeaplaneFormationPlan {
    fn run(&self, ctx: &mut Ctx) -> Result<()> {
        if ctx.args.fetch {
            let old_name = ctx.args.name_id.take();
            ctx.internal_run = true;
            SeaplaneFormationFetch.run(ctx)?;
            ctx.internal_run = false;
            ctx.args.name_id = old_name;
        }

        let formation_ctx = ctx.formation_ctx.get_or_init();

        // Check for duplicates and suggest `seaplane formation edit`
        let name = &formation_ctx.name_id;
        if ctx.db.formations.contains_name(name) {
            if !ctx.args.force {
                let mut err = CliErrorKind::DuplicateName(name.to_owned())
                    .into_err()
                    .context("(hint: try '")
                    .color_context(Color::Green, format!("seaplane formation edit {}", &name))
                    .context("' instead)\n");
                if ctx.db.needs_persist {
                    err = err.context("\nRolling back created Flight Plans!\n");
                }
                return Err(err);
            }

            // We have duplicates, but the user passed --force. So first we remove the existing
            // formations and "re-add" them

            // TODO: We should check if these ones we remove are referenced remote or not
            // TODO: if more than one formation has the exact same name, we remove them all; that's
            // *probably* what we want? But more thought should go into this...
            ctx.db.formations.remove_name(name);
        }

        if ctx.db.needs_persist {
            // Any flights we created in update_ctx can now be persisted. We didn't want to persist
            // them before as we could have still hit an error such as Duplicate Formation Names
            ctx.persist_flights()?;
            ctx.db.needs_persist = false;
        }

        // Add the new formation
        let mut new_formation = Formation::new(&formation_ctx.name_id);

        let cfg = formation_ctx.configuration_model(ctx)?;
        let formation_cfg = FormationConfiguration::new(cfg);
        new_formation.local.insert(formation_cfg.id);
        ctx.db.formations.configurations.push(formation_cfg);

        let id = new_formation.id.to_string();
        ctx.db.formations.formations.push(new_formation);

        ctx.persist_formations()?;

        cli_print!("Successfully created local Formation Plan '");
        cli_print!(@Green, "{}", &formation_ctx.name_id);
        cli_print!("' with ID '");
        cli_print!(@Green, "{}", &id[..8]);
        cli_println!("'");

        // Equivalent of doing 'seaplane formation launch NAME --exact'
        if formation_ctx.launch || formation_ctx.grounded {
            // Set the name of the formation for launch
            ctx.args.name_id = Some(formation_ctx.name_id.clone());
            // We only want to match this exact formation
            ctx.args.exact = true;
            // If `--fetch` was passed, we already did it, no need to do it again
            ctx.args.fetch = false;
            // release the MutexGuard
            SeaplaneFormationLaunch.run(ctx)?;
        }

        Ok(())
    }

    fn update_ctx(&self, matches: &ArgMatches, ctx: &mut Ctx) -> Result<()> {
        ctx.args.fetch = matches.contains_id("fetch");
        ctx.args.force = matches.contains_id("force");

        // Create any flights required
        let mut flights: Vec<_> = matches
            .get_many::<String>("include-flight-plan")
            .unwrap_or_default()
            .collect();

        // Flights declared with i.e. name=FOO,image=nginx:latest
        let inline_flights = vec_remove_if!(flights, |f: &str| f.contains('='));
        for flight in inline_flights {
            let mut cloned_ctx = ctx.clone();
            // We set stateless because we don't want the created flights to be persisted until
            // we're ready (i.e. we're sure this formation will be created)
            cloned_ctx.args.stateless = true;
            cloned_ctx.internal_run = true;
            cloned_ctx
                .flight_ctx
                .init(FlightCtx::from_inline_flight(flight, &ctx.registry)?);

            let flight_plan: Box<dyn CliCommand> = Box::new(SeaplaneFlightPlan);
            flight_plan.run(&mut cloned_ctx)?;

            let name = cloned_ctx.flight_ctx.get_or_init().name_id.clone();
            // copy the newly created flight out of the cloned context into the "real" one
            ctx.db
                .flights
                .add_flight(cloned_ctx.db.flights.remove_flight(&name, true).unwrap());

            // Store the newly created Flight name as if it was passed by name via
            // `--include-flight-plan FOO`
            ctx.formation_ctx
                .get_mut_or_init()
                .cfg_ctx
                .flights
                .push(name);

            ctx.db.needs_persist = true;
        }

        // Flights using @path or @-
        for name in ctx
            .db
            .flights
            .add_from_at_strs(vec_remove_if!(flights, |f: &str| f.starts_with('@')))?
        {
            ctx.formation_ctx
                .get_mut_or_init()
                .cfg_ctx
                .flights
                .push(name);
            ctx.db.needs_persist = true;
        }

        // Any flights we created will be persisted during `run` as we could still hit an error
        // such as Duplicate Formation Names and would need to roll them back

        ctx.formation_ctx
            .get_mut_or_init()
            .update_from_formation_plan(
                &SeaplaneFormationPlanArgMatches(matches),
                &ctx.db.flights,
            )?;

        Ok(())
    }
}