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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! which
//!
//! A Rust equivalent of Unix command `which(1)`.
//! # Example:
//!
//! To find which rustc executable binary is using:
//!
//! ``` norun
//! use which::which;
//!
//! let result = which::which("rustc").unwrap();
//! assert_eq!(result, PathBuf::from("/usr/bin/rustc"));
//!
//! ```

extern crate failure;
extern crate libc;
#[cfg(test)]
extern crate tempdir;

use failure::ResultExt;
mod checker;
mod error;
mod finder;
#[cfg(windows)]
mod helper;

use std::env;
use std::path::{Path, PathBuf};

// Remove the `AsciiExt` will make `which-rs` build failed in older versions of Rust.
// Please Keep it here though we don't need it in the new Rust version(>=1.23).
#[allow(unused_imports)]
use std::ascii::AsciiExt;

use std::ffi::OsStr;

use checker::CompositeChecker;
use checker::ExecutableChecker;
use checker::ExistedChecker;
pub use error::*;
use finder::Finder;

/// Find a exectable binary's path by name.
///
/// If given an absolute path, returns it if the file exists and is executable.
///
/// If given a relative path, returns an absolute path to the file if
/// it exists and is executable.
///
/// If given a string without path separators, looks for a file named
/// `binary_name` at each directory in `$PATH` and if it finds an executable
/// file there, returns it.
///
/// # Example
///
/// ``` norun
/// use which::which;
/// use std::path::PathBuf;
///
/// let result = which::which("rustc").unwrap();
/// assert_eq!(result, PathBuf::from("/usr/bin/rustc"));
///
/// ```
pub fn which<T: AsRef<OsStr>>(binary_name: T) -> Result<PathBuf> {
    let cwd = env::current_dir().context(ErrorKind::CannotGetCurrentDir)?;
    which_in(binary_name, env::var_os("PATH"), &cwd)
}

/// Find `binary_name` in the path list `paths`, using `cwd` to resolve relative paths.
pub fn which_in<T, U, V>(binary_name: T, paths: Option<U>, cwd: V) -> Result<PathBuf>
where
    T: AsRef<OsStr>,
    U: AsRef<OsStr>,
    V: AsRef<Path>,
{
    let binary_checker = CompositeChecker::new()
        .add_checker(Box::new(ExistedChecker::new()))
        .add_checker(Box::new(ExecutableChecker::new()));

    let finder = Finder::new();

    finder.find(binary_name, paths, cwd, &binary_checker)
}

#[cfg(test)]
mod test {
    use super::*;

    use std::env;
    use std::ffi::{OsStr, OsString};
    use std::fs;
    use std::io;
    use std::path::{Path, PathBuf};
    use tempdir::TempDir;

    struct TestFixture {
        /// Temp directory.
        pub tempdir: TempDir,
        /// $PATH
        pub paths: OsString,
        /// Binaries created in $PATH
        pub bins: Vec<PathBuf>,
    }

    const SUBDIRS: &'static [&'static str] = &["a", "b", "c"];
    const BIN_NAME: &'static str = "bin";

    #[cfg(unix)]
    fn mk_bin(dir: &Path, path: &str, extension: &str) -> io::Result<PathBuf> {
        use libc;
        use std::os::unix::fs::OpenOptionsExt;
        let bin = dir.join(path).with_extension(extension);
        fs::OpenOptions::new()
            .write(true)
            .create(true)
            .mode(0o666 | (libc::S_IXUSR as u32))
            .open(&bin)
            .and_then(|_f| bin.canonicalize())
    }

    fn touch(dir: &Path, path: &str, extension: &str) -> io::Result<PathBuf> {
        let b = dir.join(path).with_extension(extension);
        fs::File::create(&b).and_then(|_f| b.canonicalize())
    }

    #[cfg(windows)]
    fn mk_bin(dir: &Path, path: &str, extension: &str) -> io::Result<PathBuf> {
        touch(dir, path, extension)
    }

    impl TestFixture {
        // tmp/a/bin
        // tmp/a/bin.exe
        // tmp/a/bin.cmd
        // tmp/b/bin
        // tmp/b/bin.exe
        // tmp/b/bin.cmd
        // tmp/c/bin
        // tmp/c/bin.exe
        // tmp/c/bin.cmd
        pub fn new() -> TestFixture {
            let tempdir = TempDir::new("which_tests").unwrap();
            let mut builder = fs::DirBuilder::new();
            builder.recursive(true);
            let mut paths = vec![];
            let mut bins = vec![];
            for d in SUBDIRS.iter() {
                let p = tempdir.path().join(d);
                builder.create(&p).unwrap();
                bins.push(mk_bin(&p, &BIN_NAME, "").unwrap());
                bins.push(mk_bin(&p, &BIN_NAME, "exe").unwrap());
                bins.push(mk_bin(&p, &BIN_NAME, "cmd").unwrap());
                paths.push(p);
            }
            TestFixture {
                tempdir: tempdir,
                paths: env::join_paths(paths).unwrap(),
                bins: bins,
            }
        }

        #[allow(dead_code)]
        pub fn touch(&self, path: &str, extension: &str) -> io::Result<PathBuf> {
            touch(self.tempdir.path(), &path, &extension)
        }

        pub fn mk_bin(&self, path: &str, extension: &str) -> io::Result<PathBuf> {
            mk_bin(self.tempdir.path(), &path, &extension)
        }
    }

    fn _which<T: AsRef<OsStr>>(f: &TestFixture, path: T) -> Result<PathBuf> {
        which_in(path, Some(f.paths.clone()), f.tempdir.path())
    }

    #[test]
    #[cfg(unix)]
    fn it_works() {
        use std::process::Command;
        let result = which("rustc");
        assert!(result.is_ok());

        let which_result = Command::new("which").arg("rustc").output();

        assert_eq!(
            String::from(result.unwrap().to_str().unwrap()),
            String::from_utf8(which_result.unwrap().stdout)
                .unwrap()
                .trim()
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_which() {
        let f = TestFixture::new();
        assert_eq!(
            _which(&f, &BIN_NAME).unwrap().canonicalize().unwrap(),
            f.bins[0]
        )
    }

    #[test]
    #[cfg(windows)]
    fn test_which() {
        let f = TestFixture::new();
        assert_eq!(
            _which(&f, &BIN_NAME).unwrap().canonicalize().unwrap(),
            f.bins[1]
        )
    }

    #[test]
    #[cfg(unix)]
    fn test_which_extension() {
        let f = TestFixture::new();
        let b = Path::new(&BIN_NAME).with_extension("");
        assert_eq!(_which(&f, &b).unwrap().canonicalize().unwrap(), f.bins[0])
    }

    #[test]
    #[cfg(windows)]
    fn test_which_extension() {
        let f = TestFixture::new();
        let b = Path::new(&BIN_NAME).with_extension("cmd");
        assert_eq!(_which(&f, &b).unwrap().canonicalize().unwrap(), f.bins[2])
    }

    #[test]
    fn test_which_not_found() {
        let f = TestFixture::new();
        assert!(_which(&f, "a").is_err());
    }

    #[test]
    fn test_which_second() {
        let f = TestFixture::new();
        let b = f.mk_bin("b/another", env::consts::EXE_EXTENSION).unwrap();
        assert_eq!(_which(&f, "another").unwrap().canonicalize().unwrap(), b);
    }

    #[test]
    #[cfg(unix)]
    fn test_which_absolute() {
        let f = TestFixture::new();
        assert_eq!(
            _which(&f, &f.bins[3]).unwrap().canonicalize().unwrap(),
            f.bins[3].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(windows)]
    fn test_which_absolute() {
        let f = TestFixture::new();
        assert_eq!(
            _which(&f, &f.bins[4]).unwrap().canonicalize().unwrap(),
            f.bins[4].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(windows)]
    fn test_which_absolute_path_case() {
        // Test that an absolute path with an uppercase extension
        // is accepted.
        let f = TestFixture::new();
        let p = &f.bins[4];
        assert_eq!(
            _which(&f, &p).unwrap().canonicalize().unwrap(),
            f.bins[4].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_which_absolute_extension() {
        let f = TestFixture::new();
        // Don't append EXE_EXTENSION here.
        let b = f.bins[3].parent().unwrap().join(&BIN_NAME);
        assert_eq!(
            _which(&f, &b).unwrap().canonicalize().unwrap(),
            f.bins[3].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(windows)]
    fn test_which_absolute_extension() {
        let f = TestFixture::new();
        // Don't append EXE_EXTENSION here.
        let b = f.bins[4].parent().unwrap().join(&BIN_NAME);
        assert_eq!(
            _which(&f, &b).unwrap().canonicalize().unwrap(),
            f.bins[4].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_which_relative() {
        let f = TestFixture::new();
        assert_eq!(
            _which(&f, "b/bin").unwrap().canonicalize().unwrap(),
            f.bins[3].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(windows)]
    fn test_which_relative() {
        let f = TestFixture::new();
        assert_eq!(
            _which(&f, "b/bin").unwrap().canonicalize().unwrap(),
            f.bins[4].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_which_relative_extension() {
        // test_which_relative tests a relative path without an extension,
        // so test a relative path with an extension here.
        let f = TestFixture::new();
        let b = Path::new("b/bin").with_extension(env::consts::EXE_EXTENSION);
        assert_eq!(
            _which(&f, &b).unwrap().canonicalize().unwrap(),
            f.bins[3].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(windows)]
    fn test_which_relative_extension() {
        // test_which_relative tests a relative path without an extension,
        // so test a relative path with an extension here.
        let f = TestFixture::new();
        let b = Path::new("b/bin").with_extension("cmd");
        assert_eq!(
            _which(&f, &b).unwrap().canonicalize().unwrap(),
            f.bins[5].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(windows)]
    fn test_which_relative_extension_case() {
        // Test that a relative path with an uppercase extension
        // is accepted.
        let f = TestFixture::new();
        let b = Path::new("b/bin").with_extension("EXE");
        assert_eq!(
            _which(&f, &b).unwrap().canonicalize().unwrap(),
            f.bins[4].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_which_relative_leading_dot() {
        let f = TestFixture::new();
        assert_eq!(
            _which(&f, "./b/bin").unwrap().canonicalize().unwrap(),
            f.bins[3].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(windows)]
    fn test_which_relative_leading_dot() {
        let f = TestFixture::new();
        assert_eq!(
            _which(&f, "./b/bin").unwrap().canonicalize().unwrap(),
            f.bins[4].canonicalize().unwrap()
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_which_non_executable() {
        // Shouldn't return non-executable files.
        let f = TestFixture::new();
        f.touch("b/another", "").unwrap();
        assert!(_which(&f, "another").is_err());
    }

    #[test]
    #[cfg(unix)]
    fn test_which_absolute_non_executable() {
        // Shouldn't return non-executable files, even if given an absolute path.
        let f = TestFixture::new();
        let b = f.touch("b/another", "").unwrap();
        assert!(_which(&f, &b).is_err());
    }

    #[test]
    #[cfg(unix)]
    fn test_which_relative_non_executable() {
        // Shouldn't return non-executable files.
        let f = TestFixture::new();
        f.touch("b/another", "").unwrap();
        assert!(_which(&f, "b/another").is_err());
    }

    #[test]
    fn test_failure() {
        let f = TestFixture::new();

        let run = || -> std::result::Result<PathBuf, failure::Error> {
            // Test the conversion to failure
            let p = _which(&f, "./b/bin")?;
            Ok(p)
        };

        let _ = run();
    }
}