semora-cli 1.1.0

Semora CLI: publish Markdown and HTML, and hear back from the page
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! `.semora`: marks a folder as a Semora project, and where a push came from.
//!
//! The file is TOML meant to be committed:
//!
//! ```toml
//! server = "3f9c0e7a5b1d4e2f8a6c9b0d1e2f3a4b"
//! project = "semora"
//! ```
//!
//! `server` is the id the server gave itself, so the file does not say where the server is.
//! It is only compared with the id of the configured server, never used to reach one: a cloned
//! repository must not be able to send your API key to another host. A file from before ids
//! holds the server's URL; one for the configured server is moved to the id on first use.

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

use anyhow::{Context, bail};
use serde::Deserialize;

use crate::client::Client;
use crate::config::{origin, parse_server};
use crate::local_links::{self, LocalLink};
use crate::{checkout, exit, output, server_id};

pub const FILE: &str = ".semora";

/// A path for messages: without the `\\?\` prefix that `canonicalize` adds on Windows.
pub fn shown(path: &Path) -> String {
    let s = path.display().to_string();
    match s.strip_prefix(r"\\?\") {
        Some(rest) => match rest.strip_prefix(r"UNC\") {
            Some(share) => format!(r"\\{share}"),
            None => rest.to_string(),
        },
        None => s,
    }
}

/// A `.semora` names another server than the one this command uses. Commands add their own
/// way out (push: `--id` or `--new`).
#[derive(Debug)]
pub struct OtherServer(pub String);

impl std::fmt::Display for OtherServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for OtherServer {}

/// What a `.semora` names its server by.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServerRef {
    /// The server's id, trimmed and lowercase.
    Id(String),
    /// A URL from before ids, as an origin.
    Url(String),
}

/// A `.semora` as it is written, before the CLI has asked its server whether the file is for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileLink {
    /// The folder that holds `.semora` (canonical).
    pub root: PathBuf,
    pub server: ServerRef,
    pub slug: String,
}

/// A `.semora` that is for the server this command uses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Link {
    /// The folder that holds `.semora` (canonical).
    pub root: PathBuf,
    /// The origin of the server this command uses.
    pub server: String,
    /// The project id the commands use.
    pub slug: String,
    /// The project id `.semora` names.
    pub file_slug: String,
    /// Set when the file is used for this server through a record on this machine
    /// (`semora project link`), not because it names this server. A new project id then goes in
    /// the record, never in the shared file.
    pub local: Option<Mapped>,
}

/// The record a link is used through, and the config folder that holds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mapped {
    pub config_dir: PathBuf,
    pub record: LocalLink,
}

impl Link {
    pub fn mapped(&self) -> bool {
        self.local.is_some()
    }
}

/// How a `.semora` relates to the server this command uses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Fit {
    /// It names this server's id.
    Ours,
    /// It names this server by URL, from before ids.
    LegacyOurs,
    /// It names another server by URL, this origin.
    LegacyOther(String),
    /// It names another server's id.
    Other,
    /// It names another server, and a record on this machine uses it with this one.
    Mapped(LocalLink),
}

/// The `server` value of a file as local records key it.
pub fn server_value(server: &ServerRef) -> String {
    match server {
        ServerRef::Id(id) | ServerRef::Url(id) => id.clone(),
    }
}

#[derive(Deserialize)]
struct Raw {
    server: Option<String>,
    project: Option<String>,
}

/// `[a-z0-9-]`, 1 to 40 characters, not starting with a dash.
pub fn valid_slug(s: &str) -> bool {
    (1..=40).contains(&s.len())
        && s.bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
        && !s.starts_with('-')
}

/// A project id from a directory name: lowercase it, turn every run of other characters into
/// one `-`, trim `-` from both ends, cut to 40 characters, trim again.
pub fn slug_from(dir_name: &str) -> Option<String> {
    let mut out = String::new();
    for c in dir_name.to_lowercase().chars() {
        if c.is_ascii_lowercase() || c.is_ascii_digit() {
            out.push(c);
        } else if !out.ends_with('-') {
            out.push('-');
        }
    }
    let cut: String = out.trim_matches('-').chars().take(40).collect();
    let slug = cut.trim_matches('-').to_string();
    valid_slug(&slug).then_some(slug)
}

/// The `.semora` in `dir` itself, if there is one.
pub fn read_at(dir: &Path) -> anyhow::Result<Option<FileLink>> {
    let file = dir.join(FILE);
    if !file.is_file() {
        return Ok(None);
    }
    let text =
        std::fs::read_to_string(&file).with_context(|| format!("reading {}", shown(&file)))?;
    let raw: Raw = toml::from_str(&text).with_context(|| format!("parsing {}", shown(&file)))?;
    let server = raw
        .server
        .filter(|s| !s.trim().is_empty())
        .with_context(|| format!("{} needs a `server` line", shown(&file)))?;
    let slug = raw
        .project
        .filter(|s| !s.trim().is_empty())
        .with_context(|| format!("{} needs a `project` line", shown(&file)))?;
    if !valid_slug(&slug) {
        bail!(
            "{}: `{slug}` is not a valid project id (lowercase letters, digits and dashes, up to 40, starting with a letter or digit)",
            shown(&file)
        );
    }
    let server = if server_id::is_id(&server) {
        ServerRef::Id(server_id::normal(&server))
    } else {
        let url =
            parse_server(&server).with_context(|| format!("{}: bad `server`", shown(&file)))?;
        ServerRef::Url(origin(&url))
    };
    Ok(Some(FileLink {
        root: dir.to_path_buf(),
        server,
        slug,
    }))
}

/// The folder to start looking from: the path's folder, or the path itself for a folder.
fn start_dir(full: &Path) -> Option<&Path> {
    if full.is_dir() {
        Some(full)
    } else {
        full.parent()
    }
}

/// Looks for `.semora` in the path's folder and each parent. The nearest file wins. The
/// current directory plays no part. `Err` means a file was found but is unusable.
pub fn find(path: &Path) -> anyhow::Result<Option<FileLink>> {
    let full =
        std::fs::canonicalize(path).with_context(|| format!("cannot read {}", shown(path)))?;
    let mut dir = start_dir(&full);
    while let Some(d) = dir {
        if let Some(link) = read_at(d)? {
            return Ok(Some(link));
        }
        dir = d.parent();
    }
    Ok(None)
}

/// Writes `dir/.semora` naming the server by its id. Returns its path.
pub fn write(dir: &Path, server_id: &str, slug: &str) -> anyhow::Result<PathBuf> {
    let file = dir.join(FILE);
    let text = format!(
        "# Semora project. Commit this file so every checkout publishes to the same place.\nserver = \"{server_id}\"\nproject = \"{slug}\"\n"
    );
    std::fs::write(&file, text).with_context(|| format!("writing {}", shown(&file)))?;
    Ok(file)
}

/// Sets the `key` line (`project` or `server`) of `dir/.semora` to `value`, keeping every other
/// line as it is.
pub fn set_line(dir: &Path, key: &str, value: &str) -> anyhow::Result<()> {
    let file = dir.join(FILE);
    let text =
        std::fs::read_to_string(&file).with_context(|| format!("reading {}", shown(&file)))?;
    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
    let mut found = false;
    let mut lines: Vec<String> = Vec::new();
    for line in text.lines() {
        let is_key = line
            .trim_start()
            .strip_prefix(key)
            .is_some_and(|rest| rest.trim_start().starts_with('='));
        if is_key && !found {
            found = true;
            lines.push(format!("{key} = \"{value}\""));
        } else {
            lines.push(line.to_string());
        }
    }
    if !found {
        bail!("{} has no `{key}` line to update", shown(&file));
    }
    let new_text = lines.join(eol) + eol;
    std::fs::write(&file, &new_text).with_context(|| format!("writing {}", shown(&file)))?;
    // The line must have said what we meant; if not, put the file back.
    let meant = |l: &FileLink| match key {
        "project" => l.slug == value,
        _ => l.server == ServerRef::Id(value.to_string()),
    };
    match read_at(dir) {
        Ok(Some(l)) if meant(&l) => Ok(()),
        _ => {
            std::fs::write(&file, &text).ok();
            bail!("could not update the `{key}` line in {}", shown(&file))
        }
    }
}

/// The project has the id `slug` on the server now. Rewrites `.semora` (or, for a link used
/// through a record on this machine, the record) and the checkout record to it and says so. Any
/// other answer leaves the link as it is.
pub fn adopt(link: Link, slug: &str) -> Link {
    if slug == link.slug || !valid_slug(slug) {
        return link;
    }
    if let Some(m) = &link.local {
        let record = LocalLink {
            project: slug.to_string(),
            ..m.record.clone()
        };
        if let Err(e) = local_links::save(&m.config_dir, record.clone()) {
            output::warn(format!(
                "project `{}` is now `{slug}` on {}, but this machine's link could not be updated: {e:#}. Run `semora project link --project {slug}`.",
                link.slug, link.server
            ));
            return link;
        }
        let moved = Link {
            slug: slug.to_string(),
            local: Some(Mapped {
                config_dir: m.config_dir.clone(),
                record,
            }),
            ..link.clone()
        };
        if let Err(e) = checkout::move_to(&link, &moved) {
            output::warn(format!(
                "could not carry this folder's record over to the new id: {e:#}. Run `semora pull` to start it again."
            ));
        }
        output::warn(format!(
            "project '{}' is now '{slug}' on {}. Updated this machine's link.",
            link.slug, link.server
        ));
        return moved;
    }
    if let Err(e) = set_line(&link.root, "project", slug) {
        output::warn(format!(
            "project `{}` is now `{slug}` on {}, but {e:#}. Change the `project` line yourself.",
            link.slug, link.server
        ));
        return link;
    }
    let moved = Link {
        slug: slug.to_string(),
        file_slug: slug.to_string(),
        ..link.clone()
    };
    if let Err(e) = checkout::move_to(&link, &moved) {
        output::warn(format!(
            "could not carry this folder's record over to the new id: {e:#}. Run `semora pull` to start it again."
        ));
    }
    output::warn(format!(
        "project `{}` is now `{slug}` on {}. Updated {}; commit it so other checkouts follow.",
        link.slug,
        link.server,
        shown(&link.root.join(FILE))
    ));
    moved
}

/// The project as the server knows it now. An owner can give a project a new id; while the old
/// one is an alias the server answers it with the new one. When the old id is gone, a document
/// this folder pulled or pushed still says which project it is in. Errors other than a missing
/// project are left for the command itself to report.
pub async fn follow(client: &Client, link: Link) -> anyhow::Result<Link> {
    let link = match client.project(&link.slug).await {
        Ok(info) => adopt(link, &info.slug),
        Err(e) if exit::is_not_found(&e) => recover(client, link).await,
        Err(_) => link,
    };
    keep_record(client, &link).await;
    Ok(link)
}

/// Another checkout followed the project to a new id and the new `.semora` came in with git,
/// so this folder's record is still under the old id. When a document in it is in this
/// project now, the record is kept under the new id; without it, pushes could no longer tell
/// a stale copy, and pull could no longer tell local changes from the server's.
async fn keep_record(client: &Client, link: &Link) {
    for id in checkout::ids_under_other_id(link)
        .into_iter()
        .take(RECOVER_TRIES)
    {
        let Ok(d) = client.doc(&id).await else {
            continue;
        };
        if d.summary.project.as_deref() == Some(link.slug.as_str())
            && let Err(e) = checkout::relabel(link)
        {
            output::warn(format!(
                "could not carry this folder's record over to project `{}`: {e:#}",
                link.slug
            ));
        }
        // The first document still there decides: in another project, the record is not ours.
        return;
    }
}

/// How many recorded documents to ask about before giving up.
const RECOVER_TRIES: usize = 3;

/// The old id is unknown to the server. Asks for documents this folder recorded and takes the
/// project the first one that is still there is in.
async fn recover(client: &Client, link: Link) -> Link {
    let Ok(records) = checkout::load(&link) else {
        return link;
    };
    let mut ids: Vec<String> = records.into_values().map(|r| r.id).collect();
    ids.dedup();
    for id in ids.into_iter().take(RECOVER_TRIES) {
        if let Ok(d) = client.doc(&id).await
            && let Some(project) = d.summary.project
        {
            return adopt(link, &project);
        }
    }
    link
}

/// How `file` relates to the server `client` uses. An id that differs from the cached one is
/// checked once more with the server, in case the address now leads to another server. A file
/// for another server may still be used here through a record on this machine.
pub async fn fit(client: &Client, config_dir: &Path, file: &FileLink) -> anyhow::Result<Fit> {
    let ours = match &file.server {
        ServerRef::Id(id) => {
            *id == server_id::of(client, config_dir, false).await?
                || *id == server_id::of(client, config_dir, true).await?
        }
        ServerRef::Url(u) if *u == client.origin() => return Ok(Fit::LegacyOurs),
        ServerRef::Url(_) => false,
    };
    if ours {
        return Ok(Fit::Ours);
    }
    if let Some(record) = local_links::find(config_dir, &server_value(&file.server), &file.slug)? {
        let id = server_id::of(client, config_dir, false).await?;
        if record.server_id == id
            || record.server_id == server_id::of(client, config_dir, true).await?
        {
            return Ok(Fit::Mapped(record));
        }
    }
    Ok(match &file.server {
        ServerRef::Url(u) => Fit::LegacyOther(u.clone()),
        ServerRef::Id(_) => Fit::Other,
    })
}

/// `file` as a link for the server `client` uses, or the error that says why it is not and what
/// to do. Nothing is sent for the project before this answers.
pub async fn resolve(client: &Client, config_dir: &Path, file: FileLink) -> anyhow::Result<Link> {
    let path = shown(&file.root.join(FILE));
    let have = client.origin();
    let mut local = None;
    let mut slug = file.slug.clone();
    match fit(client, config_dir, &file).await? {
        Fit::Ours => drop_shadowed(client, config_dir, &file, &path).await,
        Fit::LegacyOurs => {
            // The id goes into a committed file, so it is asked for, not taken from the cache.
            let id = server_id::of(client, config_dir, true).await?;
            match set_line(&file.root, "server", &id) {
                Ok(()) => output::warn(format!(
                    "{path} now names its server by id instead of address. Commit it. Older commits still hold the address."
                )),
                Err(e) => output::warn(format!(
                    "could not update {path}: {e:#}. Change the `server` line to \"{id}\" yourself."
                )),
            }
        }
        Fit::Mapped(record) => {
            slug = record.project.clone();
            local = Some(Mapped {
                config_dir: config_dir.to_path_buf(),
                record,
            });
        }
        Fit::LegacyOther(theirs) => {
            return Err(OtherServer(format!(
                "{path} is for {theirs}, but this command uses {have}. To use that server, set SEMORA_URL or pass --server {theirs}."
            ))
            .into());
        }
        Fit::Other => return Err(OtherServer(other_server_message(&path, &have)).into()),
    }
    Ok(Link {
        root: file.root,
        server: have,
        slug,
        file_slug: file.slug,
        local,
    })
}

/// The file names this server now, so records on this machine that sent its project here from
/// another server are no longer used. They are dropped; one that used another project id is
/// worth a word, since the file's id is used from now on.
async fn drop_shadowed(client: &Client, config_dir: &Path, file: &FileLink, path: &str) {
    let Ok(id) = server_id::of(client, config_dir, false).await else {
        return;
    };
    match local_links::remove_shadowed(config_dir, &id, &file.slug, &file.root) {
        Ok(gone) => {
            for g in gone.iter().filter(|g| g.project != file.slug) {
                output::warn(format!(
                    "{path} now names this server, so this machine's link to project '{}' is dropped; the file's project '{}' is used.",
                    g.project, file.slug
                ));
            }
        }
        Err(e) => output::warn(format!("{e:#}")),
    }
}

/// The file names another server's id. It can't say which server that is, so the message names
/// only this one and the ways out.
fn other_server_message(path: &str, have: &str) -> String {
    format!(
        "{path} is for another Semora server than the one this CLI uses ({have}).
The file does not say which server it is. Either:
  - log in to the project's server: semora login --server ADDRESS (ask whoever set up the project)
  - use your server for this project on this machine only: semora project link
    (your documents drift from everyone else's; nobody else sees them)
  - point .semora at your server: semora project link --rewrite
    (once you commit it, every other checkout stops working until it does the same)"
    )
}

impl Link {
    /// The pushed path relative to the project root, joined with `/`.
    pub fn relative_path(&self, target: &Path) -> anyhow::Result<String> {
        let full = std::fs::canonicalize(target)
            .with_context(|| format!("cannot read {}", shown(target)))?;
        let rel = full.strip_prefix(&self.root).with_context(|| {
            format!(
                "{} is not inside the project at {}",
                shown(&full),
                shown(&self.root)
            )
        })?;
        let mut parts = Vec::new();
        for c in rel.components() {
            let s = c.as_os_str().to_str().with_context(|| {
                format!(
                    "{} isn't valid Unicode, so it can't be a project path",
                    shown(&full)
                )
            })?;
            parts.push(s.to_string());
        }
        if parts.is_empty() {
            bail!(
                "{} is here: push a file or a folder inside this project, not the project root.",
                shown(&self.root.join(FILE))
            );
        }
        Ok(parts.join("/"))
    }
}

/// The branch of the git checkout the path is in, read from `HEAD` (no `git` process).
/// A worktree's `.git` is a file that names its git folder; a relative name is relative to
/// the folder that holds that file. The walk starts from `std::path::absolute`, not
/// `canonicalize`: on Windows a canonical path is a `\\?\` path, and those do not resolve `..`
/// or `/`, so the relative name is joined and cleaned up lexically instead.
pub fn git_branch(path: &Path) -> Option<String> {
    let full = std::path::absolute(path).ok()?;
    let mut dir = start_dir(&full);
    while let Some(d) = dir {
        let dot = d.join(".git");
        if dot.is_dir() {
            return branch_in(&dot);
        }
        if dot.is_file() {
            let text = std::fs::read_to_string(&dot).ok()?;
            let target = text
                .lines()
                .find_map(|l| l.trim().strip_prefix("gitdir:"))?
                .trim();
            let gitdir = if Path::new(target).is_absolute() {
                PathBuf::from(target)
            } else {
                lexical(&d.join(target))
            };
            return branch_in(&gitdir);
        }
        dir = d.parent();
    }
    None
}

/// `.` and `..` resolved without touching the file system.
fn lexical(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for c in path.components() {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                if !out.pop() {
                    out.push("..");
                }
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

fn branch_in(gitdir: &Path) -> Option<String> {
    let head = std::fs::read_to_string(gitdir.join("HEAD")).ok()?;
    head.trim()
        .strip_prefix("ref: refs/heads/")
        .map(str::to_string)
        .filter(|b| !b.is_empty())
}

/// Where a push came from: `machine · branch`, or just the machine.
pub fn origin_for(path: &Path) -> String {
    let machine = crate::commands::login::hostname();
    match git_branch(path) {
        Some(b) => format!("{machine} \u{b7} {b}"),
        None => machine,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn dir() -> tempfile::TempDir {
        tempfile::tempdir().unwrap()
    }

    /// The link a command gets for a file that is for its server.
    fn linked(f: FileLink) -> Link {
        Link {
            root: f.root,
            server: "https://a.example.com".into(),
            slug: f.slug.clone(),
            file_slug: f.slug,
            local: None,
        }
    }

    fn put(root: &Path, rel: &str, text: &str) -> PathBuf {
        let p = root.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(&p, text).unwrap();
        p
    }

    #[test]
    fn slugs_follow_the_rule() {
        let (x40, x41) = ("x".repeat(40), "x".repeat(41));
        for ok in ["semora", "a", "9-a", x40.as_str()] {
            assert!(valid_slug(ok), "{ok}");
        }
        for bad in ["", "Semora", "-x", "a b", x41.as_str()] {
            assert!(!valid_slug(bad), "{bad}");
        }
    }

    #[test]
    fn a_slug_is_made_from_a_directory_name() {
        assert_eq!(slug_from("My Docs_v2").as_deref(), Some("my-docs-v2"));
        assert_eq!(slug_from(".tmpAbC123").as_deref(), Some("tmpabc123"));
        assert_eq!(slug_from("--a--b--").as_deref(), Some("a-b"));
        assert_eq!(slug_from("semora").as_deref(), Some("semora"));
        assert_eq!(slug_from(&"a".repeat(50)).unwrap().len(), 40);
        let a39 = "a".repeat(39);
        assert_eq!(
            slug_from(&format!("{a39}-b")).as_deref(),
            Some(a39.as_str()),
            "no dash left at the cut"
        );
        assert_eq!(slug_from("___"), None);
        assert_eq!(slug_from(""), None);
    }

    #[test]
    fn dot_semora_is_parsed_and_checked() {
        let d = dir();
        put(
            d.path(),
            ".semora",
            "# note\nserver = \"https://Semora.example.com/\"\nproject = \"semora\"\nextra = 1\n",
        );
        let link = read_at(d.path()).unwrap().unwrap();
        assert_eq!(link.slug, "semora");
        assert_eq!(
            link.server,
            ServerRef::Url("https://semora.example.com".into()),
            "the origin, whatever the spelling"
        );
        put(
            d.path(),
            ".semora",
            "server = \" 3F9C0E7A5B1D4E2F8A6C9B0D1E2F3A4B \"\nproject = \"semora\"\n",
        );
        assert_eq!(
            read_at(d.path()).unwrap().unwrap().server,
            ServerRef::Id("3f9c0e7a5b1d4e2f8a6c9b0d1e2f3a4b".into()),
            "an id, normalized"
        );

        for (text, why) in [
            ("project = \"x\"\n", "server"),
            ("server = \"https://a.example.com\"\n", "project"),
            (
                "server = \"https://a.example.com\"\nproject = \"Bad Id\"\n",
                "valid project id",
            ),
            ("server = \n", "parsing"),
        ] {
            put(d.path(), ".semora", text);
            let err = read_at(d.path()).unwrap_err().to_string();
            assert!(
                err.contains(why) && err.contains(".semora"),
                "{text:?} -> {err}"
            );
        }
        std::fs::remove_file(d.path().join(".semora")).unwrap();
        assert_eq!(read_at(d.path()).unwrap(), None);
    }

    #[test]
    fn find_walks_up_from_the_path_and_the_nearest_file_wins() {
        let d = dir();
        put(
            d.path(),
            ".semora",
            "server = \"https://a.example.com\"\nproject = \"outer\"\n",
        );
        put(
            d.path(),
            "inner/.semora",
            "server = \"https://a.example.com\"\nproject = \"inner\"\n",
        );
        let file = put(d.path(), "docs/deep/x.md", "# x");
        put(d.path(), "inner/y.md", "# y");
        assert_eq!(find(&file).unwrap().unwrap().slug, "outer");
        assert_eq!(
            find(&d.path().join("docs")).unwrap().unwrap().slug,
            "outer",
            "a folder"
        );
        assert_eq!(
            find(&d.path().join("inner/y.md")).unwrap().unwrap().slug,
            "inner"
        );
        assert_eq!(
            find(&d.path().join("inner")).unwrap().unwrap().slug,
            "inner",
            "the folder's own file"
        );
        let lonely = tempfile::tempdir().unwrap();
        let f = put(lonely.path(), "z.md", "# z");
        assert_eq!(find(&f).unwrap(), None);
    }

    #[test]
    fn the_key_path_is_relative_with_forward_slashes() {
        let d = dir();
        put(
            d.path(),
            ".semora",
            "server = \"https://a.example.com\"\nproject = \"p\"\n",
        );
        let file = put(d.path(), "docs/deep/x.md", "# x");
        let link = linked(find(&file).unwrap().unwrap());
        assert_eq!(link.relative_path(&file).unwrap(), "docs/deep/x.md");
        assert_eq!(link.relative_path(&d.path().join("docs")).unwrap(), "docs");
        let err = link.relative_path(d.path()).unwrap_err().to_string();
        assert!(err.contains("not the project root"), "{err}");
    }

    #[test]
    fn the_message_for_another_servers_id_names_only_this_one_and_the_ways_out() {
        let m = other_server_message("/r/.semora", "https://mine.example.com");
        for part in [
            "/r/.semora",
            "https://mine.example.com",
            "semora login --server ADDRESS",
            "semora project link",
            "semora project link --rewrite",
        ] {
            assert!(m.contains(part), "{part}: {m}");
        }
        assert!(
            !m.contains("--id") && !m.contains("--new"),
            "push flags are push's to mention, not every command's: {m}"
        );
    }

    #[test]
    fn write_makes_a_file_that_reads_back() {
        let d = dir();
        let id = "3f9c0e7a5b1d4e2f8a6c9b0d1e2f3a4b";
        let path = write(d.path(), id, "semora").unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.starts_with("# Semora project."), "{text}");
        let link = read_at(d.path()).unwrap().unwrap();
        assert_eq!(
            (link.server, link.slug.as_str()),
            (ServerRef::Id(id.into()), "semora")
        );
    }

    #[test]
    fn paths_in_messages_lose_the_windows_verbatim_prefix() {
        assert_eq!(
            shown(Path::new(r"\\?\C:\Development\x\.semora")),
            r"C:\Development\x\.semora"
        );
        assert_eq!(shown(Path::new(r"\\?\UNC\nas\share\x")), r"\\nas\share\x");
        assert_eq!(shown(Path::new("/home/a/x")), "/home/a/x");
    }

    #[test]
    fn dots_are_resolved_without_the_file_system() {
        assert_eq!(lexical(Path::new("/a/b/../c/./d")), PathBuf::from("/a/c/d"));
        assert_eq!(lexical(Path::new("a/../../b")), PathBuf::from("../b"));
    }

    #[test]
    fn the_branch_comes_from_head() {
        let d = dir();
        put(d.path(), ".git/HEAD", "ref: refs/heads/feat/projects\n");
        let file = put(d.path(), "docs/x.md", "# x");
        assert_eq!(git_branch(&file).as_deref(), Some("feat/projects"));
        put(
            d.path(),
            ".git/HEAD",
            "0123456789abcdef0123456789abcdef01234567\n",
        );
        assert_eq!(git_branch(&file), None, "a detached HEAD has no branch");
    }

    #[test]
    fn a_worktree_points_at_its_git_folder_absolute_or_relative() {
        let d = dir();
        let main = put(
            d.path(),
            "main/.git/worktrees/wt/HEAD",
            "ref: refs/heads/feat/wt\n",
        );
        let abs = main.parent().unwrap().to_string_lossy().replace('\\', "/");
        put(d.path(), "abs/.git", &format!("gitdir: {abs}\n"));
        let file = put(d.path(), "abs/x.md", "# x");
        assert_eq!(
            git_branch(&file).as_deref(),
            Some("feat/wt"),
            "absolute gitdir"
        );
        // Relative to the folder that holds the `.git` file, not to the current directory.
        put(d.path(), "rel/.git", "gitdir: ../main/.git/worktrees/wt\n");
        let file = put(d.path(), "rel/x.md", "# x");
        assert_eq!(
            git_branch(&file).as_deref(),
            Some("feat/wt"),
            "relative gitdir"
        );
    }

    #[test]
    fn a_verbatim_path_still_reads_a_relative_gitdir() {
        // `watch` passes a canonical path; on Windows that is a `\\?\` path, where `/` is not a
        // separator, so a relative `gitdir` must not be joined onto it as it is.
        let d = dir();
        put(
            d.path(),
            "main/.git/worktrees/wt/HEAD",
            "ref: refs/heads/feat/wt\n",
        );
        put(d.path(), "rel/.git", "gitdir: ../main/.git/worktrees/wt\n");
        let file = put(d.path(), "rel/x.md", "# x");
        let canonical = std::fs::canonicalize(&file).unwrap();
        if cfg!(windows) {
            assert!(
                canonical.to_string_lossy().starts_with(r"\\?\"),
                "{canonical:?}"
            );
        }
        assert_eq!(git_branch(&canonical).as_deref(), Some("feat/wt"));
    }

    #[test]
    fn origin_is_the_machine_and_the_branch_when_there_is_one() {
        let d = dir();
        let file = put(d.path(), "x.md", "# x");
        let machine = origin_for(&file);
        assert!(!machine.contains('\u{b7}'), "no branch: {machine}");
        put(d.path(), ".git/HEAD", "ref: refs/heads/main\n");
        let with = origin_for(&file);
        assert_eq!(with, format!("{machine} \u{b7} main"));
    }
}