Skip to content

Commit 95e99ef

Browse files
committed
refactor(complete): Pull out shell lookup
1 parent 4af0cd6 commit 95e99ef

File tree

1 file changed

+26
-21
lines changed

1 file changed

+26
-21
lines changed

clap_complete/src/env/mod.rs

+26-21
Original file line numberDiff line numberDiff line change
@@ -217,27 +217,7 @@ impl<'s, F: Fn() -> clap::Command> CompleteEnv<'s, F> {
217217
// completion logic.
218218
std::env::remove_var(self.var);
219219

220-
// Strip off the parent dir in case `$SHELL` was used
221-
let name = std::path::Path::new(&name).file_stem().unwrap_or(&name);
222-
// lossy won't match but this will delegate to unknown
223-
// error
224-
let name = name.to_string_lossy();
225-
226-
let shell = self.shells.completer(&name).ok_or_else(|| {
227-
let shells = self
228-
.shells
229-
.names()
230-
.enumerate()
231-
.map(|(i, name)| {
232-
let prefix = if i == 0 { "" } else { ", " };
233-
format!("{prefix}`{name}`")
234-
})
235-
.collect::<String>();
236-
std::io::Error::new(
237-
std::io::ErrorKind::Other,
238-
format!("unknown shell `{name}`, expected one of {shells}"),
239-
)
240-
})?;
220+
let shell = self.shell(std::path::Path::new(&name))?;
241221

242222
let mut cmd = (self.factory)();
243223
cmd.build();
@@ -279,6 +259,31 @@ impl<'s, F: Fn() -> clap::Command> CompleteEnv<'s, F> {
279259

280260
Ok(true)
281261
}
262+
263+
fn shell(&self, name: &std::path::Path) -> Result<&dyn EnvCompleter, std::io::Error> {
264+
// Strip off the parent dir in case `$SHELL` was used
265+
let name = name.file_stem().unwrap_or(name.as_os_str());
266+
// lossy won't match but this will delegate to unknown
267+
// error
268+
let name = name.to_string_lossy();
269+
270+
let shell = self.shells.completer(&name).ok_or_else(|| {
271+
let shells = self
272+
.shells
273+
.names()
274+
.enumerate()
275+
.map(|(i, name)| {
276+
let prefix = if i == 0 { "" } else { ", " };
277+
format!("{prefix}`{name}`")
278+
})
279+
.collect::<String>();
280+
std::io::Error::new(
281+
std::io::ErrorKind::Other,
282+
format!("unknown shell `{name}`, expected one of {shells}"),
283+
)
284+
})?;
285+
Ok(shell)
286+
}
282287
}
283288

284289
/// Collection of shell-specific completers

0 commit comments

Comments
 (0)