github.com/meulengracht/snapd@v0.0.0-20210719210640-8bde69bcc84e/cmd/snap/cmd_keys.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2016-2021 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package main 21 22 import ( 23 "encoding/json" 24 "fmt" 25 26 "github.com/jessevdk/go-flags" 27 28 "github.com/snapcore/snapd/i18n" 29 ) 30 31 type cmdKeys struct { 32 JSON bool `long:"json"` 33 } 34 35 func init() { 36 cmd := addCommand("keys", 37 i18n.G("List cryptographic keys"), 38 i18n.G(` 39 The keys command lists cryptographic keys that can be used for signing 40 assertions. 41 `), 42 func() flags.Commander { 43 return &cmdKeys{} 44 }, map[string]string{ 45 // TRANSLATORS: This should not start with a lowercase letter. 46 "json": i18n.G("Output results in JSON format"), 47 }, nil) 48 cmd.hidden = true 49 cmd.completeHidden = true 50 } 51 52 // Key represents a key that can be used for signing assertions. 53 type Key struct { 54 Name string `json:"name"` 55 Sha3_384 string `json:"sha3-384"` 56 } 57 58 func outputJSON(keys []Key) error { 59 obj, err := json.Marshal(keys) 60 if err != nil { 61 return err 62 } 63 fmt.Fprintf(Stdout, "%s\n", obj) 64 return nil 65 } 66 67 func outputText(keys []Key) error { 68 if len(keys) == 0 { 69 fmt.Fprintf(Stderr, "No keys registered, see `snapcraft create-key`\n") 70 return nil 71 } 72 73 w := tabWriter() 74 defer w.Flush() 75 76 fmt.Fprintln(w, i18n.G("Name\tSHA3-384")) 77 for _, key := range keys { 78 fmt.Fprintf(w, "%s\t%s\n", key.Name, key.Sha3_384) 79 } 80 return nil 81 } 82 83 func (x *cmdKeys) Execute(args []string) error { 84 if len(args) > 0 { 85 return ErrExtraArgs 86 } 87 88 keypairMgr, err := getKeypairManager() 89 if err != nil { 90 return err 91 } 92 93 kinfos, err := keypairMgr.List() 94 if err != nil { 95 return err 96 } 97 keys := make([]Key, len(kinfos)) 98 for i, kinfo := range kinfos { 99 keys[i].Name = kinfo.Name 100 keys[i].Sha3_384 = kinfo.ID 101 } 102 103 if x.JSON { 104 return outputJSON(keys) 105 } 106 107 return outputText(keys) 108 }