mdsf 0.12.1

Format, and lint, markdown code snippets using your favorite tools
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use crate::{
    cli::InitCommandSchemaVersion, config::files::MdsfConfigFiles, error::MdsfError,
    terminal::print_config_not_found,
};

mod files;

#[allow(clippy::trivially_copy_pass_by_ref)]
#[inline]
const fn is_false(b: &bool) -> bool {
    !(*b)
}

#[allow(clippy::struct_excessive_bools)]
#[derive(serde::Serialize, serde::Deserialize, Hash, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct MdsfConfigRunners {
    /// Whether to support running npm packages using `bunx $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub bunx: bool,

    /// Whether to support running npm packages using `deno run -A npm:$PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub deno: bool,

    /// Whether to support running dub packages using `dotnet $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub dotnet: bool,

    /// Whether to support running dub packages using `dub run $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub dub: bool,

    /// Whether to support running ruby packages using `gem exec $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub gem_exec: bool,

    /// Whether to support running npm packages using `npx $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub npx: bool,

    /// Whether to support running pypi packages using `pipx run $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub pipx: bool,

    /// Whether to support running npm packages using `pnpm dlx $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub pnpm: bool,

    /// Whether to support running pypi packages using `uv tool run $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub uv: bool,

    /// Whether to support running npm packages using `yarn dlx $PACKAGE_NAME`
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub yarn: bool,
}

impl MdsfConfigRunners {
    #[inline]
    fn is_default(&self) -> bool {
        *self == Self::default()
    }

    #[inline]
    pub const fn all() -> Self {
        Self {
            bunx: true,
            deno: true,
            dotnet: true,
            dub: true,
            gem_exec: true,
            npx: true,
            pipx: true,
            pnpm: true,
            uv: true,
            yarn: true,
        }
    }
}

#[derive(
    Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize, Hash, Default,
)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub enum Newline {
    #[default]
    #[serde(rename = "lf")]
    Lf,
    #[serde(rename = "cr")]
    Cr,
    #[serde(rename = "crlf")]
    CrLf,
}

pub const LF_NEWLINE_CHAR: char = '\n';

impl Newline {
    #[inline]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Lf => "\n",
            Self::Cr => "\r",
            Self::CrLf => "\r\n",
        }
    }

    #[allow(clippy::trivially_copy_pass_by_ref)]
    #[inline]
    fn is_default(&self) -> bool {
        *self == Self::default()
    }

    #[inline]
    pub fn normalize(self, input: String) -> String {
        // We could most likely optimize this, but I am not sure if the added complexity is worth it

        if self == Self::Lf && !input.contains('\r') {
            input
        } else {
            input.lines().collect::<Vec<_>>().join(self.as_str())
        }
    }
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Hash, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum MdsfTool {
    Preset(crate::tools::Tooling),

    Custom(crate::custom::CustomTool),
}

impl core::fmt::Display for MdsfTool {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Preset(t) => t.fmt(f),
            Self::Custom(t) => t.fmt(f),
        }
    }
}

#[derive(serde::Serialize, serde::Deserialize, Hash, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct MdsfConfig {
    #[serde(rename = "$schema", default = "default_schema_location")]
    pub schema: String,

    /// Used for settings custom file extensions for a given language.
    ///
    /// ```json
    /// {
    ///   "custom_file_extensions": {
    ///     "rust": ".rust"
    ///   }
    /// }
    /// ```
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub custom_file_extensions: std::collections::BTreeMap<String, String>,

    #[serde(default, skip_serializing_if = "MdsfConfigFiles::is_default")]
    pub files: MdsfConfigFiles,

    /// Run the selected markdown tools on the finished output.
    ///
    /// Default: `false`
    #[serde(default, skip_serializing_if = "is_false")]
    pub format_finished_document: bool,

    /// Aliases for tools.
    ///
    /// ```json
    /// {
    ///   "language_aliases": {
    ///     "language": "is_alias_of"
    ///   }
    /// }
    /// ```
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub language_aliases: std::collections::BTreeMap<String, String>,

    ///  Defines which tools are used by the language.
    ///
    /// ```json
    /// {
    ///     "languages": {
    ///       // Only run `ruff` on Python snippets,
    ///       "python": "ruff:format",
    ///       // Run `usort` on file and then `black`
    ///       "python": ["usort", "black"],
    ///       // Run `usort`, if that fails run `isort`, finally run `black`
    ///       "python": [["usort", "isort"], "black"],
    ///
    ///       // Tools listed under "*" will be run on any snippet.
    ///       "*": ["typos"],
    ///
    ///       // Tools  listed under "_" will only be run when there is not tool configured for the file type OR globally ("*").
    ///       "_": "prettier"
    ///     }
    /// }
    /// ```
    #[serde(default)]
    pub languages: std::collections::BTreeMap<String, crate::execution::MdsfToolWrapper<MdsfTool>>,

    /// The newline used for the output.
    ///
    /// Default: `lf`
    #[serde(default, skip_serializing_if = "Newline::is_default")]
    pub newline: Newline,

    /// What to do when a codeblock language has no tools defined.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_missing_language_definition: Option<crate::cli::OnMissingLanguageDefinition>,

    /// What to do when the binary of a tool cannot be found.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_missing_tool_binary: Option<crate::cli::OnMissingToolBinary>,

    /// List of package registry script runners that should be enabled.
    ///
    /// Should be considered experimental since not all tools support being run that way.
    #[serde(default, skip_serializing_if = "MdsfConfigRunners::is_default")]
    pub runners: MdsfConfigRunners,
}

impl Default for MdsfConfig {
    #[inline]
    fn default() -> Self {
        Self {
            schema: default_schema_location(),
            custom_file_extensions: std::collections::BTreeMap::default(),
            files: MdsfConfigFiles::default(),
            format_finished_document: false,
            language_aliases: std::collections::BTreeMap::default(),
            languages: crate::languages::default_tools(),
            newline: Newline::default(),
            on_missing_language_definition: None,
            on_missing_tool_binary: None,
            runners: MdsfConfigRunners::default(),
        }
    }
}

impl MdsfConfig {
    #[inline]
    pub const fn supported_file_name() -> [&'static str; 12] {
        [
            "mdsf.json",
            ".mdsf.json",
            "mdsf.jsonc",
            ".mdsf.jsonc",
            "mdsf.json5",
            ".mdsf.json5",
            "mdsf.toml",
            ".mdsf.toml",
            "mdsf.yml",
            ".mdsf.yml",
            "mdsf.yaml",
            ".mdsf.yaml",
        ]
    }

    #[inline]
    pub fn auto_load() -> Result<Self, MdsfError> {
        let dir = std::env::current_dir()?;

        for name in Self::supported_file_name() {
            let path = dir.join(name);

            let c = Self::load(path);

            if let Err(MdsfError::ConfigNotFound(_)) = c {
                continue;
            }

            return c;
        }

        print_config_not_found(&dir);

        Ok(Self::default())
    }

    #[inline]
    pub fn load(path: impl AsRef<std::path::Path>) -> Result<Self, MdsfError> {
        let path = path.as_ref();

        let contents = std::fs::read_to_string(path).map_err(|error| {
            if error.kind() == std::io::ErrorKind::NotFound {
                MdsfError::ConfigNotFound(path.to_path_buf())
            } else {
                MdsfError::Io(error)
            }
        })?;

        Self::parse(&contents, path)
    }

    #[inline]
    fn parse(input: &str, path: &std::path::Path) -> Result<Self, MdsfError> {
        match path.extension().and_then(|ext| ext.to_str()) {
            Some("json" | "jsonc" | "json5") => Self::parse_json(input)
                .map_err(|err| MdsfError::ConfigParseJson((path.to_path_buf(), err))),
            Some("toml") => Self::parse_toml(input)
                .map_err(|err| MdsfError::ConfigParseToml((path.to_path_buf(), err))),
            Some("yml" | "yaml") => Self::parse_yaml(input)
                .map_err(|err| MdsfError::ConfigParseYaml((path.to_path_buf(), err))),
            _ => Self::parse_json(input)
                .map_err(|_| Self::parse_toml(input))
                .map_err(|_| Self::parse_yaml(input))
                .map_err(|_| MdsfError::ConfigParseUnknownFormat(path.to_path_buf())),
        }
    }

    #[inline]
    fn parse_json(input: &str) -> Result<Self, json5::Error> {
        json5::from_str(input)
    }

    #[inline]
    fn parse_toml(input: &str) -> Result<Self, toml::de::Error> {
        toml::from_str(input)
    }

    #[inline]
    fn parse_yaml(input: &str) -> Result<Self, serde_yaml::Error> {
        serde_yaml::from_str(input)
    }

    #[inline]
    pub fn setup_language_aliases(&mut self) -> Result<(), MdsfError> {
        if !self.language_aliases.is_empty() {
            let mut seen_languages: std::collections::HashMap<String, String> =
                std::collections::HashMap::new();

            for (language, alias) in &self.language_aliases {
                if let Some(already_set_by) = seen_languages.get(language) {
                    return Err(MdsfError::LanguageAliasClash(
                        language.to_owned(),
                        alias.to_owned(),
                        already_set_by.to_owned(),
                    ));
                }

                if self.languages.contains_key(language) {
                    return Err(MdsfError::LanguageAliasLanguagesContainsLanguage(
                        language.to_owned(),
                    ));
                }

                let tools = self
                    .languages
                    .get(alias)
                    .ok_or_else(|| MdsfError::LanguageAliasMissingTools(alias.to_owned()))?;

                self.languages.insert(language.to_owned(), tools.clone());

                seen_languages.insert(language.to_owned(), alias.to_owned());
            }
        }

        Ok(())
    }

    #[inline]
    pub fn parse_schema_version(&self) -> Option<(&str, bool)> {
        let package_version = env!("CARGO_PKG_VERSION");

        if self.schema == default_schema_location() {
            return Some((package_version, true));
        }

        let start = "https://raw.githubusercontent.com/hougesen/mdsf/main/schemas/";
        let end = "/mdsf.schema.json";

        // TODO: make this pretty
        if self.schema.starts_with(start)
            && self.schema.ends_with(end)
            && let Some((_, remaining)) = self.schema.split_once(start)
            && !remaining.is_empty()
            && let Some((version, _)) = remaining.rsplit_once(end)
            && !version.is_empty()
        {
            return Some((version, version == package_version));
        }

        None
    }
}

#[inline]
pub fn schema_url(v: InitCommandSchemaVersion) -> String {
    format!(
        "https://raw.githubusercontent.com/hougesen/mdsf/main/schemas/{maybe_v}{package_version}/mdsf.schema.json",
        maybe_v = if v == InitCommandSchemaVersion::Locked {
            "v"
        } else {
            ""
        },
        package_version = match v {
            InitCommandSchemaVersion::Locked => env!("CARGO_PKG_VERSION"),
            InitCommandSchemaVersion::Stable => "stable",
            InitCommandSchemaVersion::Development => "development",
        }
    )
}

#[inline]
fn default_schema_location() -> String {
    schema_url(InitCommandSchemaVersion::Locked)
}

#[cfg(test)]
mod test_config {
    use super::MdsfConfig;
    use crate::{error::MdsfError, execution::setup_snippet};

    #[test]
    fn schema_should_be_serializable() -> Result<(), serde_json::Error> {
        let config = MdsfConfig::default();

        let json = serde_json::to_string_pretty(&config)?;

        let loaded = serde_json::from_str::<MdsfConfig>(&json)?;

        assert_eq!(config, loaded);

        Ok(())
    }

    #[test]
    #[cfg(feature = "json-schema")]
    fn json_schema_should_be_serializable() -> Result<(), serde_json::Error> {
        serde_json::to_string_pretty(&schemars::schema_for!(MdsfConfig))?;

        Ok(())
    }

    #[test]
    fn it_should_ignore_comments() -> Result<(), json5::Error> {
        let r = r#"{
    // this is a slash comment
    "javascript":  ["prettier"],
    "rust": "rustfmt",
    /* this is a multiline comment
    "roc": {
        "enabled": false
    }
    */
    "go": "gofmt"         // hello world

}"#;

        MdsfConfig::parse_json(r)?;

        Ok(())
    }

    #[test]
    fn test_config_load_works() -> Result<(), Box<dyn core::error::Error>> {
        let f = tempfile::Builder::new().rand_bytes(24).tempfile()?;

        let default_config = MdsfConfig::default();

        std::fs::write(f.path(), serde_json::to_string(&default_config)?)?;

        let loaded = MdsfConfig::load(f.path())?;

        assert_eq!(default_config, loaded);

        Ok(())
    }

    #[test]
    fn test_config_load_return_error_if_not_found() {
        let before = MdsfConfig::load(std::path::Path::new(
            "ifthispathexiststhereissomethingwrong",
        ))
        .expect_err("Expect it to return file not found");

        assert!(matches!(before, MdsfError::ConfigNotFound(_)));
    }

    #[test]
    fn it_should_error_on_broken_config() -> Result<(), std::io::Error> {
        let input = "{thisisnotvalidjson}";

        let file = setup_snippet(input, ".json")?;

        let output = MdsfConfig::load(file.path()).expect_err("it should return an error");

        assert!(matches!(output, MdsfError::ConfigParseJson((_, _))));

        Ok(())
    }
}