1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use bytes::Buf;
use bytes::Bytes;
use super::operator_functions::*;
use crate::raw::*;
use crate::*;
/// BlockingOperator is the entry for all public blocking APIs.
///
/// Read [`concepts`][docs::concepts] for know more about [`Operator`].
///
/// # Examples
///
/// ## Init backends
///
/// Read more backend init examples in [`services`]
///
/// ```rust,no_run
/// # use anyhow::Result;
/// use opendal::services::Fs;
/// use opendal::BlockingOperator;
/// use opendal::Operator;
///
/// fn main() -> Result<()> {
/// // Create fs backend builder.
/// let mut builder = Fs::default();
/// // Set the root for fs, all operations will happen under this root.
/// //
/// // NOTE: the root must be absolute path.
/// builder.root("/tmp");
///
/// // Build an `BlockingOperator` to start operating the storage.
/// let _: BlockingOperator = Operator::new(builder)?.finish().blocking();
///
/// Ok(())
/// }
/// ```
///
/// ## Init backends with blocking layer
///
/// Some services like s3, gcs doesn't have native blocking supports, we can use [`layers::BlockingLayer`]
/// to wrap the async operator to make it blocking.
#[cfg_attr(feature = "layers-blocking", doc = "```rust")]
#[cfg_attr(not(feature = "layers-blocking"), doc = "```ignore")]
/// # use anyhow::Result;
/// use opendal::layers::BlockingLayer;
/// use opendal::services::S3;
/// use opendal::BlockingOperator;
/// use opendal::Operator;
///
/// async fn test() -> Result<()> {
/// // Create fs backend builder.
/// let mut builder = S3::default();
/// builder.bucket("test");
/// builder.region("us-east-1");
///
/// // Build an `BlockingOperator` with blocking layer to start operating the storage.
/// let _: BlockingOperator = Operator::new(builder)?
/// .layer(BlockingLayer::create()?)
/// .finish()
/// .blocking();
///
/// Ok(())
/// }
/// ```
#[derive(Clone, Debug)]
pub struct BlockingOperator {
accessor: Accessor,
limit: usize,
}
impl BlockingOperator {
pub(super) fn inner(&self) -> &Accessor {
&self.accessor
}
/// create a new blocking operator from inner accessor.
///
/// # Note
/// default batch limit is 1000.
pub(crate) fn from_inner(accessor: Accessor) -> Self {
let limit = accessor
.info()
.full_capability()
.batch_max_operations
.unwrap_or(1000);
Self { accessor, limit }
}
/// Get current operator's limit
pub fn limit(&self) -> usize {
self.limit
}
/// Specify the batch limit.
///
/// Default: 1000
pub fn with_limit(&self, limit: usize) -> Self {
let mut op = self.clone();
op.limit = limit;
op
}
/// Get information of underlying accessor.
///
/// # Examples
///
/// ```
/// # use std::sync::Arc;
/// # use anyhow::Result;
/// use opendal::BlockingOperator;
///
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let info = op.info();
/// # Ok(())
/// # }
/// ```
pub fn info(&self) -> OperatorInfo {
OperatorInfo::new(self.accessor.info())
}
}
/// # Operator blocking API.
impl BlockingOperator {
/// Get given path's metadata.
///
/// # Notes
///
/// For fetch metadata of entries returned by [`Lister`], it's better to use [`list_with`] and
/// [`lister_with`] with `metakey` query like `Metakey::ContentLength | Metakey::LastModified`
/// so that we can avoid extra requests.
///
/// # Behavior
///
/// ## Services that support `create_dir`
///
/// `test` and `test/` may vary in some services such as S3. However, on a local file system,
/// they're identical. Therefore, the behavior of `stat("test")` and `stat("test/")` might differ
/// in certain edge cases. Always use `stat("test/")` when you need to access a directory if possible.
///
/// Here are the behavior list:
///
/// | Case | Path | Result |
/// |------------------------|-----------------|--------------------------------------------|
/// | stat existing dir | `abc/` | Metadata with dir mode |
/// | stat existing file | `abc/def_file` | Metadata with file mode |
/// | stat dir without `/` | `abc/def_dir` | Error `NotFound` or metadata with dir mode |
/// | stat file with `/` | `abc/def_file/` | Error `NotFound` |
/// | stat not existing path | `xyz` | Error `NotFound` |
///
/// Refer to [RFC: List Prefix][crate::docs::rfcs::rfc_3243_list_prefix] for more details.
///
/// ## Services that not support `create_dir`
///
/// For services that not support `create_dir`, `stat("test/")` will return `NotFound` even
/// when `test/abc` exists since the service won't have the concept of dir. There is nothing
/// we can do about this.
///
/// # Examples
///
/// ## Check if file exists
///
/// ```
/// # use anyhow::Result;
/// # use futures::io;
/// # use opendal::BlockingOperator;
/// use opendal::ErrorKind;
/// #
/// # fn test(op: BlockingOperator) -> Result<()> {
/// if let Err(e) = op.stat("test") {
/// if e.kind() == ErrorKind::NotFound {
/// println!("file not exist")
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub fn stat(&self, path: &str) -> Result<Metadata> {
self.stat_with(path).call()
}
/// Get given path's metadata with extra options.
///
/// # Notes
///
/// For fetch metadata of entries returned by [`Lister`], it's better to use [`list_with`] and
/// [`lister_with`] with `metakey` query like `Metakey::ContentLength | Metakey::LastModified`
/// so that we can avoid extra requests.
///
/// # Behavior
///
/// ## Services that support `create_dir`
///
/// `test` and `test/` may vary in some services such as S3. However, on a local file system,
/// they're identical. Therefore, the behavior of `stat("test")` and `stat("test/")` might differ
/// in certain edge cases. Always use `stat("test/")` when you need to access a directory if possible.
///
/// Here are the behavior list:
///
/// | Case | Path | Result |
/// |------------------------|-----------------|--------------------------------------------|
/// | stat existing dir | `abc/` | Metadata with dir mode |
/// | stat existing file | `abc/def_file` | Metadata with file mode |
/// | stat dir without `/` | `abc/def_dir` | Error `NotFound` or metadata with dir mode |
/// | stat file with `/` | `abc/def_file/` | Error `NotFound` |
/// | stat not existing path | `xyz` | Error `NotFound` |
///
/// Refer to [RFC: List Prefix][crate::docs::rfcs::rfc_3243_list_prefix] for more details.
///
/// ## Services that not support `create_dir`
///
/// For services that not support `create_dir`, `stat("test/")` will return `NotFound` even
/// when `test/abc` exists since the service won't have the concept of dir. There is nothing
/// we can do about this.
///
/// # Examples
///
/// ## Get metadata while `ETag` matches
///
/// `stat_with` will
///
/// - return `Ok(metadata)` if `ETag` matches
/// - return `Err(error)` and `error.kind() == ErrorKind::ConditionNotMatch` if file exists but
/// `ETag` mismatch
/// - return `Err(err)` if other errors occur, for example, `NotFound`.
///
/// ```
/// # use anyhow::Result;
/// # use opendal::BlockingOperator;
/// use opendal::ErrorKind;
/// #
/// # fn test(op: BlockingOperator) -> Result<()> {
/// if let Err(e) = op.stat_with("test").if_match("<etag>").call() {
/// if e.kind() == ErrorKind::ConditionNotMatch {
/// println!("file exists, but etag mismatch")
/// }
/// if e.kind() == ErrorKind::NotFound {
/// println!("file not exist")
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub fn stat_with(&self, path: &str) -> FunctionStat {
let path = normalize_path(path);
FunctionStat(OperatorFunction::new(
self.inner().clone(),
path,
OpStat::default(),
|inner, path, args| {
let rp = inner.blocking_stat(&path, args)?;
let meta = rp.into_metadata();
Ok(meta)
},
))
}
/// Check if this path exists or not.
///
/// # Example
///
/// ```no_run
/// use anyhow::Result;
/// use opendal::BlockingOperator;
/// fn test(op: BlockingOperator) -> Result<()> {
/// let _ = op.is_exist("test")?;
///
/// Ok(())
/// }
/// ```
pub fn is_exist(&self, path: &str) -> Result<bool> {
let r = self.stat(path);
match r {
Ok(_) => Ok(true),
Err(err) => match err.kind() {
ErrorKind::NotFound => Ok(false),
_ => Err(err),
},
}
}
/// Create a dir at given path.
///
/// # Notes
///
/// To indicate that a path is a directory, it is compulsory to include
/// a trailing / in the path. Failure to do so may result in
/// `NotADirectory` error being returned by OpenDAL.
///
/// # Behavior
///
/// - Create on existing dir will succeed.
/// - Create dir is always recursive, works like `mkdir -p`
///
/// # Examples
///
/// ```no_run
/// # use opendal::Result;
/// # use opendal::BlockingOperator;
/// # use futures::TryStreamExt;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// op.create_dir("path/to/dir/")?;
/// # Ok(())
/// # }
/// ```
pub fn create_dir(&self, path: &str) -> Result<()> {
let path = normalize_path(path);
if !validate_path(&path, EntryMode::DIR) {
return Err(Error::new(
ErrorKind::NotADirectory,
"the path trying to create should end with `/`",
)
.with_operation("create_dir")
.with_context("service", self.inner().info().scheme())
.with_context("path", &path));
}
self.inner()
.blocking_create_dir(&path, OpCreateDir::new())?;
Ok(())
}
/// Read the whole path into a bytes.
///
/// This function will allocate a new bytes internally. For more precise memory control or
/// reading data lazily, please use [`BlockingOperator::reader`]
///
/// # Examples
///
/// ```no_run
/// # use opendal::Result;
/// # use opendal::BlockingOperator;
/// #
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let bs = op.read("path/to/file")?;
/// # Ok(())
/// # }
/// ```
pub fn read(&self, path: &str) -> Result<Buffer> {
self.read_with(path).call()
}
/// Read the whole path into a bytes with extra options.
///
/// This function will allocate a new bytes internally. For more precise memory control or
/// reading data lazily, please use [`BlockingOperator::reader`]
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let bs = op.read_with("path/to/file").range(0..10).call()?;
/// # Ok(())
/// # }
/// ```
pub fn read_with(&self, path: &str) -> FunctionRead {
let path = normalize_path(path);
FunctionRead(OperatorFunction::new(
self.inner().clone(),
path,
(OpRead::default(), BytesRange::default()),
|inner, path, (args, range)| {
if !validate_path(&path, EntryMode::FILE) {
return Err(
Error::new(ErrorKind::IsADirectory, "read path is a directory")
.with_operation("BlockingOperator::read_with")
.with_context("service", inner.info().scheme().into_static())
.with_context("path", &path),
);
}
let r = BlockingReader::create(inner, &path, args)?;
let buf = r.read(range.to_range())?;
Ok(buf)
},
))
}
/// Create a new reader which can read the whole path.
///
/// # Examples
///
/// ```no_run
/// # use opendal::Result;
/// # use opendal::BlockingOperator;
/// # use futures::TryStreamExt;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let r = op.reader("path/to/file")?;
/// # Ok(())
/// # }
/// ```
pub fn reader(&self, path: &str) -> Result<BlockingReader> {
self.reader_with(path).call()
}
/// Create a new reader with extra options
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let r = op
/// .reader_with("path/to/file")
/// .version("version_id")
/// .call()?;
/// # Ok(())
/// # }
/// ```
pub fn reader_with(&self, path: &str) -> FunctionReader {
let path = normalize_path(path);
FunctionReader(OperatorFunction::new(
self.inner().clone(),
path,
OpRead::default(),
|inner, path, args| {
if !validate_path(&path, EntryMode::FILE) {
return Err(
Error::new(ErrorKind::IsADirectory, "reader path is a directory")
.with_operation("BlockingOperator::reader_with")
.with_context("service", inner.info().scheme().into_static())
.with_context("path", &path),
);
}
BlockingReader::create(inner.clone(), &path, args)
},
))
}
/// Write bytes into given path.
///
/// # Notes
///
/// - Write will make sure all bytes has been written, or an error will be returned.
///
/// # Examples
///
/// ```no_run
/// # use opendal::Result;
/// # use opendal::BlockingOperator;
/// # use futures::StreamExt;
/// # use futures::SinkExt;
/// use bytes::Bytes;
///
/// # fn test(op: BlockingOperator) -> Result<()> {
/// op.write("path/to/file", vec![0; 4096])?;
/// # Ok(())
/// # }
/// ```
pub fn write(&self, path: &str, bs: impl Into<Bytes>) -> Result<()> {
self.write_with(path, bs).call()
}
/// Copy a file from `from` to `to`.
///
/// # Notes
///
/// - `from` and `to` must be a file.
/// - `to` will be overwritten if it exists.
/// - If `from` and `to` are the same, nothing will happen.
/// - `copy` is idempotent. For same `from` and `to` input, the result will be the same.
///
/// # Examples
///
/// ```
/// # use opendal::Result;
/// # use opendal::BlockingOperator;
///
/// # fn test(op: BlockingOperator) -> Result<()> {
/// op.copy("path/to/file", "path/to/file2")?;
/// # Ok(())
/// # }
/// ```
pub fn copy(&self, from: &str, to: &str) -> Result<()> {
let from = normalize_path(from);
if !validate_path(&from, EntryMode::FILE) {
return Err(
Error::new(ErrorKind::IsADirectory, "from path is a directory")
.with_operation("BlockingOperator::copy")
.with_context("service", self.info().scheme())
.with_context("from", from),
);
}
let to = normalize_path(to);
if !validate_path(&to, EntryMode::FILE) {
return Err(
Error::new(ErrorKind::IsADirectory, "to path is a directory")
.with_operation("BlockingOperator::copy")
.with_context("service", self.info().scheme())
.with_context("to", to),
);
}
if from == to {
return Err(
Error::new(ErrorKind::IsSameFile, "from and to paths are same")
.with_operation("BlockingOperator::copy")
.with_context("service", self.info().scheme())
.with_context("from", from)
.with_context("to", to),
);
}
self.inner().blocking_copy(&from, &to, OpCopy::new())?;
Ok(())
}
/// Rename a file from `from` to `to`.
///
/// # Notes
///
/// - `from` and `to` must be a file.
/// - `to` will be overwritten if it exists.
/// - If `from` and `to` are the same, a `IsSameFile` error will occur.
///
/// # Examples
///
/// ```
/// # use opendal::Result;
/// # use opendal::BlockingOperator;
///
/// # fn test(op: BlockingOperator) -> Result<()> {
/// op.rename("path/to/file", "path/to/file2")?;
/// # Ok(())
/// # }
/// ```
pub fn rename(&self, from: &str, to: &str) -> Result<()> {
let from = normalize_path(from);
if !validate_path(&from, EntryMode::FILE) {
return Err(
Error::new(ErrorKind::IsADirectory, "from path is a directory")
.with_operation("BlockingOperator::move")
.with_context("service", self.info().scheme())
.with_context("from", from),
);
}
let to = normalize_path(to);
if !validate_path(&to, EntryMode::FILE) {
return Err(
Error::new(ErrorKind::IsADirectory, "to path is a directory")
.with_operation("BlockingOperator::move")
.with_context("service", self.info().scheme())
.with_context("to", to),
);
}
if from == to {
return Err(
Error::new(ErrorKind::IsSameFile, "from and to paths are same")
.with_operation("BlockingOperator::move")
.with_context("service", self.info().scheme())
.with_context("from", from)
.with_context("to", to),
);
}
self.inner().blocking_rename(&from, &to, OpRename::new())?;
Ok(())
}
/// Write data with option described in OpenDAL [RFC-0661][`crate::docs::rfcs::rfc_0661_path_in_accessor`]
///
/// # Notes
///
/// - Write will make sure all bytes has been written, or an error will be returned.
///
/// # Examples
///
/// ```no_run
/// # use opendal::Result;
/// # use opendal::BlockingOperator;
/// use bytes::Bytes;
///
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let bs = b"hello, world!".to_vec();
/// let _ = op
/// .write_with("hello.txt", bs)
/// .content_type("text/plain")
/// .call()?;
/// # Ok(())
/// # }
/// ```
pub fn write_with(&self, path: &str, bs: impl Into<Bytes>) -> FunctionWrite {
let path = normalize_path(path);
let bs = bs.into();
FunctionWrite(OperatorFunction::new(
self.inner().clone(),
path,
(OpWrite::default(), bs),
|inner, path, (args, mut bs)| {
if !validate_path(&path, EntryMode::FILE) {
return Err(
Error::new(ErrorKind::IsADirectory, "write path is a directory")
.with_operation("BlockingOperator::write_with")
.with_context("service", inner.info().scheme().into_static())
.with_context("path", &path),
);
}
let (_, mut w) = inner.blocking_write(&path, args)?;
while !bs.is_empty() {
let n = w.write(bs.clone().into())?;
bs.advance(n);
}
w.close()?;
Ok(())
},
))
}
/// Write multiple bytes into given path.
///
/// # Notes
///
/// - Write will make sure all bytes has been written, or an error will be returned.
///
/// # Examples
///
/// ```no_run
/// # use opendal::Result;
/// # use opendal::BlockingOperator;
/// # use futures::StreamExt;
/// # use futures::SinkExt;
/// use bytes::Bytes;
///
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut w = op.writer("path/to/file")?;
/// w.write(vec![0; 4096])?;
/// w.write(vec![1; 4096])?;
/// w.close()?;
/// # Ok(())
/// # }
/// ```
pub fn writer(&self, path: &str) -> Result<BlockingWriter> {
self.writer_with(path).call()
}
/// Create a new reader with extra options
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut w = op.writer_with("path/to/file").call()?;
/// w.write(vec![0; 4096])?;
/// w.write(vec![1; 4096])?;
/// w.close()?;
/// # Ok(())
/// # }
/// ```
pub fn writer_with(&self, path: &str) -> FunctionWriter {
let path = normalize_path(path);
FunctionWriter(OperatorFunction::new(
self.inner().clone(),
path,
OpWrite::default(),
|inner, path, args| {
let path = normalize_path(&path);
if !validate_path(&path, EntryMode::FILE) {
return Err(
Error::new(ErrorKind::IsADirectory, "write path is a directory")
.with_operation("BlockingOperator::writer_with")
.with_context("service", inner.info().scheme().into_static())
.with_context("path", &path),
);
}
BlockingWriter::create(inner.clone(), &path, args)
},
))
}
/// Delete given path.
///
/// # Notes
///
/// - Delete not existing error won't return errors.
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// # use futures::io;
/// # use opendal::BlockingOperator;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// op.delete("path/to/file")?;
/// # Ok(())
/// # }
/// ```
pub fn delete(&self, path: &str) -> Result<()> {
self.delete_with(path).call()?;
Ok(())
}
/// Delete given path with options.
///
/// # Notes
///
/// - Delete not existing error won't return errors.
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// # use futures::io;
/// # use opendal::BlockingOperator;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let _ = op
/// .delete_with("path/to/file")
/// .version("example_version")
/// .call()?;
/// # Ok(())
/// # }
/// ```
pub fn delete_with(&self, path: &str) -> FunctionDelete {
let path = normalize_path(path);
FunctionDelete(OperatorFunction::new(
self.inner().clone(),
path,
OpDelete::new(),
|inner, path, args| {
let _ = inner.blocking_delete(&path, args)?;
Ok(())
},
))
}
/// remove will remove files via the given paths.
///
/// remove_via will remove files via the given vector iterators.
///
/// # Notes
///
/// We don't support batch delete now.
///
/// # Examples
///
/// ```
/// # use anyhow::Result;
/// # use futures::io;
/// # use opendal::BlockingOperator;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let stream = vec!["abc".to_string(), "def".to_string()].into_iter();
/// op.remove_via(stream)?;
/// # Ok(())
/// # }
/// ```
pub fn remove_via(&self, input: impl Iterator<Item = String>) -> Result<()> {
for path in input {
self.delete(&path)?;
}
Ok(())
}
/// # Notes
///
/// We don't support batch delete now.
///
/// # Examples
///
/// ```
/// # use anyhow::Result;
/// # use futures::io;
/// # use opendal::BlockingOperator;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// op.remove(vec!["abc".to_string(), "def".to_string()])?;
/// # Ok(())
/// # }
/// ```
pub fn remove(&self, paths: Vec<String>) -> Result<()> {
self.remove_via(paths.into_iter())?;
Ok(())
}
/// Remove the path and all nested dirs and files recursively.
///
/// # Notes
///
/// We don't support batch delete now.
///
/// # Examples
///
/// ```
/// # use anyhow::Result;
/// # use futures::io;
/// # use opendal::BlockingOperator;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// op.remove_all("path/to/dir")?;
/// # Ok(())
/// # }
/// ```
pub fn remove_all(&self, path: &str) -> Result<()> {
let meta = match self.stat(path) {
Ok(metadata) => metadata,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e),
};
if meta.mode() != EntryMode::DIR {
return self.delete(path);
}
let obs = self.lister_with(path).recursive(true).call()?;
for v in obs {
match v {
Ok(entry) => {
self.inner()
.blocking_delete(entry.path(), OpDelete::new())?;
}
Err(e) => return Err(e),
}
}
// Remove the directory itself.
self.delete(path)?;
Ok(())
}
/// List entries that starts with given `path` in parent dir.
///
/// # Notes
///
/// ## Recursively List
///
/// This function only read the children of the given directory. To read
/// all entries recursively, use `BlockingOperator::list_with("path").recursive(true)`
/// instead.
///
/// ## Streaming List
///
/// This function will read all entries in the given directory. It could
/// take very long time and consume a lot of memory if the directory
/// contains a lot of entries.
///
/// In order to avoid this, you can use [`BlockingOperator::lister`] to list entries in
/// a streaming way.
///
/// ## Reuse Metadata
///
/// The only metadata that is guaranteed to be available is the `Mode`.
/// For fetching more metadata, please use [`BlockingOperator::list_with`] and `metakey`.
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut entries = op.list("path/to/dir/")?;
/// for entry in entries {
/// match entry.metadata().mode() {
/// EntryMode::FILE => {
/// println!("Handling file")
/// }
/// EntryMode::DIR => {
/// println!("Handling dir {}", entry.path())
/// }
/// EntryMode::Unknown => continue,
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub fn list(&self, path: &str) -> Result<Vec<Entry>> {
self.list_with(path).call()
}
/// List entries that starts with given `path` in parent dir. with options.
///
/// # Notes
///
/// ## Streaming List
///
/// This function will read all entries in the given directory. It could
/// take very long time and consume a lot of memory if the directory
/// contains a lot of entries.
///
/// In order to avoid this, you can use [`BlockingOperator::lister`] to list entries in
/// a streaming way.
///
/// ## Reuse Metadata
///
/// The only metadata that is guaranteed to be available is the `Mode`.
/// For fetching more metadata, please specify the `metakey`.
///
/// # Examples
///
/// ## List entries with prefix
///
/// This function can also be used to list entries in recursive way.
///
/// ```no_run
/// # use anyhow::Result;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut entries = op.list_with("prefix/").recursive(true).call()?;
/// for entry in entries {
/// match entry.metadata().mode() {
/// EntryMode::FILE => {
/// println!("Handling file")
/// }
/// EntryMode::DIR => {
/// println!("Handling dir like start a new list via meta.path()")
/// }
/// EntryMode::Unknown => continue,
/// }
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## List entries with metakey for more metadata
///
/// ```no_run
/// # use anyhow::Result;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut entries = op
/// .list_with("dir/")
/// .metakey(Metakey::ContentLength | Metakey::LastModified)
/// .call()?;
/// for entry in entries {
/// let meta = entry.metadata();
/// match meta.mode() {
/// EntryMode::FILE => {
/// println!(
/// "Handling file {} with size {}",
/// entry.path(),
/// meta.content_length()
/// )
/// }
/// EntryMode::DIR => {
/// println!("Handling dir {}", entry.path())
/// }
/// EntryMode::Unknown => continue,
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub fn list_with(&self, path: &str) -> FunctionList {
let path = normalize_path(path);
FunctionList(OperatorFunction::new(
self.inner().clone(),
path,
OpList::default(),
|inner, path, args| {
let lister = BlockingLister::create(inner, &path, args)?;
lister.collect()
},
))
}
/// List entries that starts with given `path` in parent dir.
///
/// This function will create a new [`BlockingLister`] to list entries. Users can stop listing
/// via dropping this [`Lister`].
///
/// # Notes
///
/// ## Recursively List
///
/// This function only read the children of the given directory. To read
/// all entries recursively, use [`BlockingOperator::lister_with`] and `delimiter("")`
/// instead.
///
/// ## Metadata
///
/// The only metadata that is guaranteed to be available is the `Mode`.
/// For fetching more metadata, please use [`BlockingOperator::lister_with`] and `metakey`.
///
/// # Examples
///
/// ```no_run
/// # use anyhow::Result;
/// # use futures::io;
/// use futures::TryStreamExt;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut ds = op.lister("path/to/dir/")?;
/// for de in ds {
/// let de = de?;
/// match de.metadata().mode() {
/// EntryMode::FILE => {
/// println!("Handling file")
/// }
/// EntryMode::DIR => {
/// println!("Handling dir like start a new list via meta.path()")
/// }
/// EntryMode::Unknown => continue,
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub fn lister(&self, path: &str) -> Result<BlockingLister> {
self.lister_with(path).call()
}
/// List entries within a given directory as an iterator with options.
///
/// This function will create a new handle to list entries.
///
/// An error will be returned if given path doesn't end with `/`.
///
/// # Examples
///
/// ## List current dir
///
/// ```no_run
/// # use anyhow::Result;
/// # use futures::io;
/// use futures::TryStreamExt;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut ds = op
/// .lister_with("path/to/dir/")
/// .limit(10)
/// .start_after("start")
/// .call()?;
/// for entry in ds {
/// let entry = entry?;
/// match entry.metadata().mode() {
/// EntryMode::FILE => {
/// println!("Handling file {}", entry.path())
/// }
/// EntryMode::DIR => {
/// println!("Handling dir {}", entry.path())
/// }
/// EntryMode::Unknown => continue,
/// }
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## List all files recursively
///
/// ```no_run
/// # use anyhow::Result;
/// # use futures::io;
/// use futures::TryStreamExt;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut ds = op.lister_with("path/to/dir/").recursive(true).call()?;
/// for entry in ds {
/// let entry = entry?;
/// match entry.metadata().mode() {
/// EntryMode::FILE => {
/// println!("Handling file {}", entry.path())
/// }
/// EntryMode::DIR => {
/// println!("Handling dir {}", entry.path())
/// }
/// EntryMode::Unknown => continue,
/// }
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## List files with required metadata
///
/// ```no_run
/// # use anyhow::Result;
/// # use futures::io;
/// use futures::TryStreamExt;
/// use opendal::BlockingOperator;
/// use opendal::EntryMode;
/// use opendal::Metakey;
/// # fn test(op: BlockingOperator) -> Result<()> {
/// let mut ds = op
/// .lister_with("path/to/dir/")
/// .metakey(Metakey::ContentLength | Metakey::LastModified)
/// .call()?;
/// for entry in ds {
/// let entry = entry?;
/// let meta = entry.metadata();
/// match meta.mode() {
/// EntryMode::FILE => {
/// println!(
/// "Handling file {} with size {}",
/// entry.path(),
/// meta.content_length()
/// )
/// }
/// EntryMode::DIR => {
/// println!("Handling dir {}", entry.path())
/// }
/// EntryMode::Unknown => continue,
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub fn lister_with(&self, path: &str) -> FunctionLister {
let path = normalize_path(path);
FunctionLister(OperatorFunction::new(
self.inner().clone(),
path,
OpList::default(),
|inner, path, args| BlockingLister::create(inner, &path, args),
))
}
}
impl From<BlockingOperator> for Operator {
fn from(v: BlockingOperator) -> Self {
Operator::from_inner(v.accessor).with_limit(v.limit)
}
}