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 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
// Some documentation copied from the Rust project under the MIT license.
//
// See https://github.com/rust-lang/rust
use std::ffi::OsString;
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::Path;
use crate::Glob;
use relative_path::RelativePath;
#[cfg_attr(windows, path = "windows.rs")]
#[cfg_attr(unix, path = "unix.rs")]
mod imp;
#[cfg(not(any(windows, unix)))]
compile_error!("root is only supported on cfg(windows) and cfg(unix)");
/// An open root directory from which relative paths can be opened.
///
/// In contrast to using APIs such as [`RelativePath::to_path`], this does not
/// require allocations to open a path.
///
/// This is achieved by keeping an open handle to the directory and using
/// platform-specific APIs to open a relative path, such as [`openat`] on `unix`.
///
/// [`openat`]: https://linux.die.net/man/2/openat
pub struct Root {
inner: imp::Root,
}
impl Root {
/// Open the given directory that can be used as a root for opening and
/// manipulating relative paths.
///
/// # Errors
///
/// Errors if the underlying I/O operation fails.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn new<P>(path: P) -> io::Result<Self>
where
P: AsRef<Path>,
{
Ok(Self {
inner: imp::Root::new(path.as_ref())?,
})
}
/// Construct an open options associated with this root.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().read(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn open_options(&self) -> OpenOptions {
OpenOptions {
root: &self.inner,
options: imp::OpenOptions::new(),
}
}
/// Opens a file in write-only mode.
///
/// This function will create a file if it does not exist, and will truncate
/// it if it does.
///
/// Depending on the platform, this function may fail if the full directory
/// path does not exist. See the [`OpenOptions::open`] function for more
/// details.
///
/// See also [`Root::write()`] for a simple function to create a file with a
/// given data.
///
/// # Errors
///
/// Errors if the underlying I/O operation fails.
///
/// # Examples
///
/// ```no_run
/// use std::io::Write;
///
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let mut f = root.create("foo.txt")?;
/// f.write_all(&1234_u32.to_be_bytes())?;
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn create<P>(&self, path: P) -> io::Result<File>
where
P: AsRef<RelativePath>,
{
self.open_options().write(true).create(true).open(path)
}
/// Attempts to open a file in read-only mode.
///
/// See the [`OpenOptions::open`] method for more details.
///
/// If you only need to read the entire file contents, consider
/// [`std::fs::read()`][Root::read] or
/// [`std::fs::read_to_string()`][Root::read_to_string] instead.
///
/// # Errors
///
/// This function will return an error if `path` does not already exist.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// # Examples
///
/// ```no_run
/// use std::io::Read;
///
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let mut f = root.open("foo.txt")?;
/// let mut data = vec![];
/// f.read_to_end(&mut data)?;
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn open<P>(&self, path: P) -> io::Result<File>
where
P: AsRef<RelativePath>,
{
self.open_options().read(true).open(path)
}
/// Read the entire contents of a file into a bytes vector.
///
/// This is a convenience function for using [`File::open`] and
/// [`read_to_end`] with fewer imports and without an intermediate variable.
///
/// [`read_to_end`]: Read::read_to_end
///
/// # Errors
///
/// This function will return an error if `path` does not already exist.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// While reading from the file, this function handles
/// [`io::ErrorKind::Interrupted`] with automatic retries. See [`io::Read`]
/// documentation for details.
///
/// # Examples
///
/// ```no_run
/// use std::net::SocketAddr;
///
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
/// let foo: SocketAddr = String::from_utf8_lossy(&root.read("address.txt")?).parse()?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn read<P>(&self, path: P) -> io::Result<Vec<u8>>
where
P: AsRef<RelativePath>,
{
fn inner(this: &Root, path: &RelativePath) -> io::Result<Vec<u8>> {
let mut file = this.open(path)?;
let size = file
.metadata()
.map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX))
.ok();
let mut bytes = Vec::with_capacity(size.unwrap_or(0));
file.read_to_end(&mut bytes)?;
Ok(bytes)
}
inner(self, path.as_ref())
}
/// Read the entire contents of a file into a string.
///
/// This is a convenience function for using [`File::open`] and
/// [`read_to_string`] with fewer imports and without an intermediate
/// variable.
///
/// [`read_to_string`]: Read::read_to_string
///
/// # Errors
///
/// This function will return an error if `path` does not already exist.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// If the contents of the file are not valid UTF-8, then an error will also
/// be returned.
///
/// # Examples
///
/// ```no_run
/// use std::net::SocketAddr;
///
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
/// let foo: SocketAddr = root.read_to_string("address.txt")?.parse()?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn read_to_string<P>(&self, path: P) -> io::Result<String>
where
P: AsRef<RelativePath>,
{
fn inner(this: &Root, path: &RelativePath) -> io::Result<String> {
let mut file = this.open(path)?;
let size = file
.metadata()
.map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX))
.ok();
let mut string = String::with_capacity(size.unwrap_or(0));
file.read_to_string(&mut string)?;
Ok(string)
}
inner(self, path.as_ref())
}
/// Write a slice as the entire contents of a file.
///
/// This function will create a file if it does not exist,
/// and will entirely replace its contents if it does.
///
/// Depending on the platform, this function may fail if the
/// full directory path does not exist.
///
/// This is a convenience function for using [`File::create`] and
/// [`write_all`] with fewer imports.
///
/// [`write_all`]: Write::write_all
///
/// # Errors
///
/// Fails if an underlying I/O operation fails.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// root.write("foo.txt", b"Lorem ipsum")?;
/// root.write("bar.txt", "dolor sit")?;
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn write<P, C>(&self, path: P, contents: C) -> io::Result<()>
where
P: AsRef<RelativePath>,
C: AsRef<[u8]>,
{
self.create(path)?.write_all(contents.as_ref())
}
/// Given a path, query the file system to get information about a file,
/// directory, etc.
///
/// This function will traverse symbolic links to query information about
/// the destination file.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `stat` function on Unix and
/// the `GetFileInformationByHandle` function on Windows. Note that, this
/// [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
///
/// # Errors
///
/// This function will return an error in the following situations, but is
/// not limited to just these cases:
///
/// * The user lacks permissions to perform `metadata` call on `path`.
/// * `path` does not exist.
///
/// # Examples
///
/// ```rust,no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
/// let attr = root.metadata("file/path.txt")?;
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn metadata<P>(&self, path: P) -> io::Result<Metadata>
where
P: AsRef<RelativePath>,
{
Ok(Metadata {
inner: self.inner.metadata(path.as_ref())?,
})
}
/// Returns `true` if the path exists on disk and is pointing at a
/// directory.
///
/// This function will traverse symbolic links to query information about
/// the destination file.
///
/// If you cannot access the metadata of the file, e.g. because of a
/// permission error or broken symbolic links, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// assert_eq!(root.is_dir("./is_a_directory/"), true);
/// assert_eq!(root.is_dir("a_file.txt"), false);
/// # Ok::<_, std::io::Error>(())
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want
/// to check errors, call [`Root::metadata`] and handle its [`Result`]. Then
/// call [`Metadata::is_dir`] if it was [`Ok`].
pub fn is_dir<P>(&self, path: P) -> bool
where
P: AsRef<RelativePath>,
{
self.metadata(path).map(|m| m.is_dir()).unwrap_or(false)
}
/// Returns an iterator over the entries within a directory.
///
/// The iterator will yield instances of
/// <code>[`io::Result`]<[`DirEntry`]></code>. New errors may be encountered
/// after an iterator is initially constructed. Entries for the current and
/// parent directories (typically `.` and `..`) are skipped.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `opendir` function on Unix
/// and the `FindFirstFile` function on Windows. Advancing the iterator
/// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
/// Note that, this [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
///
/// The order in which this iterator returns entries is platform and filesystem
/// dependent.
///
/// # Errors
///
/// This function will return an error in the following situations, but is not
/// limited to just these cases:
///
/// * The provided `path` doesn't exist.
/// * The process lacks permissions to view the contents.
/// * The `path` points at a non-directory file.
///
/// # Examples
///
/// ```
/// use std::io;
///
/// use relative_path_utils::{Root, DirEntry};
/// use relative_path::RelativePath;
///
/// // one possible implementation of walking a directory only visiting files
/// fn visit_dirs(root: &Root, dir: &RelativePath, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
/// if root.is_dir(dir) {
/// for entry in root.read_dir(dir)? {
/// let entry = entry?;
/// let file_name = entry.file_name();
/// let path = dir.join(file_name.to_string_lossy().as_ref());
///
/// if root.is_dir(&path) {
/// visit_dirs(root, &path, cb)?;
/// } else {
/// cb(&entry);
/// }
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn read_dir<P>(&self, path: P) -> io::Result<ReadDir>
where
P: AsRef<RelativePath>,
{
self.inner
.read_dir(path.as_ref())
.map(|inner| ReadDir { inner })
}
/// Parse a glob over the specified path.
///
/// To perform the globbing, use [`Glob::matcher`].
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new("src")?;
///
/// let glob = root.glob("**/*.rs");
///
/// let mut results = Vec::new();
///
/// for e in glob.matcher() {
/// results.push(e?);
/// }
///
/// results.sort();
/// assert_eq!(results, vec!["lib.rs", "main.rs"]);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn glob<'a, P>(&'a self, path: &'a P) -> Glob<'a>
where
P: ?Sized + AsRef<RelativePath>,
{
Glob::new(self, path.as_ref())
}
}
/// Options and flags which can be used to configure how a file is opened.
///
/// This builder exposes the ability to configure how a [`File`] is opened and
/// what operations are permitted on the open file. The [`File::open`] and
/// [`File::create`] methods are aliases for commonly used options using this
/// builder.
///
/// Generally speaking, when using `OpenOptions`, you'll first call
/// [`Root::open_options`], then chain calls to methods to set each option, then
/// call [`OpenOptions::open`], passing the path of the file you're trying to
/// open. This will give you a [`io::Result`] with a [`File`] inside that you
/// can further operate on.
///
/// # Examples
///
/// Opening a file to read:
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().read(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
///
/// Opening a file for both reading and writing, as well as creating it if it
/// doesn't exist:
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root
/// .open_options()
/// .read(true)
/// .write(true)
/// .create(true)
/// .open("foo.txt")?;
/// # Ok::<_, std::io::Error>(())
/// ```
#[derive(Clone, Debug)]
#[must_use]
pub struct OpenOptions<'a> {
root: &'a imp::Root,
options: imp::OpenOptions,
}
impl<'a> OpenOptions<'a> {
/// Sets the option for read access.
///
/// This option, when true, will indicate that the file should be
/// `read`-able if opened.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().read(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn read(&mut self, read: bool) -> &mut Self {
self.options.read(read);
self
}
/// Sets the option for write access.
///
/// This option, when true, will indicate that the file should be
/// `write`-able if opened.
///
/// If the file already exists, any write calls on it will overwrite its
/// contents, without truncating it.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().write(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn write(&mut self, write: bool) -> &mut Self {
self.options.write(write);
self
}
/// Sets the option for the append mode.
///
/// This option, when true, means that writes will append to a file instead
/// of overwriting previous contents. Note that setting
/// `.write(true).append(true)` has the same effect as setting only
/// `.append(true)`.
///
/// For most filesystems, the operating system guarantees that all writes
/// are atomic: no writes get mangled because another process writes at the
/// same time.
///
/// One maybe obvious note when using append-mode: make sure that all data
/// that belongs together is written to the file in one operation. This can
/// be done by concatenating strings before passing them to [`write()`], or
/// using a buffered writer (with a buffer of adequate size), and calling
/// [`flush()`] when the message is complete.
///
/// If a file is opened with both read and append access, beware that after
/// opening, and after every write, the position for reading may be set at
/// the end of the file. So, before writing, save the current position
/// (using <code>[`seek`]\([`SeekFrom`]::[`Current`]\(0))</code>), and
/// restore it before the next read.
///
/// ## Note
///
/// This function doesn't create the file if it doesn't exist. Use the
/// [`OpenOptions::create`] method to do so.
///
/// [`write()`]: Write::write "io::Write::write"
/// [`flush()`]: Write::flush "io::Write::flush"
/// [`seek`]: std::io::Seek::seek "io::Seek::seek"
/// [`SeekFrom`]: std::io::SeekFrom
/// [`Current`]: std::io::SeekFrom::Current
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().append(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn append(&mut self, append: bool) -> &mut Self {
self.options.append(append);
self
}
/// Sets the option for truncating a previous file.
///
/// If a file is successfully opened with this option set it will truncate
/// the file to 0 length if it already exists.
///
/// The file must be opened with write access for truncate to work.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().write(true).truncate(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn truncate(&mut self, truncate: bool) -> &mut Self {
self.options.truncate(truncate);
self
}
/// Sets the option to create a new file, or open it if it already exists.
///
/// In order for the file to be created, [`OpenOptions::write`] or
/// [`OpenOptions::append`] access must be used.
///
/// See also [`Root::write()`] for a simple function to create a file with a
/// given data.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().write(true).create(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn create(&mut self, create: bool) -> &mut Self {
self.options.create(create);
self
}
/// Sets the option to create a new file, failing if it already exists.
///
/// No file is allowed to exist at the target location, also no (dangling) symlink. In this
/// way, if the call succeeds, the file returned is guaranteed to be new.
///
/// This option is useful because it is atomic. Otherwise between checking
/// whether a file exists and creating a new one, the file may have been
/// created by another process (a TOCTOU race condition / attack).
///
/// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
/// ignored.
///
/// The file must be opened with write or append access in order to create
/// a new file.
///
/// [`.create()`]: OpenOptions::create
/// [`.truncate()`]: OpenOptions::truncate
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().write(true).create_new(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn create_new(&mut self, create_new: bool) -> &mut Self {
self.options.create_new(create_new);
self
}
/// Opens a file at `path` with the options specified by `self`.
///
/// # Errors
///
/// This function will return an error under a number of different
/// circumstances. Some of these error conditions are listed here, together
/// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
/// part of the compatibility contract of the function.
///
/// * [`NotFound`]: The specified file does not exist and neither `create`
/// or `create_new` is set.
/// * [`NotFound`]: One of the directory components of the file path does
/// not exist.
/// * [`PermissionDenied`]: The user lacks permission to get the specified
/// access rights for the file.
/// * [`PermissionDenied`]: The user lacks permission to open one of the
/// directory components of the specified path.
/// * [`AlreadyExists`]: `create_new` was specified and the file already
/// exists.
/// * [`InvalidInput`]: Invalid combinations of open options (truncate
/// without write access, no access mode set, etc.).
///
/// The following errors don't match any existing [`io::ErrorKind`] at the moment:
/// * One of the directory components of the specified file path
/// was not, in fact, a directory.
/// * Filesystem-level errors: full disk, write permission
/// requested on a read-only file system, exceeded disk quota, too many
/// open files, too long filename, too many symbolic links in the
/// specified path (Unix-like systems only), etc.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let file = root.open_options().read(true).open("foo.txt");
/// # Ok::<_, std::io::Error>(())
/// ```
///
/// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
/// [`InvalidInput`]: io::ErrorKind::InvalidInput
/// [`NotFound`]: io::ErrorKind::NotFound
/// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
pub fn open<P>(&self, path: P) -> io::Result<File>
where
P: AsRef<RelativePath>,
{
self.root.open_at(path.as_ref(), &self.options)
}
}
/// Iterator over the entries in a directory.
///
/// This iterator is returned from the [`Root::read_dir`] function and will
/// yield instances of <code>[`io::Result`]<[`DirEntry`]></code>. Through a
/// [`DirEntry`] information like the entry's path and possibly other metadata
/// can be learned.
///
/// The order in which this iterator returns entries is platform and filesystem
/// dependent.
///
/// # Errors
///
/// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
/// IO error during iteration.
pub struct ReadDir {
inner: imp::ReadDir,
}
impl Iterator for ReadDir {
type Item = io::Result<DirEntry>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let inner = self.inner.next()?;
Some(inner.map(|inner| DirEntry { inner }))
}
}
/// Entries returned by the [`ReadDir`] iterator.
///
/// An instance of `DirEntry` represents an entry inside of a directory on the
/// filesystem. Each entry can be inspected via methods to learn about the full
/// path or possibly other metadata through per-platform extension traits.
///
/// # Platform-specific behavior
///
/// On Unix, the `DirEntry` struct contains an internal reference to the open
/// directory. Holding `DirEntry` objects will consume a file handle even after
/// the `ReadDir` iterator is dropped.
pub struct DirEntry {
inner: imp::DirEntry,
}
impl DirEntry {
/// Returns the file name of this directory entry without any
/// leading path component(s).
///
/// As an example,
/// the output of the function will result in "foo" for all the following paths:
/// - "./foo"
/// - "/the/foo"
/// - "../../foo"
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let mut root = Root::new(".")?;
///
/// for entry in root.read_dir("src")? {
/// let entry = entry?;
/// println!("{:?}", entry.file_name());
/// }
/// # Ok::<_, std::io::Error>(())
/// ```
#[must_use]
pub fn file_name(&self) -> OsString {
self.inner.file_name()
}
}
/// Metadata information about a file.
///
/// This structure is returned from the [`metadata`] function and represents
/// known metadata about a file such as its permissions, size, modification
/// times, etc.
///
/// [`metadata`]: Root::metadata
#[derive(Clone)]
pub struct Metadata {
inner: imp::Metadata,
}
impl Metadata {
/// Returns `true` if this metadata is for a directory. The result is
/// mutually exclusive to the result of [`Metadata::is_file`].
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let metadata = root.metadata("foo.txt")?;
/// assert!(!metadata.is_dir());
/// # Ok::<_, std::io::Error>(())
/// ```
#[must_use]
#[inline]
pub fn is_dir(&self) -> bool {
self.inner.is_dir()
}
/// Returns `true` if this metadata is for a regular file. The result is
/// mutually exclusive to the result of [`Metadata::is_dir`].
///
/// When the goal is simply to read from (or write to) the source, the most
/// reliable way to test the source can be read (or written to) is to open
/// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
/// a Unix-like system for example. See [`Root::open`] or
/// [`OpenOptions::open`] for more information.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let metadata = root.metadata("foo.txt")?;
/// assert!(metadata.is_file());
/// # Ok::<_, std::io::Error>(())
/// ```
#[must_use]
#[inline]
pub fn is_file(&self) -> bool {
self.inner.is_file()
}
/// Returns `true` if this metadata is for a symbolic link.
///
/// # Examples
///
/// ```no_run
/// use relative_path_utils::Root;
///
/// let root = Root::new(".")?;
///
/// let metadata = root.metadata("foo.txt")?;
/// assert!(metadata.is_symlink());
/// # Ok::<_, std::io::Error>(())
/// ```
#[must_use]
pub fn is_symlink(&self) -> bool {
self.inner.is_symlink()
}
}