Skip to content

Commit

Permalink
Pass in context
Browse files Browse the repository at this point in the history
  • Loading branch information
casey committed Jan 22, 2025
1 parent c2d889c commit 522311c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
5 changes: 2 additions & 3 deletions src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,8 +514,7 @@ fn replace(_context: Context, s: &str, from: &str, to: &str) -> FunctionResult {
}

fn require(context: Context, name: &str) -> FunctionResult {
crate::which(&context.evaluator.context.working_directory(), name)?
.ok_or_else(|| format!("could not find executable `{name}`"))
crate::which(context, name)?.ok_or_else(|| format!("could not find executable `{name}`"))
}

fn replace_regex(_context: Context, s: &str, regex: &str, replacement: &str) -> FunctionResult {
Expand Down Expand Up @@ -669,7 +668,7 @@ fn uuid(_context: Context) -> FunctionResult {
}

fn which(context: Context, name: &str) -> FunctionResult {
Ok(crate::which(&context.evaluator.context.working_directory(), name)?.unwrap_or_default())
Ok(crate::which(context, name)?.unwrap_or_default())
}

fn without_extension(_context: Context, path: &str) -> FunctionResult {
Expand Down
19 changes: 11 additions & 8 deletions src/which.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
use super::*;

pub(crate) fn which(working_directory: &Path, s: &str) -> Result<Option<String>, String> {
let cmd = Path::new(s);
pub(crate) fn which(context: function::Context, name: &str) -> Result<Option<String>, String> {
let name = Path::new(name);

let candidates = match cmd.components().count() {
let candidates = match name.components().count() {
0 => return Err("empty command".into()),
1 => {
// cmd is a regular command
let path_var = env::var_os("PATH").ok_or("Environment variable `PATH` is not set")?;
env::split_paths(&path_var)
.map(|path| path.join(cmd))
env::split_paths(&env::var_os("PATH").ok_or("`PATH` environment variable not set")?)
.map(|path| path.join(name))
.collect()
}
_ => {
// cmd contains a path separator, treat it as a path
vec![cmd.into()]
vec![name.into()]
}
};

Expand All @@ -23,7 +22,11 @@ pub(crate) fn which(working_directory: &Path, s: &str) -> Result<Option<String>,
// This candidate is a relative path, either because the user invoked `which("rel/path")`,
// or because there was a relative path in `PATH`. Resolve it to an absolute path,
// relative to the working directory of the just invocation.
candidate = working_directory.join(candidate);
candidate = context
.evaluator
.context
.working_directory()
.join(candidate);
}

candidate = candidate.lexiclean();
Expand Down

0 comments on commit 522311c

Please sign in to comment.