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
//! The `project` subcommand (0.2.0): manage **projects** — the owning Workspace above
//! sites/functions/compute. `create` / `ls` / `show` / `rm` over the control-plane
//! `/api/projects` surface. Scoping *other* commands to a project is the global
//! `--project` flag (resolved in `main`), not here.
use clap::Subcommand;
use crate::client;
use crate::config::ProjectConfig;
/// A failure in the `project` subcommand.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Talking to the control plane failed.
#[error(transparent)]
Client(#[from] crate::client::ClientError),
/// Serializing the create request failed.
#[error("serializing the project request failed: {0}")]
Serde(#[from] serde_json::Error),
/// Reading/writing the confirmation prompt failed.
#[error("prompt I/O failed: {0}")]
Io(std::io::Error),
/// The operator aborted (or could not be prompted for) a destructive delete.
#[error("{0}")]
Aborted(String),
}
/// `project` module result; `Err` is [`Error`].
type Result<T> = std::result::Result<T, Error>;
/// Arguments for `boatramp project`.
#[derive(Debug, clap::Args)]
pub struct ProjectArgs {
/// boatramp server base URL (overrides `[deploy].server`).
#[arg(long, env = "BOATRAMP_SERVER", global = true)]
server: Option<String>,
#[command(subcommand)]
command: ProjectCommand,
}
#[derive(Debug, Subcommand)]
enum ProjectCommand {
/// Create a new project.
Create {
/// The project slug (unique, no `/`).
name: String,
/// Human display name (defaults to the slug).
#[arg(long)]
display: Option<String>,
/// Free-text description.
#[arg(long)]
description: Option<String>,
/// Default region for the project's compute/replicas.
#[arg(long)]
region: Option<String>,
},
/// List all projects.
Ls,
/// Show one project's full record.
Show {
/// The project slug.
name: String,
},
/// Delete a project. Refused while it owns resources (unless `--force`) or if it
/// is the reserved `default`.
Rm {
/// The project slug.
name: String,
/// Cascade: tear down **everything** the project owns (sites, functions,
/// compute + their volumes, secrets, GraphQL registry) and remove the project.
/// Destructive and irreversible.
#[arg(long)]
force: bool,
/// Preview what a delete would remove and exit — mutate nothing.
#[arg(long)]
dry_run: bool,
/// Skip the interactive confirmation prompt (required to `--force` when stdin
/// is not a TTY).
#[arg(long, short = 'y')]
yes: bool,
},
}
/// Whether a `--force` confirmation `typed` at the prompt authorizes deleting
/// `project` — an exact match (after trimming surrounding whitespace/newline) of the
/// project name. A pure function so the confirmation gate is unit-testable without a
/// TTY.
fn confirmation_matches(project: &str, typed: &str) -> bool {
typed.trim() == project
}
/// A one-line human summary of a teardown [plan](crate::client) for the operator, e.g.
/// `project \`x\` owns: 2 sites (a, b), 1 function (f), 1 compute (pg + volume pg-data), 3 secrets`.
/// Reads the fields defensively from the plan JSON so a server that adds fields does
/// not break the CLI.
fn summarize_plan(name: &str, plan: &serde_json::Value) -> String {
let arr = |k: &str| -> Vec<String> {
plan.get(k)
.and_then(|v| v.as_array())
.map(|a| {
a.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default()
};
let mut parts: Vec<String> = Vec::new();
let sites = arr("sites");
if !sites.is_empty() {
parts.push(format!(
"{} site{} ({})",
sites.len(),
if sites.len() == 1 { "" } else { "s" },
sites.join(", ")
));
}
let functions = arr("functions");
if !functions.is_empty() {
parts.push(format!(
"{} function{} ({})",
functions.len(),
if functions.len() == 1 { "" } else { "s" },
functions.join(", ")
));
}
if let Some(compute) = plan.get("compute").and_then(|v| v.as_array()) {
if !compute.is_empty() {
let items: Vec<String> = compute
.iter()
.map(|c| {
let cname = c.get("name").and_then(|v| v.as_str()).unwrap_or("?");
let vols: Vec<&str> = c
.get("volumes")
.and_then(|v| v.as_array())
.map(|a| a.iter().filter_map(|v| v.as_str()).collect())
.unwrap_or_default();
if vols.is_empty() {
cname.to_string()
} else {
format!(
"{cname} + volume{} {}",
if vols.len() == 1 { "" } else { "s" },
vols.join(", ")
)
}
})
.collect();
parts.push(format!("{} compute ({})", compute.len(), items.join("; ")));
}
}
let secrets = arr("secrets");
if !secrets.is_empty() {
parts.push(format!(
"{} secret{}",
secrets.len(),
if secrets.len() == 1 { "" } else { "s" }
));
}
if let Some(n) = plan.get("safelist").and_then(serde_json::Value::as_u64) {
if n > 0 {
parts.push(format!(
"{n} graphql safelist entr{}",
if n == 1 { "y" } else { "ies" }
));
}
}
let subgraphs = arr("subgraphs");
if !subgraphs.is_empty() {
parts.push(format!(
"{} subgraph{} ({})",
subgraphs.len(),
if subgraphs.len() == 1 { "" } else { "s" },
subgraphs.join(", ")
));
}
if let Some(other) = plan.get("other_families").and_then(|v| v.as_object()) {
for (family, count) in other {
let c = count.as_u64().unwrap_or(0);
parts.push(format!("{c} {family} key{}", if c == 1 { "" } else { "s" }));
}
}
if parts.is_empty() {
format!("project `{name}` owns nothing")
} else {
format!("project `{name}` owns: {}", parts.join(", "))
}
}
/// Entry point for `boatramp project`.
pub async fn run(args: ProjectArgs, config: &ProjectConfig) -> Result<()> {
let (server, http) = client::connect(args.server, config)?;
// The `project` subcommand only calls project-collection endpoints (list/create/
// get/delete), which are not site-scoped, so the resolved project is inert here —
// passed only to satisfy the constructor.
let cp = client::ControlPlane::new(server, http, client::resolve_project(config));
match args.command {
ProjectCommand::Create {
name,
display,
description,
region,
} => {
let mut body = serde_json::Map::new();
body.insert("name".into(), serde_json::Value::String(name.clone()));
if let Some(d) = display {
body.insert("display".into(), serde_json::Value::String(d));
}
if let Some(d) = description {
body.insert("description".into(), serde_json::Value::String(d));
}
if let Some(r) = region {
body.insert("region".into(), serde_json::Value::String(r));
}
cp.create_project(&serde_json::Value::Object(body)).await?;
println!("created project `{name}`");
}
ProjectCommand::Ls => {
let projects = cp.list_projects().await?;
if projects.is_empty() {
println!("no projects");
} else {
for p in projects {
let name = p.get("name").and_then(|v| v.as_str()).unwrap_or("?");
let display = p
.get("meta")
.and_then(|m| m.get("display"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty());
match display {
Some(d) => println!("{name}\t{d}"),
None => println!("{name}"),
}
}
}
}
ProjectCommand::Show { name } => {
let project = cp.get_project(&name).await?;
println!("{}", serde_json::to_string_pretty(&project)?);
}
ProjectCommand::Rm {
name,
force,
dry_run,
yes,
} => {
if dry_run {
// Preview only — mutate nothing.
let plan = cp.project_teardown_plan(&name).await?;
println!(
"{} — nothing deleted (--dry-run)",
summarize_plan(&name, &plan)
);
} else if force {
// Always show the plan first, then require confirmation unless -y.
let plan = cp.project_teardown_plan(&name).await?;
println!("{}", summarize_plan(&name, &plan));
if !yes {
if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
return Err(Error::Aborted(
"refusing to force-delete non-interactively; pass --yes to confirm"
.to_string(),
));
}
use std::io::Write;
print!(
"this permanently destroys the above and cannot be undone; \
type the project name to confirm: "
);
std::io::stdout().flush().map_err(Error::Io)?;
let mut typed = String::new();
std::io::stdin().read_line(&mut typed).map_err(Error::Io)?;
if !confirmation_matches(&name, &typed) {
return Err(Error::Aborted(format!(
"confirmation `{}` does not match project `{name}` — aborted",
typed.trim()
)));
}
}
let report = cp.force_delete_project(&name).await?;
println!("force-deleted {}", summarize_plan(&name, &report));
} else {
match cp.delete_project(&name).await {
Ok(()) => println!("deleted project `{name}`"),
// The server's `409` enumerated refusal, printed verbatim plus a
// hint to cascade instead.
Err(crate::client::ClientError::Refused(msg)) => {
return Err(Error::Aborted(format!(
"{msg}\n… or `project rm {name} --force` to cascade the teardown"
)));
}
Err(e) => return Err(e.into()),
}
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
/// A minimal top-level parser mirroring `main`'s `project` arm, so the
/// `project rm …` flag surface can be arg-parsed in isolation.
#[derive(Parser)]
struct Cli {
#[command(subcommand)]
cmd: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
Project(ProjectArgs),
}
fn parse(argv: &[&str]) -> std::result::Result<ProjectCommand, clap::Error> {
let cli = Cli::try_parse_from(std::iter::once("boatramp").chain(argv.iter().copied()))?;
let Cmd::Project(args) = cli.cmd;
Ok(args.command)
}
#[test]
fn rm_flags_parse() {
// Bare `rm <name>` → no force, no dry-run, no yes.
match parse(&["project", "rm", "acme"]) {
Ok(ProjectCommand::Rm {
name,
force,
dry_run,
yes,
}) => {
assert_eq!(name, "acme");
assert!(!force && !dry_run && !yes);
}
other => panic!("expected rm, got {other:?}"),
}
// `--force --dry-run -y` all set (short `-y` for `--yes`).
match parse(&["project", "rm", "acme", "--force", "--dry-run", "-y"]) {
Ok(ProjectCommand::Rm {
force,
dry_run,
yes,
..
}) => {
assert!(force && dry_run && yes);
}
other => panic!("expected rm with flags, got {other:?}"),
}
// `--yes` long form.
match parse(&["project", "rm", "acme", "--yes"]) {
Ok(ProjectCommand::Rm { yes, .. }) => assert!(yes),
other => panic!("expected rm --yes, got {other:?}"),
}
// `rm` requires a name.
assert!(parse(&["project", "rm"]).is_err());
}
#[test]
fn confirmation_match_is_exact_after_trim() {
// An exact typed name (with the trailing newline stdin leaves) authorizes.
assert!(confirmation_matches("acme", "acme\n"));
assert!(confirmation_matches("acme", " acme "));
// Any mismatch aborts.
assert!(!confirmation_matches("acme", "acm"));
assert!(!confirmation_matches("acme", "acme-prod"));
assert!(!confirmation_matches("acme", ""));
assert!(!confirmation_matches("acme", "Acme"));
}
#[test]
fn summarize_plan_reads_families() {
let plan = serde_json::json!({
"project": "x",
"sites": ["a", "b"],
"functions": ["f"],
"compute": [{ "name": "pg", "volumes": ["pg-data"] }],
"secrets": ["s1", "s2", "s3"],
"safelist": 2,
"subgraphs": ["users"],
"other_families": {}
});
let s = summarize_plan("x", &plan);
assert!(s.contains("2 sites (a, b)"), "{s}");
assert!(s.contains("1 function (f)"), "{s}");
assert!(s.contains("pg + volume pg-data"), "{s}");
assert!(s.contains("3 secrets"), "{s}");
assert!(s.contains("2 graphql safelist entries"), "{s}");
assert!(s.contains("1 subgraph (users)"), "{s}");
// An empty plan says so.
let empty = serde_json::json!({ "project": "x" });
assert_eq!(summarize_plan("x", &empty), "project `x` owns nothing");
}
}