nightporter 0.4.1

Handles your PRs while you're away: an agentic night shift for GitHub and GitLab
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
//! First-run wizard. In a terminal it uses interactive prompts (editable text with a cursor,
//! menus, a searchable checklist of repos). Plain line-based prompts are kept for screen readers,
//! `TERM=dumb`, pipes and scripts, or whenever `NIGHTPORTER_PLAIN` is set.

use crate::config::{AgentKind, Config, Level, TEMPLATE, Window, edit_file};
use crate::forge::ForgeKind;
use crate::paths::Paths;
use anyhow::{Context, Result, bail};
use std::io::{BufRead, IsTerminal, Write};

/// Interactive prompts, or the plain fallback.
fn fancy() -> bool {
    std::io::stdin().is_terminal()
        && std::io::stdout().is_terminal()
        && std::env::var("TERM").map_or(true, |t| t != "dumb")
        && std::env::var_os("NIGHTPORTER_PLAIN").is_none()
}

/// A leading newline in a question becomes a blank line before the prompt, not part of it.
fn label(q: &str) -> &str {
    q.strip_prefix('\n').inspect(|_| println!()).unwrap_or(q)
}

/// Ctrl-C / Esc in a prompt stop the wizard, like end of input does in plain mode.
fn answer<T>(r: std::result::Result<T, inquire::InquireError>) -> Result<T> {
    use inquire::InquireError::{OperationCanceled, OperationInterrupted};
    r.map_err(|e| match e {
        OperationCanceled | OperationInterrupted => anyhow::anyhow!("setup cancelled"),
        e => e.into(),
    })
}

fn ask_plain(q: &str, default: &str) -> Result<String> {
    print!("{q}{}: ", if default.is_empty() { String::new() } else { format!(" [{default}]") });
    std::io::stdout().flush()?;
    let mut s = String::new();
    if std::io::stdin().lock().read_line(&mut s)? == 0 {
        bail!("setup cancelled (end of input)");
    }
    let s = s.trim();
    Ok(if s.is_empty() { default.to_string() } else { s.to_string() })
}

fn ask(q: &str, default: &str) -> Result<String> {
    if !fancy() {
        return ask_plain(q, default);
    }
    // The default is pre-filled, so it can be edited instead of retyped.
    let s = answer(inquire::Text::new(label(q)).with_initial_value(default).with_help_message("Enter to accept, Esc to stop").prompt())?;
    Ok(s.trim().to_string())
}

/// Ask until `parse` accepts the answer; explain what was wrong each time.
fn ask_valid<T>(q: &str, default: &str, parse: impl Fn(&str) -> Result<T>) -> Result<T> {
    let mut last = default.to_string();
    loop {
        last = ask(q, &last)?;
        match parse(&last) {
            Ok(v) => return Ok(v),
            Err(e) => println!("  {e:#}. Please try again."),
        }
    }
}

pub fn yes(q: &str, default: bool) -> Result<bool> {
    if fancy() {
        return answer(inquire::Confirm::new(label(q)).with_default(default).prompt());
    }
    ask_valid(&format!("{q} (y/n)"), if default { "y" } else { "n" }, |a| match a.to_ascii_lowercase().as_str() {
        "y" | "yes" => Ok(true),
        "n" | "no" => Ok(false),
        _ => bail!("answer y or n"),
    })
}

/// Pick one of `options`; returns its index.
fn choose(q: &str, options: &[&str], default: usize) -> Result<usize> {
    if fancy() {
        let picked = answer(inquire::Select::new(label(q), options.to_vec()).with_starting_cursor(default).prompt())?;
        return Ok(options.iter().position(|o| *o == picked).unwrap_or(default));
    }
    println!("{q}");
    for (i, o) in options.iter().enumerate() {
        println!("  {}) {o}", i + 1);
    }
    ask_valid("Choose", &(default + 1).to_string(), |a| match a.parse::<usize>() {
        Ok(n) if (1..=options.len()).contains(&n) => Ok(n - 1),
        _ => bail!("choose a number from 1 to {}", options.len()),
    })
}

/// `mon-fri 08:00-09:00,17:00-22:00`, or empty / `always` for no schedule.
pub fn parse_schedule(a: &str) -> Result<Option<Window>> {
    let a = a.trim();
    if a.is_empty() || a.eq_ignore_ascii_case("always") {
        return Ok(None);
    }
    let (days, ranges) = a.split_once(' ').context("use `<days> <HH:MM-HH:MM,...>`, e.g. `mon-fri 08:00-09:00,17:00-22:00`")?;
    let w = Window { days: days.into(), windows: ranges.split(',').map(|r| r.trim().to_string()).collect(), ..Default::default() };
    crate::schedule::validate(std::slice::from_ref(&w))?;
    Ok(Some(w))
}

/// Comma-separated hosts, at least one.
fn ask_hosts(q: &str, default: &str) -> Result<Vec<String>> {
    ask_valid(q, default, |a| {
        let v: Vec<String> = a.split(',').map(|h| h.trim().to_ascii_lowercase()).filter(|h| !h.is_empty()).collect();
        if v.is_empty() {
            bail!("enter at least one host")
        }
        Ok(v)
    })
}

/// Step 1: which forges and hosts.
fn ask_forges() -> Result<Vec<(ForgeKind, String)>> {
    let f = choose(
        "\n1. Which forges?",
        &["GitHub", "GitLab (gitlab.com or self-hosted)", "Forgejo / Gitea (codeberg.org, gitea.com or self-hosted)", "Several of these"],
        0,
    )?;
    let want = |i: usize, name: &str| -> Result<bool> { if f == 3 { yes(&format!("Use {name}?"), true) } else { Ok(f == i) } };
    let mut forges: Vec<(ForgeKind, String)> = Vec::new();
    if want(0, "GitHub")? {
        forges.push((ForgeKind::GitHub, ask("GitHub host", "github.com")?.to_ascii_lowercase()));
    }
    if want(1, "GitLab")? {
        let hosts = ask_hosts("GitLab host(s), comma-separated (e.g. gitlab.com, git.drupalcode.org)", "gitlab.com")?;
        forges.extend(hosts.into_iter().map(|h| (ForgeKind::GitLab, h)));
    }
    if want(2, "Forgejo / Gitea")? {
        let hosts = ask_hosts("Forgejo / Gitea host(s), comma-separated (e.g. codeberg.org, gitea.com)", "codeberg.org")?;
        forges.extend(hosts.into_iter().map(|h| (ForgeKind::Forgejo, h)));
    }
    Ok(forges)
}

/// Forgejo/Gitea token: `tea`'s login if it has one for the host, else paste one into the
/// keychain. Returns the hosts that now use the keychain.
fn forgejo_tokens(forges: &[(ForgeKind, String)]) -> Result<Vec<String>> {
    let mut keyring = Vec::new();
    for (_, host) in forges.iter().filter(|(f, _)| *f == ForgeKind::Forgejo) {
        if crate::http::tea_token(host).is_ok() {
            println!("  {host}: using your `tea` login");
            continue;
        }
        println!(
            "  {host}: create an access token at https://{host}/user/settings/applications\n  with scopes: {}",
            crate::forge::forgejo::SCOPES
        );
        let q = format!("Paste the token for {host} (hidden; empty to skip)");
        let t = if fancy() {
            answer(inquire::Password::new(&q).without_confirmation().with_display_mode(inquire::PasswordDisplayMode::Hidden).prompt())?
        } else {
            print!("{q}: ");
            std::io::stdout().flush()?;
            crate::read_secret()?
        };
        if t.trim().is_empty() {
            println!("  skipped; later: `nightporter token set forgejo {host}` and token = \"keyring\"");
            continue;
        }
        crate::http::store_token(ForgeKind::Forgejo, host, t.trim())?;
        println!("  stored in the OS keychain");
        keyring.push(host.clone());
    }
    Ok(keyring)
}

/// Step 7: pick which of the clones found under the code dir to watch. Already-subscribed repos
/// start ticked; unticking one unsubscribes it.
fn subscribe_repos(paths: &Paths) -> Result<()> {
    let cfg = Config::load(paths)?;
    let clones: Vec<_> = crate::repos::scan(&cfg.code_dir(), cfg.scan_depth, &cfg.accounts).into_keys().collect();
    if clones.is_empty() {
        println!("\n7. No clones found under {}. Add repos later in the TUI (tab 4).", cfg.code_dir().display());
        return Ok(());
    }
    let was: Vec<bool> = clones.iter().map(|r| cfg.settings_for(paths, r).is_ok_and(|s| s.subscribed)).collect();
    let labels: Vec<String> = clones.iter().map(|r| format!("{}/{}", r.host, r.path)).collect();
    let picked: Vec<usize> = if fancy() {
        let on: Vec<usize> = (0..clones.len()).filter(|&i| was[i]).collect();
        println!();
        answer(
            inquire::MultiSelect::new(&format!("7. Found {} repos. Which should Night Porter watch?", clones.len()), labels.clone())
                .with_default(&on)
                .with_page_size(15)
                .with_help_message("type to search, ↑↓ move, space toggle, → all, ← none, Enter confirm")
                .raw_prompt(),
        )?
        .into_iter()
        .map(|o| o.index)
        .collect()
    } else {
        println!("\n7. Found {} repos. Subscribe to which? (numbers, comma-separated; empty = keep as is)", clones.len());
        for (i, l) in labels.iter().enumerate() {
            println!("  {:>3}) [{}] {l}", i + 1, if was[i] { "x" } else { " " });
        }
        let picks = ask_valid("Subscribe", "", |a| {
            a.split(',')
                .map(str::trim)
                .filter(|x| !x.is_empty())
                .map(|x| match x.parse::<usize>() {
                    Ok(n) if (1..=clones.len()).contains(&n) => Ok(n - 1),
                    _ => bail!("{x:?} is not a number between 1 and {}", clones.len()),
                })
                .collect::<Result<Vec<_>>>()
        })?;
        // Plain mode only adds: an empty answer must not unsubscribe everything.
        (0..clones.len()).filter(|i| was[*i] || picks.contains(i)).collect()
    };
    for (i, r) in clones.iter().enumerate() {
        let on = picked.contains(&i);
        if on != was[i] {
            crate::actions::set_subscribed(paths, r, on)?;
            println!("  {} {}", if on { "subscribed" } else { "unsubscribed" }, labels[i]);
        }
    }
    Ok(())
}

pub fn run(paths: &Paths) -> Result<()> {
    paths.ensure()?;
    if std::env::var_os("NO_COLOR").is_some() {
        inquire::set_global_render_config(inquire::ui::RenderConfig::empty());
    }
    println!("Night Porter setup. Enter accepts each answer, Esc stops.\n");
    if paths.config_file().exists() && !yes(&format!("{} exists. Update it?", paths.config_file().display()), true)? {
        return Ok(());
    }
    if !paths.config_file().exists() {
        std::fs::write(paths.config_file(), TEMPLATE)?;
    }

    let forges = ask_forges()?;
    let keyring_hosts = forgejo_tokens(&forges)?;

    // 2. Agents
    let agent = AgentKind::ALL[choose("\n2. Which agent by default?", &AgentKind::ALL.map(AgentKind::label), 0)?];

    // 3. Tools
    println!("\n3. Checking tools…");
    let checks = crate::doctor::tools(&forges, &[agent]);
    crate::doctor::print(&checks);
    if checks.iter().any(|c| !c.ok && !c.optional) {
        println!("  Some tools are missing or logged out. Nothing is installed for you: run the fix commands, then `nightporter doctor`.");
    }

    // 4. Code dir + defaults
    let code_dir = ask_valid("\n4. Where are your clones?", "~/coding", |a| {
        if crate::paths::expand_tilde(a).is_dir() { Ok(a.to_string()) } else { bail!("{a} is not a directory") }
    })?;
    let levels = [
        (Level::Observe, "observe   notify only"),
        (Level::Suggest, "suggest   commit locally, you copy/paste"),
        (Level::Draft, "draft     you approve each push/reply (recommended)"),
        (Level::Auto, "auto      push/reply on its own (checks still apply)"),
    ];
    let level = levels[choose("\n5. Default autonomy level?", &levels.map(|l| l.1), 2)?].0;
    let sched = ask_valid("\n6. Active hours, e.g. `mon-fri 08:00-09:00,17:00-22:00` (empty = always)", "", parse_schedule)?;
    save(&paths.config_file(), &code_dir, &forges, &keyring_hosts, agent, level, sched.as_ref())?;

    subscribe_repos(paths)?;

    // 8. Service
    if yes("\n8. Install the background service now?", true)? {
        match crate::service::install(&paths.log_file()) {
            Ok(m) => println!("  {m}"),
            Err(e) => println!("  could not install: {e:#}"),
        }
    }
    println!("\nDone. Open the TUI with `nightporter`, check health with `nightporter doctor`.");
    Ok(())
}

/// Write the wizard's answers into config.toml, keeping everything else in it.
fn save(
    file: &std::path::Path,
    code_dir: &str,
    forges: &[(ForgeKind, String)],
    keyring_hosts: &[String],
    agent: AgentKind,
    level: Level,
    sched: Option<&Window>,
) -> Result<()> {
    edit_file(file, |d| {
        d["code_dir"] = toml_edit::value(code_dir);
        // Keep accounts that are already there (and their token settings); add new ones.
        let accounts = d["accounts"].or_insert(toml_edit::Item::ArrayOfTables(toml_edit::ArrayOfTables::new()));
        if let Some(aot) = accounts.as_array_of_tables_mut() {
            for (f, host) in forges {
                let default_host = f.default_host();
                let keyring = *f == ForgeKind::Forgejo && keyring_hosts.contains(host);
                let existing = aot.iter_mut().find(|t| {
                    t.get("forge").and_then(|v| v.as_str()).and_then(ForgeKind::parse) == Some(*f)
                        && t.get("host").and_then(|v| v.as_str()).unwrap_or(default_host).eq_ignore_ascii_case(host)
                });
                if let Some(t) = existing {
                    if keyring {
                        t["token"] = toml_edit::value("keyring");
                    }
                } else {
                    let mut t = toml_edit::Table::new();
                    t["forge"] = toml_edit::value(f.as_str());
                    if host != default_host {
                        t["host"] = toml_edit::value(host.as_str());
                    }
                    if keyring {
                        t["token"] = toml_edit::value("keyring");
                    }
                    aot.push(t);
                }
            }
        }
        // A real `[defaults]` table: indexing a missing key makes an inline table, which can't
        // hold `[[defaults.schedule]]` (the schedule would be silently dropped).
        if !d.contains_table("defaults") {
            let mut t = toml_edit::Table::new();
            if let Some(old) = d.get("defaults").and_then(toml_edit::Item::as_inline_table) {
                t = old.clone().into_table();
            }
            d["defaults"] = toml_edit::Item::Table(t);
        }
        d["defaults"]["agent"] = toml_edit::value(agent.bin());
        d["defaults"]["level"] = toml_edit::value(level.as_str());
        if let Some(w) = sched {
            let mut t = toml_edit::Table::new();
            t["days"] = toml_edit::value(&w.days);
            t["windows"] = toml_edit::value(w.windows.iter().map(String::as_str).collect::<toml_edit::Array>());
            let mut aot = toml_edit::ArrayOfTables::new();
            aot.push(t);
            d["defaults"]["schedule"] = toml_edit::Item::ArrayOfTables(aot);
        }
    })
}

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

    #[test]
    fn validates_answers() {
        assert!(parse_schedule("").unwrap().is_none());
        assert!(parse_schedule("always").unwrap().is_none());
        assert_eq!(parse_schedule("mon-fri 08:00-09:00, 17:00-22:00").unwrap().unwrap().windows.len(), 2);
        assert!(parse_schedule("daily").is_err());
        assert!(parse_schedule("mon-fri 8-9").is_err());
    }

    #[test]
    fn prompts_stop_on_cancel() {
        assert_eq!(label("\nQ?"), "Q?");
        assert_eq!(label("Q?"), "Q?");
        assert_eq!(answer(Ok(3)).unwrap(), 3);
        let e = answer::<()>(Err(inquire::InquireError::OperationCanceled)).unwrap_err();
        assert_eq!(e.to_string(), "setup cancelled");
        assert!(answer::<()>(Err(inquire::InquireError::OperationInterrupted)).is_err());
        assert!(answer::<()>(Err(inquire::InquireError::NotTTY)).unwrap_err().to_string() != "setup cancelled");
    }

    #[test]
    fn saves_answers_and_keeps_existing_accounts() {
        let d = tempfile::tempdir().unwrap();
        let file = d.path().join("config.toml");
        std::fs::write(
            &file,
            "# my notes\n[[accounts]]\nforge = \"github\" # mine\n[[accounts]]\nforge = \"forgejo\"\nhost = \"Codeberg.org\"\n[defaults]\n",
        )
        .unwrap();
        let forges = [
            (ForgeKind::GitHub, "github.com".to_string()),
            (ForgeKind::Forgejo, "codeberg.org".to_string()),
            (ForgeKind::Forgejo, "git.example.org".to_string()),
            (ForgeKind::GitLab, "gitlab.com".to_string()),
            (ForgeKind::GitLab, "git.drupalcode.org".to_string()),
        ];
        let sched = parse_schedule("mon-fri 08:00-09:00,17:00-22:00").unwrap();
        let keyring = ["codeberg.org".to_string(), "git.example.org".to_string()];
        save(&file, "~/src", &forges, &keyring, AgentKind::Codex, Level::Auto, sched.as_ref()).unwrap();
        let text = std::fs::read_to_string(&file).unwrap();
        assert!(text.contains("# my notes") && text.contains("forge = \"github\" # mine"), "{text}");
        let cfg = Config::parse(&text).unwrap();
        assert_eq!(cfg.code_dir, "~/src");
        let accts: Vec<_> = cfg.accounts.iter().map(|a| (a.forge, a.host().to_string())).collect();
        assert_eq!(accts.len(), 5, "existing accounts are matched by forge and host, not duplicated: {text}");
        assert!(accts.contains(&(ForgeKind::Forgejo, "Codeberg.org".into())) && accts.contains(&(ForgeKind::GitLab, "gitlab.com".into())));
        assert_eq!(text.matches("token = \"keyring\"").count(), 2, "{text}");
        assert!(!text.contains("host = \"gitlab.com\""), "default hosts aren't written: {text}");
        let s = cfg.resolve(None).unwrap();
        assert_eq!((s.agent, s.level), (AgentKind::Codex, Level::Auto));
        assert!(text.contains("days = \"mon-fri\"") && text.contains("\"17:00-22:00\""), "{text}");

        // A config with no [defaults] table still gets the schedule.
        std::fs::create_dir(d.path().join("bare")).unwrap();
        let bare = d.path().join("bare/config.toml");
        std::fs::write(&bare, "[[accounts]]\nforge = \"github\"\n").unwrap();
        save(&bare, "~/src", &forges[..1], &[], AgentKind::Claude, Level::Draft, sched.as_ref()).unwrap();
        let s = Config::parse(&std::fs::read_to_string(&bare).unwrap()).unwrap().resolve(None).unwrap();
        assert_eq!(s.schedule.len(), 1);

        // Without a schedule the existing one stays.
        save(&file, "~/src", &forges[..1], &[], AgentKind::Claude, Level::Draft, None).unwrap();
        let text = std::fs::read_to_string(&file).unwrap();
        assert!(text.contains("days = \"mon-fri\"") && text.contains("level = \"draft\""), "{text}");
    }
}