vpac / src / autoremove.v
72 lines · 58 sloc · 1.99 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
Raw
1module main
2
3import alpm
4
5// mirrors pacman's -Rns $(pacman -Qtdq) idiom: remove every orphaned
6// package, letting the transaction pull in the dependencies that become
7// unneeded along the way (recurse), dropping their config files (nosave)
8fn autoremove(config ConfigAutoRemove) ! {
9 mut ui := new_trans_ui(noconfirm: config.noconfirm)
10 check_ask_db_lock(mut ui)
11
12 mut handle := init_handle(ui)!
13 defer { handle.release() or { went_on('release the alpm handle', err) } }
14 defer { ui.stop() }
15 defer { trans_cleanup(handle) }
16
17 mut s := ui.spinner(text: 'finding orphans')
18 s.start()
19 defer { stop_spinner(mut s) }
20
21 mut pkgcache := local_pkgcache(handle)!
22
23 orphs := orphan_pkgs(mut pkgcache, false)
24 if orphs.len == 0 {
25 stop_spinner(mut s)
26 ui.pause()
27 report('no orphans')
28 return
29 }
30 // the config can hold a package even when it is an orphan
31 check_hold(orphs.map(it.get_name()))!
32
33 s.set_text('preparing removal')
34 trans_begin(handle, alpm.TransFlag.recurse | alpm.TransFlag.no_save)!
35 for pkg in orphs {
36 handle.remove_pkg(pkg)!
37 }
38
39 trans_prepare_checked(handle)!
40
41 // never empty: every orphan is a target, recurse only adds to them, and
42 // without the unneeded flag libalpm drops no target, it fails instead
43 victims := handle.trans_get_remove().pkgs()
44
45 stop_spinner(mut s)
46
47 // the transaction is the truth of what goes: a package held by the
48 // config that only the recurse would reach counts for the hold list too
49 check_hold(victims.map(it.get_name()))!
50
51 if !trans_confirm(mut ui, handle, victims, .autoremove) {
52 return
53 }
54
55 // the names are read before the commit, which frees the removed packages
56 names := victims.map(it.get_name())
57
58 mut s2 := ui.spinner(text: 'removing orphans')
59 s2.start()
60 defer { stop_spinner(mut s2) }
61 trans_commit(handle)!
62 stop_spinner(mut s2)
63 // a frontend learns what went as from every transaction: a done event
64 if ipc_on() {
65 emit(DoneEvent{
66 action: 'removed'
67 packages: names
68 })
69 return
70 }
71 ui.say('removed ${success(names.len.str())} orphaned packages')
72}
73