furet 0.3.0

Postgres and ClickHouse per repo: tunnels, read-only remotes, rows you can follow, for you and your agents
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
mod config;
mod conn;
mod detect;
mod engine;
mod panel;
mod picker;
mod query;
mod store;
mod tunnel;
mod update;

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand, ValueEnum};
use config::{Entry, File, Origin, Scope, tilde};
use conn::Resolved;
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use toml_edit::DocumentMut;
use tunnel::Tunnel;

const SKILL: &str = include_str!("skill.md");
const ICON: &str = include_str!("../assets/herdr-icon.svg");

/// Database connections scoped to the repo you're in, kept outside it.
///
/// Run `furet` to pick a connection, `furet <name>` to open one in its client.
/// Secrets are read when needed (env, .env, a command); tunnels start and stop on their own;
/// anything that isn't local opens read-only unless you pass -w.
#[derive(Parser)]
#[command(
    name = "furet",
    version,
    args_conflicts_with_subcommands = true,
    after_help = "Are you an AI agent? Run `furet --skill` to learn how to query the user's databases."
)]
struct Cli {
    /// Print the guide for AI agents
    #[arg(long, exclusive = true)]
    skill: bool,

    /// Connection to open (default: pick one)
    name: Option<String>,

    /// Allow writes on a connection that is read-only by default
    #[arg(short, long)]
    write: bool,

    #[command(subcommand)]
    cmd: Option<Cmd>,
}

#[derive(Subcommand)]
enum Cmd {
    /// List the connections visible from here
    #[command(visible_alias = "ls")]
    List {
        /// Every project's own connections, and the global ones
        #[arg(short, long)]
        all: bool,
        #[arg(long)]
        json: bool,
    },
    /// Open a connection in its client (same as `furet <name>`)
    Open {
        name: String,
        #[arg(short, long)]
        write: bool,
    },
    /// Run a command with the connection's env (PG*/CLICKHOUSE_*, DATABASE_URL) and tunnel
    Run {
        name: String,
        #[arg(short, long)]
        write: bool,
        #[arg(last = true, required = true)]
        argv: Vec<String>,
    },
    /// Run SQL through the engine and print the result (read-only rules apply; kept in the history)
    Query {
        name: String,
        /// The SQL; `-` reads it from stdin
        sql: Option<String>,
        /// A saved query (.furet/queries/<name>.sql) instead
        #[arg(long, conflicts_with = "sql")]
        saved: Option<String>,
        #[arg(short, long)]
        write: bool,
        #[arg(long, conflicts_with = "csv")]
        json: bool,
        #[arg(long)]
        csv: bool,
        /// Rows per result
        #[arg(long, default_value_t = 200)]
        limit: usize,
    },
    /// Compare two connections' schemas (Postgres): what differs, and the SQL to align the second
    Drift {
        left: String,
        right: String,
        /// Only this schema
        #[arg(long)]
        schema: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Print the connection URL, password included
    Url {
        name: String,
        #[arg(short, long)]
        write: bool,
    },
    /// Print the connection's variables as `export` lines
    Env {
        name: String,
        #[arg(short, long)]
        write: bool,
    },
    /// Keep a connection's tunnel up until Ctrl-C
    Tunnel { name: String },
    /// Add a connection to this repo (or the global file)
    Add {
        name: String,
        /// postgres://… or clickhouse://…
        url: String,
        /// local, dev, stg, prod…
        #[arg(long)]
        stage: Option<String>,
        /// Command that makes the url's host:port reachable
        #[arg(long)]
        tunnel: Option<String>,
        #[arg(long)]
        global: bool,
    },
    /// Remove a connection (and its keychain password) from this repo or the global file
    Rm { name: String },
    /// Also use another repo's connections from this one
    Include { path: PathBuf },
    /// Copy a connection from another repo into this one
    Cp {
        name: String,
        /// A folder of the repo to copy from
        #[arg(long)]
        from: PathBuf,
        /// Name in this repo
        #[arg(long = "as")]
        rename: Option<String>,
    },
    /// Open this repo's connections file (or the global one) in $EDITOR
    Edit {
        #[arg(long)]
        global: bool,
    },
    /// Print the path of this repo's connections file (or the global one)
    Path {
        #[arg(long)]
        global: bool,
    },
    /// Set up an integration: `herdr` installs the panel and gives furet its name and icon there
    Setup { target: Integration },
    /// Update furet (and the herdr panel with it)
    Update,
    /// The local engine behind the herdr panel (127.0.0.1, token-protected)
    Serve {
        /// Start it in the background unless it's running; print its url and token as JSON
        #[arg(long)]
        ensure: bool,
        /// Stop the running server (its sessions and tunnels close)
        #[arg(long, conflicts_with = "ensure")]
        stop: bool,
        /// Stop after this many idle minutes with no session open
        #[arg(long, default_value_t = 60)]
        idle_minutes: u64,
    },
}

#[derive(Clone, ValueEnum)]
enum Integration {
    Herdr,
}

fn main() {
    tunnel::stop_tunnels_on_exit_signals();
    match run(Cli::parse()) {
        Ok(code) => std::process::exit(code),
        Err(e) => {
            eprintln!("furet: {e:#}");
            std::process::exit(1);
        }
    }
}

fn cwd() -> Result<PathBuf> {
    std::env::current_dir().context("cannot read current directory")
}

fn run(cli: Cli) -> Result<i32> {
    if cli.skill {
        print!("{SKILL}");
        return Ok(0);
    }
    let cwd = cwd()?;
    match (cli.cmd, cli.name) {
        (None, Some(name)) => open(&Scope::load_for(&cwd, &name)?, &name, cli.write, None),
        (None, None) => pick(&cwd),
        (Some(cmd), _) => command(cmd, &cwd),
    }
}

fn command(cmd: Cmd, cwd: &Path) -> Result<i32> {
    match cmd {
        Cmd::List { all, json } => list(cwd, all, json),
        Cmd::Open { name, write } => open(&Scope::load_for(cwd, &name)?, &name, write, None),
        Cmd::Run { name, write, argv } => {
            let scope = Scope::load_for(cwd, &name)?;
            let (r, _tunnel) = prepare(&scope, &name, write)?;
            exec(&r, &argv)
        }
        Cmd::Query {
            name,
            sql,
            saved,
            write,
            json,
            csv,
            limit,
        } => {
            let sql = match (sql, saved) {
                (_, Some(s)) => query::saved_sql(cwd, &s)?,
                (Some(s), None) if s == "-" => std::io::read_to_string(std::io::stdin())?,
                (Some(s), None) => s,
                (None, None) => bail!("give the SQL (- reads it from stdin), or --saved <name>"),
            };
            let scope = Scope::load_for(cwd, &name)?;
            let e = scope.get(&name)?;
            let confirm = if write && e.conn.is_prod() && e.conn.readonly() {
                confirm_prod(&name)?;
                Some(name.clone())
            } else {
                None
            };
            let format = match (json, csv) {
                (true, _) => query::Format::Json,
                (_, true) => query::Format::Csv,
                _ => query::Format::Table,
            };
            query::run(
                cwd,
                query::Args {
                    name: &name,
                    sql: &sql,
                    write,
                    confirm,
                    format,
                    limit,
                },
            )
        }
        Cmd::Drift {
            left,
            right,
            schema,
            json,
        } => {
            let info = engine::server::ensure()?;
            let out = query::request(
                &info,
                "POST",
                "/drift",
                Some(
                    serde_json::json!({ "cwd": cwd, "left": left, "right": right, "schema": schema }),
                ),
            )?;
            if json {
                println!("{}", serde_json::to_string_pretty(&out)?);
                return Ok(0);
            }
            let diffs = out["differences"].as_array().cloned().unwrap_or_default();
            for d in &diffs {
                let mark = match (d["left"].is_null(), d["right"].is_null()) {
                    (false, true) => format!("only in {left}"),
                    (true, false) => format!("only in {right}"),
                    _ => "differs".into(),
                };
                println!(
                    "{:<10} {:<40} {mark}",
                    d["kind"].as_str().unwrap_or(""),
                    d["object"].as_str().unwrap_or("")
                );
                for side in [("left", &left), ("right", &right)] {
                    if let Some(v) = d[side.0].as_str() {
                        println!("    {:<8} {v}", side.1);
                    }
                }
                for line in d["fix"].as_str().unwrap_or("").lines() {
                    println!("    > {line}");
                }
            }
            println!(
                "{} difference{}, {} the same",
                diffs.len(),
                if diffs.len() == 1 { "" } else { "s" },
                out["same"]
            );
            Ok(if diffs.is_empty() { 0 } else { 1 })
        }
        Cmd::Url { name, write } => {
            let scope = Scope::load_for(cwd, &name)?;
            println!("{}", resolve(&scope, &name, write)?.url());
            Ok(0)
        }
        Cmd::Env { name, write } => {
            let scope = Scope::load_for(cwd, &name)?;
            for (k, v) in resolve(&scope, &name, write)?.env() {
                println!("export {k}='{}'", v.replace('\'', r"'\''"));
            }
            Ok(0)
        }
        Cmd::Tunnel { name } => keep_tunnel(&Scope::load_for(cwd, &name)?, &name),
        Cmd::Add {
            name,
            url,
            stage,
            tunnel,
            global,
        } => add(cwd, &name, &url, stage, tunnel, global),
        Cmd::Rm { name } => {
            println!("removed {name} from {}", tilde(&store::remove(cwd, &name)?));
            Ok(0)
        }
        Cmd::Include { path } => include(cwd, &path),
        Cmd::Cp { name, from, rename } => copy(cwd, &name, &from, rename.as_deref()),
        Cmd::Edit { global } => edit(&store::target_file(cwd, global)?, global),
        Cmd::Path { global } => {
            println!("{}", store::target_file(cwd, global)?.display());
            Ok(0)
        }
        Cmd::Serve { stop: true, .. } => {
            println!(
                "{}",
                if engine::server::stop() {
                    "stopped"
                } else {
                    "not running"
                }
            );
            Ok(0)
        }
        Cmd::Serve { ensure: true, .. } => {
            println!("{}", engine::server::ensure()?.to_json());
            Ok(0)
        }
        Cmd::Serve { idle_minutes, .. } => {
            engine::server::serve(std::time::Duration::from_secs(idle_minutes * 60))?;
            Ok(0)
        }
        Cmd::Setup {
            target: Integration::Herdr,
        } => {
            herdr_kit::herdr::setup(&herdr_kit::herdr::Program {
                id: "furet",
                name: "Databases",
                icon_svg: ICON,
                tile: "#336791",
                matches: &["furet"],
            })?;
            use herdr_kit::herdr::Installed;
            match panel::PANEL.install()? {
                Installed::Written => {
                    println!("installed the Databases panel (herdr loads it live)")
                }
                Installed::Unchanged => println!("the Databases panel is up to date"),
                Installed::LeftAlone(why) => println!("left the Databases panel alone: {why}"),
                Installed::NoHerdr => {}
            }
            Ok(0)
        }
        Cmd::Update => update::run(),
    }
}

fn resolve(scope: &Scope, name: &str, write: bool) -> Result<Resolved> {
    let e = scope.get(name)?;
    if write && e.conn.readonly() && e.conn.is_prod() {
        confirm_prod(name)?;
    }
    let mut r = conn::resolve(e, scope.layer(e))?;
    if write {
        r.readonly = false;
    }
    Ok(r)
}

fn confirm_prod(name: &str) -> Result<()> {
    if !std::io::stdin().is_terminal() {
        bail!("writing to {name} (prod) needs a person at a terminal to confirm");
    }
    eprint!(
        "{} Type its name to allow writes: ",
        paint("1;31", &format!("{name} is prod."))
    );
    std::io::stderr().flush()?;
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    if answer.trim() != name {
        bail!("not confirmed");
    }
    Ok(())
}

fn prepare(scope: &Scope, name: &str, write: bool) -> Result<(Resolved, Option<Tunnel>)> {
    let r = resolve(scope, name, write)?;
    let e = scope.get(name)?;
    let tunnel = match &e.conn.tunnel {
        Some(cmd) => Tunnel::ensure(cmd, &r.host, r.port, &scope.layer(e).base, &scope.owner(e))?,
        None => None,
    };
    Ok((r, tunnel))
}

fn exec(r: &Resolved, argv: &[String]) -> Result<i32> {
    let mut cmd = Command::new(&argv[0]);
    cmd.args(&argv[1..]).envs(r.env());
    let status = tunnel::run_foreground(&mut cmd).map_err(|e| match e.kind() {
        std::io::ErrorKind::NotFound => anyhow::anyhow!("{} not found on PATH", argv[0]),
        _ => e.into(),
    })?;
    Ok(status.code().unwrap_or(1))
}

fn set_title(title: &str) {
    if std::io::stdout().is_terminal() {
        print!("\x1b]0;{title}\x07");
        let _ = std::io::stdout().flush();
    }
}

/// Opens `name` in its client; `tunnels` keeps tunnels alive across opens from the picker.
fn open(scope: &Scope, name: &str, write: bool, tunnels: Option<&mut Vec<Tunnel>>) -> Result<i32> {
    let (r, tunnel) = prepare(scope, name, write)?;
    let e = scope.get(name)?;
    let custom = e
        .conn
        .client
        .as_deref()
        .or_else(|| scope.clients.get(r.kind.name()).map(Vec::as_slice));
    let argv = r.client(custom);
    eprintln!("{}", banner(e, &r));
    set_title(&format!("furet · {name}"));
    let code = exec(&r, &argv);
    set_title("furet");
    if let (Some(keep), Some(t)) = (tunnels, tunnel) {
        keep.push(t);
    }
    code
}

fn stage_color(stage: &str) -> &'static str {
    match stage {
        "local" | "dev" | "test" => "32",
        "prod" | "production" => "1;31",
        "stg" | "staging" | "preprod" => "33",
        _ => "34",
    }
}

fn banner(e: &Entry, r: &Resolved) -> String {
    let stage = e.conn.stage();
    let mode = if r.readonly {
        "read-only"
    } else {
        "read-write"
    };
    let who = r
        .user
        .as_deref()
        .map(|u| format!("{u}@"))
        .unwrap_or_default();
    let db = r
        .database
        .as_deref()
        .map(|d| format!("/{d}"))
        .unwrap_or_default();
    let c = |code: &str, s: &str| paint(code, s);
    format!(
        "{} {} {} {}",
        c("2", "furet:"),
        c("1", &e.name),
        c(stage_color(stage), stage),
        c(
            "2",
            &format!(
                "{} · {mode} · {who}{}:{}{db}",
                r.kind.name(),
                r.host,
                r.port
            )
        ),
    )
}

/// Colours text for stderr, when it is a terminal.
pub fn paint(code: &str, s: &str) -> String {
    if std::io::stderr().is_terminal() {
        format!("\x1b[{code}m{s}\x1b[0m")
    } else {
        s.to_string()
    }
}

fn keep_tunnel(scope: &Scope, name: &str) -> Result<i32> {
    let e = scope.get(name)?;
    let Some(cmd) = &e.conn.tunnel else {
        bail!("{name} has no tunnel")
    };
    let r = conn::resolve(e, scope.layer(e))?;
    let Some(mut t) = Tunnel::ensure(cmd, &r.host, r.port, &scope.layer(e).base, &scope.owner(e))?
    else {
        eprintln!(
            "{}:{} is already reachable (another tunnel?)",
            r.host, r.port
        );
        return Ok(0);
    };
    eprintln!(
        "tunnel for {name} is up on {}:{}; Ctrl-C to stop",
        r.host, r.port
    );
    set_title(&format!("furet · {name} tunnel"));
    let status = t.wait();
    eprintln!("tunnel stopped");
    Ok(status.map(|s| s.code().unwrap_or(0)).unwrap_or(0))
}

#[derive(serde::Serialize)]
pub struct Row {
    pub name: String,
    pub kind: Option<&'static str>,
    pub stage: String,
    pub readonly: bool,
    pub endpoint: String,
    pub source: String,
    pub tunnel: bool,
    pub tunnel_up: Option<bool>,
    pub note: Option<String>,
    /// Running in Docker, not configured: nothing to edit or remove, but it can be saved.
    pub detected: bool,
}

pub fn rows(scope: &Scope) -> Vec<Row> {
    scope
        .entries
        .iter()
        .map(|e| {
            let c = &e.conn;
            let host = c
                .host
                .as_ref()
                .and_then(|h| h.plain())
                .unwrap_or("localhost");
            Row {
                name: e.name.clone(),
                kind: c.kind().map(|k| k.name()),
                stage: c.stage().into(),
                readonly: c.readonly(),
                endpoint: conn::endpoint(c),
                source: scope.layer(e).label(),
                detected: scope.layer(e).origin == config::Origin::Detected,
                tunnel: c.tunnel.is_some(),
                tunnel_up: c
                    .tunnel
                    .as_ref()
                    .and_then(|_| conn::local_port(c))
                    .map(|p| tunnel::is_up(host, p)),
                note: c.note.clone(),
            }
        })
        .collect()
}

fn list(cwd: &Path, all: bool, json: bool) -> Result<i32> {
    let scopes: Vec<(String, Scope)> = if all {
        let mut v = Vec::new();
        for root in config::all_projects() {
            let mut s = Scope::load(&root)?;
            s.entries
                .retain(|e| s.layers[e.layer].origin == Origin::Project);
            v.push((tilde(&root), s));
        }
        let mut g = Scope::load(cwd)?;
        g.entries
            .retain(|e| g.layers[e.layer].origin == Origin::Global);
        v.push(("global".into(), g));
        v
    } else {
        let s = Scope::load(cwd)?.with_detected();
        vec![(tilde(&s.root), s)]
    };
    if json {
        let out: Vec<_> = scopes
            .iter()
            .map(|(_, s)| {
                serde_json::json!({
                    "root": s.root,
                    "file": config::project_file(&s.root),
                    "connections": rows(s),
                })
            })
            .collect();
        let out = if all {
            serde_json::Value::Array(out)
        } else {
            out.into_iter().next().unwrap()
        };
        println!("{}", serde_json::to_string_pretty(&out)?);
        return Ok(0);
    }
    let tty = std::io::stdout().is_terminal();
    let c = |code: &str, s: &str| {
        if tty {
            format!("\x1b[{code}m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    };
    for (i, (label, s)) in scopes.iter().enumerate() {
        let rows = rows(s);
        if all && rows.is_empty() {
            continue;
        }
        if i > 0 {
            println!();
        }
        println!("{}", c("1", label));
        if let Some(why) = &s.docker {
            println!(
                "  {}",
                c(
                    "2",
                    &format!("(running databases in Docker not listed: {why})")
                )
            );
        }
        if rows.is_empty() {
            println!(
                "  {}",
                c(
                    "2",
                    "no connections yet: `furet add <name> <url>`, `furet edit` or `furet include <other clone>`"
                )
            );
        }
        let w = rows.iter().map(|r| r.name.len()).max().unwrap_or(0);
        let sw = rows.iter().map(|r| r.stage.len()).max().unwrap_or(0);
        for r in rows {
            let tunnel = match r.tunnel_up {
                Some(true) => c("32", "⇄"),
                Some(false) => c("2", "⇄"),
                None => " ".into(),
            };
            let from = if r.source == "this repo" || all {
                String::new()
            } else {
                c("2", &format!("  ({})", r.source))
            };
            let note = r
                .note
                .map(|n| c("2", &format!("  {n}")))
                .unwrap_or_default();
            println!(
                "  {tunnel} {}  {}  {}  {}{from}{note}",
                c("36", &format!("{:w$}", r.name)),
                c(stage_color(&r.stage), &format!("{:sw$}", r.stage)),
                c("2", &format!("{:10}", r.kind.unwrap_or("?"))),
                r.endpoint,
            );
        }
    }
    Ok(0)
}

fn pick(cwd: &Path) -> Result<i32> {
    if !std::io::stdout().is_terminal() {
        return list(cwd, false, false);
    }
    let mut tunnels = Vec::new();
    let mut message: Option<String> = None;
    loop {
        let scope = Scope::load(cwd).map(Scope::with_detected);
        let rows = scope.as_ref().map(rows).unwrap_or_default();
        if let Err(e) = &scope {
            message = Some(format!("{e:#}"));
        }
        set_title("furet");
        let label = scope.as_ref().map(|s| tilde(&s.root)).unwrap_or_default();
        match picker::run(&label, &rows, message.take())? {
            picker::Action::Quit => return Ok(0),
            picker::Action::Refresh => {}
            picker::Action::Edit => {
                edit(&store::target_file(cwd, false)?, false)?;
            }
            picker::Action::Open { name, write } => {
                let Ok(scope) = scope else { continue };
                if let Err(e) = open(&scope, &name, write, Some(&mut tunnels)) {
                    message = Some(format!("{e:#}"));
                }
            }
        }
    }
}

fn add(
    cwd: &Path,
    name: &str,
    url: &str,
    stage: Option<String>,
    tunnel: Option<String>,
    global: bool,
) -> Result<i32> {
    let draft = store::Draft {
        name: name.into(),
        url: url.into(),
        stage,
        tunnel,
        global,
        ..Default::default()
    };
    let saved = store::save(cwd, &draft, None)?;
    println!("added {name} to {}", tilde(&saved.file));
    for n in saved.notes {
        println!("{n}");
    }
    Ok(0)
}

fn include(cwd: &Path, path: &Path) -> Result<i32> {
    let other = herdr_kit::scope::project_root(&cwd.join(path));
    let own = herdr_kit::scope::project_root(cwd);
    if other == own {
        bail!("that is this repo");
    }
    let file = store::target_file(cwd, false)?;
    let mut doc = store::load_doc(&file)?;
    let list = doc
        .entry("include")
        .or_insert(toml_edit::value(toml_edit::Array::new()));
    let arr = list.as_array_mut().context("`include` is not a list")?;
    let entry = tilde(&other);
    if arr.iter().any(|v| v.as_str() == Some(&entry)) {
        println!("already including {entry}");
        return Ok(0);
    }
    arr.push(entry.as_str());
    store::save_doc(&file, &doc, false)?;
    let n = File::read(&config::project_file(&other))?.conn.len();
    println!("{} now includes {entry} ({n} connections)", tilde(&own));
    Ok(0)
}

fn copy(cwd: &Path, name: &str, from: &Path, rename: Option<&str>) -> Result<i32> {
    let source = Scope::load(&cwd.join(from))?;
    let e = source.get(name)?;
    let src_file = &source.layer(e).file;
    let src: DocumentMut = std::fs::read_to_string(src_file)?.parse()?;
    let mut item = src["conn"][name].clone();
    let new = rename.unwrap_or(name);
    let file = store::target_file(cwd, false)?;
    // A keychain password is copied into this repo's own entry: references never cross repos.
    if let Some(config::Value::Keychain { keychain }) = &e.conn.password {
        let secret = store::keychain_get(keychain)?;
        let account = store::account(&tilde(&herdr_kit::scope::project_root(cwd)), new);
        store::keychain_set(&account, &secret)?;
        let mut it = toml_edit::InlineTable::new();
        it.insert("keychain", account.as_str().into());
        item["password"] = toml_edit::value(it);
    }
    let mut doc = store::load_doc(&file)?;
    let conns = doc
        .entry("conn")
        .or_insert(toml_edit::table())
        .as_table_mut()
        .context("`conn` is not a table")?;
    conns.set_implicit(true);
    if conns.contains_key(new) {
        bail!("{new} already exists in {}", file.display());
    }
    conns.insert(new, item);
    store::save_doc(&file, &doc, false)?;
    println!("copied {name} from {} as {new}", tilde(src_file));
    Ok(0)
}

fn edit(file: &Path, global: bool) -> Result<i32> {
    if !file.exists() {
        store::write_private(file, &store::template(file, global))?;
    }
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vi".into());
    let status = tunnel::run_foreground(
        Command::new("sh")
            .arg("-c")
            .arg(format!("{editor} \"$1\""))
            .arg("sh")
            .arg(file),
    )?;
    if let Err(e) = File::read(file) {
        eprintln!("furet: {e:#}");
        return Ok(1);
    }
    Ok(status.code().unwrap_or(0))
}