Skip to content

Commit 1fdd4a7

Browse files
authored
Display current_dir and envs in commands (#25)
Teach `Utf8ProgramAndArgs` about `current_dir` and `envs` when displaying commands. Closes #21
1 parent b165a51 commit 1fdd4a7

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/utf8_program_and_args.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,44 @@ use crate::CommandDisplay;
2020
/// displayed.to_string(),
2121
/// "echo 'puppy doggy'"
2222
/// );
23+
///
24+
/// let mut command = Command::new("echo");
25+
/// command.arg("doggy")
26+
/// .current_dir("/puppy")
27+
/// .env("COLOR", "GOLDEN")
28+
/// .env_remove("STINKY");
29+
/// let displayed: Utf8ProgramAndArgs = (&command).into();
30+
/// assert_eq!(
31+
/// displayed.to_string(),
32+
/// "cd /puppy && COLOR=GOLDEN STINKY= echo doggy"
33+
/// );
2334
/// ```
2435
#[derive(Debug, Clone)]
2536
pub struct Utf8ProgramAndArgs {
37+
current_dir: Option<String>,
38+
envs: Vec<(String, Option<String>)>,
2639
program: String,
2740
args: Vec<String>,
2841
}
2942

3043
impl Display for Utf8ProgramAndArgs {
3144
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45+
if let Some(current_dir) = &self.current_dir {
46+
write!(f, "cd {} && ", shell_words::quote(current_dir))?;
47+
}
48+
49+
for (key, value) in self.envs.iter() {
50+
// TODO: Should I care about spaces in environment variable names???
51+
write!(
52+
f,
53+
"{key}={} ",
54+
value
55+
.as_deref()
56+
.map(|value| shell_words::quote(value))
57+
.unwrap_or_default()
58+
)?;
59+
}
60+
3261
write!(f, "{}", shell_words::quote(&self.program))?;
3362
if !self.args.is_empty() {
3463
write!(f, " {}", shell_words::join(&self.args))?;
@@ -54,6 +83,18 @@ impl CommandDisplay for Utf8ProgramAndArgs {
5483
impl<'a> From<&'a Command> for Utf8ProgramAndArgs {
5584
fn from(command: &'a Command) -> Self {
5685
Utf8ProgramAndArgs {
86+
current_dir: command
87+
.get_current_dir()
88+
.map(|path| path.to_string_lossy().into_owned()),
89+
envs: command
90+
.get_envs()
91+
.map(|(key, value)| {
92+
(
93+
key.to_string_lossy().into_owned(),
94+
value.map(|value| value.to_string_lossy().into_owned()),
95+
)
96+
})
97+
.collect(),
5798
program: command.get_program().to_string_lossy().into_owned(),
5899
args: command
59100
.get_args()

0 commit comments

Comments
 (0)