1use std::borrow::Cow;
2use std::collections::VecDeque;
3use std::path::{Path, PathBuf};
4use std::sync::{Arc, LazyLock};
5
6use polars_buffer::Buffer;
7use polars_core::config;
8use polars_core::error::{PolarsResult, polars_bail, to_compute_err};
9use polars_utils::aliases::PlHashMap;
10use polars_utils::pl_path::{CloudScheme, PlRefPath};
11use polars_utils::pl_str::PlSmallStr;
12
13#[cfg(feature = "cloud")]
14mod hugging_face;
15
16use crate::cloud::CloudOptions;
17
18#[allow(clippy::bind_instead_of_map)]
19pub static POLARS_TEMP_DIR_BASE_PATH: LazyLock<Box<Path>> = LazyLock::new(|| {
20 (|| {
21 let verbose = config::verbose();
22
23 let path = if let Ok(v) = std::env::var("POLARS_TEMP_DIR").map(PathBuf::from) {
24 if verbose {
25 eprintln!("init_temp_dir: sourced from POLARS_TEMP_DIR")
26 }
27 v
28 } else if cfg!(target_family = "unix") {
29 let id = std::env::var("USER")
30 .inspect(|_| {
31 if verbose {
32 eprintln!("init_temp_dir: sourced $USER")
33 }
34 })
35 .or_else(|_e| {
36 #[cfg(feature = "file_cache")]
39 {
40 std::env::var("HOME")
41 .inspect(|_| {
42 if verbose {
43 eprintln!("init_temp_dir: sourced $HOME")
44 }
45 })
46 .map(|x| blake3::hash(x.as_bytes()).to_hex()[..32].to_string())
47 }
48 #[cfg(not(feature = "file_cache"))]
49 {
50 Err(_e)
51 }
52 });
53
54 if let Ok(v) = id {
55 std::env::temp_dir().join(format!("polars-{v}/"))
56 } else {
57 return Err(std::io::Error::other(
58 "could not load $USER or $HOME environment variables",
59 ));
60 }
61 } else if cfg!(target_family = "windows") {
62 std::env::temp_dir().join("polars/")
66 } else {
67 std::env::temp_dir().join("polars/")
68 }
69 .into_boxed_path();
70
71 let perm_result = create_dir_owner_only(path.as_ref());
72
73 if std::env::var("POLARS_ALLOW_UNSECURED_TEMP_DIR").as_deref() != Ok("1") {
74 perm_result?;
75 }
76
77 std::io::Result::Ok(path)
78 })()
79 .map_err(|e| {
80 std::io::Error::new(
81 e.kind(),
82 format!(
83 "error initializing temporary directory: {e} \
84 consider explicitly setting POLARS_TEMP_DIR"
85 ),
86 )
87 })
88 .unwrap()
89});
90
91pub fn create_dir_owner_only(path: &Path) -> std::io::Result<()> {
93 std::fs::create_dir_all(path)?;
94
95 #[cfg(target_family = "unix")]
96 {
97 use std::os::unix::fs::PermissionsExt;
98
99 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))?;
100 let perms = std::fs::metadata(path)?.permissions();
101
102 if (perms.mode() % 0o1000) != 0o700 {
103 return Err(std::io::Error::other(format!(
104 "error setting directory permissions: permission mismatch: {perms:?} (path = {path:?})"
105 )));
106 }
107 }
108
109 Ok(())
110}
111
112pub fn resolve_homedir<'a, S: AsRef<Path> + ?Sized>(path: &'a S) -> Cow<'a, Path> {
114 return inner(path.as_ref());
115
116 fn inner(path: &Path) -> Cow<'_, Path> {
117 if path.starts_with("~") {
118 #[cfg(not(target_family = "wasm"))]
120 if let Some(homedir) = home::home_dir() {
121 return Cow::Owned(homedir.join(path.strip_prefix("~").unwrap()));
122 }
123 }
124
125 Cow::Borrowed(path)
126 }
127}
128
129fn has_glob(path: &[u8]) -> bool {
130 return get_glob_start_idx(path).is_some();
131
132 fn get_glob_start_idx(path: &[u8]) -> Option<usize> {
134 memchr::memchr3(b'*', b'?', b'[', path)
135 }
136}
137
138fn is_file_uri_with_escape(path: &PlRefPath) -> bool {
140 path.scheme().is_some_and(|s| s.is_file()) && path.strip_scheme().contains('%')
141}
142
143pub fn decode_file_uri_paths(paths: &[PlRefPath], glob: bool) -> Cow<'_, [PlRefPath]> {
158 if !paths.iter().any(is_file_uri_with_escape) {
160 return Cow::Borrowed(paths);
161 }
162
163 Cow::Owned(
164 paths
165 .iter()
166 .map(|path| {
167 if is_file_uri_with_escape(path)
168 && let Some(decoded) = decode_file_uri_path(path.strip_scheme(), glob)
169 {
170 PlRefPath::new(decoded)
171 } else {
172 path.clone()
175 }
176 })
177 .collect(),
178 )
179}
180
181fn decode_file_uri_path(path: &str, glob: bool) -> Option<String> {
185 let decoded = percent_encoding::percent_decode_str(path)
186 .decode_utf8()
187 .ok()?;
188 let path = strip_windows_drive_slash(&decoded);
189 Some(if glob {
190 glob::Pattern::escape(path)
191 } else {
192 path.to_owned()
193 })
194}
195
196fn strip_windows_drive_slash(path: &str) -> &str {
200 #[cfg(target_family = "windows")]
201 {
202 let b = path.as_bytes();
203 if b.len() >= 3 && b[0] == b'/' && b[1].is_ascii_alphabetic() && b[2] == b':' {
204 return &path[1..];
205 }
206 }
207 path
208}
209
210pub fn expanded_from_single_directory(paths: &[PlRefPath], expanded_paths: &[PlRefPath]) -> bool {
212 paths.len() == 1 && !has_glob(paths[0].strip_scheme().as_bytes())
214 && {
216 (
217 !paths[0].has_scheme() && paths[0].as_std_path().is_dir()
219 )
220 || (
221 expanded_paths.is_empty() || (paths[0] != expanded_paths[0])
224 )
225 }
226}
227
228pub async fn expand_paths(
230 paths: &[PlRefPath],
231 glob: bool,
232 hidden_file_prefix: &[PlSmallStr],
233 #[allow(unused_variables)] cloud_options: &mut Option<CloudOptions>,
234) -> PolarsResult<Buffer<PlRefPath>> {
235 expand_paths_hive(paths, glob, hidden_file_prefix, cloud_options, false)
236 .await
237 .map(|x| x.0)
238}
239
240pub type BytesPerSource = Option<Arc<[u64]>>;
245
246struct HiveIdxTracker<'a> {
247 idx: usize,
248 paths: &'a [PlRefPath],
249 check_directory_level: bool,
250}
251
252impl HiveIdxTracker<'_> {
253 fn update(&mut self, i: usize, path_idx: usize) -> PolarsResult<()> {
254 let check_directory_level = self.check_directory_level;
255 let paths = self.paths;
256
257 if check_directory_level
258 && ![usize::MAX, i].contains(&self.idx)
259 && (path_idx > 0 && paths[path_idx].parent() != paths[path_idx - 1].parent())
261 {
262 polars_bail!(
263 InvalidOperation:
264 "attempted to read from different directory levels with hive partitioning enabled: \
265 first path: {}, second path: {}",
266 &paths[path_idx - 1],
267 &paths[path_idx],
268 )
269 } else {
270 self.idx = std::cmp::min(self.idx, i);
271 Ok(())
272 }
273 }
274}
275
276#[cfg(feature = "cloud")]
277async fn expand_path_cloud(
278 path: PlRefPath,
279 cloud_options: Option<&CloudOptions>,
280 glob: bool,
281 first_path_has_scheme: bool,
282) -> PolarsResult<(usize, Vec<(PlRefPath, Option<u64>)>)> {
283 let format_path = |scheme: &str, bucket: &str, location: &str| {
284 if first_path_has_scheme {
285 format!("{scheme}://{bucket}/{location}")
286 } else {
287 format!("/{location}")
288 }
289 };
290
291 use polars_utils::io::_limit_path_len_io_err;
292
293 use crate::cloud::object_path_from_str;
294 let path_str = path.as_str();
295
296 let (cloud_location, store) =
297 crate::cloud::build_object_store(path.clone(), cloud_options, glob).await?;
298 let prefix = object_path_from_str(&cloud_location.prefix)?;
299
300 let out = if !path_str.ends_with("/") && (!glob || cloud_location.expansion.is_none()) && {
301 path.has_scheme() || path.as_std_path().is_file()
306 } {
307 (
308 0,
310 vec![(
311 PlRefPath::new(format_path(
312 cloud_location.scheme,
313 &cloud_location.bucket,
314 prefix.as_ref(),
315 )),
316 None,
317 )],
318 )
319 } else {
320 use futures::TryStreamExt;
321
322 if !path.has_scheme() {
323 path.as_std_path()
328 .metadata()
329 .map_err(|err| _limit_path_len_io_err(path.as_std_path(), err))?;
330 }
331
332 let cloud_location = &cloud_location;
333 let prefix_ref = &prefix;
334
335 let mut paths = store
336 .exec_with_rebuild_retry_on_err(|s| async move {
337 let out = s
338 .list(Some(prefix_ref))
339 .try_filter_map(|x| async move {
340 let out = (x.size > 0).then(|| {
342 (
343 PlRefPath::new({
344 format_path(
345 cloud_location.scheme,
346 &cloud_location.bucket,
347 x.location.as_ref(),
348 )
349 }),
350 Some(x.size),
351 )
352 });
353 Ok(out)
354 })
355 .try_collect::<Vec<_>>()
356 .await?;
357
358 Ok(out)
359 })
360 .await?;
361
362 let mut prefix = prefix.to_string();
365 if path_str.ends_with('/') && !prefix.ends_with('/') {
366 prefix.push('/')
367 };
368
369 paths.sort_unstable();
370
371 (
372 format_path(
373 cloud_location.scheme,
374 &cloud_location.bucket,
375 prefix.as_ref(),
376 )
377 .len(),
378 paths,
379 )
380 };
381
382 PolarsResult::Ok(out)
383}
384
385pub async fn expand_paths_hive(
389 paths: &[PlRefPath],
390 glob: bool,
391 hidden_file_prefix: &[PlSmallStr],
392 #[allow(unused_variables)] cloud_options: &mut Option<CloudOptions>,
393 check_directory_level: bool,
394) -> PolarsResult<(Buffer<PlRefPath>, usize, BytesPerSource)> {
395 let Some(first_path) = paths.first() else {
396 return Ok((vec![].into(), 0, None));
397 };
398
399 let first_path_has_scheme = first_path.has_scheme();
400
401 let is_hidden_file = move |path: &PlRefPath| {
402 path.file_name()
403 .and_then(|x| x.to_str())
404 .is_some_and(|file_name| {
405 hidden_file_prefix
406 .iter()
407 .any(|x| file_name.starts_with(x.as_str()))
408 })
409 };
410
411 let mut out_paths = OutPaths {
412 paths: vec![],
413 exts: [None, None],
414 is_hidden_file: &is_hidden_file,
415 };
416
417 let mut sizes_by_path: PlHashMap<PlRefPath, u64> = PlHashMap::default();
420
421 let mut hive_idx_tracker = HiveIdxTracker {
422 idx: usize::MAX,
423 paths,
424 check_directory_level,
425 };
426
427 if first_path_has_scheme || {
428 cfg!(not(target_family = "windows")) && polars_config::config().force_async()
429 } {
430 #[cfg(feature = "cloud")]
431 {
432 if first_path.scheme() == Some(CloudScheme::Hf) {
433 let (expand_start_idx, paths) = hugging_face::expand_paths_hf(
434 paths,
435 check_directory_level,
436 cloud_options,
437 glob,
438 )
439 .await?;
440
441 return Ok((paths.into(), expand_start_idx, None));
443 }
444
445 for (path_idx, path) in paths.iter().enumerate() {
446 use std::borrow::Cow;
447
448 let mut path = Cow::Borrowed(path);
449
450 if matches!(path.scheme(), Some(CloudScheme::Http | CloudScheme::Https)) {
451 let mut rewrite_aws = false;
452
453 #[cfg(feature = "aws")]
454 if let Some(p) = (|| {
455 use crate::cloud::CloudConfig;
456
457 let after_scheme = path.strip_scheme();
460
461 let bucket_end = after_scheme.find(".s3.")?;
462 let offset = bucket_end + 4;
463 let region_end = offset + after_scheme[offset..].find(".amazonaws.com/")?;
465
466 if after_scheme[..region_end].contains('/') || after_scheme.contains('?') {
468 return None;
469 }
470
471 let bucket = &after_scheme[..bucket_end];
472 let region = &after_scheme[bucket_end + 4..region_end];
473 let key = &after_scheme[region_end + 15..];
474
475 if let CloudConfig::Aws(configs) = cloud_options
476 .get_or_insert_default()
477 .config
478 .get_or_insert_with(|| CloudConfig::Aws(Vec::with_capacity(1)))
479 {
480 use object_store::aws::AmazonS3ConfigKey;
481
482 if !matches!(configs.last(), Some((AmazonS3ConfigKey::Region, _))) {
483 configs.push((AmazonS3ConfigKey::Region, region.into()))
484 }
485 }
486
487 Some(format!("s3://{bucket}/{key}"))
488 })() {
489 path = Cow::Owned(PlRefPath::new(p));
490 rewrite_aws = true;
491 }
492
493 if !rewrite_aws {
494 out_paths.push(path.into_owned());
495 hive_idx_tracker.update(0, path_idx)?;
496 continue;
497 }
498 }
499
500 let sort_start_idx = out_paths.paths.len();
501
502 if glob && has_glob(path.as_bytes()) {
503 hive_idx_tracker.update(0, path_idx)?;
504
505 let iter = crate::async_glob(path.into_owned(), cloud_options.as_ref()).await?;
506
507 for (url, size) in iter {
508 let p = if first_path_has_scheme {
511 PlRefPath::new(url)
512 } else {
513 PlRefPath::new(&url[7..])
514 };
515 sizes_by_path.insert(p.clone(), size);
516 out_paths.push(p);
517 }
518 } else {
519 let (expand_start_idx, paths) = expand_path_cloud(
520 path.into_owned(),
521 cloud_options.as_ref(),
522 glob,
523 first_path_has_scheme,
524 )
525 .await?;
526 for (p, size) in paths {
527 if let Some(size) = size {
528 sizes_by_path.insert(p.clone(), size);
529 }
530 out_paths.push(p);
531 }
532 hive_idx_tracker.update(expand_start_idx, path_idx)?;
533 };
534
535 if let Some(mut_slice) = out_paths.paths.get_mut(sort_start_idx..) {
536 <[PlRefPath]>::sort_unstable(mut_slice);
537 }
538 }
539 }
540 #[cfg(not(feature = "cloud"))]
541 panic!("Feature `cloud` must be enabled to use globbing patterns with cloud urls.")
542 } else {
543 let mut stack: VecDeque<Cow<'_, Path>> = VecDeque::new();
544 let mut paths_scratch: Vec<PathBuf> = vec![];
545
546 for (path_idx, path) in paths.iter().enumerate() {
547 stack.clear();
548 let sort_start_idx = out_paths.paths.len();
549
550 if path.as_std_path().is_dir() {
551 let i = path.as_str().len();
552
553 hive_idx_tracker.update(i, path_idx)?;
554
555 stack.push_back(Cow::Borrowed(path.as_std_path()));
556
557 while let Some(dir) = stack.pop_front() {
558 let mut last_err = Ok(());
559
560 paths_scratch.clear();
561 paths_scratch.extend(std::fs::read_dir(dir)?.map_while(|x| {
562 match x.map(|x| x.path()) {
563 Ok(v) => Some(v),
564 Err(e) => {
565 last_err = Err(e);
566 None
567 },
568 }
569 }));
570
571 last_err?;
572
573 for path in paths_scratch.drain(..) {
574 let md = path.metadata()?;
575
576 if md.is_dir() {
577 stack.push_back(Cow::Owned(path));
578 } else if md.len() > 0 {
579 let p = PlRefPath::try_from_path(&path)?;
580 sizes_by_path.insert(p.clone(), md.len());
581 out_paths.push(p);
582 }
583 }
584 }
585 } else if glob && has_glob(path.as_bytes()) {
586 hive_idx_tracker.update(0, path_idx)?;
587
588 let Ok(paths) = glob::glob(path.as_str()) else {
589 polars_bail!(ComputeError: "invalid glob pattern given")
590 };
591
592 for path in paths {
593 let path = path.map_err(to_compute_err)?;
594 let md = path.metadata()?;
595 if !md.is_dir() && md.len() > 0 {
596 let p = PlRefPath::try_from_path(&path)?;
597 sizes_by_path.insert(p.clone(), md.len());
598 out_paths.push(p);
599 }
600 }
601 } else {
602 hive_idx_tracker.update(0, path_idx)?;
603 out_paths.push(path.clone());
604 };
605
606 if let Some(mut_slice) = out_paths.paths.get_mut(sort_start_idx..) {
607 <[PlRefPath]>::sort_unstable(mut_slice);
608 }
609 }
610 }
611
612 if expanded_from_single_directory(paths, out_paths.paths.as_slice()) {
613 if let [Some((_, p1)), Some((_, p2))] = out_paths.exts {
614 polars_bail!(
615 InvalidOperation: "directory contained paths with different file extensions: \
616 first path: {}, second path: {}. Please use a glob pattern to explicitly specify \
617 which files to read (e.g. 'dir/**/*', 'dir/**/*.parquet')",
618 &p1, &p2
619 )
620 }
621 }
622
623 let bytes_per_source: BytesPerSource = out_paths
625 .paths
626 .iter()
627 .map(|p| sizes_by_path.get(p).copied())
628 .collect::<Option<Vec<u64>>>()
629 .map(Arc::from);
630
631 return Ok((
632 out_paths.paths.into(),
633 hive_idx_tracker.idx,
634 bytes_per_source,
635 ));
636
637 struct OutPaths<'a, F: Fn(&PlRefPath) -> bool> {
640 paths: Vec<PlRefPath>,
641 exts: [Option<(PlSmallStr, PlRefPath)>; 2],
642 is_hidden_file: &'a F,
643 }
644
645 impl<F> OutPaths<'_, F>
646 where
647 F: Fn(&PlRefPath) -> bool,
648 {
649 fn push(&mut self, value: PlRefPath) {
650 if (self.is_hidden_file)(&value) {
651 return;
652 }
653
654 let exts = &mut self.exts;
655 Self::update_ext_status(exts, &value);
656
657 self.paths.push(value)
658 }
659
660 fn update_ext_status(exts: &mut [Option<(PlSmallStr, PlRefPath)>; 2], value: &PlRefPath) {
661 let ext = value
662 .extension()
663 .map_or(PlSmallStr::EMPTY, PlSmallStr::from);
664
665 if exts[0].is_none() {
666 exts[0] = Some((ext, value.clone()));
667 } else if exts[1].is_none() && ext != exts[0].as_ref().unwrap().0 {
668 exts[1] = Some((ext, value.clone()));
669 }
670 }
671 }
672}
673
674#[cfg(feature = "file_cache")]
676pub(crate) fn ensure_directory_init(path: &Path) -> std::io::Result<()> {
677 let result = std::fs::create_dir_all(path);
678
679 if path.is_dir() { Ok(()) } else { result }
680}
681
682#[cfg(test)]
683mod tests {
684 use std::path::PathBuf;
685
686 use polars_core::runtime::ASYNC;
687 use polars_utils::pl_path::PlRefPath;
688
689 use super::resolve_homedir;
690
691 #[cfg(not(target_os = "windows"))]
692 #[test]
693 fn test_resolve_homedir() {
694 let paths: Vec<PathBuf> = vec![
695 "~/dir1/dir2/test.csv".into(),
696 "/abs/path/test.csv".into(),
697 "rel/path/test.csv".into(),
698 "/".into(),
699 "~".into(),
700 ];
701
702 let resolved: Vec<PathBuf> = paths
703 .iter()
704 .map(resolve_homedir)
705 .map(|x| x.into_owned())
706 .collect();
707
708 assert_eq!(resolved[0].file_name(), paths[0].file_name());
709 assert!(resolved[0].is_absolute());
710 assert_eq!(resolved[1], paths[1]);
711 assert_eq!(resolved[2], paths[2]);
712 assert_eq!(resolved[3], paths[3]);
713 assert!(resolved[4].is_absolute());
714 }
715
716 #[cfg(target_os = "windows")]
717 #[test]
718 fn test_resolve_homedir_windows() {
719 let paths: Vec<PathBuf> = vec![
720 r#"c:\Users\user1\test.csv"#.into(),
721 r#"~\user1\test.csv"#.into(),
722 "~".into(),
723 ];
724
725 let resolved: Vec<PathBuf> = paths
726 .iter()
727 .map(resolve_homedir)
728 .map(|x| x.into_owned())
729 .collect();
730
731 assert_eq!(resolved[0], paths[0]);
732 assert_eq!(resolved[1].file_name(), paths[1].file_name());
733 assert!(resolved[1].is_absolute());
734 assert!(resolved[2].is_absolute());
735 }
736
737 #[test]
738 fn test_http_path_with_query_parameters_is_not_expanded_as_glob() {
739 use super::expand_paths;
743
744 let path = "https://pola.rs/test.csv?token=bear";
745 let paths = &[PlRefPath::new(path)];
746 let out = ASYNC
747 .block_on(expand_paths(paths, true, &[], &mut None))
748 .unwrap();
749 assert_eq!(out.as_ref(), paths);
750 }
751}