go_engine/vfs/
vfs_map.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 go_parser::Map;
7use std::borrow::Cow;
8use std::io;
9use std::path::{Path, PathBuf};
10
11pub struct VfsMap {
12    map: Map<PathBuf, Cow<'static, str>>,
13}
14
15impl VfsMap {
16    pub fn new(map: Map<PathBuf, Cow<'static, str>>) -> VfsMap {
17        VfsMap { map }
18    }
19}
20
21impl VirtualFs for VfsMap {
22    fn read_file(&self, path: &Path) -> io::Result<String> {
23        self.map
24            .get(path)
25            .map(|x| x.to_string())
26            .ok_or(io::Error::from(io::ErrorKind::NotFound))
27    }
28
29    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
30        let result: Vec<PathBuf> = self
31            .map
32            .iter()
33            .filter_map(|(p, _)| p.starts_with(path).then(|| p.to_path_buf()))
34            .collect();
35        if result.is_empty() {
36            Err(io::Error::from(io::ErrorKind::NotFound))
37        } else {
38            Ok(result)
39        }
40    }
41
42    fn is_file(&self, path: &Path) -> bool {
43        path.extension().is_some()
44    }
45
46    fn is_dir(&self, path: &Path) -> bool {
47        path.extension().is_none()
48    }
49
50    fn canonicalize_path(&self, path: &PathBuf) -> io::Result<PathBuf> {
51        Ok(path.clone())
52    }
53}