tauri_plugin_fs/
desktop.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5use std::path::PathBuf;
6
7use tauri::{AppHandle, Runtime};
8
9use crate::{FilePath, OpenOptions};
10
11pub struct Fs<R: Runtime>(pub(crate) AppHandle<R>);
12
13fn path_or_err<P: Into<FilePath>>(p: P) -> std::io::Result<PathBuf> {
14    match p.into() {
15        FilePath::Path(p) => Ok(p),
16        FilePath::Url(u) if u.scheme() == "file" => u
17            .to_file_path()
18            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid file URL")),
19        FilePath::Url(_) => Err(std::io::Error::new(
20            std::io::ErrorKind::InvalidInput,
21            "cannot use a URL to load files on desktop and iOS",
22        )),
23    }
24}
25
26impl<R: Runtime> Fs<R> {
27    pub fn open<P: Into<FilePath>>(
28        &self,
29        path: P,
30        opts: OpenOptions,
31    ) -> std::io::Result<std::fs::File> {
32        let path = path_or_err(path)?;
33        std::fs::OpenOptions::from(opts).open(path)
34    }
35}