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
// Copyright 2022 The Goscript Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

use crate::vfs::VirtualFs;
use go_parser::Map;
use std::borrow::Cow;
use std::io;
use std::path::{Path, PathBuf};

pub struct VfsMap {
    map: Map<PathBuf, Cow<'static, str>>,
}

impl VfsMap {
    pub fn new(map: Map<PathBuf, Cow<'static, str>>) -> VfsMap {
        VfsMap { map }
    }
}

impl VirtualFs for VfsMap {
    fn read_file(&self, path: &Path) -> io::Result<String> {
        self.map
            .get(path)
            .map(|x| x.to_string())
            .ok_or(io::Error::from(io::ErrorKind::NotFound))
    }

    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
        let result: Vec<PathBuf> = self
            .map
            .iter()
            .filter_map(|(p, _)| p.starts_with(path).then(|| p.to_path_buf()))
            .collect();
        if result.is_empty() {
            Err(io::Error::from(io::ErrorKind::NotFound))
        } else {
            Ok(result)
        }
    }

    fn is_file(&self, path: &Path) -> bool {
        path.extension().is_some()
    }

    fn is_dir(&self, path: &Path) -> bool {
        path.extension().is_none()
    }

    fn canonicalize_path(&self, path: &PathBuf) -> io::Result<PathBuf> {
        Ok(path.clone())
    }
}