logoxide-cli 0.1.1

lx, logoxide's command line: Bibles, commentaries, lexicons, books, and media as versioned packages
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
/*!
Registries of archives: `lx registry init` sets one up, and `lx publish` adds a package's release
to it (its archive, and its entry in the registry's `catalog.toml`). A registry is hosted as:

- **A folder**: `catalog.toml` and each archive beside it (`romans/romans-1.0.0.tar.gz`). Any
  static host serves it (a web server, GitHub Pages, Netlify, an S3 bucket), and on disk it's a
  registry too
- **GitHub Releases** (`github:owner/repo`): each archive is a release's file, and the catalog is
  the file of a release named `index`, so the repository itself stays empty however many books it
  publishes. `gh` (logged in) does the work
*/

use std::path::{Path, PathBuf};

use logoxide::{
    LogoxideError, MemoryStorage, Storage,
    catalog::CatalogRelease,
    git::{Fetcher, GitRef},
    publish,
    storage::write_atomic,
};

/// Where a registry's releases go
pub enum Host {
    Folder(PathBuf),
    /// `owner/repo`
    GitHub(String),
}

impl Host {
    pub fn parse(text: &str) -> Host {
        match text.strip_prefix("github:") {
            Some(repo) => Host::GitHub(repo.trim_matches('/').to_string()),
            None => Host::Folder(PathBuf::from(text)),
        }
    }

    /// Where its catalog is read from, for `lx catalog add`
    fn catalog_location(&self) -> String {
        match self {
            Host::Folder(dir) => dir.join(CATALOG).display().to_string(),
            Host::GitHub(repo) => {
                format!("https://github.com/{repo}/releases/download/{INDEX}/{CATALOG}")
            }
        }
    }

    /// A name for its catalog: the folder's or the repository's
    fn default_name(&self) -> String {
        let name = match self {
            Host::Folder(dir) => (dir.canonicalize().ok())
                .and_then(|d| d.file_name().map(|n| n.to_string_lossy().into_owned())),
            Host::GitHub(repo) => repo.rsplit('/').next().map(String::from),
        };
        name.unwrap_or_else(|| String::from("registry"))
    }
}

const CATALOG: &str = "catalog.toml";
/// The GitHub release whose file is the catalog
const INDEX: &str = "index";

fn io(path: &Path, e: std::io::Error) -> LogoxideError {
    LogoxideError::io(&path.display().to_string(), e)
}

/// Writes a file whole or not at all (a catalog that's half written is a broken registry)
fn write(path: &Path, bytes: impl AsRef<[u8]>) -> logoxide::Result<()> {
    write_atomic(path, bytes.as_ref()).map_err(|e| io(path, e))
}

/// Runs `gh`; what it printed
fn gh(args: &[&str]) -> logoxide::Result<String> {
    let output = std::process::Command::new("gh")
        .args(args)
        .output()
        .map_err(|e| {
            LogoxideError::network(
                "gh",
                format!("couldn't run gh (https://cli.github.com, then gh auth login): {e}"),
            )
        })?;
    if !output.status.success() {
        return Err(LogoxideError::network(
            &format!("gh {}", args.join(" ")),
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

fn scratch(what: &str) -> logoxide::Result<PathBuf> {
    let dir = std::env::temp_dir().join(format!("lx-{what}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).map_err(|e| io(&dir, e))?;
    Ok(dir)
}

const README: &str = "# A logoxide registry

`catalog.toml` lists each package and its releases; each release is an archive beside it
(`<id>/<id>-<version>.tar.gz`), with its SHA-256. `lx publish --to <this folder>` adds one.

Serve this folder from any static host (a web server, GitHub Pages, Netlify, an S3 bucket), then:

```sh
lx catalog add https://example.org/<where>/catalog.toml --name <name>
lx add <name>:<id>
```

On this computer it's a registry already: `lx catalog add <this folder>/catalog.toml --name <name>`.
";

/// `lx registry init`: an empty registry, ready to publish to; how to use it
pub fn init(host: &Host, name: Option<&str>, private: bool) -> logoxide::Result<()> {
    let name = name.map_or_else(|| host.default_name(), String::from);
    let catalog =
        format!("# A logoxide registry: lx publish --to … adds releases\nname = \"{name}\"\n");
    match host {
        Host::Folder(dir) => {
            std::fs::create_dir_all(dir).map_err(|e| io(dir, e))?;
            let path = dir.join(CATALOG);
            if path.exists() {
                outln!("{} is a registry already", dir.display());
            } else {
                write(&path, &catalog)?;
                let readme = dir.join("README.md");
                if !readme.exists() {
                    write(&readme, README)?;
                }
                outln!("Made the registry {name} in {}", dir.display());
            }
            outln!(
                "Publish to it:  lx publish <package folder> --to {}\n\
                 Use it here:    lx catalog add {} --name {name}\n\
                 Host it:        serve the folder from any static host, then\n                \
                 lx catalog add https://<where>/{CATALOG} --name {name}",
                dir.display(),
                host.catalog_location(),
            );
        }
        Host::GitHub(repo) => {
            if gh(&["repo", "view", repo, "--json", "name"]).is_err() {
                let visibility = if private { "--private" } else { "--public" };
                gh(&[
                    "repo",
                    "create",
                    repo,
                    visibility,
                    "--add-readme",
                    "--description",
                    "A logoxide registry: each package release is a GitHub release",
                ])?;
                outln!("Made the repository github.com/{repo}");
            }
            if gh(&["release", "view", INDEX, "-R", repo]).is_ok() {
                outln!("github.com/{repo} is a registry already");
            } else {
                let dir = scratch("registry")?;
                let path = dir.join(CATALOG);
                write(&path, &catalog)?;
                gh(&[
                    "release",
                    "create",
                    INDEX,
                    &path.display().to_string(),
                    "-R",
                    repo,
                    "--title",
                    "Registry index",
                    "--notes",
                    "This release's catalog.toml lists every package and release here (lx publish updates it).",
                    "--latest=false",
                ])?;
                let _ = std::fs::remove_dir_all(&dir);
                outln!("Made the registry {name} in github.com/{repo}'s releases");
            }
            outln!(
                "Publish to it:  lx publish <package folder> --to github:{repo}\n\
                 Use it:         lx catalog add {} --name {name}",
                host.catalog_location()
            );
        }
    }
    Ok(())
}

/// A package's newest release, read from git: its archive and what's needed to list it
struct Packed {
    info: logoxide::manifest::Package,
    bytes: Vec<u8>,
    checksum: String,
    /// The package's folder in its repository (`books/romans`), if not at its root
    path: Option<String>,
}

/**
The package in `dir` at its release tag for the version its `logoxide.toml` gives (`v1.0.0`, or
`<folder>/v1.0.0` in a folder of its repository): its declared files, packed
*/
fn pack(dir: &Path, git: &logoxide::git::GitCli) -> logoxide::Result<Packed> {
    let (root, prefix) = git.package_in(dir)?;
    // Never through a link: what's packed comes from the release's commit, which has none
    let folder = logoxide::FsStorage::new(dir).no_symlinks();
    let manifest = logoxide::Manifest::parse(&folder.read_string(logoxide::manifest::MANIFEST)?)?;
    let version = (manifest.package.as_ref())
        .map(|p| p.version.clone())
        .ok_or_else(|| LogoxideError::Manifest(format!("{}: no [package]", dir.display())))?;
    let tag = logoxide::release::tag_for(&prefix, &version);
    if !git.local_versions(dir)?.iter().any(|(_, t)| *t == tag) {
        return Err(LogoxideError::Resolve(format!(
            "{} has no release {tag}: lx release first (a published version is a release)",
            dir.display()
        )));
    }
    let all = MemoryStorage::new();
    git.fetch(&root.display().to_string(), &GitRef::Tag(tag), &all)?;
    let files = logoxide::package::only_declared(&logoxide::release::within(&all, &prefix)?)?;
    let info = logoxide::Manifest::parse(&files.read_string(logoxide::manifest::MANIFEST)?)?
        .package
        .ok_or_else(|| LogoxideError::Manifest(String::from("no [package] at its release")))?;
    Ok(Packed {
        bytes: publish::pack(&files, &info)?,
        checksum: logoxide::package::checksum(&files)?,
        info,
        path: Some(prefix.trim_end_matches('/').to_string()).filter(|p| !p.is_empty()),
    })
}

/**
Says what may keep a package from being shared ([`logoxide::license::assess`]) before publishing
it: a warning for each, and for a serious one (its rights say it isn't redistributable) a loud
one and a question, the owner's D8 (`yes` answers it; elsewhere than a terminal, it must).
Licenses are shown, never enforced: whether to publish is the user's. False when they decline
*/
fn confirm_license(info: &logoxide::manifest::Package, yes: bool) -> logoxide::Result<bool> {
    let concerns = logoxide::license::assess(info);
    for concern in concerns.iter().filter(|c| !c.is_serious()) {
        errln!("warning: {}", concern.message);
    }
    let Some(serious) = concerns.iter().find(|c| c.is_serious()) else {
        return Ok(true);
    };
    errln!("");
    errln!("WARNING: {}", serious.message);
    errln!("");
    if yes {
        return Ok(true);
    }
    use std::io::IsTerminal;
    if !std::io::stdin().is_terminal() {
        return Err(LogoxideError::Catalog(format!(
            "{} {} wasn't published: pass --yes to publish it anyway",
            info.id, info.version
        )));
    }
    eprint!("Publish {} {} anyway? [y/N] ", info.id, info.version);
    let mut answer = String::new();
    let _ = std::io::stdin().read_line(&mut answer);
    let publish = matches!(answer.trim(), "y" | "Y" | "yes");
    if !publish {
        outln!("{} {}: not published", info.id, info.version);
    }
    Ok(publish)
}

/// `lx publish`: a package's release (its archive) added to a registry
pub fn publish(
    dir: &Path,
    host: &Host,
    git: &logoxide::git::GitCli,
    yes: bool,
) -> logoxide::Result<()> {
    let packed = pack(dir, git)?;
    let info = &packed.info;
    if !confirm_license(info, yes)? {
        return Ok(());
    }
    let file = publish::archive_name(info);
    let sha256 = publish::sha256(&packed.bytes);
    let release = |url: String| CatalogRelease {
        version: info.version.to_string(),
        url,
        mirrors: vec![],
        sha256: sha256.clone(),
        checksum: Some(packed.checksum.clone()),
        size: Some(packed.bytes.len() as u64),
        yanked: false,
    };
    let label = format!("{} {}", info.id, info.version);
    let size = packed.bytes.len() as f64 / 1_000_000.0;
    match host {
        Host::Folder(registry) => {
            let catalog = registry.join(CATALOG);
            let text = std::fs::read_to_string(&catalog).map_err(|_| {
                LogoxideError::Catalog(format!(
                    "{} isn't a registry (lx registry init {})",
                    registry.display(),
                    registry.display()
                ))
            })?;
            let relative = format!("{}/{file}", info.id);
            let release = release(relative.clone());
            let Some(updated) = publish::add_release(
                Some(&text),
                &host.default_name(),
                info,
                packed.path.as_deref(),
                &release,
            )?
            else {
                outln!("{label} is published there already");
                return Ok(());
            };
            let archive = registry.join(&relative);
            std::fs::create_dir_all(registry.join(&info.id)).map_err(|e| io(registry, e))?;
            write(&archive, &packed.bytes)?;
            write(&catalog, updated)?;
            outln!("Published {label} ({size:.1} MB) to {}", registry.display());
        }
        Host::GitHub(repo) => {
            let work = scratch("publish")?;
            gh(&[
                "release",
                "download",
                INDEX,
                "-R",
                repo,
                "-p",
                CATALOG,
                "-D",
                &work.display().to_string(),
                "--clobber",
            ])
            .map_err(|e| {
                LogoxideError::Catalog(format!(
                    "github.com/{repo} isn't a registry yet (lx registry init github:{repo}): {e}"
                ))
            })?;
            let catalog = work.join(CATALOG);
            let text = std::fs::read_to_string(&catalog).map_err(|e| io(&catalog, e))?;
            let tag = format!("{}-v{}", info.id, info.version);
            let url = format!("https://github.com/{repo}/releases/download/{tag}/{file}");
            let Some(updated) = publish::add_release(
                Some(&text),
                &host.default_name(),
                info,
                packed.path.as_deref(),
                &release(url),
            )?
            else {
                outln!("{label} is published there already");
                return Ok(());
            };
            let archive = work.join(&file);
            write(&archive, &packed.bytes)?;
            let archive = archive.display().to_string();
            // A release left by a publish that stopped halfway gets its file again
            if gh(&["release", "view", &tag, "-R", repo]).is_ok() {
                gh(&["release", "upload", &tag, &archive, "-R", repo, "--clobber"])?;
            } else {
                gh(&[
                    "release",
                    "create",
                    &tag,
                    &archive,
                    "-R",
                    repo,
                    "--title",
                    &format!("{} {}", info.name, info.version),
                    "--notes",
                    &format!("{label}: {sha256}"),
                    "--latest=false",
                ])?;
            }
            write(&catalog, updated)?;
            gh(&[
                "release",
                "upload",
                INDEX,
                &catalog.display().to_string(),
                "-R",
                repo,
                "--clobber",
            ])?;
            let _ = std::fs::remove_dir_all(&work);
            outln!("Published {label} ({size:.1} MB) to github.com/{repo}");
        }
    }
    outln!(
        "Readers add it with:  lx catalog add {} --name <name>, then lx add <name>:{}",
        host.catalog_location(),
        packed.path.as_deref().unwrap_or(&info.id)
    );
    Ok(())
}

/**
`lx publish --all`: every package in a folder (its own, and its folders' at any depth, not inside
`.git`) whose version has a release tag, published (each already published is said so); one
without a release is passed over
*/
pub fn publish_all(
    dir: &Path,
    host: &Host,
    git: &logoxide::git::GitCli,
    yes: bool,
) -> logoxide::Result<()> {
    let mut found = vec![];
    let mut pending = vec![dir.to_path_buf()];
    while let Some(folder) = pending.pop() {
        if folder.join(logoxide::manifest::MANIFEST).is_file() {
            found.push(folder.clone());
        }
        let entries = std::fs::read_dir(&folder).map_err(|e| io(&folder, e))?;
        for entry in entries.flatten() {
            let hidden = entry.file_name().to_string_lossy().starts_with('.');
            if !hidden && entry.file_type().is_ok_and(|t| t.is_dir()) {
                pending.push(entry.path());
            }
        }
    }
    found.sort();
    for package in found {
        match publish(&package, host, git, yes) {
            Err(LogoxideError::Resolve(message)) if message.contains("lx release first") => {
                outln!("{}: not released yet, passed over", package.display())
            }
            // A vault's manifest, or a folder that isn't a package
            Err(LogoxideError::Manifest(message)) if message.contains("no [package]") => {}
            result => result?,
        }
    }
    Ok(())
}

/// `lx yank`: a release withdrawn from a registry (new installs pass over it), or put back
pub fn yank(host: &Host, id: &str, version: &str, undo: bool) -> logoxide::Result<()> {
    let what = if undo { "Put back" } else { "Yanked" };
    match host {
        Host::Folder(registry) => {
            let catalog = registry.join(CATALOG);
            let text = std::fs::read_to_string(&catalog).map_err(|e| io(&catalog, e))?;
            let updated = publish::yank(&text, id, version, !undo)?;
            write(&catalog, updated)?;
            outln!("{what} {id} {version} in {}", registry.display());
        }
        Host::GitHub(repo) => {
            let work = scratch("yank")?;
            gh(&[
                "release",
                "download",
                INDEX,
                "-R",
                repo,
                "-p",
                CATALOG,
                "-D",
                &work.display().to_string(),
                "--clobber",
            ])?;
            let catalog = work.join(CATALOG);
            let text = std::fs::read_to_string(&catalog).map_err(|e| io(&catalog, e))?;
            write(&catalog, publish::yank(&text, id, version, !undo)?)?;
            gh(&[
                "release",
                "upload",
                INDEX,
                &catalog.display().to_string(),
                "-R",
                repo,
                "--clobber",
            ])?;
            let _ = std::fs::remove_dir_all(&work);
            outln!("{what} {id} {version} in github.com/{repo}");
        }
    }
    outln!("Lock files that have it still install it; new installs and updates pass over it");
    Ok(())
}