11package commands
22
33import (
4+ "bytes"
45 "crypto/rand"
6+ "errors"
57 "fmt"
68 "io"
79 "sort"
810 "strings"
11+ "text/tabwriter"
912
1013 cmds "github.com/ipfs/go-ipfs/commands"
1114
@@ -28,6 +31,10 @@ type KeyOutput struct {
2831 Id string
2932}
3033
34+ type KeyOutputList struct {
35+ Keys []KeyOutput
36+ }
37+
3138var KeyGenCmd = & cmds.Command {
3239 Helptext : cmds.HelpText {
3340 Tagline : "Create a new keypair" ,
@@ -125,7 +132,7 @@ var KeyGenCmd = &cmds.Command{
125132 return nil , fmt .Errorf ("expected a KeyOutput as command result" )
126133 }
127134
128- return strings .NewReader (k .Id ), nil
135+ return strings .NewReader (k .Id + " \n " ), nil
129136 },
130137 },
131138 Type : KeyOutput {},
@@ -135,6 +142,9 @@ var KeyListCmd = &cmds.Command{
135142 Helptext : cmds.HelpText {
136143 Tagline : "List all local keypairs" ,
137144 },
145+ Options : []cmds.Option {
146+ cmds .BoolOption ("l" , "Show extra information about keys." ),
147+ },
138148 Run : func (req cmds.Request , res cmds.Response ) {
139149 n , err := req .InvocContext ().GetNode ()
140150 if err != nil {
@@ -149,10 +159,52 @@ var KeyListCmd = &cmds.Command{
149159 }
150160
151161 sort .Strings (keys )
152- res .SetOutput (& stringList {keys })
162+
163+ list := make ([]KeyOutput , 0 , len (keys ))
164+
165+ for _ , key := range keys {
166+ privKey , err := n .Repo .Keystore ().Get (key )
167+ if err != nil {
168+ res .SetError (err , cmds .ErrNormal )
169+ return
170+ }
171+
172+ pubKey := privKey .GetPublic ()
173+
174+ pid , err := peer .IDFromPublicKey (pubKey )
175+ if err != nil {
176+ res .SetError (err , cmds .ErrNormal )
177+ return
178+ }
179+
180+ list = append (list , KeyOutput {Name : key , Id : pid .Pretty ()})
181+ }
182+
183+ res .SetOutput (& KeyOutputList {list })
153184 },
154185 Marshalers : cmds.MarshalerMap {
155- cmds .Text : stringListMarshaler ,
186+ cmds .Text : keyOutputListMarshaler ,
156187 },
157- Type : stringList {},
188+ Type : KeyOutputList {},
189+ }
190+
191+ func keyOutputListMarshaler (res cmds.Response ) (io.Reader , error ) {
192+ withId , _ , _ := res .Request ().Option ("l" ).Bool ()
193+
194+ list , ok := res .Output ().(* KeyOutputList )
195+ if ! ok {
196+ return nil , errors .New ("failed to cast []KeyOutput" )
197+ }
198+
199+ buf := new (bytes.Buffer )
200+ w := tabwriter .NewWriter (buf , 1 , 2 , 1 , ' ' , 0 )
201+ for _ , s := range list .Keys {
202+ if withId {
203+ fmt .Fprintf (w , "%s\t %s\t \n " , s .Id , s .Name )
204+ } else {
205+ fmt .Fprintf (w , "%s\n " , s .Name )
206+ }
207+ }
208+ w .Flush ()
209+ return buf , nil
158210}
0 commit comments