Skip to main content

polars_io/path_utils/
mod.rs

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