go_engine/vfs/
vfs_fs.rs

1// Copyright 2022 The Goscript Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5use crate::vfs::VirtualFs;
6use std::fs;
7use std::io;
8use std::path::{Path, PathBuf};
9
10pub struct VfsFs {}
11
12impl VirtualFs for VfsFs {
13    fn read_file(&self, path: &Path) -> io::Result<String> {
14        fs::read_to_string(path)
15    }
16
17    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
18        Ok(fs::read_dir(path)?
19            .filter_map(|x| {
20                x.map_or(None, |e| {
21                    let path = e.path();
22                    (!path.is_dir()).then(|| path)
23                })
24            })
25            .collect())
26    }
27
28    fn is_file(&self, path: &Path) -> bool {
29        path.is_file()
30    }
31
32    fn is_dir(&self, path: &Path) -> bool {
33        path.is_dir()
34    }
35
36    fn canonicalize_path(&self, path: &PathBuf) -> io::Result<PathBuf> {
37        if !path.exists() {
38            Err(io::Error::from(io::ErrorKind::NotFound))
39        } else {
40            path.canonicalize()
41        }
42    }
43}