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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/*!
This crate provides a safe and simple **cross platform** way to determine
whether two file paths refer to the same file or directory.

Most uses of this crate should be limited to the top-level [`is_same_file`]
function, which takes two file paths and returns true if they refer to the
same file or directory:

```rust,no_run
# use std::error::Error;
use same_file::is_same_file;

# fn try_main() -> Result<(), Box<Error>> {
assert!(is_same_file("/bin/sh", "/usr/bin/sh")?);
#    Ok(())
# }
#
# fn main() {
#    try_main().unwrap();
# }
```

Additionally, this crate provides a [`Handle`] type that permits a more efficient
equality check depending on your access pattern. For example, if one wanted to
check whether any path in a list of paths corresponded to the process' stdout
handle, then one could build a handle once for stdout. The equality check for
each file in the list then only requires one stat call instead of two. The code
might look like this:

```rust,no_run
# use std::error::Error;
use same_file::Handle;

# fn try_main() -> Result<(), Box<Error>> {
let candidates = &[
    "examples/is_same_file.rs",
    "examples/is_stderr.rs",
    "examples/stderr",
];
let stdout_handle = Handle::stdout()?;
for candidate in candidates {
    let handle = Handle::from_path(candidate)?;
    if stdout_handle == handle {
        println!("{:?} is stdout!", candidate);
    } else {
        println!("{:?} is NOT stdout!", candidate);
    }
}
#    Ok(())
# }
#
# fn main() {
#     try_main().unwrap();
# }
```

See [`examples/is_stderr.rs`] for a runnable example and compare the output of:

- `cargo run --example is_stderr 2> examples/stderr` and
- `cargo run --example is_stderr`.

[`is_same_file`]: fn.is_same_file.html
[`Handle`]: struct.Handle.html
[`examples/is_stderr.rs`]: https://github.com/BurntSushi/same-file/blob/master/examples/is_same_file.rs

*/

#![allow(bare_trait_objects, unknown_lints)]
#![deny(missing_docs)]

#[cfg(windows)]
extern crate winapi_util;

use std::fs::File;
use std::io;
use std::path::Path;

#[cfg(any(target_os = "redox", unix))]
use unix as imp;
#[cfg(windows)]
use win as imp;
#[cfg(not(any(target_os = "redox", unix, windows)))]
use unknown as imp;

#[cfg(any(target_os = "redox", unix))]
mod unix;
#[cfg(windows)]
mod win;
#[cfg(not(any(target_os = "redox", unix, windows)))]
mod unknown;

/// A handle to a file that can be tested for equality with other handles.
///
/// If two files are the same, then any two handles of those files will compare
/// equal. If two files are not the same, then any two handles of those files
/// will compare not-equal.
///
/// A handle consumes an open file resource as long as it exists.
///
/// Equality is determined by comparing inode numbers on Unix and a combination
/// of identifier, volume serial, and file size on Windows. Note that it's
/// possible for comparing two handles to produce a false positive on some
/// platforms. Namely, two handles can compare equal even if the two handles
/// *don't* point to the same file. Check the [source] for specific
/// implementation details.
///
/// [source]: https://github.com/BurntSushi/same-file/tree/master/src
#[derive(Debug, Eq, PartialEq)]
pub struct Handle(imp::Handle);

impl Handle {
    /// Construct a handle from a path.
    ///
    /// Note that the underlying [`File`] is opened in read-only mode on all
    /// platforms.
    ///
    /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html
    ///
    /// # Errors
    /// This method will return an [`io::Error`] if the path cannot
    /// be opened, or the file's metadata cannot be obtained.
    /// The most common reasons for this are: the path does not
    /// exist, or there were not enough permissions.
    ///
    /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
    ///
    /// # Examples
    /// Check that two paths are not the same file:
    ///
    /// ```rust,no_run
    /// # use std::error::Error;
    /// use same_file::Handle;
    ///
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// let source = Handle::from_path("./source")?;
    /// let target = Handle::from_path("./target")?;
    /// assert_ne!(source, target, "The files are the same.");
    /// # Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #     try_main().unwrap();
    /// # }
    /// ```
    pub fn from_path<P: AsRef<Path>>(p: P) -> io::Result<Handle> {
        imp::Handle::from_path(p).map(Handle)
    }

    /// Construct a handle from a file.
    ///
    /// # Errors
    /// This method will return an [`io::Error`] if the metadata for
    /// the given [`File`] cannot be obtained.
    ///
    /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
    /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html
    ///
    /// # Examples
    /// Check that two files are not in fact the same file:
    ///
    /// ```rust,no_run
    /// # use std::error::Error;
    /// # use std::fs::File;
    /// use same_file::Handle;
    ///
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// let source = File::open("./source")?;
    /// let target = File::open("./target")?;
    ///
    /// assert_ne!(
    ///     Handle::from_file(source)?,
    ///     Handle::from_file(target)?,
    ///     "The files are the same."
    /// );
    /// #     Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #     try_main().unwrap();
    /// # }
    /// ```
    pub fn from_file(file: File) -> io::Result<Handle> {
        imp::Handle::from_file(file).map(Handle)
    }

    /// Construct a handle from stdin.
    ///
    /// # Errors
    /// This method will return an [`io::Error`] if stdin cannot
    /// be opened due to any I/O-related reason.
    ///
    /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use std::error::Error;
    /// use same_file::Handle;
    ///
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// let stdin = Handle::stdin()?;
    /// let stdout = Handle::stdout()?;
    /// let stderr = Handle::stderr()?;
    ///
    /// if stdin == stdout {
    ///     println!("stdin == stdout");
    /// }
    /// if stdin == stderr {
    ///     println!("stdin == stderr");
    /// }
    /// if stdout == stderr {
    ///     println!("stdout == stderr");
    /// }
    /// #
    /// #     Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #     try_main().unwrap();
    /// # }
    /// ```
    ///
    /// The output differs depending on the platform.
    ///
    /// On Linux:
    ///
    /// ```text
    /// $ ./example
    /// stdin == stdout
    /// stdin == stderr
    /// stdout == stderr
    /// $ ./example > result
    /// $ cat result
    /// stdin == stderr
    /// $ ./example > result 2>&1
    /// $ cat result
    /// stdout == stderr
    /// ```
    ///
    /// Windows:
    ///
    /// ```text
    /// > example
    /// > example > result 2>&1
    /// > type result
    /// stdout == stderr
    /// ```
    pub fn stdin() -> io::Result<Handle> {
        imp::Handle::stdin().map(Handle)
    }

    /// Construct a handle from stdout.
    ///
    /// # Errors
    /// This method will return an [`io::Error`] if stdout cannot
    /// be opened due to any I/O-related reason.
    ///
    /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
    ///
    /// # Examples
    /// See the example for [`stdin()`].
    ///
    /// [`stdin()`]: #method.stdin
    pub fn stdout() -> io::Result<Handle> {
        imp::Handle::stdout().map(Handle)
    }

    /// Construct a handle from stderr.
    ///
    /// # Errors
    /// This method will return an [`io::Error`] if stderr cannot
    /// be opened due to any I/O-related reason.
    ///
    /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
    ///
    /// # Examples
    /// See the example for [`stdin()`].
    ///
    /// [`stdin()`]: #method.stdin
    pub fn stderr() -> io::Result<Handle> {
        imp::Handle::stderr().map(Handle)
    }

    /// Return a reference to the underlying file.
    ///
    /// # Examples
    /// Ensure that the target file is not the same as the source one,
    /// and copy the data to it:
    ///
    /// ```rust,no_run
    /// # use std::error::Error;
    /// use std::io::prelude::*;
    /// use std::io::Write;
    /// use std::fs::File;
    /// use same_file::Handle;
    ///
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// let source = File::open("source")?;
    /// let target = File::create("target")?;
    ///
    /// let source_handle = Handle::from_file(source)?;
    /// let mut target_handle = Handle::from_file(target)?;
    /// assert_ne!(source_handle, target_handle, "The files are the same.");
    ///
    /// let mut source = source_handle.as_file();
    /// let target = target_handle.as_file_mut();
    ///
    /// let mut buffer = Vec::new();
    /// // data copy is simplified for the purposes of the example
    /// source.read_to_end(&mut buffer)?;
    /// target.write_all(&buffer)?;
    /// #
    /// #    Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #    try_main().unwrap();
    /// # }
    /// ```
    pub fn as_file(&self) -> &File {
        self.0.as_file()
    }

    /// Return a mutable reference to the underlying file.
    ///
    /// # Examples
    /// See the example for [`as_file()`].
    ///
    /// [`as_file()`]: #method.as_file
    pub fn as_file_mut(&mut self) -> &mut File {
        self.0.as_file_mut()
    }

    /// Return the underlying device number of this handle.
    ///
    /// Note that this only works on unix platforms.
    #[cfg(any(target_os = "redox", unix))]
    pub fn dev(&self) -> u64 {
        self.0.dev()
    }

    /// Return the underlying inode number of this handle.
    ///
    /// Note that this only works on unix platforms.
    #[cfg(any(target_os = "redox", unix))]
    pub fn ino(&self) -> u64 {
        self.0.ino()
    }
}

/// Returns true if the two file paths may correspond to the same file.
///
/// Note that it's possible for this to produce a false positive on some
/// platforms. Namely, this can return true even if the two file paths *don't*
/// resolve to the same file.
/// # Errors
/// This function will return an [`io::Error`] if any of the two paths cannot
/// be opened. The most common reasons for this are: the path does not exist,
/// or there were not enough permissions.
///
/// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
///
/// # Example
///
/// ```rust,no_run
/// use same_file::is_same_file;
///
/// assert!(is_same_file("./foo", "././foo").unwrap_or(false));
/// ```
pub fn is_same_file<P, Q>(
    path1: P,
    path2: Q,
) -> io::Result<bool> where P: AsRef<Path>, Q: AsRef<Path> {
    Ok(Handle::from_path(path1)? == Handle::from_path(path2)?)
}

#[cfg(test)]
mod tests {
    use std::env;
    use std::error;
    use std::fs::{self, File};
    use std::io;
    use std::path::{Path, PathBuf};
    use std::result;

    use super::is_same_file;

    type Result<T> = result::Result<T, Box<error::Error + Send + Sync>>;

    /// Create an error from a format!-like syntax.
    macro_rules! err {
        ($($tt:tt)*) => {
            Box::<error::Error + Send + Sync>::from(format!($($tt)*))
        }
    }

    /// A simple wrapper for creating a temporary directory that is
    /// automatically deleted when it's dropped.
    ///
    /// We use this in lieu of tempfile because tempfile brings in too many
    /// dependencies.
    #[derive(Debug)]
    struct TempDir(PathBuf);

    impl Drop for TempDir {
        fn drop(&mut self) {
            fs::remove_dir_all(&self.0).unwrap();
        }
    }

    impl TempDir {
        /// Create a new empty temporary directory under the system's
        /// configured temporary directory.
        fn new() -> Result<TempDir> {
            #![allow(deprecated)]

            use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering};

            static TRIES: usize = 100;
            static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;

            let tmpdir = env::temp_dir();
            for _ in 0..TRIES {
                let count = COUNTER.fetch_add(1, Ordering::SeqCst);
                let path = tmpdir.join("rust-walkdir").join(count.to_string());
                if path.is_dir() {
                    continue;
                }
                fs::create_dir_all(&path).map_err(|e| {
                    err!("failed to create {}: {}", path.display(), e)
                })?;
                return Ok(TempDir(path));
            }
            Err(err!("failed to create temp dir after {} tries", TRIES))
        }

        /// Return the underlying path to this temporary directory.
        fn path(&self) -> &Path {
            &self.0
        }
    }

    fn tmpdir() -> TempDir {
        TempDir::new().unwrap()
    }

    #[cfg(unix)]
    pub fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>(
        src: P,
        dst: Q,
    ) -> io::Result<()> {
        use std::os::unix::fs::symlink;
        symlink(src, dst)
    }

    #[cfg(unix)]
    pub fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>(
        src: P,
        dst: Q,
    ) -> io::Result<()> {
        soft_link_dir(src, dst)
    }

    #[cfg(windows)]
    pub fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>(
        src: P,
        dst: Q,
    ) -> io::Result<()> {
        use std::os::windows::fs::symlink_dir;
        symlink_dir(src, dst)
    }

    #[cfg(windows)]
    pub fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>(
        src: P,
        dst: Q,
    ) -> io::Result<()> {
        use std::os::windows::fs::symlink_file;
        symlink_file(src, dst)
    }

    // These tests are rather uninteresting. The really interesting tests
    // would stress the edge cases. On Unix, this might be comparing two files
    // on different mount points with the same inode number. On Windows, this
    // might be comparing two files whose file indices are the same on file
    // systems where such things aren't guaranteed to be unique.
    //
    // Alas, I don't know how to create those environmental conditions. ---AG

    #[test]
    fn same_file_trivial() {
        let tdir = tmpdir();
        let dir = tdir.path();

        File::create(dir.join("a")).unwrap();
        assert!(is_same_file(dir.join("a"), dir.join("a")).unwrap());
    }

    #[test]
    fn same_dir_trivial() {
        let tdir = tmpdir();
        let dir = tdir.path();

        fs::create_dir(dir.join("a")).unwrap();
        assert!(is_same_file(dir.join("a"), dir.join("a")).unwrap());
    }

    #[test]
    fn not_same_file_trivial() {
        let tdir = tmpdir();
        let dir = tdir.path();

        File::create(dir.join("a")).unwrap();
        File::create(dir.join("b")).unwrap();
        assert!(!is_same_file(dir.join("a"), dir.join("b")).unwrap());
    }

    #[test]
    fn not_same_dir_trivial() {
        let tdir = tmpdir();
        let dir = tdir.path();

        fs::create_dir(dir.join("a")).unwrap();
        fs::create_dir(dir.join("b")).unwrap();
        assert!(!is_same_file(dir.join("a"), dir.join("b")).unwrap());
    }

    #[test]
    fn same_file_hard() {
        let tdir = tmpdir();
        let dir = tdir.path();

        File::create(dir.join("a")).unwrap();
        fs::hard_link(dir.join("a"), dir.join("alink")).unwrap();
        assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap());
    }

    #[test]
    fn same_file_soft() {
        let tdir = tmpdir();
        let dir = tdir.path();

        File::create(dir.join("a")).unwrap();
        soft_link_file(dir.join("a"), dir.join("alink")).unwrap();
        assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap());
    }

    #[test]
    fn same_dir_soft() {
        let tdir = tmpdir();
        let dir = tdir.path();

        fs::create_dir(dir.join("a")).unwrap();
        soft_link_dir(dir.join("a"), dir.join("alink")).unwrap();
        assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap());
    }

    #[test]
    fn test_send() {
        fn assert_send<T: Send>() {}
        assert_send::<super::Handle>();
    }

    #[test]
    fn test_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<super::Handle>();
    }
}