clawless-core 0.7.0

Types and traits for building command-line applications
Documentation
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Command output interface
//!
//! This module defines [`Output`], the interface commands use to produce events. `Output` wraps an
//! [`EventSender`] and provides typed methods for each event kind, decoupling commands from the
//! rendering strategy. Commands call [`message`], [`detail`], or [`artifact`] to emit events into
//! the channel; the Presenter consumes them and decides how to render.
//!
//! [`process_event`] carries the steps of an external program that a command runs. Commands do not
//! usually call it, because [`Process`] reports a run through it.
//!
//! [`prompt`] sends a question for the user.
//!
//! [`Process`]: crate::process::Process
//! [`artifact`]: Output::artifact
//! [`detail`]: Output::detail
//! [`message`]: Output::message
//! [`process_event`]: Output::process_event
//! [`prompt`]: Output::prompt

use std::fmt::{Debug, Display};

use serde::Serialize;

use crate::event::process::ProcessEvent;
use crate::event::prompt::PromptRequest;
use crate::event::{Event, EventSender, SendError};

/// Command output interface that wraps an event channel sender
///
/// `Output` provides typed methods for each event kind, decoupling commands from the event channel
/// API. Commands call [`message`], [`detail`], or [`artifact`] to emit events; the Presenter
/// consumes them for rendering.
///
/// `Output` is cheaply clonable. Cloning an `Output` produces another handle to the same
/// underlying channel, not an independent channel.
///
/// # Examples
///
/// ```
/// use clawless_core::event::event_channel;
/// use clawless_core::output::Output;
///
/// # #[tokio::main]
/// # async fn main() {
/// let (sender, mut receiver) = event_channel();
/// let output = Output::new(sender);
///
/// output.message("hello").await.expect("should send");
/// # }
/// ```
///
/// [`artifact`]: Output::artifact
/// [`detail`]: Output::detail
/// [`message`]: Output::message
// r[impl output.safety.clone]
// r[impl output.safety.send]
// r[impl output.safety.concurrent]
#[derive(Clone, Debug)]
pub struct Output {
    /// Channel that carries the emitted events
    sender: EventSender,
}

impl Output {
    /// Creates a new `Output` wrapping the given event sender
    ///
    /// # Examples
    ///
    /// ```
    /// use clawless_core::event::event_channel;
    /// use clawless_core::output::Output;
    ///
    /// let (sender, _receiver) = event_channel();
    /// let output = Output::new(sender);
    /// ```
    pub fn new(sender: EventSender) -> Self {
        Self { sender }
    }

    /// Sends an informational message event
    ///
    /// Converts the value to a string via [`Display`] and sends it as an [`Event::Message`].
    ///
    /// # Errors
    ///
    /// Returns [`SendError`] if the [`EventReceiver`] has been dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// use clawless_core::event::event_channel;
    /// use clawless_core::output::Output;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let (sender, _receiver) = event_channel();
    /// let output = Output::new(sender);
    ///
    /// output.message("processing files").await.expect("should send");
    /// output.message(format!("found {} items", 42)).await.expect("should send");
    /// # }
    /// ```
    ///
    /// [`EventReceiver`]: crate::event::EventReceiver
    // r[impl output.send.message]
    // r[impl output.send.async]
    pub async fn message(&self, message: impl Display) -> Result<(), SendError> {
        self.sender.send(Event::Message(message.to_string())).await
    }

    /// Sends a supplementary detail event
    ///
    /// Converts the value to a string via [`Display`] and sends it as an [`Event::Detail`].
    /// Details carry lower-priority information that the Presenter may suppress at default
    /// verbosity.
    ///
    /// # Errors
    ///
    /// Returns [`SendError`] if the [`EventReceiver`] has been dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// use clawless_core::event::event_channel;
    /// use clawless_core::output::Output;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let (sender, _receiver) = event_channel();
    /// let output = Output::new(sender);
    ///
    /// output.detail("reading config from ~/.config/app.toml").await.expect("should send");
    /// # }
    /// ```
    ///
    /// [`EventReceiver`]: crate::event::EventReceiver
    // r[impl output.send.detail]
    pub async fn detail(&self, detail: impl Display) -> Result<(), SendError> {
        self.sender.send(Event::Detail(detail.to_string())).await
    }

    /// Sends a structured artifact event
    ///
    /// Wraps the value in a [`Box`] and sends it as an [`Event::Artifact`]. The value must
    /// implement [`Display`] (for text rendering), [`Serialize`] (for JSON rendering), and
    /// [`Debug`] (for diagnostics).
    ///
    /// # Errors
    ///
    /// Returns [`SendError`] if the [`EventReceiver`] has been dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::fmt;
    ///
    /// use serde::Serialize;
    ///
    /// use clawless_core::event::event_channel;
    /// use clawless_core::output::Output;
    ///
    /// #[derive(Clone, Debug, Serialize)]
    /// struct UserCount {
    ///     count: usize,
    /// }
    ///
    /// impl fmt::Display for UserCount {
    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///         write!(f, "{} users", self.count)
    ///     }
    /// }
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let (sender, _receiver) = event_channel();
    /// let output = Output::new(sender);
    ///
    /// output.artifact(UserCount { count: 42 }).await.expect("should send");
    /// # }
    /// ```
    ///
    /// [`EventReceiver`]: crate::event::EventReceiver
    // r[impl output.send.artifact]
    pub async fn artifact<T>(&self, value: T) -> Result<(), SendError>
    where
        T: Display + Serialize + Debug + Send + Sync + 'static,
    {
        self.sender.send(Event::Artifact(Box::new(value))).await
    }

    /// Sends one step in the run of an external program
    ///
    /// [`Process`] calls this for every step of a run, so a command that runs a program through
    /// Clawless does not call it. An application that drives a program itself, and wants its
    /// output to reach the presenter in the same shape, reports the run through this method.
    ///
    /// # Errors
    ///
    /// Returns [`SendError`] if the [`EventReceiver`] has been dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// use clawless_core::event::event_channel;
    /// use clawless_core::event::process::{ProcessEvent, RunId};
    /// use clawless_core::output::Output;
    /// use clawless_core::process::Invocation;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let (sender, _receiver) = event_channel();
    /// let output = Output::new(sender);
    ///
    /// output
    ///     .process_event(ProcessEvent::Started {
    ///         id: RunId::next(),
    ///         invocation: Invocation::new("git").arg("status"),
    ///         process_id: None,
    ///     })
    ///     .await
    ///     .expect("should send");
    /// # }
    /// ```
    ///
    /// [`EventReceiver`]: crate::event::EventReceiver
    /// [`Process`]: crate::process::Process
    // r[impl output.send.process]
    pub async fn process_event(&self, event: ProcessEvent) -> Result<(), SendError> {
        self.sender.send(Event::Process(Box::new(event))).await
    }

    /// Sends a question for the user
    ///
    /// The request arrives after every event that this output sent before it. The answer
    /// arrives at the [`PendingAnswer`] that was created together with the request.
    ///
    /// # Errors
    ///
    /// Returns [`SendError`] if the [`EventReceiver`] has been dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// use clawless_core::event::event_channel;
    /// use clawless_core::event::prompt::PromptRequest;
    /// use clawless_core::output::Output;
    /// use clawless_core::prompt::Confirm;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let (sender, _receiver) = event_channel();
    /// let output = Output::new(sender);
    /// let (request, _pending) = PromptRequest::confirm(Confirm::new("Delete the branch?"));
    ///
    /// output.prompt(request).await.expect("should send");
    /// # }
    /// ```
    ///
    /// [`EventReceiver`]: crate::event::EventReceiver
    /// [`PendingAnswer`]: crate::event::prompt::PendingAnswer
    pub async fn prompt(&self, request: PromptRequest) -> Result<(), SendError> {
        self.sender.send(Event::Prompt(Box::new(request))).await
    }
}

#[cfg(test)]
mod tests {
    // An assertion in a test panics by design. A `# Panics` section on every test
    // would repeat that and give the reader no information.
    #![allow(clippy::missing_panics_doc)]

    use std::fmt;

    use serde::Serialize;

    use super::*;
    use crate::event::event_channel;
    use crate::event::process::RunId;
    use crate::process::Invocation;
    use crate::prompt::Confirm;

    #[derive(Clone, Debug, Serialize)]
    struct TestArtifact {
        value: String,
    }

    impl fmt::Display for TestArtifact {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.value)
        }
    }

    // r[verify output.send.artifact]
    #[tokio::test]
    async fn artifact_sends_artifact_event() {
        let (sender, mut receiver) = event_channel();
        let output = Output::new(sender);

        output
            .artifact(TestArtifact {
                value: "result".to_string(),
            })
            .await
            .expect("should send");

        let event = receiver.recv().await.expect("should receive");

        assert!(matches!(event, Event::Artifact(ref a) if a.to_string() == "result"));
    }

    #[tokio::test]
    async fn artifact_to_closed_channel_returns_error() {
        let (sender, receiver) = event_channel();
        let output = Output::new(sender);
        drop(receiver);

        let error = output
            .artifact(TestArtifact {
                value: "lost".to_string(),
            })
            .await
            .expect_err("should fail");

        assert_eq!(error.to_string(), "event channel closed");
    }

    // r[verify output.safety.clone]
    #[tokio::test]
    async fn clone_produces_independent_handle() {
        let (sender, mut receiver) = event_channel();
        let output = Output::new(sender);
        let cloned = output.clone();

        output.message("from original").await.expect("should send");
        cloned.message("from clone").await.expect("should send");

        let first = receiver.recv().await.expect("should receive first");
        let second = receiver.recv().await.expect("should receive second");

        assert!(matches!(first, Event::Message(ref s) if s == "from original"));
        assert!(matches!(second, Event::Message(ref s) if s == "from clone"));
    }

    // r[verify output.send.process]
    #[tokio::test]
    async fn process_event_sends_process_event() {
        let (sender, mut receiver) = event_channel();
        let output = Output::new(sender);
        let invocation = Invocation::new("git").arg("status");

        output
            .process_event(ProcessEvent::Started {
                id: RunId::next(),
                invocation: invocation.clone(),
                process_id: None,
            })
            .await
            .expect("should send");

        assert_eq!(
            receiver.recv().await.map(|event| match event {
                Event::Process(event) => event.to_string(),
                Event::Message(text) => text,
                Event::Detail(text) => text,
                Event::Artifact(artifact) => artifact.to_string(),
                Event::Prompt(request) => format!("{request:?}"),
            }),
            Some(format!("$ {invocation}"))
        );
    }

    #[tokio::test]
    async fn prompt_sends_prompt_event() {
        let (sender, mut receiver) = event_channel();
        let output = Output::new(sender);
        let (request, _pending) = PromptRequest::confirm(Confirm::new("Release?"));

        output.prompt(request).await.expect("should send");

        assert_eq!(
            receiver.recv().await.map(|event| match event {
                Event::Prompt(request) => request.question().to_owned(),
                Event::Process(event) => event.to_string(),
                Event::Message(text) => text,
                Event::Detail(text) => text,
                Event::Artifact(artifact) => artifact.to_string(),
            }),
            Some("Release?".to_owned())
        );
    }

    // r[verify output.send.detail]
    #[tokio::test]
    async fn detail_sends_detail_event() {
        let (sender, mut receiver) = event_channel();
        let output = Output::new(sender);

        output
            .detail("supplementary info")
            .await
            .expect("should send");

        let event = receiver.recv().await.expect("should receive");

        assert!(matches!(event, Event::Detail(ref s) if s == "supplementary info"));
    }

    #[tokio::test]
    async fn detail_to_closed_channel_returns_error() {
        let (sender, receiver) = event_channel();
        let output = Output::new(sender);
        drop(receiver);

        let error = output.detail("lost").await.expect_err("should fail");

        assert_eq!(error.to_string(), "event channel closed");
    }

    // r[verify output.send.message]
    // r[verify output.send.async]
    #[tokio::test]
    async fn message_sends_message_event() {
        let (sender, mut receiver) = event_channel();
        let output = Output::new(sender);

        output.message("hello").await.expect("should send");

        let event = receiver.recv().await.expect("should receive");

        assert!(matches!(event, Event::Message(ref s) if s == "hello"));
    }

    // r[verify output.send.error]
    #[tokio::test]
    async fn message_to_closed_channel_returns_error() {
        let (sender, receiver) = event_channel();
        let output = Output::new(sender);
        drop(receiver);

        let error = output.message("lost").await.expect_err("should fail");

        assert_eq!(error.to_string(), "event channel closed");
    }

    #[tokio::test]
    async fn message_with_format_args_sends_formatted_string() {
        let (sender, mut receiver) = event_channel();
        let output = Output::new(sender);

        output
            .message(format!("count: {}", 42))
            .await
            .expect("should send");

        let event = receiver.recv().await.expect("should receive");

        assert!(matches!(event, Event::Message(ref s) if s == "count: 42"));
    }

    #[test]
    fn trait_send() {
        fn assert_send<T: Send>() {}
        assert_send::<Output>();
    }

    #[test]
    fn trait_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<Output>();
    }

    #[test]
    fn trait_unpin() {
        fn assert_unpin<T: Unpin>() {}
        assert_unpin::<Output>();
    }
}