Skip to main content

egui_pop_model/
commands.rs

1//! Commands: every action of the application, named. A menu, a key, the
2//! palette, an agent and a test all run the same command by its id, and
3//! each run says where it came from.
4//!
5//! A [`CommandSpec`] is declared once and the rest is derived from it
6//! (its key bindings, menu entries, palette entry and agent surface).
7//! The registry is generic over the handler type so an upper layer can
8//! give handlers whatever context it has; [`FnHandler`] is the plain one.
9//!
10//! ```
11//! use egui_pop_model::commands::{CommandSpec, Commands, Origin};
12//! use egui_pop_model::ids::{CommandId, OwnerId};
13//! use egui_pop_model::when::WhenContext;
14//! use serde_json::json;
15//!
16//! let mut commands = Commands::new();
17//! let id = CommandId::from_static("demo.echo");
18//! commands
19//!     .register_fn(&OwnerId::FRAMEWORK, CommandSpec::new(id.clone(), "Echo", "Demo"), |args, _| {
20//!         Ok(args.clone())
21//!     })
22//!     .unwrap();
23//! let out = commands.run(&id, json!(3), Origin::User, &WhenContext::new());
24//! assert_eq!(out, Ok(json!(3)));
25//! ```
26
27mod error;
28pub use error::CommandError;
29
30use std::collections::VecDeque;
31use std::fmt;
32
33use serde::Serialize;
34use serde_json::Value as Json;
35
36use crate::ids::{CommandId, MenuId, OwnerId};
37use crate::keymap::BindOptions;
38use crate::registry::Registry;
39use crate::when::{When, WhenContext};
40
41/// Who asked for a command: shown in the history, and used to keep an
42/// agent from fighting a human's gesture.
43#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, serde::Deserialize)]
44#[serde(tag = "kind", content = "id", rename_all = "lowercase")]
45pub enum Origin {
46    /// A person, with the mouse or the keyboard.
47    User,
48    /// An automated agent, by session.
49    Agent(String),
50    /// A script, by name.
51    Script(String),
52    /// A hardware controller, by name.
53    Device(String),
54    /// Another process or machine.
55    Remote(String),
56}
57
58impl fmt::Display for Origin {
59    /// The origin as the journal and the history name it: `user`,
60    /// `agent:<session>`, `script:<name>`, `device:<name>`,
61    /// `remote:<name>`.
62    ///
63    /// ```
64    /// use egui_pop_model::commands::Origin;
65    /// assert_eq!(Origin::User.to_string(), "user");
66    /// assert_eq!(Origin::Agent("debug-bridge".into()).to_string(), "agent:debug-bridge");
67    /// ```
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        match self {
70            Origin::User => f.write_str("user"),
71            Origin::Agent(n) => write!(f, "agent:{n}"),
72            Origin::Script(n) => write!(f, "script:{n}"),
73            Origin::Device(n) => write!(f, "device:{n}"),
74            Origin::Remote(n) => write!(f, "remote:{n}"),
75        }
76    }
77}
78
79impl Origin {
80    /// Who writes a value for this origin (ADR 0016): a person writes
81    /// through the framework, which may write any path; anyone else
82    /// writes as itself (`agent:debug-bridge`, `script:<name>`...), so a
83    /// value's declared writers apply. A name an id cannot hold is
84    /// written with `_` for each character it refuses.
85    pub fn writer(&self) -> OwnerId {
86        let (kind, name) = match self {
87            Origin::User => return OwnerId::FRAMEWORK,
88            Origin::Agent(n) => ("agent", n),
89            Origin::Script(n) => ("script", n),
90            Origin::Device(n) => ("device", n),
91            Origin::Remote(n) => ("remote", n),
92        };
93        let text = format!("{kind}:{name}");
94        OwnerId::new(text.clone()).unwrap_or_else(|_| {
95            let clean: String = text
96                .chars()
97                .take(128)
98                .map(|c| {
99                    if c.is_ascii_alphanumeric() || "._:/-".contains(c) {
100                        c
101                    } else {
102                        '_'
103                    }
104                })
105                .collect();
106            OwnerId::new(clean).unwrap_or(OwnerId::from_static("unnamed"))
107        })
108    }
109}
110
111/// Where a command's menu entry goes.
112#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
113pub struct MenuPlacement {
114    pub menu: MenuId,
115    pub group: String,
116    pub order: i32,
117}
118
119/// One of a command's default key bindings: its keys and how it listens
120/// (global or on a surface, while typing, through modals).
121#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
122pub struct KeySpec {
123    pub keys: String,
124    pub options: BindOptions,
125}
126
127/// A rule on a call's arguments: the argument `arg` equals `equals`
128/// ([`CommandSpec::destructive_if`]).
129#[derive(Clone, Debug, PartialEq, Serialize)]
130#[non_exhaustive]
131pub struct ArgMatch {
132    /// A top-level argument's name (`clash`), or a JSON Pointer into the
133    /// arguments (`/options/clash`).
134    pub arg: String,
135    /// The value it must equal.
136    pub equals: Json,
137}
138
139impl ArgMatch {
140    /// Whether `args` hold `equals` at `arg`.
141    pub fn matches(&self, args: &Json) -> bool {
142        let found = if self.arg.starts_with('/') {
143            args.pointer(&self.arg)
144        } else {
145            args.get(&self.arg)
146        };
147        found == Some(&self.equals)
148    }
149}
150
151/// What a command declares.
152#[derive(Clone, Debug, PartialEq, Serialize)]
153#[non_exhaustive]
154pub struct CommandSpec {
155    /// Stable, never translated: `view.palette`.
156    pub id: CommandId,
157    pub title: String,
158    pub category: String,
159    /// What it does, for the palette and agents.
160    pub description: String,
161    /// Where the command applies; empty: everywhere.
162    pub when: String,
163    /// When its menu entries show ticked (a toggle that is on, the theme
164    /// in use); empty: never.
165    pub checked: String,
166    /// Its default key bindings (`Ctrl+K`, `Ctrl+K Ctrl+S`).
167    pub keys: Vec<KeySpec>,
168    /// Its menu entries.
169    pub menus: Vec<MenuPlacement>,
170    /// Listed in the command palette.
171    pub palette: bool,
172    /// Offered to agents through the debug bridge.
173    pub agent: bool,
174    /// It only reads: running it changes nothing in the application
175    /// (`about.read`, `value.get`). The debug bridge reports it
176    /// (`commands.run` does not mutate then) and a read-only bridge runs
177    /// only these.
178    pub read_only: bool,
179    /// It destroys or discards what cannot easily be had back (deletes
180    /// files, empties a trash, drops unsaved work). Asked by anyone but
181    /// the user (an agent), it waits for the user to confirm it first:
182    /// the agent socket asks, through a dialog. The user's own runs are
183    /// never asked.
184    #[serde(skip_serializing_if = "std::ops::Not::not")]
185    pub destructive: bool,
186    /// The calls that are destructive by their arguments, when the
187    /// command is not destructive whole: a run whose arguments match one
188    /// of these ([`CommandSpec::destructive_if`]) is asked about as a
189    /// destructive command's is; the others run at once. An export that
190    /// only overwrites with `clash: "overwrite"` says so here.
191    #[serde(skip_serializing_if = "Vec::is_empty")]
192    pub destructive_if: Vec<ArgMatch>,
193    /// Its result carries the user's private data: places (GPS), people
194    /// (faces, names), absolute file paths. An agent whose grant
195    /// withholds private data is refused it (the agent socket's
196    /// `Grant::private`); the user's own runs are never held.
197    #[serde(skip_serializing_if = "std::ops::Not::not")]
198    pub private: bool,
199    /// Its arguments: a JSON Schema ([`CommandSpec::schema`]), or a free
200    /// description (an example, a text); `null` when it takes none. A
201    /// schema (an object of schema keywords naming a `type`, see
202    /// `egui_pop_core::debug::is_schema`) is enforced: a run whose
203    /// arguments do not match is refused before its handler, whoever
204    /// asks it (`command.refused`, `by: "pop.command.args"`). A free
205    /// description checks nothing.
206    pub args: Json,
207    /// Its icon's name (`save`, `phosphor:export`, `my-plugin:crop`):
208    /// every surface running the command shows it. Checked against the
209    /// icon vocabulary when the application resolves its declarations.
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub icon: Option<String>,
212    /// The icon shown instead while `checked` holds (eye-off for a
213    /// toggle whose icon is the eye).
214    #[serde(skip_serializing_if = "Option::is_none")]
215    pub icon_on: Option<String>,
216    /// A note at the end of its menu entries, muted, in the keys' column
217    /// (a version, "sessions kept"); its keys, if any, come first.
218    #[serde(skip_serializing_if = "Option::is_none")]
219    pub menu_note: Option<String>,
220    /// It opens a page outside the application: its menu entries end
221    /// with ↗.
222    #[serde(skip_serializing_if = "std::ops::Not::not")]
223    pub opens_link: bool,
224}
225
226impl CommandSpec {
227    pub fn new(id: CommandId, title: &str, category: &str) -> Self {
228        Self {
229            id,
230            title: title.into(),
231            category: category.into(),
232            description: String::new(),
233            when: String::new(),
234            checked: String::new(),
235            keys: Vec::new(),
236            menus: Vec::new(),
237            palette: true,
238            agent: true,
239            read_only: false,
240            destructive: false,
241            destructive_if: Vec::new(),
242            private: false,
243            args: Json::Null,
244            icon: None,
245            icon_on: None,
246            menu_note: None,
247            opens_link: false,
248        }
249    }
250
251    /// Its icon, by name: egui-pop's (`save`), a Phosphor glyph's
252    /// (`phosphor:export`) or a registered one (`my-plugin:crop`).
253    /// Declared once, shown by every surface running the command.
254    pub fn icon(mut self, name: &str) -> Self {
255        self.icon = Some(name.into());
256        self
257    }
258
259    /// The icon shown while its `checked` clause holds, by name.
260    pub fn icon_on(mut self, name: &str) -> Self {
261        self.icon_on = Some(name.into());
262        self
263    }
264
265    /// A note at the end of its menu entries ([`CommandSpec::menu_note`]).
266    pub fn menu_note(mut self, note: &str) -> Self {
267        self.menu_note = Some(note.into());
268        self
269    }
270
271    /// Its menu entries end with ↗: it opens a page outside the
272    /// application ([`CommandSpec::opens_link`]).
273    pub fn opens_link(mut self, link: bool) -> Self {
274        self.opens_link = link;
275        self
276    }
277
278    /// The icon's name to show: `icon_on` while checked (when declared),
279    /// else `icon`.
280    pub fn icon_for(&self, checked: bool) -> Option<&str> {
281        if checked && let Some(on) = &self.icon_on {
282            return Some(on);
283        }
284        self.icon.as_deref()
285    }
286
287    pub fn when(mut self, when: &str) -> Self {
288        self.when = when.into();
289        self
290    }
291
292    /// Ticks its menu entries when the clause holds.
293    pub fn checked(mut self, clause: &str) -> Self {
294        self.checked = clause.into();
295        self
296    }
297
298    pub fn description(mut self, text: &str) -> Self {
299        self.description = text.into();
300        self
301    }
302
303    /// Adds a default global key binding (a text input keeps plain
304    /// keys, see `keymap::Typing`).
305    pub fn key(self, keys: &str) -> Self {
306        self.key_with(keys, BindOptions::global())
307    }
308
309    /// Adds a default key binding listening as `options` say: on a
310    /// surface, while typing, through modals.
311    pub fn key_with(mut self, keys: &str, options: BindOptions) -> Self {
312        self.keys.push(KeySpec {
313            keys: keys.into(),
314            options,
315        });
316        self
317    }
318
319    /// Adds a menu entry.
320    pub fn menu(mut self, menu: MenuId, group: &str, order: i32) -> Self {
321        self.menus.push(MenuPlacement {
322            menu,
323            group: group.into(),
324            order,
325        });
326        self
327    }
328
329    /// Kept out of the palette.
330    pub fn hidden(mut self) -> Self {
331        self.palette = false;
332        self
333    }
334
335    /// Kept away from agents.
336    pub fn no_agent(mut self) -> Self {
337        self.agent = false;
338        self
339    }
340
341    /// It only reads: running it changes nothing in the application (no
342    /// value, file, window or state of any kind). Say it only when true:
343    /// a read-only debug bridge runs these and refuses the others.
344    pub fn read_only(mut self) -> Self {
345        self.read_only = true;
346        self
347    }
348
349    /// It destroys or discards what cannot easily be had back
350    /// ([`CommandSpec::destructive`]): an agent's run waits for the
351    /// user's confirmation.
352    pub fn destructive(mut self) -> Self {
353        self.destructive = true;
354        self
355    }
356
357    /// A call whose argument `arg` equals `value` is destructive
358    /// ([`CommandSpec::destructive_if`]): an agent's run with it waits
359    /// for the user's confirmation, other runs do not. `arg` is a
360    /// top-level argument's name, or a JSON Pointer (`/options/clash`).
361    /// Several rules: any one matching makes the call destructive.
362    /// [`CommandSpec::destructive`] still makes every call destructive.
363    pub fn destructive_if(mut self, arg: &str, value: Json) -> Self {
364        self.destructive_if.push(ArgMatch {
365            arg: arg.into(),
366            equals: value,
367        });
368        self
369    }
370
371    /// Whether a call with `args` is destructive: the command is
372    /// ([`CommandSpec::destructive`]), or its arguments match one of
373    /// [`CommandSpec::destructive_if`].
374    pub fn is_destructive(&self, args: &Json) -> bool {
375        self.destructive || self.destructive_if.iter().any(|m| m.matches(args))
376    }
377
378    /// Its result carries private data ([`CommandSpec::private`]): an
379    /// agent whose grant withholds private data is refused it. A command
380    /// whose result only partly is private may instead leave the private
381    /// parts out for such an agent (the agent socket's
382    /// `grants::reads_private`).
383    pub fn private(mut self) -> Self {
384        self.private = true;
385        self
386    }
387
388    /// Describes the arguments ([`CommandSpec::args`]): a JSON Schema is
389    /// enforced, a free description (an example) only shown.
390    pub fn args(mut self, args: Json) -> Self {
391        self.args = args;
392        self
393    }
394
395    /// Its arguments' JSON Schema, enforced before every run: arguments
396    /// that do not match are refused before the handler runs
397    /// (`command.refused`, `by: "pop.command.args"`). The checked subset
398    /// is `egui_pop_core::schema`'s (types, `required`, `enum`, ranges,
399    /// lengths, `items`, `additionalProperties`, combinators). `null`
400    /// arguments are checked as `{}` when the schema is an object's. The
401    /// same as [`CommandSpec::args`], said for what it is.
402    pub fn schema(self, schema: Json) -> Self {
403        self.args(schema)
404    }
405}
406
407/// The plain handler: arguments and origin in, a JSON result out.
408pub type FnHandler = Box<dyn Fn(&Json, &Origin) -> Result<Json, String> + Send + Sync>;
409
410/// Why a command could not be registered.
411#[derive(Clone, Debug, PartialEq, Eq)]
412pub enum RegisterError {
413    /// Its `when` clause does not parse.
414    BadWhen { id: CommandId, error: String },
415    /// The id is taken.
416    Duplicate { id: CommandId, by: OwnerId },
417}
418
419impl fmt::Display for RegisterError {
420    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421        match self {
422            RegisterError::BadWhen { id, error } => write!(f, "command `{id}`: {error}"),
423            RegisterError::Duplicate { id, by } => {
424                write!(f, "command `{id}` is already declared by `{by}`")
425            }
426        }
427    }
428}
429
430impl std::error::Error for RegisterError {}
431
432/// Why a command did not run.
433#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
434#[serde(tag = "refused", rename_all = "snake_case")]
435pub enum RunRefused {
436    Unknown { id: String },
437    NotHere { id: String, when: String },
438}
439
440impl fmt::Display for RunRefused {
441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442        match self {
443            RunRefused::Unknown { id } => write!(f, "no command `{id}`"),
444            RunRefused::NotHere { id, when } => write!(f, "`{id}` does not apply here ({when})"),
445        }
446    }
447}
448
449/// A registered command.
450pub struct Entry<H> {
451    pub spec: CommandSpec,
452    when: When,
453    pub handler: H,
454}
455
456impl<H> fmt::Debug for Entry<H> {
457    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458        f.debug_struct("Entry").field("spec", &self.spec).finish()
459    }
460}
461
462/// One run, as the history keeps it.
463#[derive(Clone, Debug, PartialEq, Serialize)]
464pub struct Run {
465    pub id: CommandId,
466    pub args: Json,
467    pub origin: Origin,
468    pub result: Result<Json, String>,
469}
470
471/// How many runs the history keeps.
472pub const HISTORY: usize = 256;
473
474/// The commands, by id, each owned.
475pub struct Commands<H = FnHandler> {
476    entries: Registry<CommandId, Entry<H>>,
477    history: VecDeque<Run>,
478}
479
480impl<H> Default for Commands<H> {
481    fn default() -> Self {
482        Self {
483            entries: Registry::new(),
484            history: VecDeque::new(),
485        }
486    }
487}
488
489impl<H> fmt::Debug for Commands<H> {
490    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491        f.debug_struct("Commands")
492            .field("ids", &self.specs().map(|s| &s.id).collect::<Vec<_>>())
493            .field("history", &self.history.len())
494            .finish()
495    }
496}
497
498impl<H> Commands<H> {
499    pub fn new() -> Self {
500        Self::default()
501    }
502
503    /// Declares a command; a second declaration of an id is refused.
504    pub fn register(
505        &mut self,
506        owner: &OwnerId,
507        spec: CommandSpec,
508        handler: H,
509    ) -> Result<(), RegisterError> {
510        let when = When::parse(&spec.when).map_err(|error| RegisterError::BadWhen {
511            id: spec.id.clone(),
512            error,
513        })?;
514        When::parse(&spec.checked).map_err(|error| RegisterError::BadWhen {
515            id: spec.id.clone(),
516            error: format!("checked: {error}"),
517        })?;
518        let id = spec.id.clone();
519        self.entries
520            .insert(
521                owner,
522                id,
523                Entry {
524                    spec,
525                    when,
526                    handler,
527                },
528            )
529            .map_err(|t| RegisterError::Duplicate { id: t.id, by: t.by })
530    }
531
532    pub fn spec(&self, id: &CommandId) -> Option<&CommandSpec> {
533        self.entries.get(id).map(|e| &e.spec)
534    }
535
536    pub fn owner(&self, id: &CommandId) -> Option<&OwnerId> {
537        self.entries.owner(id)
538    }
539
540    /// Every declared command, by id.
541    pub fn specs(&self) -> impl Iterator<Item = &CommandSpec> {
542        self.entries.iter().map(|(_, s)| &s.item.spec)
543    }
544
545    /// Whether a command applies in a context.
546    pub fn applies(&self, id: &CommandId, cx: &WhenContext) -> bool {
547        self.entries.get(id).is_some_and(|e| e.when.eval(cx))
548    }
549
550    /// The commands that apply in a context.
551    pub fn available(&self, cx: &WhenContext) -> Vec<&CommandSpec> {
552        self.entries
553            .iter()
554            .filter(|(_, s)| s.item.when.eval(cx))
555            .map(|(_, s)| &s.item.spec)
556            .collect()
557    }
558
559    /// Palette commands whose category, title or id contains every word of
560    /// `query`, in that context, best first: a title starting with the
561    /// query, then one with a word starting with each query word, then
562    /// the rest, each by title.
563    pub fn search(&self, query: &str, cx: &WhenContext) -> Vec<&CommandSpec> {
564        let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
565        let q = query.trim().to_lowercase();
566        let mut hits: Vec<(u8, &CommandSpec)> = self
567            .available(cx)
568            .into_iter()
569            .filter(|s| s.palette)
570            .filter_map(|s| {
571                let hay = format!("{} {} {}", s.category, s.title, s.id).to_lowercase();
572                if !words.iter().all(|w| hay.contains(w)) {
573                    return None;
574                }
575                let title = s.title.to_lowercase();
576                let rank = if !q.is_empty() && title.starts_with(&q) {
577                    0
578                } else if words.iter().all(|w| {
579                    hay.split(|c: char| !c.is_alphanumeric())
580                        .any(|t| t.starts_with(w.as_str()))
581                }) {
582                    1
583                } else {
584                    2
585                };
586                Some((rank, s))
587            })
588            .collect();
589        hits.sort_by(|a, b| (a.0, &a.1.title).cmp(&(b.0, &b.1.title)));
590        hits.into_iter().map(|(_, s)| s).collect()
591    }
592
593    /// The handler of a command that may run here.
594    pub fn prepare(&self, id: &CommandId, cx: &WhenContext) -> Result<&H, RunRefused> {
595        let entry = self
596            .entries
597            .get(id)
598            .ok_or_else(|| RunRefused::Unknown { id: id.to_string() })?;
599        if entry.when.eval(cx) {
600            Ok(&entry.handler)
601        } else {
602            Err(RunRefused::NotHere {
603                id: id.to_string(),
604                when: entry.spec.when.clone(),
605            })
606        }
607    }
608
609    /// Keeps a run in the history (the oldest goes past [`HISTORY`]).
610    pub fn record(&mut self, run: Run) {
611        if self.history.len() == HISTORY {
612            self.history.pop_front();
613        }
614        self.history.push_back(run);
615    }
616
617    /// The runs kept, oldest first.
618    pub fn history(&self) -> impl Iterator<Item = &Run> {
619        self.history.iter()
620    }
621
622    /// Removes one command; returns its owner.
623    pub fn remove(&mut self, id: &CommandId) -> Option<OwnerId> {
624        self.entries.remove(id).map(|slot| slot.owner)
625    }
626
627    /// Removes an owner's commands; returns their ids.
628    pub fn remove_owner(&mut self, owner: &OwnerId) -> Vec<CommandId> {
629        self.entries
630            .remove_owner(owner)
631            .into_iter()
632            .map(|(id, _)| id)
633            .collect()
634    }
635
636    pub fn len(&self) -> usize {
637        self.entries.len()
638    }
639
640    pub fn is_empty(&self) -> bool {
641        self.entries.is_empty()
642    }
643}
644
645impl Commands<FnHandler> {
646    /// Declares a command with a plain handler.
647    pub fn register_fn(
648        &mut self,
649        owner: &OwnerId,
650        spec: CommandSpec,
651        handler: impl Fn(&Json, &Origin) -> Result<Json, String> + Send + Sync + 'static,
652    ) -> Result<(), RegisterError> {
653        self.register(owner, spec, Box::new(handler))
654    }
655
656    /// Runs a command; refused when unknown or when it does not apply
657    /// here. A refusal for an unknown id is not a run and is not kept.
658    pub fn run(
659        &mut self,
660        id: &CommandId,
661        args: Json,
662        origin: Origin,
663        cx: &WhenContext,
664    ) -> Result<Json, String> {
665        let result = match self.prepare(id, cx) {
666            Ok(h) => h(&args, &origin),
667            Err(e @ RunRefused::Unknown { .. }) => return Err(e.to_string()),
668            Err(e) => Err(e.to_string()),
669        };
670        self.record(Run {
671            id: id.clone(),
672            args,
673            origin,
674            result: result.clone(),
675        });
676        result
677    }
678}
679
680#[cfg(test)]
681mod destructive_tests {
682    use super::*;
683    use serde_json::json;
684
685    #[test]
686    fn a_call_is_destructive_whole_or_by_its_arguments() {
687        let id = CommandId::from_static("library.export");
688        let plain = CommandSpec::new(id.clone(), "Export", "Library");
689        assert!(!plain.is_destructive(&json!({ "clash": "overwrite" })));
690
691        let whole = plain.clone().destructive();
692        assert!(whole.is_destructive(&Json::Null));
693        assert!(whole.destructive_if.is_empty());
694
695        let by_args = plain
696            .destructive_if("clash", json!("overwrite"))
697            .destructive_if("/options/purge", json!(true));
698        assert!(!by_args.destructive);
699        assert!(!by_args.is_destructive(&Json::Null));
700        assert!(!by_args.is_destructive(&json!({ "clash": "rename" })));
701        assert!(by_args.is_destructive(&json!({ "clash": "overwrite" })));
702        assert!(!by_args.is_destructive(&json!({ "options": { "purge": false } })));
703        assert!(by_args.is_destructive(&json!({ "options": { "purge": true } })));
704        let shown = serde_json::to_value(&by_args).unwrap();
705        assert_eq!(
706            shown["destructive_if"][0],
707            json!({ "arg": "clash", "equals": "overwrite" })
708        );
709        assert!(shown.get("destructive").is_none());
710    }
711}