typst_as_lib/
file_resolver.rs

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
194
195
196
197
198
use ecow::eco_format;
use std::{
    borrow::Cow,
    collections::HashMap,
    path::{Path, PathBuf},
};
use typst::{
    diag::{FileError, FileResult},
    foundations::Bytes,
    syntax::{FileId, Source},
};

use crate::{
    cached_file_resolver::CachedFileResolver,
    util::{bytes_to_source, not_found},
    FileIdNewType, SourceNewType,
};

// https://github.com/typst/typst/blob/16736feb13eec87eb9ca114deaeb4f7eeb7409d2/crates/typst-kit/src/package.rs#L18
/// The default packages sub directory within the package and package cache paths.
pub const DEFAULT_PACKAGES_SUBDIR: &str = "typst/packages";

pub trait FileResolver {
    fn resolve_binary(&self, id: FileId) -> FileResult<Cow<Bytes>>;
    fn resolve_source(&self, id: FileId) -> FileResult<Cow<Source>>;
}

#[derive(Debug, Clone)]
pub(crate) struct MainSourceFileResolver {
    main_source: Source,
}

impl MainSourceFileResolver {
    pub(crate) fn new(main_source: Source) -> Self {
        Self { main_source }
    }
}

impl FileResolver for MainSourceFileResolver {
    fn resolve_binary(&self, id: FileId) -> FileResult<Cow<Bytes>> {
        Err(not_found(id))
    }

    fn resolve_source(&self, id: FileId) -> FileResult<Cow<Source>> {
        let Self { main_source } = self;
        if id == main_source.id() {
            return Ok(Cow::Borrowed(main_source));
        }
        Err(not_found(id))
    }
}

#[derive(Debug, Clone)]
pub struct StaticSourceFileResolver {
    sources: HashMap<FileId, Source>,
}

impl StaticSourceFileResolver {
    pub(crate) fn new<IS, S>(sources: IS) -> Self
    where
        IS: IntoIterator<Item = S>,
        S: Into<SourceNewType>,
    {
        let sources = sources
            .into_iter()
            .map(|s| {
                let SourceNewType(s) = s.into();
                (s.id(), s)
            })
            .collect();
        Self { sources }
    }
}

impl FileResolver for StaticSourceFileResolver {
    fn resolve_binary(&self, id: FileId) -> FileResult<Cow<Bytes>> {
        Err(not_found(id))
    }

    fn resolve_source(&self, id: FileId) -> FileResult<Cow<Source>> {
        self.sources
            .get(&id)
            .map(|s| Cow::Borrowed(s))
            .ok_or_else(|| not_found(id))
    }
}

#[derive(Debug, Clone)]
pub struct StaticFileResolver {
    binaries: HashMap<FileId, Bytes>,
}

impl StaticFileResolver {
    pub(crate) fn new<IB, F, B>(binaries: IB) -> Self
    where
        IB: IntoIterator<Item = (F, B)>,
        F: Into<FileIdNewType>,
        B: Into<Bytes>,
    {
        let binaries = binaries
            .into_iter()
            .map(|(id, b)| {
                let FileIdNewType(id) = id.into();
                (id, b.into())
            })
            .collect();
        Self { binaries }
    }
}

impl FileResolver for StaticFileResolver {
    fn resolve_binary(&self, id: FileId) -> FileResult<Cow<Bytes>> {
        self.binaries
            .get(&id)
            .map(|b| Cow::Borrowed(b))
            .ok_or_else(|| not_found(id))
    }

    fn resolve_source(&self, id: FileId) -> FileResult<Cow<Source>> {
        Err(not_found(id))
    }
}

#[derive(Debug, Clone)]
pub struct FileSystemResolver {
    root: PathBuf,
    local_package_root: Option<PathBuf>,
}

impl FileSystemResolver {
    pub fn new(root: PathBuf) -> Self {
        let mut root = root.clone();
        // trailing slash is necessary for resolve function, which is, what this 'hack' does
        // https://users.rust-lang.org/t/trailing-in-paths/43166/9
        root.push("");
        Self {
            root,
            local_package_root: None,
        }
    }

    /// Use other path to look for local packages
    pub fn with_local_package_root(self, path: PathBuf) -> Self {
        Self {
            local_package_root: Some(path),
            ..self
        }
    }

    fn resolve_bytes(&self, id: FileId) -> FileResult<Vec<u8>> {
        let Self {
            root,
            local_package_root,
        } = self;
        // https://github.com/typst/typst/blob/16736feb13eec87eb9ca114deaeb4f7eeb7409d2/crates/typst-kit/src/package.rs#L102C16-L102C38
        let dir: Cow<Path> = if let Some(package) = id.package() {
            let data_dir = if let Some(data_dir) = local_package_root {
                Cow::Borrowed(data_dir)
            } else if let Some(data_dir) = dirs::data_dir() {
                Cow::Owned(data_dir.join(DEFAULT_PACKAGES_SUBDIR))
            } else {
                return Err(FileError::Other(Some(eco_format!("No data dir set!"))));
            };
            let subdir = Path::new(package.namespace.as_str())
                .join(package.name.as_str())
                .join(package.version.to_string());
            Cow::Owned(data_dir.join(subdir))
        } else {
            Cow::Borrowed(root)
        };

        let path = id
            .vpath()
            .resolve(&dir)
            .ok_or_else(|| FileError::NotFound(dir.to_path_buf()))?;
        let content = std::fs::read(&path).map_err(|error| FileError::from_io(error, &path))?;
        Ok(content.into())
    }

    pub fn cached(self) -> CachedFileResolver<Self> {
        CachedFileResolver::new(self)
            .with_in_memory_source_cache()
            .with_in_memory_binary_cache()
    }
}

impl FileResolver for FileSystemResolver {
    fn resolve_binary(&self, id: FileId) -> FileResult<Cow<Bytes>> {
        let b = self.resolve_bytes(id)?;
        Ok(Cow::Owned(b.into()))
    }

    fn resolve_source(&self, id: FileId) -> FileResult<Cow<Source>> {
        let file = self.resolve_bytes(id)?;
        let source = bytes_to_source(id, &file)?;
        Ok(Cow::Owned(source))
    }
}