This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new 803daad018 feat(services/fs): implement native list_with_glob with 
directory pruning (#9018)
803daad018 is described below

commit 803daad018c4f4eda74a9c1435218033547279cf
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 23:37:15 2026 +0800

    feat(services/fs): implement native list_with_glob with directory pruning 
(#9018)
    
    * feat(services/fs): implement native list_with_glob with directory pruning
    
    * test(services/fs): cover leading literal symlink glob pagination and 
clarify docs
---
 core/core/src/layers/glob.rs      |   1 -
 core/core/src/raw/glob_matcher.rs |  43 +-
 core/core/src/raw/mod.rs          |   3 +-
 core/services/fs/src/backend.rs   |   3 +-
 core/services/fs/src/docs.md      |   6 +
 core/services/fs/src/lister.rs    | 846 ++++++++++++++++++++++++++++++++++++--
 website/data/capabilities.json    |   1 +
 7 files changed, 847 insertions(+), 56 deletions(-)

diff --git a/core/core/src/layers/glob.rs b/core/core/src/layers/glob.rs
index 612c9f42ae..3582ab08d6 100644
--- a/core/core/src/layers/glob.rs
+++ b/core/core/src/layers/glob.rs
@@ -17,7 +17,6 @@
 
 use std::sync::Arc;
 
-use crate::raw::glob_matcher::GlobPattern;
 use crate::raw::oio::{self, List};
 use crate::raw::*;
 use crate::*;
diff --git a/core/core/src/raw/glob_matcher.rs 
b/core/core/src/raw/glob_matcher.rs
index 83a1ce75a9..227f2e7802 100644
--- a/core/core/src/raw/glob_matcher.rs
+++ b/core/core/src/raw/glob_matcher.rs
@@ -17,14 +17,25 @@
 
 use crate::{Error, ErrorKind, Result};
 
+/// Compiled Unix shell style glob pattern for path-component matching.
+///
+/// Services implementing native [`crate::Capability::list_with_glob`] and
+/// [`crate::layers::GlobLayer`] share this matcher to evaluate
+/// [`crate::options::ListOptions::glob`] consistently and prune directories
+/// during traversal.
 #[derive(Debug)]
-pub(crate) struct GlobPattern {
+pub struct GlobPattern {
     segments: Vec<Segment>,
     directories_only: bool,
 }
 
 impl GlobPattern {
-    pub(crate) fn new(pattern: &str) -> Result<Self> {
+    /// Parse and compile a glob pattern.
+    ///
+    /// Returns [`ErrorKind::ConfigInvalid`] if the pattern is empty, contains
+    /// malformed syntax, or uses disallowed literal components such as `.` or
+    /// `..`.
+    pub fn new(pattern: &str) -> Result<Self> {
         let mut segments = Vec::new();
         for segment in pattern.split('/').filter(|part| !part.is_empty()) {
             if segment == "**" {
@@ -52,8 +63,9 @@ impl GlobPattern {
         })
     }
 
-    /// Leading literal directories can be addressed without listing their 
parents.
-    pub(crate) fn literal_directories(&self) -> impl Iterator<Item = &str> {
+    /// Yield leading literal directory components that can be entered directly
+    /// without listing their parent directories.
+    pub fn literal_directories(&self) -> impl Iterator<Item = &str> {
         let terminal_components = if matches!(self.segments.last(), 
Some(Segment::Recursive)) {
             // The directory before a trailing `**` can itself match.
             2
@@ -69,12 +81,17 @@ impl GlobPattern {
             })
     }
 
-    pub(crate) fn spans_directories(&self) -> bool {
+    /// Return `true` if the pattern can match entries deeper than one 
directory level.
+    pub fn spans_directories(&self) -> bool {
         self.segments.len() > 1 || matches!(self.segments[0], 
Segment::Recursive)
     }
 
-    /// Advance every viable pattern position against one path component.
-    pub(crate) fn advance(&self, positions: &[usize], name: &str) -> 
Vec<usize> {
+    /// Advance every viable pattern position against a single path component.
+    ///
+    /// The returned positions are sorted and deduplicated. Start from `&[0]` 
at
+    /// the base directory, or `&[n]` after skipping `n` leading literal
+    /// directories returned by [`Self::literal_directories`].
+    pub fn advance(&self, positions: &[usize], name: &str) -> Vec<usize> {
         let mut next = Vec::new();
         for &position in positions {
             match self.segments.get(position) {
@@ -95,7 +112,10 @@ impl GlobPattern {
         next
     }
 
-    pub(crate) fn accepts(&self, positions: &[usize], is_dir: bool) -> bool {
+    /// Return `true` if `positions` represent a complete match for an entry.
+    ///
+    /// Patterns with a trailing `/` require `is_dir` to be `true`.
+    pub fn accepts(&self, positions: &[usize], is_dir: bool) -> bool {
         if self.directories_only && !is_dir {
             return false;
         }
@@ -106,13 +126,16 @@ impl GlobPattern {
                 && positions.last() == Some(&(end - 1)))
     }
 
-    pub(crate) fn can_descend(&self, positions: &[usize]) -> bool {
+    /// Return `true` if descending into a directory at `positions` can still
+    /// match descendants.
+    pub fn can_descend(&self, positions: &[usize]) -> bool {
         positions
             .first()
             .is_some_and(|&first| first < self.segments.len())
     }
 
-    pub(crate) fn matches(&self, path: &str, is_dir: bool) -> bool {
+    /// Return `true` if a relative path matches the pattern.
+    pub fn matches(&self, path: &str, is_dir: bool) -> bool {
         let mut positions = vec![0];
         for component in path.trim_end_matches('/').split('/') {
             positions = self.advance(&positions, component);
diff --git a/core/core/src/raw/mod.rs b/core/core/src/raw/mod.rs
index 89a7ea6461..b6059853e9 100644
--- a/core/core/src/raw/mod.rs
+++ b/core/core/src/raw/mod.rs
@@ -47,7 +47,8 @@ pub use rps::*;
 mod ops;
 pub use ops::*;
 
-pub(crate) mod glob_matcher;
+mod glob_matcher;
+pub use glob_matcher::GlobPattern;
 
 mod http_transport_cache;
 pub use http_transport_cache::HttpTransportCache;
diff --git a/core/services/fs/src/backend.rs b/core/services/fs/src/backend.rs
index 3ebc5095da..d5d4f4ac86 100644
--- a/core/services/fs/src/backend.rs
+++ b/core/services/fs/src/backend.rs
@@ -212,6 +212,7 @@ impl Builder for FsBuilder {
                     list: true,
                     list_with_recursive: true,
                     list_with_start_after: true,
+                    list_with_glob: true,
 
                     copy: true,
                     rename: true,
@@ -297,7 +298,7 @@ impl Service for FsBackend {
     }
 
     fn list(&self, _ctx: &OperationContext, path: &str, args: OpList) -> 
Result<Self::Lister> {
-        Ok(FsLister::new(self.core.clone(), path, args))
+        FsLister::new(self.core.clone(), path, args)
     }
 
     fn copy(
diff --git a/core/services/fs/src/docs.md b/core/services/fs/src/docs.md
index 449ce7b451..4d190e7f4e 100644
--- a/core/services/fs/src/docs.md
+++ b/core/services/fs/src/docs.md
@@ -51,6 +51,12 @@ yielding its entries. This can increase latency and memory 
usage for large
 directories. With `start_after` unset, the traversal follows the order of
 entries from the filesystem.
 
+When `glob` is set, the service evaluates the pattern natively during directory
+traversal, entering leading literal directories directly and skipping
+subdirectories that cannot match. Discovered subdirectories that become
+unreadable or disappear during traversal are skipped, while errors on the
+starting and leading literal directories are returned.
+
 ## Delete
 
 Recursive deletion targets the named filesystem entry. Deleting `a/`
diff --git a/core/services/fs/src/lister.rs b/core/services/fs/src/lister.rs
index 09ad5f302e..def0a6f9cf 100644
--- a/core/services/fs/src/lister.rs
+++ b/core/services/fs/src/lister.rs
@@ -15,6 +15,7 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::fs::Metadata as StdMetadata;
 use std::path::Path;
 use std::sync::Arc;
 use std::vec::IntoIter;
@@ -24,11 +25,36 @@ use opendal_core::ErrorKind;
 use opendal_core::MetadataBuilder;
 use opendal_core::Result;
 use opendal_core::raw::*;
-use tokio::fs::ReadDir;
+use tokio::fs::{DirEntry, ReadDir};
 
 use super::core::FsCore;
 
-pub struct FsLister {
+pub enum FsLister {
+    Plain(PlainLister),
+    Glob(GlobLister),
+}
+
+impl FsLister {
+    pub(super) fn new(core: Arc<FsCore>, path: &str, args: OpList) -> 
Result<Self> {
+        if let Some(glob) = args.glob() {
+            let pattern = GlobPattern::new(glob)?;
+            Ok(Self::Glob(GlobLister::new(core, path, args, pattern)))
+        } else {
+            Ok(Self::Plain(PlainLister::new(core, path, args)))
+        }
+    }
+}
+
+impl oio::List for FsLister {
+    async fn next(&mut self) -> Result<Option<oio::Entry>> {
+        match self {
+            Self::Plain(lister) => lister.next().await,
+            Self::Glob(lister) => lister.next().await,
+        }
+    }
+}
+
+pub struct PlainLister {
     core: Arc<FsCore>,
     prefix: String,
     recursive: bool,
@@ -78,8 +104,8 @@ enum DirectoryEntries {
     Sorted(IntoIter<ListedEntry>),
 }
 
-impl FsLister {
-    pub(super) fn new(core: Arc<FsCore>, path: &str, args: OpList) -> Self {
+impl PlainLister {
+    fn new(core: Arc<FsCore>, path: &str, args: OpList) -> Self {
         let directory = if path.ends_with('/') {
             path
         } else {
@@ -95,9 +121,7 @@ impl FsLister {
             active: Vec::new(),
         }
     }
-}
 
-impl oio::List for FsLister {
     async fn next(&mut self) -> Result<Option<oio::Entry>> {
         loop {
             if let Some(dir) = &self.next_dir {
@@ -214,13 +238,217 @@ impl oio::List for FsLister {
     }
 }
 
-async fn next_entry(
+pub struct GlobLister {
+    core: Arc<FsCore>,
+    pattern: GlobPattern,
+    prefix: String,
+    start_after: Option<String>,
+    next_dir: Option<GlobPendingDir>,
+    active: Vec<GlobDirectoryEntries>,
+}
+
+struct GlobPendingDir {
+    path: String,
+    positions: Vec<usize>,
+    /// Found while listing a parent rather than requested directly.
+    discovered: bool,
+}
+
+struct GlobListedEntry {
+    path: String,
+    entry: Option<oio::Entry>,
+    descend_positions: Option<Vec<usize>>,
+}
+
+enum GlobDirectoryEntries {
+    Streaming {
+        reader: Box<ReadDir>,
+        positions: Vec<usize>,
+    },
+    Sorted(IntoIter<GlobListedEntry>),
+}
+
+impl GlobLister {
+    fn new(core: Arc<FsCore>, path: &str, args: OpList, pattern: GlobPattern) 
-> Self {
+        let base = if path.ends_with('/') {
+            path
+        } else {
+            get_parent(path)
+        };
+        let prefix = if path == "/" { "" } else { path };
+        let start_after = args.start_after().map(str::to_owned);
+
+        let mut directory = if base == "/" {
+            String::new()
+        } else {
+            base.to_owned()
+        };
+        let mut position = 0;
+        for component in pattern.literal_directories() {
+            directory.push_str(component);
+            directory.push('/');
+            position += 1;
+        }
+        if directory.is_empty() {
+            directory.push('/');
+        }
+
+        let in_prefix = position == 0 || directory.starts_with(prefix);
+        // Since `directory` ends with `/`, when it sits strictly before 
`start_after` and is not
+        // a prefix of it, every descendant also sorts before `start_after`, 
so an empty lister is safe.
+        let in_cursor = position == 0
+            || start_after.as_deref().is_none_or(|marker| {
+                directory.as_str() > marker || 
marker.starts_with(directory.as_str())
+            });
+        let next_dir = (in_prefix && in_cursor).then_some(GlobPendingDir {
+            path: directory,
+            positions: vec![position],
+            discovered: false,
+        });
+
+        Self {
+            core,
+            pattern,
+            prefix: prefix.to_string(),
+            start_after,
+            next_dir,
+            active: Vec::new(),
+        }
+    }
+
+    async fn next(&mut self) -> Result<Option<oio::Entry>> {
+        loop {
+            if let Some(dir) = &self.next_dir {
+                let mut reader = match self.core.fs_list(&dir.path).await {
+                    Ok(Some(reader)) => reader,
+                    Ok(None) => {
+                        if dir.discovered {
+                            log::warn!("FS glob listing skipped missing 
directory: {}", dir.path);
+                        }
+                        self.next_dir = None;
+                        continue;
+                    }
+                    Err(err)
+                        if dir.discovered
+                            && matches!(
+                                err.kind(),
+                                ErrorKind::PermissionDenied | 
ErrorKind::NotFound
+                            ) =>
+                    {
+                        log::warn!("FS glob listing skipped directory {}: 
{err}", dir.path);
+                        self.next_dir = None;
+                        continue;
+                    }
+                    Err(err) => return Err(err),
+                };
+
+                if let Some(marker) = &self.start_after {
+                    // Keep next_dir until the buffer is complete, so an error 
or
+                    // cancelled read leaves the entire directory available to 
retry.
+                    let mut entries = Vec::new();
+                    while let Some(entry) = next_glob_entry(
+                        &mut reader,
+                        &self.core.root,
+                        &self.prefix,
+                        Some(marker),
+                        &self.pattern,
+                        &dir.positions,
+                    )
+                    .await?
+                    {
+                        entries.push(entry);
+                    }
+                    entries.sort_unstable_by(|a, b| a.path.cmp(&b.path));
+                    self.next_dir = None;
+                    self.active
+                        
.push(GlobDirectoryEntries::Sorted(entries.into_iter()));
+                } else {
+                    let dir = self.next_dir.take().expect("pending directory 
exists");
+                    self.active.push(GlobDirectoryEntries::Streaming {
+                        reader: Box::new(reader),
+                        positions: dir.positions,
+                    });
+                }
+            }
+
+            let Some(directory) = self.active.last_mut() else {
+                return Ok(None);
+            };
+            let entry = match directory {
+                GlobDirectoryEntries::Streaming { reader, positions } => {
+                    next_glob_entry(
+                        reader,
+                        &self.core.root,
+                        &self.prefix,
+                        None,
+                        &self.pattern,
+                        positions,
+                    )
+                    .await?
+                }
+                GlobDirectoryEntries::Sorted(entries) => entries.next(),
+            };
+            let Some(listed) = entry else {
+                self.active.pop();
+                continue;
+            };
+            if let Some(positions) = listed.descend_positions {
+                self.next_dir = Some(GlobPendingDir {
+                    path: listed.path,
+                    positions,
+                    discovered: true,
+                });
+            }
+            if let Some(entry) = listed.entry {
+                return Ok(Some(entry));
+            }
+        }
+    }
+}
+
+struct RawDirEntry {
+    path: String,
+    mode: EntryMode,
+    descend: bool,
+    target_metadata: Option<StdMetadata>,
+    de: DirEntry,
+}
+
+impl RawDirEntry {
+    async fn into_entry(self) -> Result<Option<oio::Entry>> {
+        let de_metadata = match self.target_metadata {
+            Some(meta) => meta,
+            None => match self.de.metadata().await {
+                Ok(de_metadata) => de_metadata,
+                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+                    // Entry can be deleted between readdir and metadata calls.
+                    return Ok(None);
+                }
+                Err(e) => return Err(new_std_io_error(e)),
+            },
+        };
+        let last_modified = match de_metadata.modified() {
+            Ok(v) => v,
+            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+                return Ok(None);
+            }
+            Err(e) => return Err(new_std_io_error(e)),
+        };
+        let mut metadata = match self.mode {
+            EntryMode::FILE => MetadataBuilder::file(de_metadata.len()),
+            EntryMode::DIR => MetadataBuilder::dir(),
+            EntryMode::Unknown => MetadataBuilder::unknown(),
+        };
+        metadata.last_modified(Timestamp::try_from(last_modified)?);
+        Ok(Some(oio::Entry::new(&self.path, metadata.build())))
+    }
+}
+
+async fn read_dir_entry(
     reader: &mut ReadDir,
     root: &Path,
-    prefix: &str,
-    start_after: Option<&str>,
-    recursive: bool,
-) -> Result<Option<ListedEntry>> {
+    resolve_symlinks: bool,
+) -> Result<Option<RawDirEntry>> {
     loop {
         let de = match reader.next_entry().await {
             Ok(Some(de)) => de,
@@ -254,12 +482,12 @@ async fn next_entry(
             (format!("{rel_path}/"), EntryMode::DIR, true, None)
         } else if ft.is_file() {
             (rel_path, EntryMode::FILE, false, None)
-        } else if ft.is_symlink() && start_after.is_some() {
+        } else if ft.is_symlink() && resolve_symlinks {
             // Resolve symlinks before start_after filtering and sorting so
             // directory symlinks carry their trailing '/' and sort in their
             // final path order. Keep streaming listings (start_after == None)
-            // returning EntryMode::Unknown so GlobLayer does not descend into
-            // discovered symlinks before CompleteLayer refines them.
+            // returning EntryMode::Unknown so CompleteLayer refines only
+            // emitted entries and traversal never descends into symlinks.
             match tokio::fs::metadata(&entry_path).await {
                 Ok(meta) if meta.is_dir() => {
                     (format!("{rel_path}/"), EntryMode::DIR, false, Some(meta))
@@ -268,7 +496,7 @@ async fn next_entry(
                 Ok(meta) => (rel_path, EntryMode::Unknown, false, Some(meta)),
                 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                     // Dangling symlink (or removed concurrently; de.metadata()
-                    // below distinguishes the two).
+                    // in into_entry distinguishes the two).
                     (rel_path, EntryMode::Unknown, false, None)
                 }
                 Err(e) => return Err(new_std_io_error(e)),
@@ -277,47 +505,90 @@ async fn next_entry(
             (rel_path, EntryMode::Unknown, false, None)
         };
 
-        if !path.starts_with(prefix) {
+        return Ok(Some(RawDirEntry {
+            path,
+            mode,
+            descend,
+            target_metadata,
+            de,
+        }));
+    }
+}
+
+async fn next_entry(
+    reader: &mut ReadDir,
+    root: &Path,
+    prefix: &str,
+    start_after: Option<&str>,
+    recursive: bool,
+) -> Result<Option<ListedEntry>> {
+    while let Some(raw) = read_dir_entry(reader, root, 
start_after.is_some()).await? {
+        if !raw.path.starts_with(prefix) {
             continue;
         }
         // A directory we will descend into can still have later children.
         if let Some(marker) = start_after
-            && path.as_str() <= marker
-            && !(recursive && descend && marker.starts_with(path.as_str()))
+            && raw.path.as_str() <= marker
+            && !(recursive && raw.descend && 
marker.starts_with(raw.path.as_str()))
         {
             continue;
         }
 
-        let de_metadata = match target_metadata {
-            Some(meta) => meta,
-            None => match de.metadata().await {
-                Ok(de_metadata) => de_metadata,
-                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
-                    // Entry can be deleted between readdir and metadata calls.
-                    continue;
-                }
-                Err(e) => return Err(new_std_io_error(e)),
-            },
+        let descend = raw.descend;
+        let Some(entry) = raw.into_entry().await? else {
+            continue;
         };
-        let last_modified = match de_metadata.modified() {
-            Ok(v) => v,
-            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+        return Ok(Some(ListedEntry { entry, descend }));
+    }
+    Ok(None)
+}
+
+async fn next_glob_entry(
+    reader: &mut ReadDir,
+    root: &Path,
+    prefix: &str,
+    start_after: Option<&str>,
+    pattern: &GlobPattern,
+    positions: &[usize],
+) -> Result<Option<GlobListedEntry>> {
+    while let Some(raw) = read_dir_entry(reader, root, 
start_after.is_some()).await? {
+        if !raw.path.starts_with(prefix) {
+            continue;
+        }
+        let trimmed = raw.path.trim_end_matches('/');
+        let name = trimmed.rsplit_once('/').map_or(trimmed, |(_, name)| name);
+        let next_positions = pattern.advance(positions, name);
+        let matches = pattern.accepts(&next_positions, raw.mode.is_dir());
+        let can_descend = raw.descend && pattern.can_descend(&next_positions);
+        if !matches && !can_descend {
+            continue;
+        }
+
+        let after_marker = start_after.is_none_or(|marker| raw.path.as_str() > 
marker);
+        let emit = matches && after_marker;
+        let descend = can_descend
+            && (after_marker
+                || start_after.is_some_and(|marker| 
marker.starts_with(raw.path.as_str())));
+        if !emit && !descend {
+            continue;
+        }
+
+        let path = raw.path.clone();
+        let entry = if emit {
+            let Some(entry) = raw.into_entry().await? else {
                 continue;
-            }
-            Err(e) => return Err(new_std_io_error(e)),
-        };
-        let mut metadata = match mode {
-            EntryMode::FILE => MetadataBuilder::file(de_metadata.len()),
-            EntryMode::DIR => MetadataBuilder::dir(),
-            EntryMode::Unknown => MetadataBuilder::unknown(),
+            };
+            Some(entry)
+        } else {
+            None
         };
-        metadata.last_modified(Timestamp::try_from(last_modified)?);
-
-        return Ok(Some(ListedEntry {
-            entry: oio::Entry::new(&path, metadata.build()),
-            descend,
+        return Ok(Some(GlobListedEntry {
+            path,
+            entry,
+            descend_positions: descend.then_some(next_positions),
         }));
     }
+    Ok(None)
 }
 
 #[cfg(all(test, unix))]
@@ -360,6 +631,72 @@ mod tests {
         assert_eq!(paths, ["dir/photo.jpg"]);
     }
 
+    #[tokio::test]
+    async fn 
glob_follows_leading_literal_symlink_consistently_with_start_after() {
+        let root = tempfile::tempdir().unwrap();
+        let op = Operator::new_without_glob_simulation(
+            Fs::default().root(root.path().to_str().unwrap()),
+        )
+        .unwrap();
+        op.write("dir/photo.jpg", "data").await.unwrap();
+        op.write("dir/sub/deep.jpg", "data").await.unwrap();
+        std::os::unix::fs::symlink("dir", root.path().join("alias")).unwrap();
+
+        let mut recursive: Vec<_> = op
+            .list_with("/")
+            .glob("alias/**/*.jpg")
+            .await
+            .unwrap()
+            .into_iter()
+            .map(|entry| entry.path().to_owned())
+            .collect();
+        recursive.sort_unstable();
+        assert_eq!(recursive, ["alias/photo.jpg", "alias/sub/deep.jpg"]);
+
+        for (glob, marker, expected) in [
+            (
+                "alias/**/*.jpg",
+                "",
+                vec!["alias/photo.jpg", "alias/sub/deep.jpg"],
+            ),
+            (
+                "alias/**/*.jpg",
+                "alias/",
+                vec!["alias/photo.jpg", "alias/sub/deep.jpg"],
+            ),
+            (
+                "alias/**/*.jpg",
+                "alias/photo.jpg",
+                vec!["alias/sub/deep.jpg"],
+            ),
+            ("alias/*", "", vec!["alias/photo.jpg", "alias/sub/"]),
+            ("alias/*", "alias/", vec!["alias/photo.jpg", "alias/sub/"]),
+            ("alias/*", "alias/photo.jpg", vec!["alias/sub/"]),
+        ] {
+            let paths: Vec<_> = op
+                .list_with("/")
+                .glob(glob)
+                .start_after(marker)
+                .await
+                .unwrap()
+                .into_iter()
+                .map(|entry| entry.path().to_owned())
+                .collect();
+            assert_eq!(paths, expected, "glob={glob:?}, 
start_after={marker:?}");
+        }
+
+        let mut shallow: Vec<_> = op
+            .list_with("/")
+            .glob("alias/*")
+            .await
+            .unwrap()
+            .into_iter()
+            .map(|entry| entry.path().to_owned())
+            .collect();
+        shallow.sort_unstable();
+        assert_eq!(shallow, ["alias/photo.jpg", "alias/sub/"]);
+    }
+
     #[tokio::test]
     async fn list_recursively_skips_unreadable_child() {
         let root = tempfile::tempdir().unwrap();
@@ -434,6 +771,422 @@ mod tests {
         }
         assert_eq!(direct.unwrap_err().kind(), ErrorKind::PermissionDenied);
     }
+
+    #[tokio::test]
+    async fn glob_literal_directories_skip_unreadable_parents() {
+        let root = tempfile::tempdir().unwrap();
+        let parent = root.path().join("data");
+        let target = parent.join("open");
+        fs::create_dir_all(&target).unwrap();
+        fs::write(target.join("b.jpg"), b"data").unwrap();
+        let op = Operator::new_without_glob_simulation(
+            Fs::default().root(root.path().to_str().unwrap()),
+        )
+        .unwrap();
+
+        let permissions = fs::metadata(&parent).unwrap().permissions();
+        // Searchable (x) without read (r): read_dir(data) fails, 
read_dir(data/open) succeeds.
+        fs::set_permissions(&parent, 
fs::Permissions::from_mode(0o111)).unwrap();
+
+        match fs::read_dir(&parent) {
+            Ok(_) => {
+                fs::set_permissions(&parent, permissions).unwrap();
+                return;
+            }
+            Err(err) => assert_eq!(err.kind(), 
std::io::ErrorKind::PermissionDenied),
+        }
+
+        let literal = op.list_with("/").glob("data/open/*.jpg").await;
+        let literal_sorted = op
+            .list_with("/")
+            .glob("data/open/*.jpg")
+            .start_after("")
+            .await;
+        let wildcard = op.list_with("data/").glob("*/*.jpg").await;
+        fs::set_permissions(&parent, permissions).unwrap();
+
+        assert_eq!(
+            literal
+                .unwrap()
+                .iter()
+                .map(|entry| entry.path())
+                .collect::<Vec<_>>(),
+            ["data/open/b.jpg"]
+        );
+        assert_eq!(
+            literal_sorted
+                .unwrap()
+                .iter()
+                .map(|entry| entry.path())
+                .collect::<Vec<_>>(),
+            ["data/open/b.jpg"]
+        );
+        assert_eq!(wildcard.unwrap_err().kind(), ErrorKind::PermissionDenied);
+    }
+}
+
+#[cfg(test)]
+mod glob_tests {
+    use std::fs;
+    use std::sync::Arc;
+
+    use opendal_core::options::ListOptions;
+    use opendal_core::raw::{
+        GlobPattern, OpCompose, OpCopy, OpCreateDir, OpList, OpPresign, 
OpRead, OpRename, OpStat,
+        OpWrite, RpCreateDir, RpPresign, RpRename, RpStat, Service, 
ServiceInfo, Servicer, oio,
+    };
+    use opendal_core::{
+        Builder, Capability, EntryMode, ErrorKind, OperationContext, Operator, 
Result,
+    };
+
+    use super::{FsLister, GlobLister};
+    use crate::{Fs, FsConfig};
+
+    #[derive(Debug, Default)]
+    struct StripGlobBuilder(Fs);
+
+    impl Builder for StripGlobBuilder {
+        type Config = FsConfig;
+
+        fn build(self) -> Result<impl Service> {
+            let inner = Arc::new(self.0.build()?) as Servicer;
+            Ok(StripGlobService { inner })
+        }
+    }
+
+    #[derive(Debug)]
+    struct StripGlobService {
+        inner: Servicer,
+    }
+
+    impl Service for StripGlobService {
+        type Reader = oio::Reader;
+        type Writer = oio::Writer;
+        type Lister = oio::Lister;
+        type Deleter = oio::Deleter;
+        type Copier = oio::Copier;
+        type Composer = oio::Composer;
+
+        fn info(&self) -> ServiceInfo {
+            self.inner.info()
+        }
+
+        fn capability(&self) -> Capability {
+            let mut cap = self.inner.capability();
+            cap.list_with_glob = false;
+            cap
+        }
+
+        async fn create_dir(
+            &self,
+            ctx: &OperationContext,
+            path: &str,
+            args: OpCreateDir,
+        ) -> Result<RpCreateDir> {
+            self.inner.create_dir(ctx, path, args).await
+        }
+
+        async fn stat(&self, ctx: &OperationContext, path: &str, args: OpStat) 
-> Result<RpStat> {
+            self.inner.stat(ctx, path, args).await
+        }
+
+        fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) -> 
Result<Self::Reader> {
+            self.inner.read(ctx, path, args)
+        }
+
+        fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> 
Result<Self::Writer> {
+            self.inner.write(ctx, path, args)
+        }
+
+        fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
+            self.inner.delete(ctx)
+        }
+
+        fn list(&self, ctx: &OperationContext, path: &str, args: OpList) -> 
Result<Self::Lister> {
+            self.inner.list(ctx, path, args)
+        }
+
+        fn copy(
+            &self,
+            ctx: &OperationContext,
+            from: &str,
+            to: &str,
+            args: OpCopy,
+        ) -> Result<Self::Copier> {
+            self.inner.copy(ctx, from, to, args)
+        }
+
+        fn compose(
+            &self,
+            ctx: &OperationContext,
+            to: &str,
+            args: OpCompose,
+        ) -> Result<Self::Composer> {
+            self.inner.compose(ctx, to, args)
+        }
+
+        async fn rename(
+            &self,
+            ctx: &OperationContext,
+            from: &str,
+            to: &str,
+            args: OpRename,
+        ) -> Result<RpRename> {
+            self.inner.rename(ctx, from, to, args).await
+        }
+
+        async fn presign(
+            &self,
+            ctx: &OperationContext,
+            path: &str,
+            args: OpPresign,
+        ) -> Result<RpPresign> {
+            self.inner.presign(ctx, path, args).await
+        }
+    }
+
+    #[tokio::test]
+    async fn native_glob_works_without_glob_simulation() {
+        let root = tempfile::tempdir().unwrap();
+        let op = Operator::new_without_glob_simulation(
+            Fs::default().root(root.path().to_str().unwrap()),
+        )
+        .unwrap();
+        assert!(op.info().capability().list_with_glob);
+
+        op.write("a.jpg", "data").await.unwrap();
+        op.write("sub/b.jpg", "data").await.unwrap();
+        op.write("sub/c.png", "data").await.unwrap();
+
+        let mut paths: Vec<_> = op
+            .list_with("/")
+            .glob("**/*.jpg")
+            .await
+            .unwrap()
+            .into_iter()
+            .map(|entry| entry.path().to_owned())
+            .collect();
+        paths.sort_unstable();
+        assert_eq!(paths, ["a.jpg", "sub/b.jpg"]);
+
+        for invalid in ["", "/", "a**b", "../*.jpg", "[z-a]", "{a,b", 
"file\\"] {
+            let err = op.list_with("/").glob(invalid).await.unwrap_err();
+            assert_eq!(err.kind(), ErrorKind::ConfigInvalid, "pattern 
{invalid:?}");
+        }
+    }
+
+    #[tokio::test]
+    async fn glob_lister_prunes_non_matching_subdirectories() {
+        let root = tempfile::tempdir().unwrap();
+        fs::create_dir_all(root.path().join("keep")).unwrap();
+        fs::create_dir_all(root.path().join("keep1")).unwrap();
+        fs::create_dir_all(root.path().join("skip/nested")).unwrap();
+        fs::write(root.path().join("keep/a.jpg"), b"data").unwrap();
+        fs::write(root.path().join("keep1/a.jpg"), b"data").unwrap();
+        fs::write(root.path().join("skip/nested/b.jpg"), b"data").unwrap();
+
+        let core = Arc::new(crate::core::FsCore {
+            info: ServiceInfo::new(crate::FS_SCHEME, 
root.path().to_string_lossy(), ""),
+            capability: Capability {
+                list: true,
+                list_with_glob: true,
+                ..Default::default()
+            },
+            root: root.path().canonicalize().unwrap(),
+            atomic_write_dir: None,
+            direct_io: false,
+            buf_pool: oio::PooledBuf::new(1),
+        });
+
+        // Leading literal directory jumps straight to `keep/`.
+        let FsLister::Glob(lister) =
+            FsLister::new(core.clone(), "/", 
OpList::default().with_glob("keep/*.jpg")).unwrap()
+        else {
+            panic!("expected GlobLister");
+        };
+        assert_eq!(lister.next_dir.as_ref().unwrap().path, "keep/");
+
+        // Single-level glob never schedules subdirectories for descent.
+        let mut shallow = GlobLister::new(
+            core.clone(),
+            "/",
+            OpList::default().with_glob("*.jpg"),
+            GlobPattern::new("*.jpg").unwrap(),
+        );
+        assert!(shallow.next().await.unwrap().is_none());
+        assert!(shallow.next_dir.is_none());
+
+        // Pattern matching only `keep*` skips `skip/` completely.
+        let list_args = OpList::from_options(
+            &Capability {
+                list: true,
+                list_with_glob: true,
+                list_with_start_after: true,
+                ..Default::default()
+            },
+            ListOptions {
+                glob: Some("keep*/*.jpg".to_string()),
+                start_after: Some(String::new()),
+                ..Default::default()
+            },
+        )
+        .unwrap();
+        let mut pruned = GlobLister::new(
+            core,
+            "/",
+            list_args,
+            GlobPattern::new("keep*/*.jpg").unwrap(),
+        );
+        let mut found = Vec::new();
+        while let Some(entry) = pruned.next().await.unwrap() {
+            assert_ne!(
+                pruned.next_dir.as_ref().map(|dir| dir.path.as_str()),
+                Some("skip/")
+            );
+            found.push(entry.path().to_owned());
+        }
+        assert_eq!(found, ["keep/a.jpg", "keep1/a.jpg"]);
+    }
+
+    #[tokio::test]
+    async fn native_glob_matches_glob_layer_differentially() {
+        let root = tempfile::tempdir().unwrap();
+        for dir in [
+            "a/b/b",
+            "a/b/x",
+            "a/x/b",
+            "a/empty",
+            "ab",
+            "a-1",
+            "dir/[b]/sub",
+            "dir/c",
+            "empty",
+        ] {
+            fs::create_dir_all(root.path().join(dir)).unwrap();
+        }
+        for file in [
+            "a.jpg",
+            "a-1.jpg",
+            "a0.jpg",
+            "b.png",
+            "é.jpg",
+            "猫.jpg",
+            "[b].txt",
+            "a/x.jpg",
+            "a/b/c.jpg",
+            "a/b/b/c.jpg",
+            "a/b/x/c.jpg",
+            "a/x/b/c.jpg",
+            "ab/x.jpg",
+            "a-1/x.jpg",
+            "dir/[b]/file.json",
+            "dir/[b]/sub/deep.json",
+            "dir/c/file.json",
+        ] {
+            fs::write(root.path().join(file), b"data").unwrap();
+        }
+        #[cfg(unix)]
+        {
+            std::os::unix::fs::symlink("a", 
root.path().join("alias")).unwrap();
+            std::os::unix::fs::symlink("a.jpg", 
root.path().join("link.jpg")).unwrap();
+            std::os::unix::fs::symlink("missing", 
root.path().join("dangling.jpg")).unwrap();
+        }
+
+        let root_str = root.path().to_str().unwrap();
+        let native_op =
+            
Operator::new_without_glob_simulation(Fs::default().root(root_str)).unwrap();
+        let layer_op = 
Operator::new(StripGlobBuilder(Fs::default().root(root_str))).unwrap();
+
+        let cases: &[(&str, &str, bool, Option<&str>)] = &[
+            ("/", "*.jpg", false, None),
+            ("/", "*.jpg", true, None),
+            ("/", "?.jpg", false, None),
+            ("/", "?.jpg", true, None),
+            ("/", "[a-b].{jpg,png}", false, None),
+            ("/", "[!a-z].jpg", false, None),
+            ("/", r"\[b\].txt", false, None),
+            ("/", r"dir/\[b\]/**/*.json", false, None),
+            ("/", "**/*.jpg", false, None),
+            ("/", "**/?.jpg", false, None),
+            ("/", "a/**/**/b/**/c.jpg", false, None),
+            ("/", "a/b/**", false, None),
+            ("/", "**", false, None),
+            ("/", "*/", false, None),
+            ("/", "**/", false, None),
+            ("/", "a/*/", false, None),
+            ("/", "a/b/", false, None),
+            ("/", "a/x.jpg/", false, None),
+            ("/", "a/b/*.jpg", false, None),
+            ("/", "missing/sub/*.jpg", false, None),
+            ("/", "a.jpg/*.txt", false, None),
+            ("a/", "?.jpg", true, None),
+            ("a/", "**/c.jpg", false, None),
+            ("a/", "b/", false, None),
+            ("a/b", "b/*.jpg", false, None),
+            ("a/b", "b/**", false, None),
+            ("a/b", "b", false, None),
+            ("a/x", "b/*.jpg", false, None),
+            ("a", "**/*.jpg", false, None),
+            ("a", "*.jpg", false, None),
+            // start_after cases
+            ("/", "*.jpg", false, Some("")),
+            ("/", "*.jpg", false, Some("a.jpg")),
+            ("/", "**/*.jpg", false, Some("")),
+            ("/", "**/*.jpg", false, Some("a/")),
+            ("/", "**/*.jpg", false, Some("a/b/")),
+            ("/", "**/*.jpg", false, Some("a/b/c.jpg")),
+            ("/", "**/*.jpg", false, Some("a0.jpg")),
+            ("/", "**/*.jpg", false, Some("z")),
+            ("/", "**", false, Some("")),
+            ("/", "**", false, Some("a/b/")),
+            ("/", "*/", false, Some("")),
+            ("/", "a/b/*.jpg", false, Some("")),
+            ("/", "a/b/*.jpg", false, Some("a/b/c.jpg")),
+            ("/", "a/b/*.jpg", false, Some("z")),
+            ("a/b", "b/*.jpg", false, Some("")),
+            ("a", "**/*.jpg", false, Some("a/b/")),
+        ];
+
+        for &(path, glob, recursive, start_after) in cases {
+            let mut native_req = 
native_op.list_with(path).glob(glob).recursive(recursive);
+            let mut layer_req = 
layer_op.list_with(path).glob(glob).recursive(recursive);
+            if let Some(marker) = start_after {
+                native_req = native_req.start_after(marker);
+                layer_req = layer_req.start_after(marker);
+            }
+
+            let mut native: Vec<(String, EntryMode)> = native_req
+                .await
+                .unwrap()
+                .into_iter()
+                .map(|entry| (entry.path().to_owned(), 
entry.metadata().mode()))
+                .collect();
+            let mut expected: Vec<(String, EntryMode)> = layer_req
+                .await
+                .unwrap()
+                .into_iter()
+                .map(|entry| (entry.path().to_owned(), 
entry.metadata().mode()))
+                .collect();
+
+            if start_after.is_some() {
+                assert!(
+                    native.windows(2).all(|pair| pair[0].0 < pair[1].0),
+                    "native output not strictly sorted for ({path:?}, 
{glob:?}, {recursive}, {start_after:?}): {native:?}"
+                );
+                assert_eq!(
+                    native, expected,
+                    "ordered mismatch for ({path:?}, {glob:?}, {recursive}, 
{start_after:?})"
+                );
+            } else {
+                native.sort_unstable_by(|a, b| a.0.cmp(&b.0));
+                expected.sort_unstable_by(|a, b| a.0.cmp(&b.0));
+                assert_eq!(
+                    native, expected,
+                    "set mismatch for ({path:?}, {glob:?}, {recursive}, 
{start_after:?})"
+                );
+            }
+        }
+    }
 }
 
 #[cfg(test)]
@@ -460,6 +1213,13 @@ mod oversized_path {
                     .start_after("marker")
                     .await,
             );
+            
assert_oversized_list_result(op.list_with(&path).glob("*.jpg").await);
+            assert_oversized_list_result(
+                op.list_with(&path)
+                    .glob("*.jpg")
+                    .start_after("marker")
+                    .await,
+            );
         }
     }
 
diff --git a/website/data/capabilities.json b/website/data/capabilities.json
index 616c4bdd84..87942cdcdd 100644
--- a/website/data/capabilities.json
+++ b/website/data/capabilities.json
@@ -1131,6 +1131,7 @@
         "delete": true,
         "delete_with_recursive": true,
         "list": true,
+        "list_with_glob": true,
         "list_with_recursive": true,
         "list_with_start_after": true,
         "read": true,

Reply via email to