/
cmd_advise.go
336 lines (289 loc) · 8.61 KB
/
cmd_advise.go
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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2018 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net"
"os"
"sort"
"strconv"
"github.com/jessevdk/go-flags"
"github.com/snapcore/snapd/advisor"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/osutil"
)
type cmdAdviseSnap struct {
Positionals struct {
CommandOrPkg string
} `positional-args:"true"`
Format string `long:"format" default:"pretty" choice:"pretty" choice:"json"`
// Command makes advise try to find snaps that provide this command
Command bool `long:"command"`
// FromApt tells advise that it got started from an apt hook
// and needs to communicate over a socket
FromApt bool `long:"from-apt"`
// DumpDb dumps the whole advise database
DumpDb bool `long:"dump-db"`
}
var shortAdviseSnapHelp = i18n.G("Advise on available snaps")
var longAdviseSnapHelp = i18n.G(`
The advise-snap command searches for and suggests the installation of snaps.
If --command is given, it suggests snaps that provide the given command.
Otherwise it suggests snaps with the given name.
`)
func init() {
cmd := addCommand("advise-snap", shortAdviseSnapHelp, longAdviseSnapHelp, func() flags.Commander {
return &cmdAdviseSnap{}
}, map[string]string{
// TRANSLATORS: This should not start with a lowercase letter.
"command": i18n.G("Advise on snaps that provide the given command"),
// TRANSLATORS: This should not start with a lowercase letter.
"dump-db": i18n.G("Dump advise database for use by command-not-found."),
// TRANSLATORS: This should not start with a lowercase letter.
"from-apt": i18n.G("Run as an apt hook"),
// TRANSLATORS: This should not start with a lowercase letter.
"format": i18n.G("Use the given output format"),
}, []argDesc{
// TRANSLATORS: This needs to begin with < and end with >
{name: i18n.G("<command or pkg>")},
})
cmd.hidden = true
}
func outputAdviseExactText(command string, result []advisor.Command) error {
fmt.Fprintf(Stdout, "\n")
// TRANSLATORS: %q is a command name (like "gimp" or "loimpress")
fmt.Fprintf(Stdout, i18n.G("Command %q not found, but can be installed with:\n"), command)
fmt.Fprintf(Stdout, "\n")
for _, snap := range result {
fmt.Fprintf(Stdout, "sudo snap install %s\n", snap.Snap)
}
fmt.Fprintf(Stdout, "\n")
fmt.Fprintln(Stdout, i18n.G("See 'snap info <snap name>' for additional versions."))
fmt.Fprintf(Stdout, "\n")
return nil
}
func outputAdviseMisspellText(command string, result []advisor.Command) error {
fmt.Fprintf(Stdout, "\n")
fmt.Fprintf(Stdout, i18n.G("Command %q not found, did you mean:\n"), command)
fmt.Fprintf(Stdout, "\n")
for _, snap := range result {
fmt.Fprintf(Stdout, i18n.G(" command %q from snap %q\n"), snap.Command, snap.Snap)
}
fmt.Fprintf(Stdout, "\n")
fmt.Fprintln(Stdout, i18n.G("See 'snap info <snap name>' for additional versions."))
fmt.Fprintf(Stdout, "\n")
return nil
}
func outputAdviseJSON(command string, results []advisor.Command) error {
enc := json.NewEncoder(Stdout)
enc.Encode(results)
return nil
}
type jsonRPC struct {
JsonRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params struct {
Command string `json:"command"`
UnknownPackages []string `json:"unknown-packages"`
}
}
// readRpc reads a apt json rpc protocol 0.1 message as described in
// https://salsa.debian.org/apt-team/apt/blob/master/doc/json-hooks-protocol.md#wire-protocol
func readRpc(r *bufio.Reader) (*jsonRPC, error) {
line, err := r.ReadBytes('\n')
if err != nil && err != io.EOF {
return nil, fmt.Errorf("cannot read json-rpc: %v", err)
}
if osutil.GetenvBool("SNAP_APT_HOOK_DEBUG") {
fmt.Fprintf(os.Stderr, "%s\n", line)
}
var rpc jsonRPC
if err := json.Unmarshal(line, &rpc); err != nil {
return nil, err
}
// empty \n
emptyNL, _, err := r.ReadLine()
if err != nil {
return nil, err
}
if string(emptyNL) != "" {
return nil, fmt.Errorf("unexpected line: %q (empty)", emptyNL)
}
return &rpc, nil
}
func adviseViaAptHook() error {
sockFd := os.Getenv("APT_HOOK_SOCKET")
if sockFd == "" {
return fmt.Errorf("cannot find APT_HOOK_SOCKET env")
}
fd, err := strconv.Atoi(sockFd)
if err != nil {
return fmt.Errorf("expected APT_HOOK_SOCKET to be a decimal integer, found %q", sockFd)
}
f := os.NewFile(uintptr(fd), "apt-hook-socket")
if f == nil {
return fmt.Errorf("cannot open file descriptor %v", fd)
}
defer f.Close()
conn, err := net.FileConn(f)
if err != nil {
return fmt.Errorf("cannot connect to %v: %v", fd, err)
}
defer conn.Close()
r := bufio.NewReader(conn)
// handshake
rpc, err := readRpc(r)
if err != nil {
return err
}
if rpc.Method != "org.debian.apt.hooks.hello" {
return fmt.Errorf("expected 'hello' method, got: %v", rpc.Method)
}
if _, err := conn.Write([]byte(`{"jsonrpc":"2.0","id":0,"result":{"version":"0.1"}}` + "\n\n")); err != nil {
return err
}
// payload
rpc, err = readRpc(r)
if err != nil {
return err
}
if rpc.Method == "org.debian.apt.hooks.install.fail" {
for _, pkgName := range rpc.Params.UnknownPackages {
match, err := advisor.FindPackage(pkgName)
if err == nil && match != nil {
fmt.Fprintf(Stdout, "\n")
fmt.Fprintf(Stdout, i18n.G("No apt package %q, but there is a snap with that name.\n"), pkgName)
fmt.Fprintf(Stdout, i18n.G("Try \"snap install %s\"\n"), pkgName)
fmt.Fprintf(Stdout, "\n")
}
}
}
// if rpc.Method == "org.debian.apt.hooks.search.post" {
// // FIXME: do a snap search here
// // FIXME2: figure out why apt does not tell us the search results
// }
// bye
rpc, err = readRpc(r)
if err != nil {
return err
}
if rpc.Method != "org.debian.apt.hooks.bye" {
return fmt.Errorf("expected 'bye' method, got: %v", rpc.Method)
}
return nil
}
type Snap struct {
Snap string
Version string
Command string
}
func dumpDbHook() error {
commands, err := advisor.DumpCommands()
if err != nil {
return err
}
commands_processed := make([]string, 0)
var b []Snap
var sortedCmds []string
for cmd := range commands {
sortedCmds = append(sortedCmds, cmd)
}
sort.Strings(sortedCmds)
for _, key := range sortedCmds {
value := commands[key]
err := json.Unmarshal([]byte(value), &b)
if err != nil {
return err
}
for i := range b {
var s = fmt.Sprintf("%s %s %s\n", key, b[i].Snap, b[i].Version)
commands_processed = append(commands_processed, s)
}
}
for _, value := range commands_processed {
fmt.Fprint(Stdout, value)
}
return nil
}
func (x *cmdAdviseSnap) Execute(args []string) error {
if len(args) > 0 {
return ErrExtraArgs
}
if x.DumpDb {
return dumpDbHook()
}
if x.FromApt {
return adviseViaAptHook()
}
if len(x.Positionals.CommandOrPkg) == 0 {
return fmt.Errorf("the required argument `<command or pkg>` was not provided")
}
if x.Command {
return adviseCommand(x.Positionals.CommandOrPkg, x.Format)
}
return advisePkg(x.Positionals.CommandOrPkg)
}
func advisePkg(pkgName string) error {
match, err := advisor.FindPackage(pkgName)
if err != nil {
return fmt.Errorf("advise for pkgname failed: %s", err)
}
if match != nil {
fmt.Fprintf(Stdout, i18n.G("Packages matching %q:\n"), pkgName)
fmt.Fprintf(Stdout, " * %s - %s\n", match.Snap, match.Summary)
fmt.Fprintf(Stdout, i18n.G("Try: snap install <selected snap>\n"))
}
// FIXME: find mispells
return nil
}
func adviseCommand(cmd string, format string) error {
// find exact matches
matches, err := advisor.FindCommand(cmd)
if err != nil {
return fmt.Errorf("advise for command failed: %s", err)
}
if len(matches) > 0 {
switch format {
case "json":
return outputAdviseJSON(cmd, matches)
case "pretty":
return outputAdviseExactText(cmd, matches)
default:
return fmt.Errorf("unsupported format %q", format)
}
}
// find misspellings
matches, err = advisor.FindMisspelledCommand(cmd)
if err != nil {
return err
}
if len(matches) > 0 {
switch format {
case "json":
return outputAdviseJSON(cmd, matches)
case "pretty":
return outputAdviseMisspellText(cmd, matches)
default:
return fmt.Errorf("unsupported format %q", format)
}
}
return fmt.Errorf("%s: command not found", cmd)
}