-
Notifications
You must be signed in to change notification settings - Fork 8
/
elvish.rs
240 lines (214 loc) · 7.36 KB
/
elvish.rs
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
use super::Shell;
use crate::helpers::{get_config_dir, get_env_var_regex, normalize_newlines, PATH_DELIMITER};
use crate::hooks::*;
use std::collections::HashSet;
use std::fmt;
use std::path::{Path, PathBuf};
#[derive(Clone, Copy, Debug)]
pub struct Elvish;
impl Elvish {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self
}
}
fn format(value: impl AsRef<str>) -> String {
get_env_var_regex()
.replace_all(value.as_ref(), "$$E:$name")
.replace("$E:HOME", "{~}")
}
// https://elv.sh/ref/command.html#using-elvish-interactivelyn
impl Shell for Elvish {
fn format(&self, statement: Statement<'_>) -> String {
match statement {
Statement::PrependPath {
paths,
key,
orig_key,
} => {
let key = key.unwrap_or("PATH");
let orig_key = orig_key.unwrap_or(key);
if key == "PATH" && orig_key == "PATH" {
format!(
"set paths = [{} $@paths];",
format(
paths
.iter()
.map(|p| self.quote(p))
.collect::<Vec<_>>()
.join(" ")
)
)
} else {
format!(
r#"set-env {key} "{}{}"$E:{orig_key};"#,
paths.join(PATH_DELIMITER),
PATH_DELIMITER,
)
}
}
Statement::SetEnv { key, value } => {
format!(
"set-env {} {};",
self.quote(key),
self.quote(&format(value)).as_str()
)
}
Statement::UnsetEnv { key } => {
format!("unset-env {};", self.quote(key))
}
}
}
fn format_hook(&self, hook: Hook) -> Result<String, crate::ShellError> {
Ok(normalize_newlines(match hook {
Hook::OnChangeDir { command, function } => {
format!(
r#"
set-env __ORIG_PATH $E:PATH
fn {function} {{
eval ({command});
}}
set @edit:before-readline = $@edit:before-readline {{
{function}
}}
"#
)
}
}))
}
fn get_config_path(&self, home_dir: &Path) -> PathBuf {
get_config_dir(home_dir).join("elvish").join("rc.elv")
}
fn get_env_path(&self, home_dir: &Path) -> PathBuf {
self.get_config_path(home_dir)
}
fn get_profile_paths(&self, home_dir: &Path) -> Vec<PathBuf> {
#[allow(unused_mut)]
let mut profiles = HashSet::<PathBuf>::from_iter([
get_config_dir(home_dir).join("elvish").join("rc.elv"),
home_dir.join(".config").join("elvish").join("rc.elv"),
home_dir.join(".elvish").join("rc.elv"), // Legacy
]);
#[cfg(windows)]
{
profiles.insert(
home_dir
.join("AppData")
.join("Roaming")
.join("elvish")
.join("rc.elv"),
);
}
profiles.into_iter().collect()
}
/// Quotes a string according to Elvish shell quoting rules.
/// @see <https://elv.sh/ref/language.html#single-quoted-string>
#[allow(clippy::no_effect_replace)]
fn quote(&self, value: &str) -> String {
// Check if the value is a bareword (only specific characters allowed)
let is_bareword = value
.chars()
.all(|c| c.is_ascii_alphanumeric() || "-._:@/%~=+".contains(c));
if is_bareword {
// Barewords: no quotes needed
value.to_string()
} else if value.contains("{~}") {
// Special case for {~} within the value to escape quoting
value.to_string()
} else if value.chars().any(|c| {
c.is_whitespace()
|| [
'$', '"', '`', '\\', '\n', '\t', '\x07', '\x08', '\x0C', '\r', '\x1B', '\x7F',
]
.contains(&c)
}) {
// Double-quoted strings with escape sequences
format!(
r#""{}""#,
value
.replace('\\', "\\\\")
.replace('\n', "\\n")
.replace('\t', "\\t")
.replace('\x07', "\\a")
.replace('\x08', "\\b")
.replace('\x0C', "\\f")
.replace('\r', "\\r")
.replace('\x1B', "\\e")
.replace('\"', "\\\"")
.replace('\x7F', "\\^?")
.replace('\0', "\x00")
)
} else {
// Single-quoted strings for non-barewords containing special characters
format!("'{}'", value.replace('\'', "''").replace('\0', "\x00"))
}
}
}
impl fmt::Display for Elvish {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "elvish")
}
}
#[cfg(test)]
mod tests {
use super::*;
use starbase_sandbox::assert_snapshot;
#[test]
fn formats_env_var() {
assert_eq!(
Elvish.format_env_set("PROTO_HOME", "$HOME/.proto"),
"set-env PROTO_HOME {~}/.proto;"
);
assert_eq!(Elvish.format_env_set("FOO", "bar"), "set-env FOO bar;");
}
#[test]
fn formats_path() {
assert_eq!(
Elvish.format_path_set(&["$PROTO_HOME/shims".into(), "$PROTO_HOME/bin".into()]),
r#"set paths = ["$E:PROTO_HOME/shims" "$E:PROTO_HOME/bin" $@paths];"#
);
}
#[test]
fn formats_cd_hook() {
let hook = Hook::OnChangeDir {
command: "starbase hook elvish".into(),
function: "_starbase_hook".into(),
};
assert_snapshot!(Elvish.format_hook(hook).unwrap());
}
#[test]
fn test_elvish_quoting() {
// Barewords
assert_eq!(Elvish.quote("simple"), "simple");
assert_eq!(Elvish.quote("a123"), "a123");
assert_eq!(Elvish.quote("foo_bar"), "foo_bar");
assert_eq!(Elvish.quote("A"), "A");
// Single quotes
assert_eq!(Elvish.quote("it's"), "'it''s'");
assert_eq!(Elvish.quote("value'with'quotes"), "'value''with''quotes'");
// Double quotes
assert_eq!(Elvish.quote("value with spaces"), r#""value with spaces""#);
assert_eq!(
Elvish.quote("value\"with\"quotes"),
r#""value\"with\"quotes""#
);
assert_eq!(
Elvish.quote("value\nwith\nnewlines"),
r#""value\nwith\nnewlines""#
);
assert_eq!(Elvish.quote("value\twith\ttabs"), r#""value\twith\ttabs""#);
assert_eq!(
Elvish.quote("value\\with\\backslashes"),
r#""value\\with\\backslashes""#
);
// Escape sequences
assert_eq!(Elvish.quote("\x41"), "A"); // A is a bareword
assert_eq!(Elvish.quote("\u{0041}"), "A"); // A is a bareword
assert_eq!(Elvish.quote("\x09"), r#""\t""#);
assert_eq!(Elvish.quote("\x07"), r#""\a""#);
assert_eq!(Elvish.quote("\x1B"), r#""\e""#);
assert_eq!(Elvish.quote("\x7F"), r#""\^?""#);
// Unsupported sequences
assert_eq!(Elvish.quote("\0"), "'\x00'".to_string());
}
}