Skip to main content

shrub_core/shell/
expansion.rs

1//! Expansion support for shell instances.
2
3use std::borrow::Cow;
4
5use crate::interp::ExecutionParameters;
6use crate::{error, expansion, extensions};
7
8impl<SE: extensions::ShellExtensions> crate::Shell<SE> {
9    /// Returns the current value of the IFS variable, or the default value if
10    /// it is not set.
11    pub fn ifs(&self) -> Cow<'_, str> {
12        self.env_var("IFS")
13            .filter(|var| var.value().is_set())
14            .map_or_else(|| " \t\n".into(), |var| var.value().to_cow_str(self))
15    }
16
17    /// Returns the separator that joins the fields of `$*` and `${arr[*]}`: the
18    /// first character of IFS, or nothing at all when IFS is empty (an
19    /// unset IFS is a space).
20    pub(crate) fn ifs_joiner(&self) -> String {
21        self.ifs()
22            .chars()
23            .next()
24            .map_or_else(String::new, String::from)
25    }
26
27    /// Applies basic shell expansion to the provided string.
28    ///
29    /// # Arguments
30    ///
31    /// * `s` - The string to expand.
32    pub async fn basic_expand_string<S: AsRef<str>>(
33        &mut self,
34        params: &ExecutionParameters,
35        s: S,
36    ) -> Result<String, error::Error> {
37        let result = expansion::basic_expand_word(self, params, s.as_ref()).await?;
38        Ok(result)
39    }
40
41    /// Applies full shell expansion and field splitting to the provided string;
42    /// returns a sequence of fields.
43    ///
44    /// # Arguments
45    ///
46    /// * `s` - The string to expand and split.
47    pub async fn full_expand_and_split_string<S: AsRef<str>>(
48        &mut self,
49        params: &ExecutionParameters,
50        s: S,
51    ) -> Result<Vec<String>, error::Error> {
52        let result = expansion::full_expand_and_split_word(self, params, s.as_ref()).await?;
53        Ok(result)
54    }
55}