Skip to content

Commit 7134cc7

Browse files
committed
implement file_stem() for directories
1 parent 386a7c7 commit 7134cc7

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

library/std/src/path.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2591,6 +2591,7 @@ impl Path {
25912591
///
25922592
/// * [`None`], if there is no file name;
25932593
/// * The entire file name if there is no embedded `.`;
2594+
/// * The entire file name if the path is a directory;
25942595
/// * The entire file name if the file name begins with `.` and has no other `.`s within;
25952596
/// * Otherwise, the portion of the file name before the final `.`
25962597
///
@@ -2603,6 +2604,13 @@ impl Path {
26032604
/// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
26042605
/// ```
26052606
///
2607+
/// if the path is a directory, the function will always return the complete filename
2608+
/// ```no_run
2609+
/// use std::path::Path;
2610+
///
2611+
/// assert_eq!("2024.11.23_directory", Path::new("2024.11.23_directory").file_stem().unwrap());
2612+
/// ```
2613+
///
26062614
/// # See Also
26072615
/// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
26082616
/// before the *first* `.`
@@ -2612,7 +2620,11 @@ impl Path {
26122620
#[stable(feature = "rust1", since = "1.0.0")]
26132621
#[must_use]
26142622
pub fn file_stem(&self) -> Option<&OsStr> {
2615-
self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2623+
if self.is_dir() {
2624+
self.file_name()
2625+
} else {
2626+
self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2627+
}
26162628
}
26172629

26182630
/// Extracts the prefix of [`self.file_name`].

0 commit comments

Comments
 (0)