Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support tilde expansion #128

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 98 additions & 1 deletion src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use anyhow::bail;
use anyhow::Result;
use monch::*;
use std::path::PathBuf;

// Shell grammar rules this is loosely based on:
// https://pubs.opengroup.org/onlinepubs/009604499/utilities/xcu_chap02.html#tag_02_10_02
Expand Down Expand Up @@ -338,6 +339,15 @@ pub fn parse(input: &str) -> Result<SequentialList> {
}
}

fn home_dir() -> Option<PathBuf> {
if let Some(userprofile) = std::env::var_os("USERPROFILE") {
if !userprofile.is_empty() {
return Some(PathBuf::from(userprofile));
}
}
None
}

fn parse_sequential_list(input: &str) -> ParseResult<SequentialList> {
let (input, items) = separated_list(
terminated(parse_sequential_list_item, skip_whitespace),
Expand Down Expand Up @@ -758,6 +768,25 @@ fn parse_word_parts(
)
}

fn expand_tilde(result: &mut [WordPart]) {
if let Some(WordPart::Text(text)) = result.last_mut() {
if text.contains(" ~ ")
|| text.contains("~/")
|| (text.find('~').unwrap_or(0) == text.len() - 1)
{
let temp = text.clone().replace(
'~',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add this as a test case? I think it will fail: echo ~/test/~/test (should only expand ~/)

home_dir()
.unwrap_or(PathBuf::from("~"))
.to_str()
.unwrap_or("~"),
);
text.clear();
text.push_str(temp.as_str());
}
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should do this while parsing, but instead during execution. The home directory in the shell might change while running. For example, the following test case should pass:

$ export HOME=test ; echo ~/test/~/test
test/test/~/test


move |input| {
enum PendingPart<'a> {
Char(char),
Expand Down Expand Up @@ -791,7 +820,7 @@ fn parse_word_parts(
if_true(next_char, |&c| match mode {
ParseWordPartsMode::DoubleQuotes => c != '"',
ParseWordPartsMode::Unquoted => {
!c.is_whitespace() && !"~(){}<>|&;\"'".contains(c)
!c.is_whitespace() && !"(){}<>|&;\"'".contains(c)
}
}),
PendingPart::Char,
Expand Down Expand Up @@ -828,6 +857,10 @@ fn parse_word_parts(
}
}

if mode == ParseWordPartsMode::Unquoted {
expand_tilde(&mut result);
}

Ok((input, result))
}
}
Expand Down Expand Up @@ -1507,6 +1540,70 @@ mod test {
}
}

#[test]
fn test_tilde_unquoted_expansion() {
let home_dir = home_dir()
.unwrap_or(PathBuf::from("~"))
.to_str()
.unwrap_or("~")
.to_string();
run_test(
parse_sequential_list,
"echo ~",
Ok(SequentialList {
items: vec![SequentialListItem {
is_async: false,
sequence: Sequence::Pipeline(Pipeline {
negated: false,
inner: PipelineInner::Command(Command {
inner: CommandInner::Simple(SimpleCommand {
env_vars: [].to_vec(),
args: [
Word([WordPart::Text("echo".to_string())].to_vec()),
Word([WordPart::Text(home_dir)].to_vec()),
]
.to_vec(),
}),
redirect: None,
}),
}),
}],
}),
);
}

#[test]
fn test_tilde_as_char() {
run_test(
parse_sequential_list,
"echo \"~\"",
Ok(SequentialList {
items: vec![SequentialListItem {
is_async: false,
sequence: Sequence::Pipeline(Pipeline {
negated: false,
inner: PipelineInner::Command(Command {
inner: CommandInner::Simple(SimpleCommand {
env_vars: [].to_vec(),
args: [
Word([WordPart::Text("echo".to_string())].to_vec()),
Word(
[WordPart::Quoted(
[WordPart::Text("~".to_string())].to_vec(),
)]
.to_vec(),
),
]
.to_vec(),
}),
redirect: None,
}),
}),
}],
}),
);
}

#[test]
fn test_redirects() {
let expected = Ok(Command {
Expand Down