repoke 0.7.0

Finds the package managers on your system and keeps them up to date, interactively or unattended
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
mod catalog;
mod check;
mod config;
mod crypt;
mod export;
mod init;
mod manager;
mod managers;
mod mcp;
mod plugins;
mod progress;
mod run;
mod schedule;
mod self_update;
mod snapshot;
mod upgrade;

use std::io::IsTerminal;
use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Args, Parser, Subcommand};
use serde::Serialize;

/// Same convention as `dnf check-update`: an agent can tell "updates pending" from "failed".
const EXIT_UPDATES: u8 = 100;
const EXIT_USAGE: u8 = 2;

#[derive(Parser)]
#[command(
    version,
    about = "Finds the package managers on this system and keeps them up to date"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// List the package managers repoke supports here and whether they are installed
    List {
        /// Print JSON instead of text
        #[arg(long)]
        json: bool,
    },
    /// Show pending updates without changing anything; exits 100 when there are some
    Check {
        /// Print JSON instead of text
        #[arg(long)]
        json: bool,
        #[command(flatten)]
        selection: Selection,
    },
    /// Upgrade pending packages, picking them in a list or all at once with --yes
    Upgrade(UpgradeArgs),
    /// Save what is installed, and optionally its config, to a folder another machine can restore
    Export(ExportArgs),
    /// Install a saved snapshot (--from) or pick tools from a catalog, on a new machine
    Init(InitArgs),
    /// Update repoke itself, through Homebrew or cargo when it was installed with them
    SelfUpdate(SelfUpdateArgs),
    /// Serve repoke's tools to AI agents over MCP (stdio)
    Mcp,
    /// Managers added as plugins: `repoke-<id>` executables or TOML files
    Plugin {
        #[command(subcommand)]
        action: PluginAction,
    },
    /// Keep the machine up to date on a schedule, through the system scheduler
    Schedule {
        #[command(subcommand)]
        action: ScheduleAction,
    },
}

#[derive(Subcommand)]
enum ScheduleAction {
    /// Register the periodic run, replacing any earlier one
    Install(ScheduleInstallArgs),
    /// Show the schedule and how the last run went
    Status {
        /// Print JSON instead of text
        #[arg(long)]
        json: bool,
    },
    /// Unregister the periodic run
    Remove {
        /// Print what would be removed
        #[arg(long)]
        dry_run: bool,
    },
    /// Run the scheduled job now, as the scheduler does: log it and notify
    Run,
}

#[derive(Subcommand)]
enum PluginAction {
    /// Show the plugins found and any problem with them
    List {
        /// Print JSON instead of text
        #[arg(long)]
        json: bool,
    },
    /// Start a plugin from a template: a TOML manager, or a script with --exec
    New(PluginNewArgs),
    /// Show the official plugins (github.com/paveldelpozo/repoke-plugins)
    Search {
        /// Print JSON instead of text
        #[arg(long)]
        json: bool,
    },
    /// Download an official plugin, show its code and install it
    Install(PluginInstallArgs),
    /// Remove a plugin that `plugin install` installed
    Remove {
        /// Plugin id
        id: String,
    },
}

#[derive(Args)]
struct PluginInstallArgs {
    /// Plugin id, as `repoke plugin search` lists it
    id: String,
    /// Install without showing the code or asking
    #[arg(long, short)]
    yes: bool,
    /// Replace a plugin already installed with that id
    #[arg(long)]
    force: bool,
}

#[derive(Args)]
struct PluginNewArgs {
    /// Manager id: lowercase letters, digits and dashes
    id: String,
    /// Write a `repoke-<id>` script speaking the JSON protocol instead of a TOML manager
    #[arg(long)]
    exec: bool,
    /// Where to write it (default: ~/.config/repoke/managers/<id>.toml, or ./repoke-<id>)
    #[arg(long, short)]
    output: Option<PathBuf>,
}

#[derive(Args)]
struct SelfUpdateArgs {
    /// Only say whether a newer version exists; exits 100 when it does
    #[arg(long)]
    check: bool,
    /// Update without asking
    #[arg(long, short)]
    yes: bool,
    /// Print JSON instead of text
    #[arg(long)]
    json: bool,
}

#[derive(Args)]
struct ScheduleInstallArgs {
    #[command(flatten)]
    managers: Managers,
    #[arg(long, value_enum, default_value = "daily")]
    every: schedule::Every,
    /// Local time, 24-hour clock; weekly runs are on Mondays. Missed while asleep, it runs on wake
    #[arg(long, default_value = "03:00")]
    at: String,
    /// Only check and notify; don't upgrade
    #[arg(long)]
    check_only: bool,
    /// Print the scheduler files and commands, register nothing
    #[arg(long)]
    dry_run: bool,
}

#[derive(Args)]
struct Managers {
    /// Only these managers (comma separated ids, see `repoke list`)
    #[arg(long, value_delimiter = ',')]
    only: Vec<String>,
    /// Skip these managers
    #[arg(long, value_delimiter = ',')]
    exclude: Vec<String>,
}

#[derive(Args)]
struct Selection {
    #[command(flatten)]
    managers: Managers,
    /// Leave these packages alone, as `name` or `manager:name`
    #[arg(long, value_delimiter = ',')]
    hold: Vec<String>,
    /// Refresh package indexes first (brew update)
    #[arg(long)]
    refresh: bool,
}

#[derive(Args)]
struct UpgradeArgs {
    #[command(flatten)]
    selection: Selection,
    /// Upgrade everything selected without asking; required outside a terminal
    #[arg(long, short)]
    yes: bool,
    /// Print the commands that would run, change nothing
    #[arg(long)]
    dry_run: bool,
    /// Skip managers that need root instead of calling sudo
    #[arg(long)]
    no_sudo: bool,
    /// Only these packages, as `name` or `manager:name`
    #[arg(long = "package", value_delimiter = ',')]
    packages: Vec<String>,
    /// Print one JSON event per line
    #[arg(long)]
    json: bool,
}

#[derive(Args)]
struct ExportArgs {
    #[command(flatten)]
    managers: Managers,
    /// Folder to write (default: repoke-<host>-<date>)
    #[arg(long, short)]
    output: Option<PathBuf>,
    /// Include every manager's config files without asking
    #[arg(long, conflicts_with = "no_config")]
    config: bool,
    /// Leave all config files out
    #[arg(long)]
    no_config: bool,
    /// Don't ask anything: config only with --config, and secret-looking values are removed
    #[arg(long, short)]
    yes: bool,
    /// Include every config file, secrets and all, encrypted with a password (asked, or REPOKE_PASSWORD)
    #[arg(long, conflicts_with = "no_config")]
    encrypt: bool,
    /// Replace a snapshot already in the output folder
    #[arg(long)]
    force: bool,
    /// Print JSON instead of text
    #[arg(long)]
    json: bool,
}

#[derive(Args)]
struct InitArgs {
    #[command(flatten)]
    managers: Managers,
    /// Snapshot folder written by `repoke export`
    #[arg(long)]
    from: Option<PathBuf>,
    /// Catalog tools to install without the picker (comma separated ids, see the picker)
    #[arg(long, value_delimiter = ',', conflicts_with = "from")]
    tools: Vec<String>,
    /// Install everything without asking; required outside a terminal
    #[arg(long, short)]
    yes: bool,
    /// Show what would be installed and restored, change nothing
    #[arg(long)]
    dry_run: bool,
    /// Skip managers that need root instead of calling sudo
    #[arg(long)]
    no_sudo: bool,
    /// Don't restore config files
    #[arg(long)]
    no_config: bool,
    /// Replace config files that differ without asking (yours are backed up first)
    #[arg(long)]
    overwrite: bool,
    /// Print JSON instead of text
    #[arg(long)]
    json: bool,
}

#[derive(Serialize)]
struct Detected {
    id: &'static str,
    name: &'static str,
    installed: bool,
    path: Option<PathBuf>,
    version: Option<String>,
}

fn main() -> ExitCode {
    if std::env::var_os("NO_COLOR").is_some() {
        console::set_colors_enabled(false);
        console::set_colors_enabled_stderr(false);
    }
    let command = Cli::parse().command;
    let code = dispatch(&command);
    if notices_updates(&command) {
        self_update::notice();
    }
    code
}

/// Only for people at a terminal: never under --json, in a pipe or in the scheduled job.
fn notices_updates(command: &Command) -> bool {
    let json = match command {
        Command::List { json } | Command::Check { json, .. } => *json,
        Command::Upgrade(args) => args.json,
        Command::Export(args) => args.json,
        Command::Init(args) => args.json,
        Command::SelfUpdate(_)
        | Command::Schedule { .. }
        | Command::Mcp
        | Command::Plugin { .. } => true,
    };
    !json && std::io::stdout().is_terminal() && std::io::stderr().is_terminal()
}

fn dispatch(command: &Command) -> ExitCode {
    let scheduled = match command {
        Command::List { json } => return list(*json),
        Command::Mcp => Some(mcp::serve()),
        Command::Plugin { action } => Some(match action {
            PluginAction::List { json } => plugins::list(*json),
            PluginAction::New(args) => plugins::new(args),
            PluginAction::Search { json } => plugins::registry::search(*json),
            PluginAction::Install(args) => plugins::registry::install(args),
            PluginAction::Remove { id } => plugins::registry::remove(id),
        }),
        Command::Schedule { action } => Some(match action {
            ScheduleAction::Install(args) => schedule::install(args),
            ScheduleAction::Status { json } => schedule::status(*json),
            ScheduleAction::Remove { dry_run } => schedule::remove(*dry_run),
            ScheduleAction::Run => schedule::run_job(),
        }),
        _ => None,
    };
    if let Some(outcome) = scheduled {
        return outcome.unwrap_or_else(|e| {
            eprintln!("repoke: {e}");
            ExitCode::from(EXIT_USAGE)
        });
    }
    let outcome = config::load().and_then(|config| match &command {
        Command::Check { json, selection } => check::run(selection, &config, *json),
        Command::Upgrade(args) => upgrade::run(args, &config),
        Command::Export(args) => export::run(args, &config),
        Command::Init(args) => init::run(args, &config),
        Command::SelfUpdate(args) => self_update::run(args),
        Command::List { .. } | Command::Schedule { .. } | Command::Mcp | Command::Plugin { .. } => {
            unreachable!("handled above")
        }
    });
    outcome.unwrap_or_else(|e| {
        eprintln!("repoke: {e}");
        ExitCode::from(EXIT_USAGE)
    })
}

fn list(json: bool) -> ExitCode {
    let progress = progress::Progress::new(json);
    let bar = progress.spinner("", "looking for package managers");
    let detected: Vec<Detected> = check::parallel(managers::all(), |m| {
        let path = m.locate();
        Detected {
            id: m.id(),
            name: m.name(),
            installed: path.is_some(),
            version: path.as_deref().and_then(|p| m.version(p)),
            path,
        }
    });
    bar.finish_and_clear();

    if json {
        print_json(&detected);
    } else {
        print_list(&detected);
    }
    ExitCode::SUCCESS
}

/// Found managers first, with their version; the ones missing after them, dimmed.
fn print_list(detected: &[Detected]) {
    use console::style;
    let id_width = detected.iter().map(|d| d.id.len()).max().unwrap_or(0);
    let name_width = detected.iter().map(|d| d.name.len()).max().unwrap_or(0);
    let plugins: Vec<&str> = plugins::loaded().managers.iter().map(|m| m.id()).collect();
    let (found, missing): (Vec<&Detected>, Vec<&Detected>) =
        detected.iter().partition(|d| d.installed);

    println!(
        "{} {}",
        style("Found").bold(),
        style(format!("({} of {})", found.len(), detected.len())).dim()
    );
    for d in &found {
        let version = d.version.as_deref().unwrap_or("installed");
        let plugin = if plugins.contains(&d.id) {
            style("  plugin").dim().to_string()
        } else {
            String::new()
        };
        println!(
            "  {} {}  {:<name_width$}  {}{plugin}",
            style("✓").green(),
            style(format!("{:<id_width$}", d.id)).bold(),
            d.name,
            style(version).cyan()
        );
    }
    if !missing.is_empty() {
        println!("\n{}", style("Not found").bold());
        for d in &missing {
            let line = format!("{:<id_width$}  {}", d.id, d.name);
            println!("  {} {}", style("·").dim(), style(line).dim());
        }
    }
}

fn print_json<T: Serialize>(value: &T) {
    println!(
        "{}",
        serde_json::to_string_pretty(value).expect("serializable output")
    );
}