1use camino::{Utf8Path, Utf8PathBuf};
13
14use super::manifest::{self, Alignment};
15use crate::cli::Commands;
16use crate::cli::branches::BranchesAction;
17use crate::cli::issue::IssueAction;
18use crate::cli::lines::LinesAction;
19use crate::cli::migrate::MigrateAction;
20use crate::cli::release::ReleaseAction;
21use crate::cli::setup::SetupAction;
22use crate::cli::stage::StageAction;
23use crate::cli::worktree::WorktreeAction;
24use crate::diagnostic::{Diagnostic, Reason};
25use crate::error::RkError;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Class {
30 Exempt,
32 PreLanding,
35 Upgrade,
37 ReadOnly,
39 Writing,
41}
42
43impl Class {
44 #[must_use]
46 pub const fn as_str(self) -> &'static str {
47 match self {
48 Self::Exempt => "exempt",
49 Self::PreLanding => "pre-landing",
50 Self::Upgrade => "upgrade",
51 Self::ReadOnly => "read-only",
52 Self::Writing => "writing",
53 }
54 }
55}
56
57pub const CLASSES: &[(&str, Class)] = &[
63 ("method", Class::Exempt),
64 ("binding", Class::Exempt),
65 ("snippet", Class::Exempt),
66 ("guide", Class::Exempt),
67 ("forge", Class::Exempt),
68 ("versions", Class::Exempt),
69 ("init", Class::PreLanding),
70 ("profile", Class::PreLanding),
71 ("status", Class::Exempt),
72 ("upgrade", Class::Upgrade),
73 ("adopt", Class::PreLanding),
74 ("assess", Class::PreLanding),
75 ("stage", Class::PreLanding),
76 ("stage clean", Class::Exempt),
77 ("stage compare", Class::PreLanding),
78 ("setup", Class::PreLanding),
79 ("setup check", Class::PreLanding),
80 ("setup checkpoint", Class::PreLanding),
81 ("setup status", Class::PreLanding),
82 ("setup step", Class::PreLanding),
83 ("setup script", Class::Exempt),
84 ("branches prune", Class::Writing),
85 ("lines list", Class::ReadOnly),
86 ("lines open", Class::Writing),
87 ("lines mint", Class::Writing),
88 ("lines rc", Class::ReadOnly),
89 ("lines retire", Class::Writing),
90 ("release status", Class::ReadOnly),
91 ("release merge", Class::Writing),
92 ("release request", Class::Writing),
93 ("release build", Class::Writing),
94 ("release eligible", Class::ReadOnly),
95 ("release publish", Class::Writing),
96 ("integrate", Class::Writing),
97 ("message", Class::ReadOnly),
98 ("migrate inventory", Class::PreLanding),
99 ("migrate archive", Class::PreLanding),
100 ("migrate mark", Class::PreLanding),
101 ("migrate status", Class::PreLanding),
102 ("migrate close", Class::PreLanding),
103 ("worktree list", Class::ReadOnly),
104 ("worktree add", Class::Writing),
105 ("worktree prune", Class::Writing),
106 ("issue start", Class::Writing),
107 ("runs", Class::Exempt),
108 ("skill", Class::Exempt),
109 ("self-depend", Class::Exempt),
110 ("doctor", Class::Exempt),
111 ("usage", Class::Exempt),
112 ("license", Class::Exempt),
113 ("completions", Class::Exempt),
114];
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum Effect {
119 ReadOnly,
121 Writing,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct Gated {
128 pub class: Class,
130 pub effect: Effect,
132 pub target: Utf8PathBuf,
134}
135
136const fn effect(apply: bool) -> Effect {
137 if apply {
138 Effect::Writing
139 } else {
140 Effect::ReadOnly
141 }
142}
143
144#[allow(
145 clippy::unnecessary_wraps,
146 reason = "every arm of classify answers an Option, and this builds the Some arm"
147)]
148fn gated(class: Class, effect: Effect, target: &Utf8Path) -> Option<Gated> {
149 Some(Gated {
150 class,
151 effect,
152 target: target.to_owned(),
153 })
154}
155
156#[must_use]
160pub fn classify(command: &Commands) -> Option<Gated> {
161 use Class::{PreLanding, ReadOnly, Writing};
162 use Effect::{ReadOnly as Reads, Writing as Writes};
163 match command {
164 Commands::Method(_)
165 | Commands::Binding(_)
166 | Commands::Snippet(_)
167 | Commands::Guide(_)
168 | Commands::Forge(_)
169 | Commands::Versions(_)
170 | Commands::Status(_)
171 | Commands::Upgrade(_)
172 | Commands::Runs(_)
173 | Commands::Skill(_)
174 | Commands::SelfDepend(_)
175 | Commands::Doctor(_)
176 | Commands::Usage
177 | Commands::License
178 | Commands::Completions(_) => None,
179 Commands::Init(args) => gated(PreLanding, effect(args.apply), &args.target),
180 Commands::Adopt(args) => gated(PreLanding, effect(args.apply), &args.target),
181 Commands::Profile(args) => gated(PreLanding, Reads, &args.target),
182 Commands::Assess(args) => gated(PreLanding, Reads, &args.target),
183 Commands::Stage(args) => match &args.action {
184 None => gated(PreLanding, Reads, &args.target),
185 Some(StageAction::Clean { .. }) => None,
186 Some(StageAction::Compare { target, .. }) => gated(PreLanding, Reads, target),
187 },
188 Commands::Setup(args) => match &args.action {
189 None if args.list => None,
190 None => args
191 .target
192 .as_deref()
193 .and_then(|target| gated(PreLanding, effect(args.apply), target)),
194 Some(SetupAction::Check { target, .. } | SetupAction::Status { target, .. }) => {
195 gated(PreLanding, Reads, target)
196 }
197 Some(SetupAction::Checkpoint { target, .. }) => gated(PreLanding, Writes, target),
198 Some(SetupAction::Step { target, apply, .. }) => {
199 gated(PreLanding, effect(*apply), target)
200 }
201 Some(SetupAction::Script { .. }) => None,
202 },
203 Commands::Migrate(args) => match &args.action {
204 MigrateAction::Inventory { target, .. } | MigrateAction::Status { target, .. } => {
205 gated(PreLanding, Reads, target)
206 }
207 MigrateAction::Archive { target, apply, .. }
208 | MigrateAction::Close { target, apply, .. } => {
209 gated(PreLanding, effect(*apply), target)
210 }
211 MigrateAction::Mark { target, .. } => gated(PreLanding, Writes, target),
212 },
213 Commands::Branches(args) => match &args.action {
214 BranchesAction::Prune { target, apply, .. } => gated(Writing, effect(*apply), target),
215 },
216 Commands::Lines(args) => match &args.action {
217 LinesAction::List { target, .. } | LinesAction::Rc { target, .. } => {
218 gated(ReadOnly, Reads, target)
219 }
220 LinesAction::Open { target, apply, .. }
221 | LinesAction::Mint { target, apply, .. }
222 | LinesAction::Retire { target, apply, .. } => gated(Writing, effect(*apply), target),
223 },
224 Commands::Release(args) => match &args.action {
225 ReleaseAction::Status { target, .. } | ReleaseAction::Eligible { target, .. } => {
226 gated(ReadOnly, Reads, target)
227 }
228 ReleaseAction::Merge { target, apply, .. } => gated(Writing, effect(*apply), target),
229 ReleaseAction::Request { target, .. } | ReleaseAction::Publish { target, .. } => {
230 gated(Writing, Writes, target)
231 }
232 ReleaseAction::Build { target, list, .. } => gated(Writing, effect(!*list), target),
233 },
234 Commands::Integrate(args) => gated(Writing, effect(args.apply), &args.target),
235 Commands::Message(args) => gated(ReadOnly, Reads, &args.target),
236 Commands::Worktree(args) => match &args.action {
237 WorktreeAction::List { target, .. } => gated(ReadOnly, Reads, target),
238 WorktreeAction::Add { target, apply, .. }
239 | WorktreeAction::Prune { target, apply, .. } => gated(Writing, effect(*apply), target),
240 },
241 Commands::Issue(args) => match &args.action {
242 IssueAction::Start { target, apply, .. } => gated(Writing, effect(*apply), target),
243 },
244 }
245}
246
247pub fn require_aligned(command: &Commands) -> Result<(), RkError> {
257 let Some(gated) = classify(command) else {
258 return Ok(());
259 };
260 if !gated.target.is_dir() {
263 return Ok(());
264 }
265 if let Commands::Integrate(args) = command
269 && let Some(recorded) = branch_record_version(&gated.target, &args.branch)
270 {
271 return judge_branch(&gated, &args.branch, &recorded);
272 }
273 let Ok(loaded) = manifest::load(&gated.target) else {
276 return Ok(());
277 };
278 let Some(record) = loaded else {
279 if gated.class == Class::PreLanding {
280 return Ok(());
281 }
282 return Err(no_record(&gated.target));
283 };
284 let binary = env!("CARGO_PKG_VERSION");
285 let recorded = record.rk_version.as_str();
286 match manifest::alignment(recorded, binary) {
287 Alignment::Aligned => Ok(()),
288 Alignment::BinaryNewer => {
289 let pin = crate::self_depend::pinned_version(&gated.target);
290 let outside = pin
291 .as_deref()
292 .is_some_and(|pin| manifest::alignment(pin, binary) == Alignment::BinaryNewer);
293 if gated.effect == Effect::ReadOnly {
294 crate::output::Output::human().warn(binary_newer_warning(recorded, outside));
295 return Ok(());
296 }
297 Err(binary_newer(&gated.target, recorded, outside))
298 }
299 Alignment::TargetNewer => {
300 let pin = crate::self_depend::pinned_version(&gated.target)
301 .filter(|pin| manifest::alignment(recorded, pin) == Alignment::TargetNewer);
302 Err(record_newer(&gated.target, recorded, pin.as_deref()))
303 }
304 }
305}
306
307fn branch_record_version(target: &Utf8Path, branch: &str) -> Option<String> {
313 let out = std::process::Command::new(crate::probes::git_bin())
314 .arg("-C")
315 .arg(target)
316 .args([
317 "show",
318 &format!("refs/heads/{branch}:{}", manifest::MANIFEST_PATH),
319 ])
320 .output()
321 .ok()?;
322 if !out.status.success() {
323 return None;
324 }
325 let value: serde_json::Value = serde_json::from_slice(&out.stdout).ok()?;
326 value["rk_version"].as_str().map(str::to_owned)
327}
328
329fn seat_of(target: &Utf8Path, branch: &str) -> Option<Utf8PathBuf> {
331 let out = std::process::Command::new(crate::probes::git_bin())
332 .arg("-C")
333 .arg(target)
334 .args(["worktree", "list", "--porcelain", "-z"])
335 .output()
336 .ok()?;
337 crate::worktree::parse_worktrees(&out.stdout)
338 .ok()?
339 .into_iter()
340 .find(|seat| seat.branch.as_deref() == Some(branch))
341 .map(|seat| seat.path)
342}
343
344fn judge_branch(gated: &Gated, branch: &str, recorded: &str) -> Result<(), RkError> {
347 let binary = env!("CARGO_PKG_VERSION");
348 let seat = seat_of(&gated.target, branch)
349 .map_or_else(|| "<worktree>".to_owned(), |seat| seat.to_string());
350 let target = &gated.target;
351 match manifest::alignment(recorded, binary) {
352 Alignment::Aligned => Ok(()),
353 Alignment::BinaryNewer => {
354 let warning = format!(
355 "branch {branch} records rk {recorded} and this rk is {binary}; run `rk upgrade --target {seat} --apply` on the branch and commit it"
356 );
357 if gated.effect == Effect::ReadOnly {
358 crate::output::Output::human().warn(warning);
359 return Ok(());
360 }
361 Err(RkError::refusal(
362 Diagnostic::new(Reason::StateDrift, warning)
363 .expected("a binary at the rk_version of the branch's record")
364 .action(format!(
365 "run `rk upgrade --target {seat} --apply` in the branch's worktree, commit the landing, then run this command again. Where the branch pins rk {recorded}, {OWN_RK}"
366 ))
367 .target_state("unchanged"),
368 ))
369 }
370 Alignment::TargetNewer => Err(RkError::refusal(
371 Diagnostic::new(
372 Reason::StateDrift,
373 format!(
374 "branch {branch} records rk {recorded} and this rk is {binary}, which is older"
375 ),
376 )
377 .expected("a binary at the rk_version of the branch's record")
378 .action(format!(
379 "run the rk of the branch's environment: `direnv exec {seat} rk integrate {branch} --target {target}`. From inside the worktree, `rk integrate {branch} --target .` works on every release, including one before 0.10.1, which judges the trunk record"
380 ))
381 .target_state("unchanged"),
382 )),
383 }
384}
385
386const OWN_RK: &str =
388 "run the rk of this project's environment, for example through `direnv exec . rk ...`";
389
390fn no_record(target: &Utf8Path) -> RkError {
391 RkError::refusal(
392 Diagnostic::new(
393 Reason::StateDrift,
394 format!("{target} has no release-kit landing, and this command reads one"),
395 )
396 .expected("a landing record at .release-kit/manifest.json")
397 .action(format!(
398 "run `rk init --target {target}` to land it. Read the setup skill with `rk skill show rk-setup`, and each file it names with `rk skill show rk-setup --file <path>`"
399 ))
400 .target_state("unchanged"),
401 )
402}
403
404fn binary_newer(target: &Utf8Path, recorded: &str, outside: bool) -> RkError {
405 let binary = env!("CARGO_PKG_VERSION");
406 let action = if outside {
407 format!(
408 "this rk comes from outside the project's environment, which pins rk {recorded}: {OWN_RK}. Where the project moved its pin to {binary}, run `rk upgrade --target {target} --apply` instead, then run this command again"
409 )
410 } else {
411 format!(
412 "run `rk upgrade --target {target} --apply` to move the landing, then run this command again. Where the project pins rk {recorded}, {OWN_RK}. {}",
413 crate::self_depend::advice::after_move()
414 )
415 };
416 RkError::refusal(
417 Diagnostic::new(
418 Reason::StateDrift,
419 format!("the landing is at rk {recorded} and this rk is {binary}"),
420 )
421 .expected("a binary at the landing's rk_version")
422 .action(action)
423 .target_state("unchanged"),
424 )
425}
426
427fn binary_newer_warning(recorded: &str, outside: bool) -> String {
428 let binary = env!("CARGO_PKG_VERSION");
429 if outside {
430 format!(
431 "the landing is at rk {recorded} and this rk is {binary}, from outside the project's environment; {OWN_RK}, or run `rk upgrade` where the pin moved"
432 )
433 } else {
434 format!(
435 "the landing is at rk {recorded} and this rk is {binary}; run `rk upgrade` to move the landing"
436 )
437 }
438}
439
440fn record_newer(target: &Utf8Path, recorded: &str, pin: Option<&str>) -> RkError {
441 let binary = env!("CARGO_PKG_VERSION");
442 let mut action = OWN_RK.to_owned();
443 if let Some(pin) = pin {
444 action = format!(
445 "{action}. The pin of {target} names {pin}. Move it to {recorded} with `rk self-depend sync --apply --tag v{recorded}`"
446 );
447 }
448 RkError::refusal(
449 Diagnostic::new(
450 Reason::StateDrift,
451 format!("the landing is at rk {recorded} and this rk is {binary}, which is older"),
452 )
453 .expected("a binary at the landing's rk_version")
454 .action(action)
455 .target_state("unchanged"),
456 )
457}
458
459#[cfg(test)]
460mod tests {
461 use super::CLASSES;
462 use clap::CommandFactory as _;
463
464 fn paths(command: &clap::Command, prefix: &str, out: &mut Vec<String>) {
468 for sub in command.get_subcommands() {
469 if sub.get_name() == "help" {
470 continue;
471 }
472 let path = if prefix.is_empty() {
473 sub.get_name().to_owned()
474 } else {
475 format!("{prefix} {}", sub.get_name())
476 };
477 if !sub.is_subcommand_required_set() || sub.get_subcommands().next().is_none() {
478 out.push(path.clone());
479 }
480 paths(sub, &path, out);
481 }
482 }
483
484 #[test]
489 fn every_action_has_a_gate_class() {
490 let mut all = Vec::new();
491 paths(&crate::cli::Cli::command(), "", &mut all);
492 let classed = |path: &str| {
493 let words: Vec<&str> = path.split(' ').collect();
494 (1..=words.len()).any(|end| {
495 let prefix = words[..end].join(" ");
496 CLASSES.iter().any(|(key, _)| *key == prefix)
497 })
498 };
499 for path in &all {
500 assert!(classed(path), "{path} has no gate class");
501 }
502 for (key, _) in CLASSES {
503 assert!(
504 all.iter().any(|path| path == key)
505 || all.iter().any(|path| path.starts_with(&format!("{key} "))),
506 "{key} names no command"
507 );
508 }
509 }
510}