mle 0.28.0

The markup link extractor (mle) extracts links from markup files (Markdown and HTML).
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// SPDX-FileCopyrightText: 2022 - 2025 Robin Vobruba <hoijui.quaero@gmail.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

mod csv;
mod json;
mod markdown;
mod txt;

use async_std::io::{ErrorKind, Write};
use async_trait::async_trait;
use cli_utils::StreamIdent;
use std::str::FromStr;

// #[cfg(feature = "async")]
// use async_std::path::PathBuf;
// #[cfg(not(feature = "async"))]
// use std::path::PathBuf;

use async_std::io;
use clap::{ValueEnum, builder::PossibleValue};
use serde::{Deserialize, Serialize};

use crate::{
    BoxError,
    anchor::{self, Anchor},
    config::Tool as Config,
    link::Link,
};

type Writer = Box<dyn Write + Unpin + Send + Sync + 'static>;
type WriterOpt = Option<Writer>;

const EXT_TEXT: &str = "txt";
const EXT_MARKDOWN: &str = "md";
const EXT_CSV: &str = "csv";
const EXT_TSV: &str = "tsv";
const EXT_JSON: &str = "json";
const EXT_RDF_TURTLE: &str = "ttl";
const ALL_EXTS: [&str; 6] = [
    EXT_TEXT,
    EXT_MARKDOWN,
    EXT_CSV,
    EXT_TSV,
    EXT_JSON,
    EXT_RDF_TURTLE,
];

#[derive(Default, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Type {
    #[default]
    Text,
    Markdown,
    Csv,
    Tsv,
    Json,
    RdfTurtle,
}

impl ValueEnum for Type {
    fn value_variants<'a>() -> &'a [Self] {
        &[
            Self::Text,
            Self::Markdown,
            Self::Csv,
            Self::Tsv,
            Self::Json,
            Self::RdfTurtle,
        ]
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        Some(self.as_str().into())
    }
}

impl Type {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Text => EXT_TEXT,
            Self::Markdown => EXT_MARKDOWN,
            Self::Csv => EXT_CSV,
            Self::Tsv => EXT_TSV,
            Self::Json => EXT_JSON,
            Self::RdfTurtle => EXT_RDF_TURTLE,
        }
    }
}

impl FromStr for Type {
    type Err = std::io::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            EXT_TEXT | "text" | "plain" | "grep" => Self::Text,
            EXT_MARKDOWN | "markdown" => Self::Markdown,
            EXT_CSV => Self::Csv,
            EXT_JSON => Self::Json,
            EXT_RDF_TURTLE | "turtle" | "rdf" | "rdf-turtle" => Self::RdfTurtle,
            _ => Err(std::io::Error::new(
                ErrorKind::InvalidInput,
                format!(
                    "Invalid result format given: '{}' \nValid formats are: {}",
                    s,
                    ALL_EXTS.join(", ")
                ),
            ))?,
        })
    }
}

#[allow(clippy::ref_option)]
async fn construct_out_stream_opt(
    specifier_opt: &Option<StreamIdent>,
) -> io::Result<Option<Box<dyn io::Write + Unpin + Send + Sync>>> {
    match specifier_opt.as_ref() {
        None => Ok(None),
        Some(specifier) => Ok(Some(specifier.create_output_writer().await?)),
    }
}

/// Pretty-prints a list of errors to `log::error!`.
pub fn write_to_stderr(errors: &[BoxError]) {
    for error in errors {
        log::error!("{error:#?}");
    }
}

/// Write results to stdout or file.
///
/// # Errors
///
/// (I/)O-error when writing to a file.
pub async fn sink(
    config: &Config,
    links: &[Link],
    anchors: &[Anchor],
    errors: &[BoxError],
) -> io::Result<()> {
    let sink_init = match config.result_format {
        Type::Text => txt::Sink::init,
        Type::Json => json::Sink::init,
        Type::Markdown => markdown::Sink::init,
        Type::Csv | Type::Tsv => csv::Sink::init,
        Type::RdfTurtle => Err(std::io::Error::new(
            ErrorKind::InvalidInput,
            "Result format not yet supported",
        ))?,
    };
    let links_writer = construct_out_stream_opt(&config.links).await?;
    let anchors_writer = construct_out_stream_opt(&config.anchors).await?;
    let mut sink = sink_init(config.result_format, config, links_writer, anchors_writer).await?;
    for link in links {
        // thread::sleep::sleep(std::time::Duration::new(0, 200000000));
        sink.sink_link(link).await?;
    }
    for anchor in anchors {
        sink.sink_anchor(anchor).await?;
    }
    for error in errors {
        sink.sink_error(error).await?;
    }
    sink.finalize().await
}

#[async_trait]
pub trait Sink: Send + Sync {
    /// Initializes this sink.
    /// This will be called once only,
    /// and before any `sink_*` function may be called.
    ///
    /// # Errors
    ///
    /// If writing to a file or other (I)/O-device failed.
    async fn init(
        format: Type,
        config: &Config,
        links_stream: WriterOpt,
        anchors_stream: WriterOpt,
    ) -> io::Result<Box<dyn Sink>>
    where
        Self: Sized;

    /// Writes-out an extracted link.
    ///
    /// # Errors
    ///
    /// If writing to the output stream for links failed.
    async fn sink_link(&mut self, link: &Link) -> io::Result<()>;

    /// Writes-out an extracted anchor.
    ///
    /// # Errors
    ///
    /// If writing to the output stream for anchors failed.
    async fn sink_anchor(&mut self, anchor: &Anchor) -> io::Result<()>;

    /// Writes-out an error generated while extracting links/anchors.
    ///
    /// # Errors
    ///
    /// If writing to the output stream for errors failed.
    async fn sink_error(&mut self, error: &BoxError) -> io::Result<()> {
        log::error!("{error:#?}");
        Ok(())
    }

    /// Finalizes/Closes this sink.
    /// This will be called exactly once,
    /// and no `sink_*` functions may be called after this function has been called.
    ///
    /// # Errors
    ///
    /// If writing to a file or other (I)/O-device failed.
    async fn finalize(&mut self) -> io::Result<()>;
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Serialize)]
struct LinkExtendedRec<'a> {
    src_file: String,
    src_line: usize,
    src_column: usize,
    src_is_file_system: bool,
    src_is_url: bool,
    src_is_local: bool,
    src_is_remote: bool,
    trg_link: String,
    trg_fragment: Option<&'a str>,
    trg_is_file_system: bool,
    trg_is_url: bool,
    trg_is_local: bool,
    trg_is_remote: bool,
}

#[derive(Debug, Serialize)]
struct LinkSimpleRec<'a> {
    src_file: String,
    src_line: usize,
    src_column: usize,
    trg_link: String,
    trg_fragment: Option<&'a str>,
}

#[derive(Debug)]
enum LinkRec<'a> {
    Simple(LinkSimpleRec<'a>),
    Extended(LinkExtendedRec<'a>),
}

impl<'a> LinkRec<'a> {
    fn new(lnk: &'a Link, extended: bool) -> Self {
        if extended {
            Self::Extended(LinkExtendedRec {
                src_file: lnk.source.file.to_string(),
                src_line: lnk.source.pos.line,
                src_column: lnk.source.pos.column,
                src_is_file_system: lnk.source.file.is_file_system(),
                src_is_url: lnk.source.file.is_url(),
                src_is_local: lnk.source.file.is_local(),
                src_is_remote: lnk.source.file.is_remote(),
                trg_link: lnk.target.without_fragment().to_string(),
                trg_fragment: lnk.target.fragment(),
                trg_is_file_system: lnk.target.is_file_system(),
                trg_is_url: lnk.target.is_url(),
                trg_is_local: lnk.target.is_local(),
                trg_is_remote: lnk.target.is_remote(),
            })
        } else {
            Self::Simple(LinkSimpleRec {
                src_file: lnk.source.file.to_string(),
                src_line: lnk.source.pos.line,
                src_column: lnk.source.pos.column,
                trg_link: lnk.target.without_fragment().to_string(),
                trg_fragment: lnk.target.fragment(),
            })
        }
    }
}

impl Serialize for LinkRec<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Simple(rec) => rec.serialize(serializer),
            Self::Extended(rec) => rec.serialize(serializer),
        }
    }
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Serialize)]
struct LinkExtendedOwnedRec {
    src_file: String,
    src_line: usize,
    src_column: usize,
    src_is_file_system: bool,
    src_is_url: bool,
    src_is_local: bool,
    src_is_remote: bool,
    trg_link: String,
    trg_fragment: Option<String>,
    trg_is_file_system: bool,
    trg_is_url: bool,
    trg_is_local: bool,
    trg_is_remote: bool,
}

#[derive(Debug, Serialize)]
struct LinkSimpleOwnedRec {
    src_file: String,
    src_line: usize,
    src_column: usize,
    trg_link: String,
    trg_fragment: Option<String>,
}

#[derive(Debug)]
enum LinkOwnedRec {
    Simple(LinkSimpleOwnedRec),
    Extended(LinkExtendedOwnedRec),
}

impl LinkOwnedRec {
    fn new(lnk: &Link, extended: bool) -> Self {
        if extended {
            Self::Extended(LinkExtendedOwnedRec {
                src_file: lnk.source.file.to_string(),
                src_line: lnk.source.pos.line,
                src_column: lnk.source.pos.column,
                src_is_file_system: lnk.source.file.is_file_system(),
                src_is_url: lnk.source.file.is_url(),
                src_is_local: lnk.source.file.is_local(),
                src_is_remote: lnk.source.file.is_remote(),
                trg_link: lnk.target.without_fragment().to_string(),
                trg_fragment: lnk.target.fragment().map(ToOwned::to_owned),
                trg_is_file_system: lnk.target.is_file_system(),
                trg_is_url: lnk.target.is_url(),
                trg_is_local: lnk.target.is_local(),
                trg_is_remote: lnk.target.is_remote(),
            })
        } else {
            Self::Simple(LinkSimpleOwnedRec {
                src_file: lnk.source.file.to_string(),
                src_line: lnk.source.pos.line,
                src_column: lnk.source.pos.column,
                trg_link: lnk.target.without_fragment().to_string(),
                trg_fragment: lnk.target.fragment().map(ToOwned::to_owned),
            })
        }
    }
}

impl Serialize for LinkOwnedRec {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Simple(rec) => rec.serialize(serializer),
            Self::Extended(rec) => rec.serialize(serializer),
        }
    }
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Serialize)]
struct AnchorExtendedRec<'a> {
    src_file: String,
    src_line: usize,
    src_column: usize,
    src_is_file_system: bool,
    src_is_url: bool,
    src_is_local: bool,
    src_is_remote: bool,
    name: &'a str,
    r#type: anchor::Type,
}

#[derive(Debug, Serialize)]
struct AnchorSimpleRec<'a> {
    src_file: String,
    src_line: usize,
    src_column: usize,
    name: &'a str,
}

#[derive(Debug)]
enum AnchorRec<'a> {
    Simple(AnchorSimpleRec<'a>),
    Extended(AnchorExtendedRec<'a>),
}

impl Serialize for AnchorRec<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Simple(rec) => rec.serialize(serializer),
            Self::Extended(rec) => rec.serialize(serializer),
        }
    }
}

impl<'a> AnchorRec<'a> {
    fn new(anchor: &'a Anchor, extended: bool) -> Self {
        if extended {
            Self::Extended(AnchorExtendedRec {
                src_file: anchor.source.file.to_string(),
                src_line: anchor.source.pos.line,
                src_column: anchor.source.pos.column,
                src_is_file_system: anchor.source.file.is_file_system(),
                src_is_url: anchor.source.file.is_url(),
                src_is_local: anchor.source.file.is_local(),
                src_is_remote: anchor.source.file.is_remote(),
                name: &anchor.name,
                r#type: anchor.r#type,
            })
        } else {
            Self::Simple(AnchorSimpleRec {
                src_file: anchor.source.file.to_string(),
                src_line: anchor.source.pos.line,
                src_column: anchor.source.pos.column,
                name: &anchor.name,
            })
        }
    }
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Serialize)]
struct AnchorExtendedOwnedRec {
    src_file: String,
    src_line: usize,
    src_column: usize,
    src_is_file_system: bool,
    src_is_url: bool,
    src_is_local: bool,
    src_is_remote: bool,
    name: String,
    r#type: anchor::Type,
}

#[derive(Debug, Serialize)]
struct AnchorSimpleOwnedRec {
    src_file: String,
    src_line: usize,
    src_column: usize,
    name: String,
}

#[derive(Debug)]
enum AnchorOwnedRec {
    Simple(AnchorSimpleOwnedRec),
    Extended(AnchorExtendedOwnedRec),
}
impl Serialize for AnchorOwnedRec {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Simple(rec) => rec.serialize(serializer),
            Self::Extended(rec) => rec.serialize(serializer),
        }
    }
}

impl AnchorOwnedRec {
    fn new(anchor: &Anchor, extended: bool) -> Self {
        if extended {
            Self::Extended(AnchorExtendedOwnedRec {
                src_file: anchor.source.file.to_string(),
                src_line: anchor.source.pos.line,
                src_column: anchor.source.pos.column,
                src_is_file_system: anchor.source.file.is_file_system(),
                src_is_url: anchor.source.file.is_url(),
                src_is_local: anchor.source.file.is_local(),
                src_is_remote: anchor.source.file.is_remote(),
                name: anchor.name.clone(),
                r#type: anchor.r#type,
            })
        } else {
            Self::Simple(AnchorSimpleOwnedRec {
                src_file: anchor.source.file.to_string(),
                src_line: anchor.source.pos.line,
                src_column: anchor.source.pos.column,
                name: anchor.name.clone(),
            })
        }
    }
}