vimwiki-core 0.1.0

Core library elements for vimwiki data structures, parsing, and more
Documentation
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use super::{HtmlConfig, HtmlWikiConfig};
use crate::Link;
use chrono::NaiveDate;
use derive_more::{Display, Error};
use relative_path::RelativePathBuf;
use serde::{de, Deserialize};
use std::{
    borrow::Cow,
    convert::TryFrom,
    ffi::OsStr,
    path::{Component, Path, PathBuf},
};
use uriparse::{
    Fragment, RelativeReference, RelativeReferenceError, URIReference,
};
use voca_rs::escape;

/// For use with serde's deserialize_with when deseriaizing to a path that
/// we also want to validate is an absolute path
pub fn deserialize_absolute_path<'de, D>(d: D) -> Result<PathBuf, D::Error>
where
    D: de::Deserializer<'de>,
{
    let value = PathBuf::deserialize(d)?;

    // Expand any shell content like ~ or $HOME
    let value = PathBuf::from(
        shellexpand::full(&value.to_string_lossy())
            .map_err(|x| {
                de::Error::invalid_value(
                    de::Unexpected::Str(value.to_string_lossy().as_ref()),
                    &x.to_string().as_str(),
                )
            })?
            .to_string(),
    );

    // Resolve .. and . in path (but not symlinks)
    let value = normalize_path(value.as_path());

    // Verify that the path given is actually absolute
    if !value.is_absolute() {
        return Err(de::Error::invalid_value(
            de::Unexpected::Str(value.to_string_lossy().as_ref()),
            &"path must be absolute",
        ));
    }

    Ok(value)
}

/// Normalizes text as an id by replacing whitespace with dashes and then
/// escaping common html
pub fn normalize_id(id: &str) -> String {
    escape::escape_html(
        id.to_lowercase()
            .split(|c: char| c.is_whitespace())
            .filter(|s| !s.is_empty())
            .collect::<Vec<&str>>()
            .join("-")
            .as_str(),
    )
}

/// Normalize a path, removing things like `.` and `..`.
///
/// CAUTION: This does not resolve symlinks (unlike
/// [`std::fs::canonicalize`]). This may cause incorrect or surprising
/// behavior at times. This should be used carefully. Unfortunately,
/// [`std::fs::canonicalize`] can be hard to use correctly, since it can often
/// fail, or on Windows returns annoying device paths. This is a problem Cargo
/// needs to improve on.
///
/// From https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81
pub fn normalize_path(path: &Path) -> PathBuf {
    let mut components = path.components().peekable();
    let mut ret =
        if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
            components.next();
            PathBuf::from(c.as_os_str())
        } else {
            PathBuf::new()
        };

    for component in components {
        match component {
            Component::Prefix(..) => unreachable!(),
            Component::RootDir => {
                ret.push(component.as_os_str());
            }
            Component::CurDir => {}
            Component::ParentDir => {
                ret.pop();
            }
            Component::Normal(c) => {
                ret.push(c);
            }
        }
    }
    ret
}

/// Converts a path to a string suitable for a uri by converting platform-specific
/// separators into /
pub fn path_to_uri_string(path: &Path) -> String {
    let out = path
        .components()
        .filter_map(|c| {
            match c {
                // Prefixes like C: are skipped
                Component::Prefix(_) => None,
                Component::RootDir => None,
                Component::CurDir => Some(Cow::Borrowed(".")),
                Component::ParentDir => Some(Cow::Borrowed("..")),
                Component::Normal(x) => Some(x.to_string_lossy()),
            }
        })
        .collect::<Vec<Cow<'_, str>>>()
        .join("/");

    if path.is_absolute() {
        format!("/{}", out)
    } else {
        out
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Display, Error)]
pub enum LinkResolutionError {
    /// Represents an error that occurred when evaluating a file in a wiki
    /// identified by index and determining that there is no loaded wiki with
    /// the specified index
    MissingWikiWithIndex {
        #[error(not(source))]
        index: usize,
    },

    /// Represents an error that occurred when evaluating a file in a wiki
    /// identified by name and determining that there is no loaded wiki with
    /// the specified name
    MissingWikiWithName {
        #[error(not(source))]
        name: String,
    },

    /// Represents an error that occurred when trying to construct a
    /// relative reference
    RelativeReference {
        #[error(source)]
        source: RelativeReferenceError,
    },
}

/// Performs link resolution to figure out the resulting URI or relative path
/// based on the file containing the link, the destination wiki, and the
/// outgoing link
pub fn resolve_link(
    config: &HtmlConfig,
    src_wiki: &HtmlWikiConfig,
    src: &Path,
    target: &Link<'_>,
) -> Result<URIReference<'static>, LinkResolutionError> {
    let ext = "html";
    let src_out = src_wiki.make_output_path(src, ext);

    // We want to figure out if the target uri is a directory to ensure that
    // certain links account for that
    let target_is_dir = is_directory_uri(&target.data().uri_ref);

    // First, build our raw uri WITHOUT anchors
    let uri_ref = match target {
        Link::Wiki { data } => {
            if data.is_local() {
                // TODO: Support alternative directory file name
                // NOTE: Don't need to provide extension as will be replaced in
                //       the absolute output path anyway
                let mut path = data.to_path_buf();
                if target_is_dir {
                    path.push("index");
                }

                // Build our output path
                //
                // 1. If absolute (starts with /), then we want to place the
                //    path relative to the root of the current wiki
                // 2. If relative, then we want to place the path relative to
                //    the current file's directory
                let target_out = if data.uri_ref.path().is_absolute() {
                    src_wiki.make_output_path(path.as_path(), ext)
                } else {
                    src_wiki.make_output_path(
                        src.parent()
                            .map(Path::to_path_buf)
                            .unwrap_or_default()
                            .join(path.as_path())
                            .as_path(),
                        ext,
                    )
                };

                let mut uri_ref = make_relative_link(src_out, target_out)
                    .map(URIReference::from)
                    .map_err(|source| {
                        LinkResolutionError::RelativeReference { source }
                    })?;

                if let Some(anchor) = data.to_anchor() {
                    uri_ref.map_fragment(|_| Fragment::try_from(anchor).ok());
                }

                uri_ref
            } else {
                data.uri_ref.clone()
            }
        }
        Link::IndexedInterWiki { index, data } => {
            let index = *index as usize;
            let wiki = config.find_wiki_by_index(index).ok_or({
                LinkResolutionError::MissingWikiWithIndex { index }
            })?;

            // TODO: Support alternative directory file name
            // NOTE: Don't need to provide extension as will be replaced in
            //       the absolute output path anyway
            let mut path = data.to_path_buf();
            if target_is_dir {
                path.push("index");
            }

            // Take the path of the target from the uri reference and make it
            // a relative path as it will always be added to the path of the
            // specified wiki
            let target_out =
                wiki.make_output_path(data.to_path_buf().as_path(), ext);

            let mut uri_ref = make_relative_link(src_out, target_out)
                .map(URIReference::from)
                .map_err(|source| LinkResolutionError::RelativeReference {
                    source,
                })?;

            if let Some(anchor) = data.to_anchor() {
                uri_ref.map_fragment(|_| Fragment::try_from(anchor).ok());
            }

            uri_ref
        }
        Link::NamedInterWiki { name, data } => {
            let wiki = config.find_wiki_by_name(name).ok_or_else(|| {
                LinkResolutionError::MissingWikiWithName {
                    name: name.to_string(),
                }
            })?;

            // TODO: Support alternative directory file name
            // NOTE: Don't need to provide extension as will be replaced in
            //       the absolute output path anyway
            let mut path = data.to_path_buf();
            if target_is_dir {
                path.push("index");
            }

            // Take the path of the target from the uri reference and make it
            // a relative path as it will always be added to the path of the
            // specified wiki
            let target_out =
                wiki.make_output_path(data.to_path_buf().as_path(), ext);

            let mut uri_ref = make_relative_link(src_out, target_out)
                .map(URIReference::from)
                .map_err(|source| LinkResolutionError::RelativeReference {
                    source,
                })?;

            if let Some(anchor) = data.to_anchor() {
                uri_ref.map_fragment(|_| Fragment::try_from(anchor).ok());
            }

            uri_ref
        }
        Link::Diary { date, data } => {
            let diary_out =
                make_diary_absolute_output_path(src_wiki, *date, ext);

            let mut uri_ref = make_relative_link(src_out, diary_out)
                .map(URIReference::from)
                .map_err(|source| LinkResolutionError::RelativeReference {
                    source,
                })?;

            if let Some(anchor) = data.to_anchor() {
                uri_ref.map_fragment(|_| Fragment::try_from(anchor).ok());
            }

            uri_ref
        }
        Link::Raw { data } => data.uri_ref.clone(),
        Link::Transclusion { data } => {
            // If target is a local link, then we need to process it the same
            // as any wiki link
            if data.is_local() {
                let path = data.to_path_buf();

                // We want to reuse the extension if there is one rather than
                // modifying it, so pull out the extension
                let ext =
                    path.extension().and_then(OsStr::to_str).unwrap_or("");

                // Build our output path
                //
                // 1. If absolute (starts with /), then we want to place the
                //    path relative to the root of the current wiki
                // 2. If relative, then we want to place the path relative to
                //    the current file's directory
                let target_out = if data.uri_ref.path().is_absolute() {
                    src_wiki.make_output_path(path.as_path(), ext)
                } else {
                    src_wiki.make_output_path(
                        src.parent()
                            .map(Path::to_path_buf)
                            .unwrap_or_default()
                            .join(path.as_path())
                            .as_path(),
                        ext,
                    )
                };

                make_relative_link(src_out, target_out)
                    .map(URIReference::from)
                    .map_err(|source| {
                        LinkResolutionError::RelativeReference { source }
                    })?

            // Otherwise, we can just pass back the link as-is
            } else {
                data.uri_ref.clone()
            }
        }
    };

    Ok(uri_ref.into_owned())
}

/// Produces an output path for a diary file
fn make_diary_absolute_output_path(
    config: &HtmlWikiConfig,
    date: NaiveDate,
    ext: &str,
) -> PathBuf {
    // Make our input path relative to wiki root
    //
    // {WIKI-ROOT}/{DIARY-REL-PATH}/{DATE}
    //
    // NOTE: The extension of our input doesn't matter (don't even need one)
    //       as we are replacing it with the provided extension
    let input = config
        .path
        .join(config.diary_rel_path.as_path())
        .join(date.format("%Y-%m-%d").to_string());
    config.make_output_path(input.as_path(), ext)
}

/// Given a src and target path, creates a relative reference
#[inline]
fn make_relative_link<P1: AsRef<Path>, P2: AsRef<Path>>(
    src: P1,
    target: P2,
) -> Result<RelativeReference<'static>, RelativeReferenceError> {
    let src_rel = RelativePathBuf::from_path(make_path_relative(src))
        .expect("Impossible: relative path should always succeed");
    let target_rel = RelativePathBuf::from_path(make_path_relative(target))
        .expect("Impossible: relative path should always succeed");

    // NOTE: a relative path of a/b -> a/c would yield ../c, but in the case
    //       of the web, we just want c as referencing from the same directory
    //       is fine; this means that we remove the first .. in the path
    let relative_path = src_rel.relative(target_rel);
    let res = RelativeReference::try_from(
        relative_path
            .strip_prefix("..")
            .unwrap_or(&relative_path)
            .as_str(),
    )
    .map(RelativeReference::into_owned);
    res
}

/// Makes a path relative by stripping it of absolute/root starting elements
pub fn make_path_relative<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref()
        .components()
        .filter(|c| {
            matches!(
                c,
                Component::CurDir | Component::ParentDir | Component::Normal(_)
            )
        })
        .collect()
}

/// Checks if a URI reference's path represents a directory
fn is_directory_uri(uri_ref: &URIReference<'_>) -> bool {
    // NOTE: URI Reference breaks up segments by /, which means that if we
    //       end with a / there is one final segment that is completely
    //       empty
    uri_ref
        .path()
        .segments()
        .last()
        .map_or(false, |s| s.as_str().is_empty())
}