cromulent 0.1.1

A safe wrapper around `wordexp-sys`.
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! A safe wrapper around the `wordexp(3)` C function.
//!
//! The main entry-point for this crate is [WordExpander], which will point you
//! towards other areas of the docs.

pub mod path;
pub mod utf8;

/// A builder-pattern struct for selecting the options to pass to `wordexp`.
///
/// # Safety
///
/// `expand` calls `wordexp(3)`, which is not thread-safe. In reality it's only
/// unsafe if you call certain functions while the call to `wordexp` is
/// occurring. See the man page for more information.
///
/// # Examples
///
/// ```
/// # use std::collections::HashSet;
/// let words = cromulent::WordExpander::default().expand("Car*l*")?;
/// let utf8 = cromulent::utf8::WordList::from(&words);
///
/// let actual = utf8.into_iter().collect::<HashSet<_>>();
/// let expected = HashSet::from(["Cargo.lock", "Cargo.toml"]);
///
/// assert_eq!(actual, expected);
/// # Ok::<(), cromulent::WordError>(())
/// ```
///
/// By default commands and undefined variables are not allowed:
///
/// ```
/// let command_words = cromulent::WordExpander::default().expand("$(echo hi)");
///
/// assert_eq!(
///     command_words,
///     Err(cromulent::WordError::CommandSubstitution)
/// );
/// ```
///
/// ```
/// # assert!(std::env::var("hopefully_this_variable_does_not_exist").is_err());
/// let var_words =
///     cromulent::WordExpander::default().expand("$hopefully_this_variable_does_not_exist");
///
/// assert_eq!(var_words, Err(cromulent::WordError::UndefinedVariable));
/// ```
/// Instead you must explicitly enable them:
///
/// ```
/// # assert!(std::env::var("hopefully_this_variable_does_not_exist").is_err());
/// let words = cromulent::WordExpander::default()
///     .allow_commands()
///     .allow_undefined()
///     .expand("$(echo hi)$hopefully_this_variable_does_not_exist")?;
/// let utf8 = cromulent::utf8::WordList::from(&words);
///
/// assert_eq!(&utf8[0], "hi");
/// # Ok::<(), cromulent::WordError>(())
/// ```
#[derive(Clone, Debug, Default)]
pub struct WordExpander {
    allow_commands: bool,
    allow_undefined: bool,
    show_stderr: bool,
}

impl WordExpander {
    /// Allow `wordexp` to run subcommands.
    ///
    /// By default `expand` will error if you try to run a subcommand, calling
    /// this function enables that functionality.
    ///
    /// # Examples
    ///
    /// ```
    /// let command_not_allowed = cromulent::WordExpander::default().expand("$(echo hi)");
    ///
    /// assert_eq!(
    ///     command_not_allowed,
    ///     Err(cromulent::WordError::CommandSubstitution)
    /// );
    /// ```
    ///
    /// ```
    /// let command_allowed = cromulent::WordExpander::default()
    ///     .allow_commands()
    ///     .expand("$(echo hi)")?;
    ///
    /// assert_eq!(command_allowed[0].to_str(), Ok("hi"));
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub fn allow_commands(self) -> Self {
        Self {
            allow_commands: true,
            ..self
        }
    }

    /// Allow `wordexp` to ignore undefined variables.
    ///
    /// By default `expand` will error if you try to expand a variable that is
    /// not in the environment, calling this function instead ignores it.
    ///
    /// # Examples
    ///
    /// ```
    /// # assert!(std::env::var("please_do_not_break_my_tests_by_defining_this_variable").is_err());
    /// let undefined_not_allowed = cromulent::WordExpander::default()
    ///     .expand("$please_do_not_break_my_tests_by_defining_this_variable");
    ///
    /// assert_eq!(
    ///     undefined_not_allowed,
    ///     Err(cromulent::WordError::UndefinedVariable)
    /// );
    /// ```
    ///
    /// ```
    /// # assert!(std::env::var("please_do_not_break_my_tests_by_defining_this_variable").is_err());
    /// let undefined_allowed = cromulent::WordExpander::default()
    ///     .allow_undefined()
    ///     .expand("$please_do_not_break_my_tests_by_defining_this_variable")?;
    ///
    /// assert!(undefined_allowed.is_empty());
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub fn allow_undefined(self) -> Self {
        Self {
            allow_undefined: true,
            ..self
        }
    }

    /// Show the error stream of subcommands.
    ///
    /// By default the error stream of subcommands is redirected to `/dev/null`,
    /// calling this function prevents that from happening.
    ///
    /// # Examples
    ///
    /// This example will not print anything to `stderr`:
    ///
    /// ```
    /// let words = cromulent::WordExpander::default()
    ///     .allow_commands()
    ///     .expand("$(>&2 echo hi)")?;
    ///
    /// assert!(words.is_empty());
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    ///
    /// This example, however, will print `"hi"` to `stderr`:
    ///
    /// ```
    /// let words = cromulent::WordExpander::default()
    ///     .allow_commands()
    ///     .show_stderr()
    ///     .expand("$(>&2 echo hi)")?;
    ///
    /// assert!(words.is_empty());
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub fn show_stderr(self) -> Self {
        Self {
            show_stderr: true,
            ..self
        }
    }

    /// Run `wordexp` with the configured options.
    ///
    /// See `man 3 wordexp` and [WordList].
    pub fn expand<'l, S: AsRef<str>>(self, string: S) -> Result<WordList<'l>, WordError> {
        let words = std::ffi::CString::new(string.as_ref())?;
        self.expand_cstr(&words)
    }

    /// Like [`expand`](WordExpander::expand), but avoids an allocation.
    ///
    /// This is useful if you already have a [`CString`](std::ffi::CString),
    /// otherwise one will need to be allocated to hold the null-byte.
    pub fn expand_cstr<'l>(self, string: &std::ffi::CStr) -> Result<WordList<'l>, WordError> {
        let words = string.as_ptr();

        let flags = {
            let mut flags = 0;

            if !self.allow_commands {
                flags |= wordexp_sys::WRDE_NOCMD;
            }

            if !self.allow_undefined {
                flags |= wordexp_sys::WRDE_UNDEF;
            }

            if self.show_stderr {
                flags |= wordexp_sys::WRDE_SHOWERR;
            }

            flags.try_into().expect("All flags are positive.")
        };

        let mut raw = wordexp_sys::wordexp_t {
            we_wordc: 0,
            we_wordv: std::ptr::null_mut(),
            we_offs: 0,
        };

        let code = unsafe { wordexp_sys::wordexp(words, &mut raw, flags) };

        if code == 0 {
            let wordexp_sys::wordexp_t {
                we_wordc: count,
                we_wordv: values,
                we_offs: offsets,
            } = raw;
            assert!(
                !values.is_null(),
                "This pointer should always point to at least a null pointer."
            );
            assert_eq!(offsets, 0, "Offsets can't have been set.");
            let count = count
                .try_into()
                .expect("Bindgen should have handled making sure this works");

            Ok(WordList(unsafe {
                std::slice::from_raw_parts(values as *const *const _, count)
            }))
        } else {
            unsafe { wordexp_sys::wordfree(&mut raw) };

            Err(
                match code
                    .try_into()
                    .expect("All the values it can take are positive.")
                {
                    wordexp_sys::WRDE_BADCHAR => WordError::IllegalCharacter,
                    wordexp_sys::WRDE_BADVAL => WordError::UndefinedVariable,
                    wordexp_sys::WRDE_CMDSUB => WordError::CommandSubstitution,
                    wordexp_sys::WRDE_NOSPACE => panic!("out of memory"),
                    wordexp_sys::WRDE_SYNTAX => WordError::Syntax,
                    _ => unreachable!("Only these values can be returned from the call."),
                },
            )
        }
    }
}

/// The error type returned by [`WordExpander::expand`].
///
/// `wordexp` only returns a integer error code, so unfortunately there is not
/// much that can be said about the error itself (e.g. syntax errors won't point
/// to the invalid syntax).
#[derive(Clone, Debug, thiserror::Error, Eq, PartialEq)]
pub enum WordError {
    /// You tried to run a command without explicitly allowing it.
    ///
    /// ```
    /// assert_eq!(
    ///     cromulent::WordExpander::default().expand("$(echo hi)"),
    ///     Err(cromulent::WordError::CommandSubstitution)
    /// );
    /// ```
    ///
    /// ```
    /// assert!(cromulent::WordExpander::default()
    ///     .allow_commands()
    ///     .expand("$(echo hi)")
    ///     .is_ok());
    /// ```
    #[error("command substitution was attempted")]
    CommandSubstitution,
    /// You tried to expand a string that contains an embedded null-byte.
    ///
    /// ```
    /// assert_eq!(
    ///     cromulent::WordExpander::default().expand("a\0b"),
    ///     Err(cromulent::WordError::EmbeddedNul(
    ///         std::ffi::CString::new("a\0b").unwrap_err()
    ///     ))
    /// );
    /// ```
    #[error("the input string has a null-byte in the middle of it: {0}")]
    EmbeddedNul(#[from] std::ffi::NulError),
    /// You tried to expand a string containing certain illegal characters.
    ///
    /// See the `wordexp(3)` man page for more information on what exactly these
    /// characters are.
    ///
    /// ```
    /// assert_eq!(
    ///     cromulent::WordExpander::default().expand("{1,2,3}"),
    ///     Err(cromulent::WordError::IllegalCharacter)
    /// );
    /// ```
    #[error("an illegal character was passed in the input")]
    IllegalCharacter,
    /// You tried to expand a string containing invalid syntax.
    ///
    /// See the `wordexp(3)` man page for more information about valid syntax.
    ///
    /// ```
    /// assert_eq!(
    ///     cromulent::WordExpander::default().expand("Hello $(echo world"),
    ///     Err(cromulent::WordError::Syntax)
    /// );
    /// ```
    #[error("there was a syntax error in the input")]
    Syntax,
    /// You tried to expand a string containing a variable with no definition.
    ///
    /// Ignoring undefined variables must be explicitly enabled.
    ///
    /// ```
    /// # assert!(std::env::var("no_breaking_my_documentation").is_err());
    /// assert_eq!(
    ///     cromulent::WordExpander::default().expand("$no_breaking_my_documentation"),
    ///     Err(cromulent::WordError::UndefinedVariable)
    /// );
    /// ```
    ///
    /// ```
    /// # assert!(std::env::var("no_breaking_my_documentation").is_err());
    /// assert!(cromulent::WordExpander::default()
    ///     .allow_undefined()
    ///     .expand("$no_breaking_my_documentation")
    ///     .is_ok());
    /// ```
    #[error("a variable used in the input was undefined")]
    UndefinedVariable,
}

/// A slice-like type representing the expanded words.
///
/// Elements of this "slice" are [`CStr`](std::ffi::CStr), if you expect your
/// words to be valid UTF-8 you might prefer to use [utf8::WordList].
///
/// # Examples
///
/// All examples will use the following expansion:
///
/// ```
/// let words = cromulent::WordExpander::default()
///     .allow_commands()
///     .expand("$(seq 3)")?;
///
/// # Ok::<(), cromulent::WordError>(())
/// ```
///
/// Length-checking:
///
/// ```
/// # let words = cromulent::WordExpander::default()
/// #     .allow_commands()
/// #     .expand("$(seq 3)")?;
///
/// assert!(!words.is_empty());
/// assert_eq!(words.len(), 3);
/// assert_eq!(words[0].to_str(), Ok("1"));
///
/// # Ok::<(), cromulent::WordError>(())
/// ```
///
/// Indexing:
///
/// ```
/// # let words = cromulent::WordExpander::default()
/// #     .allow_commands()
/// #     .expand("$(seq 3)")?;
///
/// assert_eq!(words[0].to_str(), Ok("1"));
///
/// # Ok::<(), cromulent::WordError>(())
/// ```
///
/// Iteration:
///
/// ```
/// # let words = cromulent::WordExpander::default()
/// #     .allow_commands()
/// #     .expand("$(seq 3)")?;
///
/// for (i, word) in words.into_iter().enumerate() {
///     assert_eq!(word.to_str()?.parse::<usize>()?, i + 1)
/// }
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
// TODO: Can this take a cue from CStr and be an unsized type?
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WordList<'l>(&'l [*const std::os::raw::c_char]);

impl<'l> Drop for WordList<'l> {
    fn drop(&mut self) {
        let mut raw = wordexp_sys::wordexp_t {
            we_wordc: self
                .0
                .len()
                .try_into()
                .expect("Bindgen should have handled making this work."),
            we_wordv: self.0.as_ptr() as *mut _,
            we_offs: 0,
        };

        unsafe { wordexp_sys::wordfree(&mut raw) };
    }
}

impl<'l> std::ops::Index<usize> for WordList<'l> {
    type Output = std::ffi::CStr;

    fn index(&self, index: usize) -> &'l Self::Output {
        unsafe { std::ffi::CStr::from_ptr(self.0[index]) }
    }
}

impl<'l> WordList<'l> {
    /// Return `true` if no words were expanded.
    ///
    /// # Examples
    ///
    /// ```
    /// let words = cromulent::WordExpander::default().expand("")?;
    /// assert!(words.is_empty());
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Return the number of words that the input expanded into.
    ///
    /// # Examples
    ///
    /// ```
    /// let words = cromulent::WordExpander::default().expand("")?;
    /// assert_eq!(words.len(), 0);
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    ///
    /// ```
    /// let words = cromulent::WordExpander::default()
    ///     .allow_commands()
    ///     .expand("$(seq 3)")?;
    /// assert_eq!(words.len(), 3);
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Return the word at a given index without panicking.
    ///
    /// # Examples
    ///
    /// ```
    /// let words = cromulent::WordExpander::default()
    ///     .allow_commands()
    ///     .expand("$(seq 3)")?;
    ///
    /// assert_eq!(words.get(1), Some(&words[1]));
    /// assert_eq!(words.get(3), None);
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub fn get(&self, index: usize) -> Option<&<Self as std::ops::Index<usize>>::Output> {
        if index < self.len() {
            Some(&self[index])
        } else {
            None
        }
    }

    /// Return the word at a given index without bounds checks.
    ///
    /// # Safety
    ///
    /// Callers of this function are responsible for ensuring that `index <
    /// self.len()`.
    ///
    /// # Examples
    ///
    /// ```
    /// let words = cromulent::WordExpander::default()
    ///     .allow_commands()
    ///     .expand("$(seq 3)")?;
    ///
    /// assert_eq!(unsafe { words.get_unchecked(1) }, &words[1]);
    /// // DANGER!
    /// // assert_eq!(unsafe { words.get_unchecked(3) }, None);
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub unsafe fn get_unchecked(&self, index: usize) -> &<Self as std::ops::Index<usize>>::Output {
        let element = self.0.get_unchecked(index);
        std::ffi::CStr::from_ptr(*element)
    }
}

impl<'u, 'l: 'u> WordList<'l> {
    /// Return a WordList that assumes words are valid UTF-8.
    ///
    /// UTF-8 correctness is checked lazily.
    ///
    /// # Examples
    ///
    /// ```
    /// let words = cromulent::WordExpander::default().expand("what a nice sentence")?;
    /// assert_eq!(&words[0], &*std::ffi::CString::new("what").unwrap());
    ///
    /// let utf8 = words.utf8();
    /// assert_eq!(&utf8[0], "what");
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    ///
    /// ```
    /// let invalid =
    ///     cromulent::WordExpander::default().expand_cstr(&std::ffi::CString::new(vec![243, 222])?);
    /// assert!(invalid.is_ok());
    ///
    /// let invalid = invalid.unwrap();
    /// let invalid = invalid.utf8();
    /// let result = std::panic::catch_unwind(|| &invalid[0]);
    /// assert!(result.is_err());
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub fn utf8(&'u self) -> utf8::WordList<'u, 'l> {
        utf8::WordList::new(self)
    }

    /// Return a WordList that checks words are valid UTF-8.
    ///
    /// UTF-8 correctness is checked eagerly.
    ///
    /// # Examples
    ///
    /// ```
    /// let words = cromulent::WordExpander::default().expand("what a nice sentence")?;
    /// assert_eq!(&words[0], &*std::ffi::CString::new("what").unwrap());
    ///
    /// let utf8 = words.utf8();
    /// assert_eq!(&utf8[0], "what");
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    ///
    /// ```
    /// let invalid = cromulent::WordExpander::default().expand_cstr(&std::ffi::CString::new(vec![243, 222])?);
    /// assert!(invalid.is_ok());
    ///
    /// let invalid = invalid.unwrap();
    /// let invalid = invalid.utf8_eager();
    /// assert!(invalid.is_err());
    ///
    /// # Ok::<(), cromulent::WordError>(())
    pub fn utf8_eager(&'u self) -> Result<utf8::WordList<'u, 'l>, std::str::Utf8Error> {
        utf8::WordList::new_eager(self)
    }
}

impl<'p, 'l: 'p> WordList<'l> {
    /// Return a WordList that assumes words are valid paths.
    ///
    /// # Examples
    ///
    /// ```
    /// let words = cromulent::WordExpander::default().expand("tests/lib.rs")?;
    /// assert_eq!(&words[0], &*std::ffi::CString::new("tests/lib.rs").unwrap());
    ///
    /// let path = words.path();
    /// assert_eq!(&path[0], std::path::Path::new("tests/lib.rs"));
    ///
    /// # Ok::<(), cromulent::WordError>(())
    /// ```
    pub fn path(&'p self) -> path::WordList<'p, 'l> {
        path::WordList::new(self)
    }
}

pub struct Iter<'r, 'l: 'r> {
    word_list: &'r WordList<'l>,
    index: usize,
}

impl<'r, 'l: 'r> IntoIterator for &'r WordList<'l> {
    type IntoIter = Iter<'r, 'l>;
    type Item = <Self::IntoIter as Iterator>::Item;

    fn into_iter(self) -> Self::IntoIter {
        Iter {
            word_list: self,
            index: 0,
        }
    }
}

impl<'r, 'l: 'r> Iterator for Iter<'r, 'l> {
    type Item = &'r <WordList<'l> as std::ops::Index<usize>>::Output;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.word_list.len() {
            None
        } else {
            let result = &self.word_list[self.index];
            self.index += 1;
            Some(result)
        }
    }
}