knott 0.1.17

Fast Rust package manager helper for Arch Linux repos and the AUR
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
mod aur;
mod cli;
mod dep;
mod download;
mod info;
mod install;
mod keys;
mod localdb;
mod menu;
mod output;
mod pacman;
mod resolver;
mod search;
mod transaction;
mod upgrade;
mod version;

use anyhow::{bail, Result};
use std::io;

pub async fn run(args: Vec<String>) -> Result<i32> {
    let original_args = args.clone();
    let parsed = cli::parse(args)?;

    let recovery_flags =
        parsed.options.resume as u8 + parsed.options.abort as u8 + parsed.options.repair as u8;
    if recovery_flags > 1 {
        bail!("choose only one of --resume, --abort, or --repair");
    }

    match &parsed.command {
        cli::Command::Help => {
            cli::print_help();
            return Ok(0);
        }
        cli::Command::Version => {
            println!("knott {}", env!("CARGO_PKG_VERSION"));
            return Ok(0);
        }
        cli::Command::Diagnostics => {
            print_diagnostics();
            return Ok(0);
        }
        _ => {}
    }

    let tools = pacman::Toolchain::from_env();
    let aur = aur::AurClient::from_env_with_progress(
        !parsed.options.quiet && !parsed.options.no_progress,
    )?;

    if parsed.options.abort {
        let _lock = transaction::acquire_lock()?;
        return abort_current();
    }

    if parsed.options.repair {
        let _lock = transaction::acquire_lock()?;
        return repair_current(&parsed.options, &tools, &aur).await;
    }

    if parsed.options.resume {
        let _lock = transaction::acquire_lock()?;
        return resume_current(&parsed.options, &tools, &aur).await;
    }

    if let cli::Command::Keys { args } = &parsed.command {
        let _lock = transaction::acquire_lock()?;
        let current = transaction::load_current()?;
        return keys::update(&parsed.options, &tools, current.as_ref(), args).await;
    }

    match parsed.command {
        cli::Command::DefaultUpgrade => {
            run_mutating(
                original_args,
                &parsed.options,
                &tools,
                &aur,
                &[],
                true,
                true,
            )
            .await
        }
        cli::Command::Search { terms } => {
            search::print_search(&parsed.options, &tools, &aur, &terms).await
        }
        cli::Command::Info { targets } => {
            info::print_info(&parsed.options, &tools, &aur, &targets).await
        }
        cli::Command::Install {
            targets,
            refresh,
            sysupgrade,
        } => {
            run_mutating(
                original_args,
                &parsed.options,
                &tools,
                &aur,
                &targets,
                refresh,
                sysupgrade,
            )
            .await
        }
        cli::Command::Get { targets, print } => {
            download::get_pkgbuilds(&parsed.options, &tools, &aur, &targets, print).await
        }
        cli::Command::QueryForeign => upgrade::print_foreign(&parsed.options, &tools).await,
        cli::Command::QueryAurUpdates => {
            upgrade::print_aur_updates(&parsed.options, &tools, &aur).await
        }
        cli::Command::Forward(args) => tools.forward(&args).await,
        cli::Command::Keys { .. } => unreachable!(),
        cli::Command::Interactive { terms } => {
            let selected =
                search::interactive_select(&parsed.options, &tools, &aur, &terms).await?;
            if selected.is_empty() {
                return Ok(0);
            }
            let mut command = vec!["-S".to_string()];
            command.extend(selected.iter().cloned());
            run_mutating(
                command,
                &parsed.options,
                &tools,
                &aur,
                &selected,
                false,
                false,
            )
            .await
        }
        cli::Command::Help | cli::Command::Version | cli::Command::Diagnostics => unreachable!(),
    }
}

async fn run_mutating(
    command: Vec<String>,
    options: &cli::Options,
    tools: &pacman::Toolchain,
    aur: &aur::AurClient,
    targets: &[String],
    refresh: bool,
    sysupgrade: bool,
) -> Result<i32> {
    if options.dry_run {
        return install::sync(options, tools, aur, targets, refresh, sysupgrade, None).await;
    }

    let _lock = transaction::acquire_lock()?;
    if let Some(mut tx) = transaction::load_current()? {
        print_interrupted(&tx);
        if options.no_confirm {
            output::error("--noconfirm will not choose a recovery path; run knott --resume, --abort, or --repair");
            return Ok(1);
        }

        match prompt_recovery()? {
            RecoveryChoice::Resume => return resume_loaded(options, tools, aur, &mut tx).await,
            RecoveryChoice::Abort => {
                transaction::mark_aborted(&mut tx)?;
                output::warning("interrupted transaction marked aborted; rerun the requested command to start over");
                return Ok(1);
            }
            RecoveryChoice::IgnoreOnce => {
                output::warning("not starting a second mutating transaction while one is active");
                return Ok(1);
            }
        }
    }

    let mut tx = transaction::create_current(command, refresh, sysupgrade, options)?;
    install::sync(
        options,
        tools,
        aur,
        targets,
        refresh,
        sysupgrade,
        Some(&mut tx),
    )
    .await
}

fn abort_current() -> Result<i32> {
    let Some(mut tx) = transaction::load_current()? else {
        output::line("knott: no active Knott transaction");
        return Ok(0);
    };
    transaction::mark_aborted(&mut tx)?;
    output::line(format!(
        "knott: transaction {} marked aborted; installed packages were not rolled back",
        output::inline(&tx.id)
    ));
    Ok(0)
}

async fn resume_current(
    options: &cli::Options,
    tools: &pacman::Toolchain,
    aur: &aur::AurClient,
) -> Result<i32> {
    let Some(mut tx) = transaction::load_current()? else {
        output::line("knott: no active Knott transaction");
        return Ok(0);
    };
    resume_loaded(options, tools, aur, &mut tx).await
}

async fn repair_current(
    options: &cli::Options,
    tools: &pacman::Toolchain,
    aur: &aur::AurClient,
) -> Result<i32> {
    let Some(mut tx) = transaction::load_current()? else {
        let code = tools.pacman_database_check(options.dry_run).await?;
        if code == 0 {
            output::line("knott: no active Knott transaction");
        }
        return Ok(code);
    };
    let code = install::repair_transaction(options, tools, Some(aur), &mut tx).await?;
    if code != 0 || transaction::load_current()?.is_none() {
        return Ok(code);
    }
    resume_loaded(options, tools, aur, &mut tx).await
}

async fn resume_loaded(
    options: &cli::Options,
    tools: &pacman::Toolchain,
    aur: &aur::AurClient,
    tx: &mut transaction::Transaction,
) -> Result<i32> {
    if tx.phase.blocks_aur_resume() || failed_during_repo_upgrade(tx) {
        install::print_repo_interrupted(tx);
        return Ok(1);
    }

    if tx.aur_items.is_empty()
        && tx.repo_deps.is_empty()
        && matches!(
            tx.phase,
            transaction::TransactionPhase::Planned
                | transaction::TransactionPhase::RepoUpgradeDone
                | transaction::TransactionPhase::AurPlanWritten
        )
    {
        return resume_saved_command(options, tools, aur, tx).await;
    }

    install::resume_transaction(options, tools, Some(aur), tx).await
}

async fn resume_saved_command(
    options: &cli::Options,
    tools: &pacman::Toolchain,
    aur: &aur::AurClient,
    tx: &mut transaction::Transaction,
) -> Result<i32> {
    let parsed = cli::parse(tx.command.clone())?;
    let mut tx_options = tx.options.to_options();
    tx_options.no_confirm |= options.no_confirm;
    tx_options.no_progress |= options.no_progress;

    match parsed.command {
        cli::Command::DefaultUpgrade => {
            install::sync(
                &tx_options,
                tools,
                aur,
                &[],
                tx.refresh,
                tx.sysupgrade,
                Some(tx),
            )
            .await
        }
        cli::Command::Install {
            targets,
            refresh,
            sysupgrade,
        } => {
            install::sync(
                &tx_options,
                tools,
                aur,
                &targets,
                refresh || tx.refresh,
                sysupgrade || tx.sysupgrade,
                Some(tx),
            )
            .await
        }
        _ => {
            output::error("saved transaction command cannot be resumed automatically");
            Ok(1)
        }
    }
}

fn print_interrupted(tx: &transaction::Transaction) {
    if tx.phase == transaction::TransactionPhase::RepoUpgradeStarted
        || failed_during_repo_upgrade(tx)
    {
        install::print_repo_interrupted(tx);
        return;
    }

    output::error("knott: interrupted transaction detected");
    output::line(format!("id: {}", output::inline(&tx.id)));
    output::line(format!("phase: {}", tx.phase));
    if let Some(item) = tx
        .aur_items
        .iter()
        .find(|item| item.status != transaction::AurItemStatus::Installed)
    {
        output::line(format!("package: {}", output::inline(&item.name)));
    }
    output::line("resume: knott --resume");
    output::line("abort:  knott --abort");
    output::line("repair: knott --repair");
}

fn failed_during_repo_upgrade(tx: &transaction::Transaction) -> bool {
    tx.phase == transaction::TransactionPhase::Failed
        && tx
            .last_error
            .as_deref()
            .is_some_and(|err| err.contains("pacman repo upgrade"))
}

enum RecoveryChoice {
    Resume,
    Abort,
    IgnoreOnce,
}

fn prompt_recovery() -> Result<RecoveryChoice> {
    output::prompt("Interrupted transaction: [R]esume, [A]bort, [I]gnore once? ")?;
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let input = input.trim();
    if input.is_empty() || input.eq_ignore_ascii_case("r") || input.eq_ignore_ascii_case("resume") {
        return Ok(RecoveryChoice::Resume);
    }
    if input.eq_ignore_ascii_case("a") || input.eq_ignore_ascii_case("abort") {
        return Ok(RecoveryChoice::Abort);
    }
    if input.eq_ignore_ascii_case("i") || input.eq_ignore_ascii_case("ignore") {
        return Ok(RecoveryChoice::IgnoreOnce);
    }
    Ok(RecoveryChoice::IgnoreOnce)
}

pub fn sanitize_for_terminal(input: &str) -> String {
    output::text(input)
}

fn print_diagnostics() {
    println!("knott diagnostics");
    println!("version: {}", env!("CARGO_PKG_VERSION"));
    println!("aur_info_batch_size: {}", aur::INFO_CHUNK);
    println!("aur_info_cache_limit: {}", aur::INFO_CACHE_LIMIT);
    println!("aur_search_cache_limit: {}", aur::SEARCH_CACHE_LIMIT);
    println!(
        "aur_search_cache_result_limit: {}",
        aur::SEARCH_CACHE_RESULT_LIMIT
    );
    println!("pkgbuild_byte_limit: {}", aur::MAX_PKG_BUILD_BYTES);
    println!("resolver_node_limit: {}", resolver::MAX_RESOLVE_NODES);
    println!("local_desc_byte_limit: {}", localdb::MAX_DESC_BYTES);
    println!("spawned_tokio_tasks: 0");
    println!("channels: 0");
    println!("state_root: {}", transaction::state_root_path().display());
    println!(
        "transaction_dir: {}",
        transaction::transactions_dir_path().display()
    );
    println!(
        "transaction_current: {}",
        transaction::current_path().display()
    );
    println!("transaction_lock: {}", transaction::lock_path().display());
    println!("output_sanitization: ansi-and-control-stripped");
    println!("progress_loader: aisling:tqdm");
    match current_rss_kib() {
        Some(rss) => println!("rss_kib: {rss}"),
        None => println!("rss_kib: unavailable"),
    }
}

fn current_rss_kib() -> Option<u64> {
    let status = std::fs::read_to_string("/proc/self/status").ok()?;
    status.lines().find_map(|line| {
        line.strip_prefix("VmRSS:")?
            .split_whitespace()
            .next()?
            .parse()
            .ok()
    })
}