polars_io/path_utils/
mod.rs

1use std::collections::VecDeque;
2use std::path::{Path, PathBuf};
3use std::sync::{Arc, LazyLock};
4
5use polars_core::config;
6use polars_core::error::{PolarsError, PolarsResult, polars_bail, to_compute_err};
7use polars_utils::pl_str::PlSmallStr;
8
9#[cfg(feature = "cloud")]
10mod hugging_face;
11
12use crate::cloud::CloudOptions;
13
14pub static POLARS_TEMP_DIR_BASE_PATH: LazyLock<Box<Path>> = LazyLock::new(|| {
15    (|| {
16        let verbose = config::verbose();
17
18        let path = if let Ok(v) = std::env::var("POLARS_TEMP_DIR").map(PathBuf::from) {
19            if verbose {
20                eprintln!("init_temp_dir: sourced from POLARS_TEMP_DIR")
21            }
22            v
23        } else if cfg!(target_family = "unix") {
24            let id = std::env::var("USER")
25                .inspect(|_| {
26                    if verbose {
27                        eprintln!("init_temp_dir: sourced $USER")
28                    }
29                })
30                .or_else(|_e| {
31                    // We shouldn't hit here, but we can fallback to hashing $HOME if blake3 is
32                    // available (it is available when file_cache is activated).
33                    #[cfg(feature = "file_cache")]
34                    {
35                        std::env::var("HOME")
36                            .inspect(|_| {
37                                if verbose {
38                                    eprintln!("init_temp_dir: sourced $HOME")
39                                }
40                            })
41                            .map(|x| blake3::hash(x.as_bytes()).to_hex()[..32].to_string())
42                    }
43                    #[cfg(not(feature = "file_cache"))]
44                    {
45                        Err(_e)
46                    }
47                });
48
49            if let Ok(v) = id {
50                std::env::temp_dir().join(format!("polars-{}/", v))
51            } else {
52                return Err(std::io::Error::other(
53                    "could not load $USER or $HOME environment variables",
54                ));
55            }
56        } else if cfg!(target_family = "windows") {
57            // Setting permissions on Windows is not as easy compared to Unix, but fortunately
58            // the default temporary directory location is underneath the user profile, so we
59            // shouldn't need to do anything.
60            std::env::temp_dir().join("polars/")
61        } else {
62            std::env::temp_dir().join("polars/")
63        }
64        .into_boxed_path();
65
66        if let Err(err) = std::fs::create_dir_all(path.as_ref()) {
67            if !path.is_dir() {
68                panic!(
69                    "failed to create temporary directory: {} (path = {:?})",
70                    err,
71                    path.as_ref()
72                );
73            }
74        }
75
76        #[cfg(target_family = "unix")]
77        {
78            use std::os::unix::fs::PermissionsExt;
79
80            let result = (|| {
81                std::fs::set_permissions(path.as_ref(), std::fs::Permissions::from_mode(0o700))?;
82                let perms = std::fs::metadata(path.as_ref())?.permissions();
83
84                if (perms.mode() % 0o1000) != 0o700 {
85                    std::io::Result::Err(std::io::Error::other(format!(
86                        "permission mismatch: {:?}",
87                        perms
88                    )))
89                } else {
90                    std::io::Result::Ok(())
91                }
92            })()
93            .map_err(|e| {
94                std::io::Error::new(
95                    e.kind(),
96                    format!(
97                        "error setting temporary directory permissions: {} (path = {:?})",
98                        e,
99                        path.as_ref()
100                    ),
101                )
102            });
103
104            if std::env::var("POLARS_ALLOW_UNSECURED_TEMP_DIR").as_deref() != Ok("1") {
105                result?;
106            }
107        }
108
109        std::io::Result::Ok(path)
110    })()
111    .map_err(|e| {
112        std::io::Error::new(
113            e.kind(),
114            format!(
115                "error initializing temporary directory: {} \
116                 consider explicitly setting POLARS_TEMP_DIR",
117                e
118            ),
119        )
120    })
121    .unwrap()
122});
123
124/// Replaces a "~" in the Path with the home directory.
125pub fn resolve_homedir(path: &dyn AsRef<Path>) -> PathBuf {
126    let path = path.as_ref();
127
128    if path.starts_with("~") {
129        // home crate does not compile on wasm https://github.com/rust-lang/cargo/issues/12297
130        #[cfg(not(target_family = "wasm"))]
131        if let Some(homedir) = home::home_dir() {
132            return homedir.join(path.strip_prefix("~").unwrap());
133        }
134    }
135
136    path.into()
137}
138
139polars_utils::regex_cache::cached_regex! {
140    static CLOUD_URL = r"^(s3a?|gs|gcs|file|abfss?|azure|az|adl|https?|hf)://";
141}
142
143/// Check if the path is a cloud url.
144pub fn is_cloud_url<P: AsRef<Path>>(p: P) -> bool {
145    match p.as_ref().as_os_str().to_str() {
146        Some(s) => CLOUD_URL.is_match(s),
147        _ => false,
148    }
149}
150
151/// Get the index of the first occurrence of a glob symbol.
152pub fn get_glob_start_idx(path: &[u8]) -> Option<usize> {
153    memchr::memchr3(b'*', b'?', b'[', path)
154}
155
156/// Returns `true` if `expanded_paths` were expanded from a single directory
157pub fn expanded_from_single_directory<P: AsRef<std::path::Path>>(
158    paths: &[P],
159    expanded_paths: &[P],
160) -> bool {
161    // Single input that isn't a glob
162    paths.len() == 1 && get_glob_start_idx(paths[0].as_ref().to_str().unwrap().as_bytes()).is_none()
163    // And isn't a file
164    && {
165        (
166            // For local paths, we can just use `is_dir`
167            !is_cloud_url(paths[0].as_ref()) && paths[0].as_ref().is_dir()
168        )
169        || (
170            // For cloud paths, we determine that the input path isn't a file by checking that the
171            // output path differs.
172            expanded_paths.is_empty() || (paths[0].as_ref() != expanded_paths[0].as_ref())
173        )
174    }
175}
176
177/// Recursively traverses directories and expands globs if `glob` is `true`.
178pub fn expand_paths(
179    paths: &[PathBuf],
180    glob: bool,
181    #[allow(unused_variables)] cloud_options: Option<&CloudOptions>,
182) -> PolarsResult<Arc<[PathBuf]>> {
183    expand_paths_hive(paths, glob, cloud_options, false).map(|x| x.0)
184}
185
186struct HiveIdxTracker<'a> {
187    idx: usize,
188    paths: &'a [PathBuf],
189    check_directory_level: bool,
190}
191
192impl HiveIdxTracker<'_> {
193    fn update(&mut self, i: usize, path_idx: usize) -> PolarsResult<()> {
194        let check_directory_level = self.check_directory_level;
195        let paths = self.paths;
196
197        if check_directory_level
198            && ![usize::MAX, i].contains(&self.idx)
199            // They could still be the same directory level, just with different name length
200            && (paths[path_idx].parent() != paths[path_idx - 1].parent())
201        {
202            polars_bail!(
203                InvalidOperation:
204                "attempted to read from different directory levels with hive partitioning enabled: first path: {}, second path: {}",
205                paths[path_idx - 1].to_str().unwrap(),
206                paths[path_idx].to_str().unwrap(),
207            )
208        } else {
209            self.idx = std::cmp::min(self.idx, i);
210            Ok(())
211        }
212    }
213}
214
215/// Recursively traverses directories and expands globs if `glob` is `true`.
216/// Returns the expanded paths and the index at which to start parsing hive
217/// partitions from the path.
218pub fn expand_paths_hive(
219    paths: &[PathBuf],
220    glob: bool,
221    #[allow(unused_variables)] cloud_options: Option<&CloudOptions>,
222    check_directory_level: bool,
223) -> PolarsResult<(Arc<[PathBuf]>, usize)> {
224    let Some(first_path) = paths.first() else {
225        return Ok((vec![].into(), 0));
226    };
227
228    let is_cloud = is_cloud_url(first_path);
229
230    /// Wrapper around `Vec<PathBuf>` that also tracks file extensions, so that
231    /// we don't have to traverse the entire list again to validate extensions.
232    struct OutPaths {
233        paths: Vec<PathBuf>,
234        exts: [Option<(PlSmallStr, usize)>; 2],
235        current_idx: usize,
236    }
237
238    impl OutPaths {
239        fn update_ext_status(
240            current_idx: &mut usize,
241            exts: &mut [Option<(PlSmallStr, usize)>; 2],
242            value: &Path,
243        ) {
244            let ext = value
245                .extension()
246                .map(|x| PlSmallStr::from(x.to_str().unwrap()))
247                .unwrap_or(PlSmallStr::EMPTY);
248
249            if exts[0].is_none() {
250                exts[0] = Some((ext, *current_idx));
251            } else if exts[1].is_none() && ext != exts[0].as_ref().unwrap().0 {
252                exts[1] = Some((ext, *current_idx));
253            }
254
255            *current_idx += 1;
256        }
257
258        fn push(&mut self, value: PathBuf) {
259            {
260                let current_idx = &mut self.current_idx;
261                let exts = &mut self.exts;
262                Self::update_ext_status(current_idx, exts, &value);
263            }
264            self.paths.push(value)
265        }
266
267        fn extend(&mut self, values: impl IntoIterator<Item = PathBuf>) {
268            let current_idx = &mut self.current_idx;
269            let exts = &mut self.exts;
270
271            self.paths.extend(values.into_iter().inspect(|x| {
272                Self::update_ext_status(current_idx, exts, x);
273            }))
274        }
275
276        fn extend_from_slice(&mut self, values: &[PathBuf]) {
277            self.extend(values.iter().cloned())
278        }
279    }
280
281    let mut out_paths = OutPaths {
282        paths: vec![],
283        exts: [None, None],
284        current_idx: 0,
285    };
286
287    let mut hive_idx_tracker = HiveIdxTracker {
288        idx: usize::MAX,
289        paths,
290        check_directory_level,
291    };
292
293    if is_cloud || { cfg!(not(target_family = "windows")) && config::force_async() } {
294        #[cfg(feature = "cloud")]
295        {
296            use polars_utils::_limit_path_len_io_err;
297
298            use crate::cloud::object_path_from_str;
299
300            if first_path.starts_with("hf://") {
301                let (expand_start_idx, paths) = crate::pl_async::get_runtime().block_in_place_on(
302                    hugging_face::expand_paths_hf(
303                        paths,
304                        check_directory_level,
305                        cloud_options,
306                        glob,
307                    ),
308                )?;
309
310                return Ok((Arc::from(paths), expand_start_idx));
311            }
312
313            let format_path = |scheme: &str, bucket: &str, location: &str| {
314                if is_cloud {
315                    format!("{}://{}/{}", scheme, bucket, location)
316                } else {
317                    format!("/{}", location)
318                }
319            };
320
321            let expand_path_cloud = |path: &str,
322                                     cloud_options: Option<&CloudOptions>|
323             -> PolarsResult<(usize, Vec<PathBuf>)> {
324                crate::pl_async::get_runtime().block_in_place_on(async {
325                    let (cloud_location, store) =
326                        crate::cloud::build_object_store(path, cloud_options, glob).await?;
327                    let prefix = object_path_from_str(&cloud_location.prefix)?;
328
329                    let out = if !path.ends_with("/")
330                        && (!glob || cloud_location.expansion.is_none())
331                        && {
332                            // We need to check if it is a directory for local paths (we can be here due
333                            // to FORCE_ASYNC). For cloud paths the convention is that the user must add
334                            // a trailing slash `/` to scan directories. We don't infer it as that would
335                            // mean sending one network request per path serially (very slow).
336                            is_cloud || PathBuf::from(path).is_file()
337                        } {
338                        (
339                            0,
340                            vec![PathBuf::from(format_path(
341                                &cloud_location.scheme,
342                                &cloud_location.bucket,
343                                prefix.as_ref(),
344                            ))],
345                        )
346                    } else {
347                        use futures::TryStreamExt;
348
349                        if !is_cloud {
350                            // FORCE_ASYNC in the test suite wants us to raise a proper error message
351                            // for non-existent file paths. Note we can't do this for cloud paths as
352                            // there is no concept of a "directory" - a non-existent path is
353                            // indistinguishable from an empty directory.
354                            let path = PathBuf::from(path);
355                            if !path.is_dir() {
356                                path.metadata()
357                                    .map_err(|err| _limit_path_len_io_err(&path, err))?;
358                            }
359                        }
360
361                        let cloud_location = &cloud_location;
362
363                        let mut paths = store
364                            .try_exec_rebuild_on_err(|store| {
365                                let st = store.clone();
366
367                                async {
368                                    let store = st;
369                                    let out = store
370                                        .list(Some(&prefix))
371                                        .try_filter_map(|x| async move {
372                                            let out = (x.size > 0).then(|| {
373                                                PathBuf::from({
374                                                    format_path(
375                                                        &cloud_location.scheme,
376                                                        &cloud_location.bucket,
377                                                        x.location.as_ref(),
378                                                    )
379                                                })
380                                            });
381                                            Ok(out)
382                                        })
383                                        .try_collect::<Vec<_>>()
384                                        .await?;
385
386                                    Ok(out)
387                                }
388                            })
389                            .await?;
390
391                        paths.sort_unstable();
392                        (
393                            format_path(
394                                &cloud_location.scheme,
395                                &cloud_location.bucket,
396                                &cloud_location.prefix,
397                            )
398                            .len(),
399                            paths,
400                        )
401                    };
402
403                    PolarsResult::Ok(out)
404                })
405            };
406
407            for (path_idx, path) in paths.iter().enumerate() {
408                if path.to_str().unwrap().starts_with("http") {
409                    out_paths.push(path.clone());
410                    hive_idx_tracker.update(0, path_idx)?;
411                    continue;
412                }
413
414                let glob_start_idx = get_glob_start_idx(path.to_str().unwrap().as_bytes());
415
416                let path = if glob && glob_start_idx.is_some() {
417                    path.clone()
418                } else {
419                    let (expand_start_idx, paths) =
420                        expand_path_cloud(path.to_str().unwrap(), cloud_options)?;
421                    out_paths.extend_from_slice(&paths);
422                    hive_idx_tracker.update(expand_start_idx, path_idx)?;
423                    continue;
424                };
425
426                hive_idx_tracker.update(0, path_idx)?;
427
428                let iter = crate::pl_async::get_runtime()
429                    .block_in_place_on(crate::async_glob(path.to_str().unwrap(), cloud_options))?;
430
431                if is_cloud {
432                    out_paths.extend(iter.into_iter().map(PathBuf::from));
433                } else {
434                    // FORCE_ASYNC, remove leading file:// as not all readers support it.
435                    out_paths.extend(iter.iter().map(|x| &x[7..]).map(PathBuf::from))
436                }
437            }
438        }
439        #[cfg(not(feature = "cloud"))]
440        panic!("Feature `cloud` must be enabled to use globbing patterns with cloud urls.")
441    } else {
442        let mut stack = VecDeque::new();
443
444        for path_idx in 0..paths.len() {
445            let path = &paths[path_idx];
446            stack.clear();
447
448            if path.is_dir() {
449                let i = path.to_str().unwrap().len();
450
451                hive_idx_tracker.update(i, path_idx)?;
452
453                stack.push_back(path.clone());
454
455                while let Some(dir) = stack.pop_front() {
456                    let mut paths = std::fs::read_dir(dir)
457                        .map_err(PolarsError::from)?
458                        .map(|x| x.map(|x| x.path()))
459                        .collect::<std::io::Result<Vec<_>>>()
460                        .map_err(PolarsError::from)?;
461                    paths.sort_unstable();
462
463                    for path in paths {
464                        if path.is_dir() {
465                            stack.push_back(path);
466                        } else if path.metadata()?.len() > 0 {
467                            out_paths.push(path);
468                        }
469                    }
470                }
471
472                continue;
473            }
474
475            let i = get_glob_start_idx(path.to_str().unwrap().as_bytes());
476
477            if glob && i.is_some() {
478                hive_idx_tracker.update(0, path_idx)?;
479
480                let Ok(paths) = glob::glob(path.to_str().unwrap()) else {
481                    polars_bail!(ComputeError: "invalid glob pattern given")
482                };
483
484                for path in paths {
485                    let path = path.map_err(to_compute_err)?;
486                    if !path.is_dir() && path.metadata()?.len() > 0 {
487                        out_paths.push(path);
488                    }
489                }
490            } else {
491                hive_idx_tracker.update(0, path_idx)?;
492                out_paths.push(path.clone());
493            }
494        }
495    }
496
497    assert_eq!(out_paths.current_idx, out_paths.paths.len());
498
499    if expanded_from_single_directory(paths, out_paths.paths.as_slice()) {
500        if let [Some((_, i1)), Some((_, i2))] = out_paths.exts {
501            polars_bail!(
502                InvalidOperation: r#"directory contained paths with different file extensions: \
503                first path: {}, second path: {}. Please use a glob pattern to explicitly specify \
504                which files to read (e.g. "dir/**/*", "dir/**/*.parquet")"#,
505                &out_paths.paths[i1].to_string_lossy(), &out_paths.paths[i2].to_string_lossy()
506            )
507        }
508    }
509
510    Ok((out_paths.paths.into(), hive_idx_tracker.idx))
511}
512
513/// Ignores errors from `std::fs::create_dir_all` if the directory exists.
514#[cfg(feature = "file_cache")]
515pub(crate) fn ensure_directory_init(path: &Path) -> std::io::Result<()> {
516    let result = std::fs::create_dir_all(path);
517
518    if path.is_dir() { Ok(()) } else { result }
519}
520
521#[cfg(test)]
522mod tests {
523    use std::path::PathBuf;
524
525    use super::resolve_homedir;
526
527    #[cfg(not(target_os = "windows"))]
528    #[test]
529    fn test_resolve_homedir() {
530        let paths: Vec<PathBuf> = vec![
531            "~/dir1/dir2/test.csv".into(),
532            "/abs/path/test.csv".into(),
533            "rel/path/test.csv".into(),
534            "/".into(),
535            "~".into(),
536        ];
537
538        let resolved: Vec<PathBuf> = paths.iter().map(|x| resolve_homedir(x)).collect();
539
540        assert_eq!(resolved[0].file_name(), paths[0].file_name());
541        assert!(resolved[0].is_absolute());
542        assert_eq!(resolved[1], paths[1]);
543        assert_eq!(resolved[2], paths[2]);
544        assert_eq!(resolved[3], paths[3]);
545        assert!(resolved[4].is_absolute());
546    }
547
548    #[cfg(target_os = "windows")]
549    #[test]
550    fn test_resolve_homedir_windows() {
551        let paths: Vec<PathBuf> = vec![
552            r#"c:\Users\user1\test.csv"#.into(),
553            r#"~\user1\test.csv"#.into(),
554            "~".into(),
555        ];
556
557        let resolved: Vec<PathBuf> = paths.iter().map(|x| resolve_homedir(x)).collect();
558
559        assert_eq!(resolved[0], paths[0]);
560        assert_eq!(resolved[1].file_name(), paths[1].file_name());
561        assert!(resolved[1].is_absolute());
562        assert!(resolved[2].is_absolute());
563    }
564
565    #[test]
566    fn test_http_path_with_query_parameters_is_not_expanded_as_glob() {
567        // Don't confuse HTTP URL's with query parameters for globs.
568        // See https://github.com/pola-rs/polars/pull/17774
569        use std::path::PathBuf;
570
571        use super::expand_paths;
572
573        let path = "https://pola.rs/test.csv?token=bear";
574        let paths = &[PathBuf::from(path)];
575        let out = expand_paths(paths, true, None).unwrap();
576        assert_eq!(out.as_ref(), paths);
577    }
578}