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
use crate::{OpenOptions, VFile, VMetadata, Vfs, VfsError, VfsResult};
use async_std::{fs, path::PathBuf};
use async_std::{path::Path, prelude::*};
use async_trait::async_trait;
use std::pin::Pin;

pub struct OsFs {
    root: PathBuf,
}

struct VOsMetadata {
    path: String,
    is_file: bool,
    len: u64,
}

impl OsFs {
    pub fn new(root: &str) -> Self {
        OsFs {
            root: PathBuf::from(root),
        }
    }

    // if root   => "/home"
    //    path   => "/docs"
    //    result => "/home/docs"
    fn get_raw_path(&self, path: &str) -> VfsResult<PathBuf> {
        if path.contains("..") {
            return Err(VfsError::InvalidAbsolutePath {
                path: path.to_owned(),
            });
        }

        if path.starts_with("/") {
            Ok(self.root.join(&path[1..]))
        } else {
            Err(VfsError::InvalidAbsolutePath {
                path: String::from(path),
            })
        }
    }

    // if root => "/home"
    //    path => /home/doc
    //    result => /doc
    fn get_vfs_path(&self, path: &Path) -> VfsResult<String> {
        let pathstr = path.to_str().ok_or(VfsError::InvalidAbsolutePath {
            path: String::from(""),
        })?;

        if pathstr.contains("..") {
            return Err(VfsError::InvalidAbsolutePath {
                path: pathstr.to_owned(),
            });
        }

        if !path.is_absolute() {
            return Err(VfsError::InvalidAbsolutePath {
                path: pathstr.to_owned(),
            });
        }

        if path.starts_with(&self.root) {
            let res = path
                .strip_prefix(&self.root)
                .or_else(|_| {
                    Err(VfsError::InvalidAbsolutePath {
                        path: pathstr.to_owned(),
                    })
                })?
                .to_str()
                .ok_or_else(|| VfsError::InvalidAbsolutePath {
                    path: pathstr.to_owned(),
                })?;
            Ok("/".to_owned() + res)
        } else {
            Err(VfsError::InvalidAbsolutePath {
                path: pathstr.to_owned(),
            })
        }
    }
}

impl VMetadata for VOsMetadata {
    fn path(&self) -> &str {
        &self.path
    }

    fn is_dir(&self) -> bool {
        !self.is_file
    }

    fn is_file(&self) -> bool {
        self.is_file
    }

    fn len(&self) -> u64 {
        self.len
    }
}

#[async_trait]
impl Vfs for OsFs {
    async fn exists(&self, path: &str) -> VfsResult<bool> {
        Ok(self.get_raw_path(path)?.exists().await)
    }

    async fn ls(
        &self,
        path: &str,
        _skip_token: Option<String>,
    ) -> VfsResult<(Vec<Box<dyn VMetadata>>, Option<String>)> {
        let mut dir = fs::read_dir(self.get_raw_path(path)?).await?;
        let mut list: Vec<Box<dyn VMetadata>> = Vec::new();
        while let Some(entry) = dir.next().await {
            let entry = entry?;
            let metadata = entry.metadata().await?;
            let path = entry.path();

            let vmetadata = if metadata.is_dir() {
                VOsMetadata {
                    is_file: false,
                    len: 0,
                    path: self.get_vfs_path(&path)?,
                }
            } else {
                VOsMetadata {
                    is_file: true,
                    len: metadata.len(),
                    path: self.get_vfs_path(&path)?,
                }
            };

            list.push(Box::new(vmetadata));
        }
        Ok((list, None))
    }

    async fn metadata(&self, path: &str) -> VfsResult<Box<dyn VMetadata>> {
        let path = self.get_raw_path(path)?;
        let metadata = path.metadata().await?;
        let vmetadata = if metadata.is_dir() {
            VOsMetadata {
                is_file: false,
                len: 0,
                path: self.get_vfs_path(&path)?,
            }
        } else {
            VOsMetadata {
                is_file: true,
                len: metadata.len(),
                path: self.get_vfs_path(&path)?,
            }
        };
        Ok(Box::new(vmetadata))
    }

    async fn mkdir(&self, path: &str) -> VfsResult<()> {
        Ok(fs::create_dir(self.get_raw_path(path)?).await?)
    }

    async fn mv(&self, from: &str, to: &str) -> VfsResult<()> {
        Ok(fs::rename(from, to).await?)
    }

    async fn open(&self, path: &str, options: OpenOptions) -> VfsResult<Pin<Box<dyn VFile>>> {
        let raw_path = self.get_raw_path(path)?;
        if raw_path.is_dir().await {
            return Err(VfsError::InvalidFile {
                path: path.to_owned(),
            });
        }
        let file = fs::OpenOptions::new()
            .read(options.has_read())
            .write(options.has_write())
            .create(options.has_create())
            .append(options.has_append())
            .truncate(options.has_truncate())
            .open(raw_path)
            .await?;
        Ok(Pin::from(Box::new(file)))
    }

    async fn rm(&self, path: &str) -> VfsResult<()> {
        let path = self.get_raw_path(path)?;
        let metadata = path.metadata().await?;
        if metadata.is_dir() {
            Ok(fs::remove_dir(path).await?)
        } else {
            Ok(fs::remove_file(path).await?)
        }
    }
}