tomlsmith-cli 0.4.0

Command-line adapter for TomlSmith
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
#![forbid(unsafe_code)]

use std::{
    ffi::OsString,
    io,
    path::{Path, PathBuf},
};

use clap::{Parser, Subcommand, ValueEnum};
use tomlsmith::{
    Diagnostic, DiagnosticCode, Document, FormatOptions, FormatOutcome, LineEnding, Severity,
};

#[derive(Debug, Parser)]
#[command(name = "tomlsmith", version, about = "A unified TOML toolchain")]
struct Cli {
    /// TOML language version used for parsing and validation.
    #[arg(long, value_enum, default_value_t = TomlVersionArg::V1_1, global = true)]
    toml_version: TomlVersionArg,

    #[command(subcommand)]
    command: Command,
}

#[derive(Clone, Copy, Debug, Default, ValueEnum)]
enum TomlVersionArg {
    #[value(name = "1.0")]
    V1_0,
    #[default]
    #[value(name = "1.1")]
    V1_1,
}

impl From<TomlVersionArg> for tomlsmith::TomlVersion {
    fn from(version: TomlVersionArg) -> Self {
        match version {
            TomlVersionArg::V1_0 => Self::V1_0,
            TomlVersionArg::V1_1 => Self::V1_1,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, ValueEnum)]
enum LineEndingArg {
    #[default]
    Preserve,
    Lf,
    Crlf,
}

impl From<LineEndingArg> for LineEnding {
    fn from(line_ending: LineEndingArg) -> Self {
        match line_ending {
            LineEndingArg::Preserve => Self::Preserve,
            LineEndingArg::Lf => Self::Lf,
            LineEndingArg::Crlf => Self::CrLf,
        }
    }
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Check a TOML document and report diagnostics.
    Check {
        /// Input file, or `-` for standard input.
        #[arg(default_value = "-")]
        input: PathBuf,
    },

    /// Format a TOML document.
    ///
    /// Symbolic links are followed and preserved. On Unix, files with multiple hard links are
    /// refused because an atomic replacement cannot preserve their shared inode identity.
    Fmt {
        /// Exit with status 1 instead of writing when formatting is needed.
        #[arg(long)]
        check: bool,

        /// Number of spaces per indentation level.
        #[arg(long, value_parser = clap::value_parser!(u8).range(1..))]
        indent_width: Option<u8>,

        /// Line width that triggers wrapping inside arrays and TOML 1.1 inline tables.
        #[arg(long, value_parser = clap::value_parser!(u16).range(1..))]
        line_width: Option<u16>,

        /// Line-ending policy for the formatted output.
        #[arg(long, value_enum, default_value_t = LineEndingArg::Preserve)]
        line_ending: LineEndingArg,

        /// Input file, or `-` for standard input.
        #[arg(default_value = "-")]
        input: PathBuf,
    },

    /// Parse a TOML document and emit diagnostics as JSON.
    Parse {
        /// Input file, or `-` for standard input.
        #[arg(default_value = "-")]
        input: PathBuf,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExitStatus {
    Success,
    ContentFailure,
    OperationalFailure,
}

impl ExitStatus {
    #[must_use]
    pub const fn code(self) -> u8 {
        match self {
            Self::Success => 0,
            Self::ContentFailure => 1,
            Self::OperationalFailure => 2,
        }
    }
}

struct InvalidUtf8Input {
    source_name: String,
    start: u32,
    end: u32,
}

enum SourceRead {
    Text { source_name: String, source: String },
    InvalidUtf8(InvalidUtf8Input),
}

pub fn run<I, S>(
    arguments: I,
    stdin: &mut dyn io::Read,
    stdout: &mut dyn io::Write,
    stderr: &mut dyn io::Write,
) -> ExitStatus
where
    I: IntoIterator<Item = S>,
    S: Into<OsString> + Clone,
{
    let cli = match Cli::try_parse_from(arguments) {
        Ok(cli) => cli,
        Err(error) => {
            let status = if error.use_stderr() {
                let _ = write!(stderr, "{error}");
                ExitStatus::OperationalFailure
            } else {
                let _ = write!(stdout, "{error}");
                ExitStatus::Success
            };
            return status;
        }
    };

    match execute(cli, stdin, stdout, stderr) {
        Ok(status) => status,
        Err(error) => {
            let _ = writeln!(stderr, "tomlsmith: {error}");
            ExitStatus::OperationalFailure
        }
    }
}

fn execute(
    cli: Cli,
    stdin: &mut dyn io::Read,
    stdout: &mut dyn io::Write,
    stderr: &mut dyn io::Write,
) -> io::Result<ExitStatus> {
    let version = cli.toml_version.into();
    match cli.command {
        Command::Check { input } => {
            let (source_name, source) = match read_source(&input, stdin)? {
                SourceRead::Text {
                    source_name,
                    source,
                } => (source_name, source),
                SourceRead::InvalidUtf8(diagnostic) => {
                    render_invalid_utf8(stderr, &diagnostic)?;
                    return Ok(ExitStatus::ContentFailure);
                }
            };
            let document = Document::parse_as(source, version);
            render_diagnostics(stderr, &source_name, document.diagnostics())?;

            Ok(if has_errors(document.diagnostics()) {
                ExitStatus::ContentFailure
            } else {
                ExitStatus::Success
            })
        }
        Command::Fmt {
            check,
            indent_width,
            line_width,
            line_ending,
            input,
        } => {
            let (source_name, source) = match read_source(&input, stdin)? {
                SourceRead::Text {
                    source_name,
                    source,
                } => (source_name, source),
                SourceRead::InvalidUtf8(diagnostic) => {
                    render_invalid_utf8(stderr, &diagnostic)?;
                    return Ok(ExitStatus::ContentFailure);
                }
            };
            let mut options = FormatOptions {
                target_version: version,
                line_ending: line_ending.into(),
                ..FormatOptions::default()
            };
            if let Some(indent_width) = indent_width {
                options.indent_width = indent_width;
            }
            if let Some(line_width) = line_width {
                options.line_width = line_width;
            }
            let (document, outcome) = Document::parse_and_format_with(source, version, &options);
            render_format_outcome(
                &document,
                outcome,
                check,
                &input,
                &source_name,
                stdout,
                stderr,
            )
        }
        Command::Parse { input } => {
            let source = match read_source(&input, stdin)? {
                SourceRead::Text { source, .. } => source,
                SourceRead::InvalidUtf8(diagnostic) => {
                    let output = serde_json::json!({
                        "tomlVersion": version_label(version),
                        "valid": false,
                        "diagnostics": [invalid_utf8_json(&diagnostic)],
                    });
                    serde_json::to_writer(&mut *stdout, &output).map_err(io::Error::other)?;
                    writeln!(stdout)?;
                    return Ok(ExitStatus::ContentFailure);
                }
            };
            let document = Document::parse_as(source, version);
            let diagnostics = document
                .diagnostics()
                .iter()
                .map(diagnostic_json)
                .collect::<Vec<_>>();
            let output = serde_json::json!({
                "tomlVersion": version_label(version),
                "valid": !has_errors(document.diagnostics()),
                "diagnostics": diagnostics,
            });
            serde_json::to_writer(&mut *stdout, &output).map_err(io::Error::other)?;
            writeln!(stdout)?;

            Ok(if has_errors(document.diagnostics()) {
                ExitStatus::ContentFailure
            } else {
                ExitStatus::Success
            })
        }
    }
}

const fn version_label(version: tomlsmith::TomlVersion) -> &'static str {
    match version {
        tomlsmith::TomlVersion::V1_0 => "1.0",
        tomlsmith::TomlVersion::V1_1 => "1.1",
    }
}

fn has_errors(diagnostics: &[Diagnostic]) -> bool {
    diagnostics
        .iter()
        .any(|diagnostic| diagnostic.severity() == Severity::Error)
}

fn diagnostic_json(diagnostic: &Diagnostic) -> serde_json::Value {
    serde_json::json!({
        "code": diagnostic.code().as_str(),
        "severity": match diagnostic.severity() {
            Severity::Error => "error",
            Severity::Warning => "warning",
        },
        "message": diagnostic.message(),
        "range": {
            "start": diagnostic.range().start(),
            "end": diagnostic.range().end(),
        },
    })
}

fn render_format_outcome(
    document: &Document,
    outcome: FormatOutcome,
    check: bool,
    input: &Path,
    source_name: &str,
    stdout: &mut dyn io::Write,
    stderr: &mut dyn io::Write,
) -> io::Result<ExitStatus> {
    match outcome {
        FormatOutcome::Unchanged => {
            if !check && input == Path::new("-") {
                stdout.write_all(document.text().as_bytes())?;
            }
            Ok(ExitStatus::Success)
        }
        FormatOutcome::Changed { text, .. } => {
            if check {
                writeln!(stderr, "would reformat {source_name}")?;
                Ok(ExitStatus::ContentFailure)
            } else {
                if input == Path::new("-") {
                    stdout.write_all(text.as_bytes())?;
                } else {
                    write_file_atomically(input, text.as_bytes())?;
                }
                Ok(ExitStatus::Success)
            }
        }
        FormatOutcome::Refused { diagnostics } => {
            render_diagnostics(stderr, source_name, &diagnostics)?;
            Ok(ExitStatus::ContentFailure)
        }
    }
}

/// Replaces the file reached through `input` using a same-directory temporary file, preserving a
/// symbolic link at the user-facing path. `tempfile::persist` provides replacement semantics on
/// Windows as well as rename-based atomic replacement on Unix.
fn write_file_atomically(input: &Path, contents: &[u8]) -> io::Result<()> {
    let destination = match std::fs::symlink_metadata(input) {
        Ok(metadata) if metadata.file_type().is_symlink() => std::fs::canonicalize(input)?,
        Ok(_) => input.to_owned(),
        Err(error) if error.kind() == io::ErrorKind::NotFound => input.to_owned(),
        Err(error) => return Err(error),
    };
    let directory = destination
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let metadata = std::fs::metadata(&destination)?;
    refuse_multiply_linked_file(&destination, &metadata)?;

    let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
    temporary
        .as_file()
        .set_permissions(metadata.permissions())?;
    io::Write::write_all(&mut temporary, contents)?;
    io::Write::flush(&mut temporary)?;
    temporary.as_file().sync_all()?;
    temporary
        .persist(&destination)
        .map(|_| ())
        .map_err(|error| error.error)
}

#[cfg(unix)]
fn refuse_multiply_linked_file(path: &Path, metadata: &std::fs::Metadata) -> io::Result<()> {
    use std::os::unix::fs::MetadataExt;

    let links = metadata.nlink();
    if links > 1 {
        return Err(io::Error::other(format!(
            "refusing to atomically replace {} because it has multiple hard links ({links}); format stdin and write the result explicitly instead",
            path.display(),
        )));
    }
    Ok(())
}

#[cfg(not(unix))]
fn refuse_multiply_linked_file(_path: &Path, _metadata: &std::fs::Metadata) -> io::Result<()> {
    Ok(())
}

fn read_source(input: &Path, stdin: &mut dyn io::Read) -> io::Result<SourceRead> {
    let (source_name, bytes) = if input == Path::new("-") {
        // Pre-size the buffer so `read_to_end` on a pipe does not spend the
        // cold-start budget growing a fresh Vec while the writer refills it.
        let mut bytes = Vec::with_capacity(256 * 1024);
        stdin.read_to_end(&mut bytes)?;
        ("stdin".to_owned(), bytes)
    } else {
        (input.display().to_string(), std::fs::read(input)?)
    };
    match String::from_utf8(bytes) {
        Ok(source) => Ok(SourceRead::Text {
            source_name,
            source,
        }),
        Err(error) => {
            let utf8_error = error.utf8_error();
            let start = utf8_error.valid_up_to();
            let end = start.saturating_add(utf8_error.error_len().unwrap_or(1));
            Ok(SourceRead::InvalidUtf8(InvalidUtf8Input {
                source_name,
                start: u32::try_from(start).unwrap_or(u32::MAX),
                end: u32::try_from(end).unwrap_or(u32::MAX),
            }))
        }
    }
}

fn invalid_utf8_json(diagnostic: &InvalidUtf8Input) -> serde_json::Value {
    serde_json::json!({
        "code": DiagnosticCode::INVALID_UTF8.as_str(),
        "severity": "error",
        "message": "TOML input must be valid UTF-8",
        "range": {
            "start": diagnostic.start,
            "end": diagnostic.end,
        },
    })
}

fn render_invalid_utf8(
    output: &mut dyn io::Write,
    diagnostic: &InvalidUtf8Input,
) -> io::Result<()> {
    writeln!(
        output,
        "{}:{}..{}: error[{}]: TOML input must be valid UTF-8",
        diagnostic.source_name,
        diagnostic.start,
        diagnostic.end,
        DiagnosticCode::INVALID_UTF8,
    )
}

fn render_diagnostics(
    output: &mut dyn io::Write,
    source_name: &str,
    diagnostics: &[Diagnostic],
) -> io::Result<()> {
    for diagnostic in diagnostics {
        let severity = match diagnostic.severity() {
            Severity::Error => "error",
            Severity::Warning => "warning",
        };
        writeln!(
            output,
            "{}:{}..{}: {}[{}]: {}",
            source_name,
            diagnostic.range().start(),
            diagnostic.range().end(),
            severity,
            diagnostic.code(),
            diagnostic.message(),
        )?;
    }
    Ok(())
}