clawless-core 0.8.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
//! Context for Clawless commands
//!
//! This module defines the [`Context`] struct, which provides information about the environment
//! that Clawless commands are executed in, access to shared resources like loggers, and
//! configuration settings.
//!
//! For information on the context that is available to commands, see the fields and methods of the
//! [`Context`] struct as well as the types defined in this module.

use bon::bon;
use getset::{CopyGetters, Getters};

pub use self::current_working_directory::CurrentWorkingDirectory;
pub use self::error::ContextError;
pub use self::interactivity::Interactivity;
use crate::cancellation::Cancellation;
use crate::output::Output;
use crate::process::Process;
use crate::prompt::Prompt;

/// Newtype for the directory that a command runs in
mod current_working_directory;
/// Errors that occur when Clawless builds a [`Context`]
mod error;
/// Whether a user is present who can answer the application
mod interactivity;

/// Context for Clawless commands
///
/// This struct provides information about the environment that Clawless commands are executed in,
/// access to shared resources, and configuration settings. It is passed to each command by the
/// Clawless runtime when executing commands.
///
/// # Examples
///
/// ```rust,ignore
/// #[derive(Debug, Args)]
/// pub struct GreetArgs {
///     name: String,
/// }
///
/// #[command]
/// pub async fn greet(args: GreetArgs, context: Context) -> CommandResult {
///     message!("Hello, {}!", args.name);
///     Ok(())
/// }
/// ```
// r[impl context.safety.send]
// r[impl context.safety.sync]
// r[impl context.safety.unpin]
#[derive(Clone, Debug, CopyGetters, Getters)]
pub struct Context {
    /// The working directory in which a command was called
    // r[impl context.field.cwd]
    #[getset(get = "pub")]
    current_working_directory: CurrentWorkingDirectory,

    /// The cancellation token for cooperative shutdown
    // r[impl cancel.context.field]
    // r[impl context.field.cancellation]
    #[getset(get = "pub")]
    cancellation: Cancellation,

    /// Whether a user is present who can answer the application
    #[getset(get_copy = "pub")]
    interactivity: Interactivity,

    /// The output handler for sending events to the presenter
    // r[impl context.field.output]
    #[getset(get = "pub")]
    output: Output,
}

#[bon]
impl Context {
    /// Creates a new [`Context`] instance
    ///
    /// When `current_working_directory` is omitted, it is auto-detected from the environment.
    /// When provided explicitly (e.g., in tests), the given value is used directly.
    ///
    /// When `interactivity` is omitted, the context reports [`Interactivity::NonInteractive`].
    ///
    /// # Errors
    ///
    /// Returns [`ContextError::CurrentWorkingDirectory`] if `current_working_directory` is not
    /// provided and the current working directory cannot be determined from the environment.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Production: CWD auto-detected
    /// let context = Context::builder()
    ///     .output(output)
    ///     .build()?;
    ///
    /// // Tests: explicit CWD
    /// let context = Context::builder()
    ///     .current_working_directory(tmp.path())
    ///     .output(output)
    ///     .build()?;
    /// ```
    // r[impl context.new]
    // r[impl context.new.error]
    // r[impl cancel.context.default]
    // r[impl cancel.context.injectable]
    #[builder]
    pub fn new(
        #[builder(into)] current_working_directory: Option<CurrentWorkingDirectory>,
        #[builder(default)] cancellation: Cancellation,
        #[builder(default)] interactivity: Interactivity,
        output: Output,
    ) -> Result<Self, ContextError> {
        let current_working_directory = match current_working_directory {
            Some(cwd) => cwd,
            None => CurrentWorkingDirectory::try_from_env()?,
        };

        Ok(Self {
            current_working_directory,
            cancellation,
            interactivity,
            output,
        })
    }
}

impl Context {
    /// Returns the interface that runs external programs
    ///
    /// The returned [`Process`] reports every run through the output of this context and stops a
    /// run when the cancellation token of this context is cancelled. A command therefore gets live
    /// output and cooperative shutdown without wiring either of them itself.
    ///
    /// Each call builds a handle over the same channel and the same token, so a command can call
    /// this method wherever it runs a program instead of holding the handle.
    ///
    /// The handle takes the default grace period, which is the time a program gets to end itself
    /// before Clawless kills it. A command that drives a program needing longer builds its own
    /// handle with [`Process::builder`].
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// #[command]
    /// pub async fn build(args: BuildArgs, context: Context) -> CommandResult {
    ///     context
    ///         .process()
    ///         .run(Invocation::new("cargo").arg("build"))
    ///         .await?
    ///         .require_success()?;
    ///
    ///     Ok(())
    /// }
    /// ```
    // r[impl context.process]
    pub fn process(&self) -> Process {
        Process::builder()
            .output(self.output.clone())
            .cancellation(self.cancellation.clone())
            .build()
    }

    /// Returns the interface that asks the user a question
    ///
    /// The returned [`Prompt`] uses the output, the cancellation token, and the
    /// [`Interactivity`] of this context. Each call builds a handle over the same channel and the
    /// same token, so a command does not need to keep the handle.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// #[command]
    /// pub async fn publish(args: PublishArgs, context: Context) -> CommandResult {
    ///     match context.prompt().confirm("Publish the release?").await? {
    ///         Confirmation::Yes => message!("Publishing"),
    ///         Confirmation::No => message!("Nothing published"),
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn prompt(&self) -> Prompt {
        Prompt::builder()
            .output(self.output.clone())
            .cancellation(self.cancellation.clone())
            .interactivity(self.interactivity)
            .build()
    }
}

#[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::path::Path;

    use super::*;
    use crate::event::Event;
    use crate::event::event_channel;
    use crate::process::Invocation;

    fn test_output() -> Output {
        let (sender, _receiver) = event_channel();
        Output::new(sender)
    }

    // r[verify context.field.cancellation]
    // r[verify cancel.context.injectable]
    // r[verify cancel.context.field]
    #[test]
    fn new_with_cancellation_uses_provided_token() {
        let cancellation = Cancellation::new();
        cancellation.cancel();

        let context = Context::builder()
            .current_working_directory(Path::new("/tmp"))
            .cancellation(cancellation)
            .output(test_output())
            .build()
            .expect("should create context");

        assert!(context.cancellation().is_cancelled());
    }

    // r[verify context.field.cwd]
    #[test]
    fn new_with_cwd_uses_provided_value() {
        let context = Context::builder()
            .current_working_directory(Path::new("/tmp"))
            .output(test_output())
            .build()
            .expect("should create context");

        assert_eq!(context.current_working_directory().get(), Path::new("/tmp"));
    }

    // r[verify context.new]
    // r[verify context.field.output]
    #[test]
    fn new_with_defaults_detects_cwd() {
        let expected = std::env::current_dir().expect("should get current dir");

        let context = Context::builder()
            .output(test_output())
            .build()
            .expect("should create context");

        assert_eq!(context.current_working_directory().get(), expected);
    }

    // r[verify cancel.context.default]
    #[test]
    fn new_with_defaults_has_uncancelled_token() {
        let context = Context::builder()
            .current_working_directory(Path::new("/tmp"))
            .output(test_output())
            .build()
            .expect("should create context");

        assert!(!context.cancellation().is_cancelled());
    }

    #[test]
    fn new_with_defaults_is_non_interactive() {
        let context = Context::builder()
            .current_working_directory(Path::new("/tmp"))
            .output(test_output())
            .build()
            .expect("should create context");

        assert_eq!(context.interactivity(), Interactivity::NonInteractive);
    }

    #[test]
    fn new_with_interactivity_uses_provided_value() {
        let context = Context::builder()
            .current_working_directory(Path::new("/tmp"))
            .interactivity(Interactivity::Interactive)
            .output(test_output())
            .build()
            .expect("should create context");

        assert_eq!(context.interactivity(), Interactivity::Interactive);
    }

    // r[verify context.process]
    #[cfg(unix)]
    #[tokio::test]
    async fn process_reports_through_the_output_of_the_context() {
        let (sender, mut receiver) = event_channel();
        let context = Context::builder()
            .output(Output::new(sender))
            .build()
            .expect("should build");
        let invocation = Invocation::new("sh").arg("-c").arg("exit 0");

        context
            .process()
            .run(invocation.clone())
            .await
            .expect("should run");

        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}"))
        );
    }

    #[test]
    fn prompt_carries_the_interactivity_of_the_context() {
        let context = Context::builder()
            .current_working_directory(Path::new("/tmp"))
            .interactivity(Interactivity::Interactive)
            .output(test_output())
            .build()
            .expect("should create context");

        let prompt = context.prompt();

        assert_eq!(prompt.interactivity(), Interactivity::Interactive);
    }

    #[tokio::test]
    async fn prompt_observes_the_cancellation_of_the_context() {
        let cancellation = Cancellation::new();
        let (sender, _receiver) = event_channel();
        let context = Context::builder()
            .current_working_directory(Path::new("/tmp"))
            .cancellation(cancellation.clone())
            .interactivity(Interactivity::Interactive)
            .output(Output::new(sender))
            .build()
            .expect("should create context");
        cancellation.cancel();

        let error = context
            .prompt()
            .confirm("Release?")
            .await
            .expect_err("should fail");

        assert_eq!(
            error.to_string(),
            "the prompt `Release?` was cancelled before the user answered"
        );
    }

    #[tokio::test]
    async fn prompt_sends_through_the_output_of_the_context() {
        let (sender, mut receiver) = event_channel();
        let context = Context::builder()
            .current_working_directory(Path::new("/tmp"))
            .interactivity(Interactivity::Interactive)
            .output(Output::new(sender))
            .build()
            .expect("should create context");
        let prompt = context.prompt();
        let command = tokio::spawn(async move { prompt.confirm("Release?").await });

        let event = receiver.recv().await;
        command.abort();

        assert_eq!(
            event.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 context.safety.send]
    #[test]
    fn trait_send() {
        fn assert_send<T: Send>() {}
        assert_send::<Context>();
    }

    // r[verify context.safety.sync]
    #[test]
    fn trait_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<Context>();
    }

    // r[verify context.safety.unpin]
    #[test]
    fn trait_unpin() {
        fn assert_unpin<T: Unpin>() {}
        assert_unpin::<Context>();
    }
}