ordinary 0.11.1

Ordinary CLI
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
// Copyright (C) 2026 The Ordinary Authors.
//
// SPDX-License-Identifier: BSD-3-Clause

use crate::units::{Time, UuidVersion};
use anyhow::bail;
use clap::{Subcommand, ValueEnum};
use fs_err::File;
use ordinary_build::PercentageDisplay;
use qrcodegen::{QrCode, QrCodeEcc};
use std::collections::BTreeMap;
use std::env::home_dir;
use std::fmt::Write as _;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use time::UtcDateTime;
use tracing::instrument;
use uuid::Uuid;

#[derive(Subcommand, Debug)]
pub enum Utils {
    /// generate a UUID
    Uuid {
        /// uuid version
        #[arg(long, default_value = "4")]
        v: UuidVersion,
    },
    /// generate a UNIX timestamp for the current time (i.e. `date +%s`)
    #[clap(visible_aliases(["ts"]))]
    Timestamp {
        /// unit of time
        #[arg(short, long, default_value = "seconds")]
        unit: Time,
        /// formatting (uses `time` crate <https://time-rs.github.io/book/api/format-description.html>)
        ///
        /// i.e. `"[year]/[month]/[day] [hour]:[minute]:[second]"`
        #[arg(short, long)]
        fmt: Option<String>,
    },
    /// utilities for managing HTML files
    Html {
        #[command(subcommand)]
        html: Html,
    },
    /// utilities for managing CSS files
    Css {
        #[command(subcommand)]
        css: Css,
    },
    /// utilities for managing JavaScript/TypeScript files
    Js {
        #[command(subcommand)]
        js: Js,
    },
    /// utilities for manipulating Markdown files
    #[clap(visible_aliases(["md"]))]
    Markdown {
        #[command(subcommand)]
        markdown: Markdown,
    },
    /// utilities for manipulating exif data
    Exif {
        #[command(subcommand)]
        exif: Exif,
    },
    /// tool for generating QR codes
    #[clap(visible_aliases(["qr"]))]
    QrCode {
        /// URL the QR code will represent.
        url: String,

        /// where the file should be saved.
        ///
        /// if empty, will log to stdout.
        #[arg(short, long)]
        out: Option<PathBuf>,

        /// format of the output file.
        ///
        /// if none is passed and `--out` is set, defaults to SVG.
        #[arg(long)]
        fmt: Option<QrCodeFmt>,

        /// will make the background black and code color white
        #[arg(long, default_value_t = false)]
        dark: bool,
    },
}

#[derive(Clone, Debug, ValueEnum)]
pub enum QrCodeFmt {
    Svg,
}

#[derive(Subcommand, Debug)]
pub enum Html {
    /// minify HTML files
    #[clap(visible_aliases(["min"]))]
    Minify {
        /// path to the HTML file
        path: PathBuf,
        /// destination file for output
        #[arg(short, long)]
        out: Option<PathBuf>,
        /// whether it should overwrite the existing file
        #[arg(short, long, default_value_t = false)]
        in_place: bool,
    },
    /// generate hashes for a Content-Security-Policy based on
    /// an HTML file and its inlined scripts/styles.
    CspHashes {
        /// path to the HTML file
        path: PathBuf,
    },
}

#[derive(Subcommand, Debug)]
pub enum Css {
    /// minify CSS files
    #[clap(visible_aliases(["min"]))]
    Minify {
        /// path to the CSS file
        path: PathBuf,
        /// destination file for output
        #[arg(short, long)]
        out: Option<PathBuf>,
        /// whether it should overwrite the existing file
        #[arg(short, long, default_value_t = false)]
        in_place: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum Js {
    /// minify JavaScript files
    #[clap(visible_aliases(["min"]))]
    Minify {
        /// path to the JavaScript file
        path: PathBuf,
        /// destination file for output
        #[arg(short, long)]
        out: Option<PathBuf>,
        /// whether it should overwrite the existing file
        #[arg(short, long, default_value_t = false)]
        in_place: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum Markdown {
    /// process and place an .html file next to the referenced .md file
    ToHtml {
        /// path to the Markdown file
        path: PathBuf,
        /// if `true` escape all HTML in the Markdown file
        #[arg(short, long, default_value_t = false)]
        safe: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum Exif {
    /// [`exiftool`](https://exiftool.org) command
    Tool {
        /// `exiftool` args: <https://exiftool.org/exiftool_pod.html>
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
}

impl Utils {
    #[allow(clippy::redundant_else, clippy::too_many_lines)]
    #[instrument(skip_all, name = "utils")]
    pub fn handle(&self) -> anyhow::Result<()> {
        match self {
            Self::Uuid { v } => match v {
                UuidVersion::V4 => println!("{}", Uuid::new_v4()),
                UuidVersion::V7 => println!("{}", Uuid::now_v7()),
            },
            Self::Timestamp { unit, fmt } => {
                let mut timestamp = UtcDateTime::now();

                timestamp = match unit {
                    Time::Seconds => timestamp.truncate_to_second(),
                    Time::Millis => timestamp.truncate_to_millisecond(),
                    Time::Micros => timestamp.truncate_to_microsecond(),
                    Time::Nanos => timestamp,
                };

                if let Some(fmt) = fmt {
                    let format_desc = time::format_description::parse_borrowed::<1>(fmt.as_str())?;
                    let formatted = timestamp.format(&format_desc)?;
                    println!("{formatted}");
                } else {
                    let secs = timestamp.unix_timestamp();
                    let nanos = timestamp.unix_timestamp_nanos();

                    match unit {
                        Time::Seconds => println!("{secs}"),
                        Time::Millis => {
                            println!("{}", (secs * 1000) + (i64::try_from(nanos)? / 1000 / 1000));
                        }
                        Time::Micros => {
                            println!("{}", (secs * 1000 * 1000) + (i64::try_from(nanos)? / 1000));
                        }
                        Time::Nanos => println!("{nanos}"),
                    }
                }
            }
            Self::Html { html } => match html {
                Html::Minify {
                    path,
                    out,
                    in_place,
                } => {
                    minify(
                        path,
                        out.as_deref(),
                        *in_place,
                        ordinary_build_utils::html::minify,
                    )?;
                }
                Html::CspHashes { path } => {
                    let html = fs_err::read_to_string(path)?;

                    let csp_hashes = ordinary_build_utils::csp::for_cli(&html, true, false);

                    let mut map = BTreeMap::new();

                    map.insert("script", csp_hashes.script_src_inline_hashes);
                    map.insert("style", csp_hashes.style_src_inline_hashes);

                    println!("{}", serde_json::to_string(&map)?);
                }
            },
            Self::Css { css } => match css {
                Css::Minify {
                    path,
                    out,
                    in_place,
                } => {
                    minify(
                        path,
                        out.as_deref(),
                        *in_place,
                        ordinary_build_utils::css::minify,
                    )?;
                }
            },
            Self::Js { js } => match js {
                Js::Minify {
                    path,
                    out,
                    in_place,
                } => {
                    minify(
                        path,
                        out.as_deref(),
                        *in_place,
                        ordinary_build_utils::js::minify,
                    )?;
                }
            },
            Self::Markdown { markdown } => match markdown {
                Markdown::ToHtml { path, safe } => {
                    use pulldown_cmark::{Options, Parser};

                    if *safe {
                        todo!("implement safe");
                    }

                    if path.is_dir() {
                        bail!("doesn't yet work for directories")
                    } else {
                        let md = fs_err::read_to_string(path)?;

                        let options = Options::all();
                        let parser = Parser::new_ext(&md, options);

                        let mut path = path.clone();
                        path.set_extension("html");

                        let mut file = File::create(path)?;
                        pulldown_cmark::html::write_html_io(&mut file, parser)?;
                        file.flush()?;
                    }
                }
            },
            Self::Exif { exif } => match exif {
                Exif::Tool { args } => {
                    let exiftool_path = home_dir()
                        .expect("home dir doesn't exist")
                        .join(".ordinary")
                        .join("bin")
                        .join("exiftool")
                        .join("exiftool");

                    if !exiftool_path.exists() {
                        bail!(
                            "`exiftool` not installed for `ordinary` — for install, run `ordinary doctor --fix exiftool`"
                        );
                    }

                    let output = Command::new(exiftool_path).args(args).output()?;
                    print_output(&output)?;
                }
            },
            Self::QrCode {
                url,
                out,
                fmt,
                dark,
            } => {
                let qr: QrCode = QrCode::encode_text(url, QrCodeEcc::Medium)?;

                if let Some(out) = out
                    && let Some(parent) = out.parent()
                {
                    let fmt = fmt.to_owned().unwrap_or(QrCodeFmt::Svg);

                    match fmt {
                        QrCodeFmt::Svg => {
                            let svg = to_svg_string(&qr, *dark)?;
                            fs_err::create_dir_all(parent)?;
                            fs_err::write(out, svg.as_bytes())?;
                        }
                    }
                } else {
                    let border: i32 = 1;
                    for y in -border..qr.size() + border {
                        for x in -border..qr.size() + border {
                            let c: char = if qr.get_module(x, y) { 'â–ˆ' } else { ' ' };
                            print!("{c}{c}");
                        }
                        println!();
                    }
                }
            }
        }

        Ok(())
    }
}

fn print_output(output: &Output) -> anyhow::Result<()> {
    if output.status.success() {
        for line in std::str::from_utf8(&output.stderr)?.split('\n') {
            if !line.trim().is_empty() {
                tracing::info!(stderr = %line);
            }
        }
        println!("{}", std::str::from_utf8(&output.stdout)?);
    } else {
        for line in std::str::from_utf8(&output.stderr)?.split('\n') {
            if !line.trim().is_empty() {
                tracing::error!(stderr = %line);
            }
        }
        println!("{}", std::str::from_utf8(&output.stdout)?);
    }
    Ok(())
}

#[allow(clippy::redundant_else, clippy::cast_precision_loss)]
fn minify(
    path: &Path,
    out: Option<&Path>,
    in_place: bool,
    minify: fn(file_str: &str) -> anyhow::Result<String>,
) -> anyhow::Result<()> {
    let mut path = path.to_path_buf();

    if path.is_dir() {
        bail!("doesn't yet work for directories")
    } else {
        let file_str = fs_err::read_to_string(&path)?;
        let minified = minify(&file_str)?;

        if let Some(out) = out {
            if let Some(parent) = out.parent() {
                fs_err::create_dir_all(parent)?;
            }

            fs_err::write(out, minified.as_bytes())?;
        } else {
            if !in_place {
                let ext = if let Some(ext) = path.extension() {
                    format!("min.{}", ext.display())
                } else {
                    "min".to_string()
                };

                path.set_extension(ext);
            }

            let mut file = File::create(path)?;
            file.write_all(minified.as_bytes())?;
            file.flush()?;
        }

        tracing::info!(
            size.source = %bytesize::ByteSize(file_str.len() as u64).display().si_short(),
            size.minified = %bytesize::ByteSize(minified.len() as u64).display().si_short(),
            size.reduction = %PercentageDisplay(((file_str.len() as f64 - minified.len() as f64)
                                / file_str.len() as f64)
                                * 100.0),
        );
    }

    Ok(())
}

fn to_svg_string(qr: &QrCode, dark: bool) -> anyhow::Result<String> {
    let mut result = String::new();

    let dimension = qr.size();

    let background_color = if dark { "#000000" } else { "#FFFFFF" };
    let code_color = if dark { "#FFFFFF" } else { "#000000" };

    writeln!(
        result,
        "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 {dimension} {dimension}\" stroke=\"none\">"
    )?;
    writeln!(
        result,
        "\t<rect width=\"100%\" height=\"100%\" fill=\"{background_color}\"/>\n"
    )?;
    result += "\t<path d=\"";
    for y in 0..dimension {
        for x in 0..dimension {
            if qr.get_module(x, y) {
                if x != 0 || y != 0 {
                    result += " ";
                }
                write!(result, "M{x},{y}h1v1h-1z")?;
            }
        }
    }
    writeln!(result, "\" fill=\"{code_color}\"/>\n</svg>")?;

    Ok(result)
}