@@ -305,13 +305,21 @@ pub fn uu_app() -> Command {
305305 )
306306}
307307
308+ // Function to get metadata of the provided path
309+ // If `follow` is true, the function will try to follow symlinks
310+ // If `follow` is false or the symlink is broken, the function will return metadata of the symlink itself
308311fn stat ( path : & Path , follow : bool ) -> UResult < ( FileTime , FileTime ) > {
309- let metadata = if follow {
310- fs:: symlink_metadata ( path)
311- } else {
312- fs:: metadata ( path)
313- }
314- . map_err_context ( || format ! ( "failed to get attributes of {}" , path. quote( ) ) ) ?;
312+ // Try to get metadata using fs::metadata
313+ // If the path is a symlink and `follow` is true, fs::metadata will follow the symlink
314+ let metadata = match fs:: metadata ( path) {
315+ // If successful, use the metadata
316+ Ok ( metadata) => metadata,
317+ // If there's a NotFound error and `follow` is false, try to get metadata of the symlink itself
318+ Err ( e) if e. kind ( ) == std:: io:: ErrorKind :: NotFound && !follow => fs:: symlink_metadata ( path)
319+ . map_err_context ( || format ! ( "failed to get attributes of {}" , path. quote( ) ) ) ?,
320+ // If it's any other error, return the error
321+ Err ( e) => return Err ( e. into ( ) ) ,
322+ } ;
315323
316324 Ok ( (
317325 FileTime :: from_last_access_time ( & metadata) ,
0 commit comments