/
cli.go
940 lines (772 loc) · 25 KB
/
cli.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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
)
var version = "UNDEFINED"
// globalOptions defines global command line options available for all commands.
// They're read by the top-level command and passed to the sub-command factories.
type globalOptions struct {
user string
password string
out io.StringWriter
}
// rootCommand creates the top-level `buneary` command without any functionality.
func rootCommand() *cobra.Command {
options := globalOptions{
out: os.Stdout,
}
root := &cobra.Command{
Use: "buneary",
Short: "An easy-to-use CLI client for RabbitMQ.",
Long: `buneary, pronounced bun-ear-y, is an easy-to-use RabbitMQ command line client
for managing exchanges, managing queues, publishing messages to exchanges and reading messages from queues.`,
Version: version,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
return nil
},
}
root.AddCommand(createCommand(&options))
root.AddCommand(getCommand(&options))
root.AddCommand(publishCommand(&options))
root.AddCommand(deleteCommand(&options))
root.AddCommand(versionCommand(&options))
root.PersistentFlags().
StringVarP(&options.user, "user", "u", "", "the username to connect with")
root.PersistentFlags().
StringVarP(&options.password, "password", "p", "", "the password to authenticate with")
return root
}
// createCommand creates the `buneary create` command without any functionality.
func createCommand(options *globalOptions) *cobra.Command {
create := &cobra.Command{
Use: "create <COMMAND>",
Short: "Create a resource",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
create.AddCommand(createExchangeCommand(options))
create.AddCommand(createQueueCommand(options))
create.AddCommand(createBindingCommand(options))
return create
}
// createExchangeOptions defines options for creating a new exchange.
type createExchangeOptions struct {
*globalOptions
durable bool
autoDelete bool
internal bool
noWait bool
}
// createExchangeCommand creates the `buneary create exchange` command, making sure
// that exactly three arguments are passed.
//
// At the moment, there is no support for setting Exchange.NoWait via this command.
func createExchangeCommand(options *globalOptions) *cobra.Command {
createExchangeOptions := &createExchangeOptions{
globalOptions: options,
}
createExchange := &cobra.Command{
Use: "exchange <ADDRESS> <NAME> <TYPE>",
Short: "Create a new exchange",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
return runCreateExchange(createExchangeOptions, args)
},
}
createExchange.Flags().
BoolVar(&createExchangeOptions.durable, "durable", false, "make the exchange durable")
createExchange.Flags().
BoolVar(&createExchangeOptions.autoDelete, "auto-delete", false, "make the exchange auto-deleted")
createExchange.Flags().
BoolVar(&createExchangeOptions.internal, "internal", false, "make the exchange internal")
return createExchange
}
// runCreateExchange creates a new exchange by reading the command line data, setting
// the configuration and calling the runCreateExchange function. In case the password
// or both the user and password aren't provided, it will go into interactive mode.
//
// ToDo: Move the logic for parsing the exchange type into Exchange.
func runCreateExchange(options *createExchangeOptions, args []string) error {
var (
address = args[0]
name = args[1]
exchangeType = args[2]
)
user, password := getOrReadInCredentials(options.globalOptions)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
exchange := Exchange{
Name: name,
Durable: options.durable,
AutoDelete: options.autoDelete,
Internal: options.internal,
NoWait: options.noWait,
}
switch exchangeType {
case "direct":
exchange.Type = Direct
case "headers":
exchange.Type = Headers
case "fanout":
exchange.Type = Fanout
case "topic":
exchange.Type = Topic
}
if err := provider.CreateExchange(exchange); err != nil {
return err
}
_, _ = options.out.WriteString("exchange created successfully\n")
return nil
}
// createQueueOptions defines options for creating a new queue.
type createQueueOptions struct {
*globalOptions
durable bool
autoDelete bool
}
// createQueueCommand creates the `buneary create queue` command, making sure that
// exactly three arguments are passed.
//
// The <TYPE> argument may become optional for convenience in the future. In this
// case, it should default to the classic queue type.
func createQueueCommand(options *globalOptions) *cobra.Command {
createQueueOptions := &createQueueOptions{
globalOptions: options,
}
createQueue := &cobra.Command{
Use: "queue <ADDRESS> <NAME> <TYPE>",
Short: "Create a new queue",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
return runCreateQueue(createQueueOptions, args)
},
}
createQueue.Flags().
BoolVar(&createQueueOptions.durable, "durable", false, "make the queue durable")
createQueue.Flags().
BoolVar(&createQueueOptions.autoDelete, "auto-delete", false, "make the queue auto-deleted")
return createQueue
}
// runCreateQueue creates a new queue by reading the command line data, setting the
// configuration and calling the CreateQueue function. In case the password or both
// the user and password aren't provided, it will go into interactive mode.
//
// If the queue type is empty or invalid, the queue type defaults to Classic.
func runCreateQueue(options *createQueueOptions, args []string) error {
var (
address = args[0]
name = args[1]
queueType = args[2]
)
user, password := getOrReadInCredentials(options.globalOptions)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
queue := Queue{
Name: name,
Durable: options.durable,
AutoDelete: options.autoDelete,
}
switch queueType {
case "quorum":
queue.Type = Quorum
case "classic":
fallthrough
default:
queue.Type = Classic
}
_, err := provider.CreateQueue(queue)
if err != nil {
return err
}
_, _ = options.out.WriteString("queue created successfully\n")
return nil
}
// createBindingOptions defines options for creating a new binding.
type createBindingOptions struct {
*globalOptions
toExchange bool
}
// createBindingCommand creates the `buneary create binding` command, making sure
// that exactly four arguments are passed.
func createBindingCommand(options *globalOptions) *cobra.Command {
createBindingOptions := &createBindingOptions{
globalOptions: options,
}
createQueue := &cobra.Command{
Use: "binding <ADDRESS> <NAME> <TARGET> <BINDING KEY>",
Short: "Create a new binding",
Args: cobra.ExactArgs(4),
RunE: func(cmd *cobra.Command, args []string) error {
return runCreateBinding(createBindingOptions, args)
},
}
createQueue.Flags().
BoolVar(&createBindingOptions.toExchange, "to-exchange", false, "the target is another exchange")
return createQueue
}
// runCreateBinding creates a new binding by reading the command line data, setting
// the configuration and calling the CreateQueue function. In case the password or
// both the user and password aren't provided, it will go into interactive mode.
//
// The binding type defaults to ToQueue. To create a binding to another exchange, the
// --to-exchange flag has to be used.
func runCreateBinding(options *createBindingOptions, args []string) error {
var (
address = args[0]
name = args[1]
target = args[2]
bindingKey = args[3]
)
user, password := getOrReadInCredentials(options.globalOptions)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
binding := Binding{
From: Exchange{Name: name},
TargetName: target,
Key: bindingKey,
}
switch options.toExchange {
case true:
binding.Type = ToExchange
default:
binding.Type = ToQueue
}
if err := provider.CreateBinding(binding); err != nil {
return err
}
_, _ = options.out.WriteString("queue created successfully\n")
return nil
}
// getCommand creates the `buneary get` command without any functionality.
func getCommand(options *globalOptions) *cobra.Command {
get := &cobra.Command{
Use: "get <COMMAND>",
Short: "Get a resource",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
get.AddCommand(getExchangesCommand(options))
get.AddCommand(getExchangeCommand(options))
get.AddCommand(getQueuesCommand(options))
get.AddCommand(getQueueCommand(options))
get.AddCommand(getBindingsCommand(options))
get.AddCommand(getBindingCommand(options))
get.AddCommand(getMessagesCommand(options))
return get
}
// getExchangesCommand creates the `buneary get exchanges` command, making sure that
// exactly one argument is passed.
func getExchangesCommand(options *globalOptions) *cobra.Command {
getExchanges := &cobra.Command{
Use: "exchanges <ADDRESS>",
Short: "Get all available exchanges",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runGetExchanges(options, args)
},
}
return getExchanges
}
// getExchangeCommand creates the `buneary get exchange` command, making sure that exactly
// two arguments are passed.
func getExchangeCommand(options *globalOptions) *cobra.Command {
getExchange := &cobra.Command{
Use: "exchange <ADDRESS> <NAME>",
Short: "Get a single exchange",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return runGetExchanges(options, args)
},
}
return getExchange
}
// runGetExchanges either returns all exchanges or - if an exchange name has been
// specified as second argument - a single exchange. In case the password or both
// the user and password aren't provided, it will go into interactive mode.
//
// This flexibility allows runGetExchanges to be used by both `buneary get exchanges`
// as well as `buneary get exchange`.
func runGetExchanges(options *globalOptions, args []string) error {
var (
address = args[0]
)
user, password := getOrReadInCredentials(options)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
// The default filter will let pass all exchanges regardless of their names.
filter := func(_ Exchange) bool {
return true
}
// However, if an exchange name has been specified as second argument, only
// that particular exchange should be returned.
if len(args) > 1 {
filter = func(exchange Exchange) bool {
return exchange.Name == args[1]
}
}
exchanges, err := provider.GetExchanges(filter)
if err != nil {
return err
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "Type", "Durable", "Auto-Delete", "Internal"})
for _, exchange := range exchanges {
row := make([]string, 5)
row[0] = exchange.Name
row[1] = string(exchange.Type)
row[2] = boolToString(exchange.Durable)
row[3] = boolToString(exchange.AutoDelete)
row[4] = boolToString(exchange.Internal)
table.Append(row)
}
table.Render()
return nil
}
// getQueuesCommand creates the `buneary get queues` command, making sure that
// exactly one argument is passed.
func getQueuesCommand(options *globalOptions) *cobra.Command {
getQueues := &cobra.Command{
Use: "queues <ADDRESS>",
Short: "Get all available queues",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runGetQueues(options, args)
},
}
return getQueues
}
// getQueueCommand creates the `buneary get queue` command, making sure that exactly two
// arguments are passed.
func getQueueCommand(options *globalOptions) *cobra.Command {
getQueue := &cobra.Command{
Use: "queue <ADDRESS> <NAME>",
Short: "Get a single queue",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return runGetQueues(options, args)
},
}
return getQueue
}
// runGetQueues either returns all queues or - if a queue name has been specified as second
// argument - a single queue. In case the password or both the user and password aren't
// provided, it will go into interactive mode.
//
// This flexibility allows runGetQueues to be used by both `buneary get queues` as well as
// `buneary get queue`.
func runGetQueues(options *globalOptions, args []string) error {
var (
address = args[0]
)
user, password := getOrReadInCredentials(options)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
// The default filter will let pass all queues regardless of their names.
filter := func(_ Queue) bool {
return true
}
// However, if a queue name has been specified as second argument, only that
// particular queue should be returned.
if len(args) > 1 {
filter = func(queue Queue) bool {
return queue.Name == args[1]
}
}
queues, err := provider.GetQueues(filter)
if err != nil {
return err
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "Durable", "Auto-Delete"})
for _, queue := range queues {
row := make([]string, 3)
row[0] = queue.Name
row[1] = boolToString(queue.Durable)
row[2] = boolToString(queue.AutoDelete)
table.Append(row)
}
table.Render()
return nil
}
// getBindingsCommand creates the `buneary get bindings` command, making sure that
// exactly one argument is passed.
func getBindingsCommand(options *globalOptions) *cobra.Command {
getQueues := &cobra.Command{
Use: "bindings <ADDRESS>",
Short: "Get all available bindings",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return runGetBindings(options, args)
},
}
return getQueues
}
// getBindingCommand creates the `buneary get binding` command, making sure that exactly
// three arguments are passed.
func getBindingCommand(options *globalOptions) *cobra.Command {
getQueue := &cobra.Command{
Use: "binding <ADDRESS> <EXCHANGE NAME> <TARGET NAME>",
Short: "Get the binding or bindings between two resources",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
return runGetBindings(options, args)
},
}
return getQueue
}
// runGetBindings either returns all bindings or - if a queue name has been specified as second
// argument - a single binding. In case the password or both the user and password aren't
// provided, it will go into interactive mode.
//
// This flexibility allows runGetBindings to be used by both `buneary get bindings` as well as
// `buneary get binding`.
func runGetBindings(options *globalOptions, args []string) error {
var (
address = args[0]
)
user, password := getOrReadInCredentials(options)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
// The default filter will let pass all bindings regardless of their names.
filter := func(_ Binding) bool {
return true
}
// However, if a source exchange and a binding target have been specified as
// second argument, only that particular binding should be returned.
if len(args) > 2 {
filter = func(binding Binding) bool {
return binding.From.Name == args[1] &&
binding.TargetName == args[2]
}
}
bindings, err := provider.GetBindings(filter)
if err != nil {
return err
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"From", "Target", "Type", "Binding Key"})
for _, binding := range bindings {
row := make([]string, 4)
row[0] = binding.From.Name
row[1] = binding.TargetName
row[2] = string(binding.Type)
row[3] = binding.Key
table.Append(row)
}
table.Render()
return nil
}
// getMessagesOptions defines options for reading messages.
type getMessagesOptions struct {
*globalOptions
max int
requeue bool
force bool
}
// getMessagesCommand creates the `buneary get messages` command, making sure that exactly
// two arguments are passed.
func getMessagesCommand(options *globalOptions) *cobra.Command {
getMessagesOptions := &getMessagesOptions{
globalOptions: options,
}
getMessages := &cobra.Command{
Use: "messages <ADDRESS> <QUEUE NAME>",
Short: "Get messages in a queue",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return runGetMessages(getMessagesOptions, args)
},
}
getMessages.Flags().
IntVar(&getMessagesOptions.max, "max", 1, "maximum messages to read")
getMessages.Flags().
BoolVar(&getMessagesOptions.requeue, "requeue", false, "re-queue the messages after reading them")
getMessages.Flags().
BoolVarP(&getMessagesOptions.force, "force", "f", false, "force running this command without opt-in")
return getMessages
}
// runGetMessages gets messages by reading the command line data, setting the
// configuration and calling the GetMessages function. In case the password or
// both the user and password aren't provided, it will go into interactive mode.
func runGetMessages(options *getMessagesOptions, args []string) error {
var (
address = args[0]
queue = args[1]
)
message := "Reading the messages from the queue will de-queue them." +
"To re-queue them, pass the --requeue flag. Do you want to continue?"
if !options.force {
ok := confirm(options.globalOptions, message)
if !ok {
return nil
}
}
user, password := getOrReadInCredentials(options.globalOptions)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
messages, err := provider.GetMessages(Queue{Name: queue}, options.max, options.requeue)
if err != nil {
return err
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Exchange", "Routing Key", "Body"})
for _, message := range messages {
row := make([]string, 3)
row[0] = message.Target.Name
row[1] = message.RoutingKey
row[2] = string(message.Body)
table.Append(row)
}
table.Render()
return nil
}
// publishOptions defines options for publishing a message.
type publishOptions struct {
*globalOptions
headers string
}
// publishCommand creates the `buneary publish` command, making sure that exactly
// four command arguments are passed.
func publishCommand(options *globalOptions) *cobra.Command {
publishOptions := &publishOptions{
globalOptions: options,
}
publish := &cobra.Command{
Use: "publish <ADDRESS> <EXCHANGE> <ROUTING KEY> <BODY>",
Short: "Publish a message to an exchange",
Args: cobra.ExactArgs(4),
RunE: func(cmd *cobra.Command, args []string) error {
return runPublish(publishOptions, args)
},
}
publish.Flags().
StringVar(&publishOptions.headers, "headers", "", "headers as comma-separated key-value pairs")
return publish
}
// runPublish publishes a message by reading the command line data, setting the
// configuration and calling the PublishMessage function. In case the password or
// both the user and password aren't provided, it will go into interactive mode.
func runPublish(options *publishOptions, args []string) error {
var (
address = args[0]
exchange = args[1]
routingKey = args[2]
body = args[3]
)
user, password := getOrReadInCredentials(options.globalOptions)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
message := Message{
Target: Exchange{Name: exchange},
Headers: make(map[string]interface{}),
RoutingKey: routingKey,
Body: []byte(body),
}
if options.headers != "" {
// Parse the message headers in the form key1=val1,key2=val2. If the headers
// do not adhere to this syntax, an error is returned. In case the same key
// exists multiple times, the last one wins.
for _, header := range strings.Split(options.headers, ",") {
tokens := strings.Split(strings.TrimSpace(header), "=")
if len(tokens) != 2 {
return errors.New("expected header in form key=value")
}
key := tokens[0]
value := tokens[1]
message.Headers[key] = value
}
}
if err := provider.PublishMessage(message); err != nil {
return err
}
_, _ = options.out.WriteString("message published successfully\n")
return nil
}
// deleteCommand creates the `buneary delete` command without any functionality.
func deleteCommand(options *globalOptions) *cobra.Command {
delete := &cobra.Command{
Use: "delete <COMMAND>",
Short: "Delete a resource",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
delete.AddCommand(deleteExchangeCommand(options))
delete.AddCommand(deleteQueueCommand(options))
return delete
}
// deleteExchangeCommand creates the `buneary delete exchange` command, making sure
// that exactly two arguments are passed.
func deleteExchangeCommand(options *globalOptions) *cobra.Command {
deleteExchange := &cobra.Command{
Use: "exchange <ADDRESS> <NAME>",
Short: "Delete an exchange",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return runDeleteExchange(options, args)
},
}
return deleteExchange
}
// runDeleteExchange deletes an exchange by reading the command line data, setting the
// configuration and calling the DeleteExchange function. In case the password or
// both the user and password aren't provided, it will go into interactive mode.
func runDeleteExchange(options *globalOptions, args []string) error {
var (
address = args[0]
name = args[1]
)
user, password := getOrReadInCredentials(options)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
exchange := Exchange{
Name: name,
}
if err := provider.DeleteExchange(exchange); err != nil {
return err
}
_, _ = options.out.WriteString("exchange deleted successfully\n")
return nil
}
// deleteQueueCommand creates the `buneary delete queue` command, making sure
// that exactly two arguments are passed.
func deleteQueueCommand(options *globalOptions) *cobra.Command {
deleteExchange := &cobra.Command{
Use: "queue <ADDRESS> <NAME>",
Short: "Delete a queue",
RunE: func(cmd *cobra.Command, args []string) error {
return runDeleteQueue(options, args)
},
}
return deleteExchange
}
// runDeleteQueue deletes a queue by reading the command line data, setting the
// configuration and calling the DeleteQueue function. In case the password or
// both the user and password aren't provided, it will go into interactive mode.
func runDeleteQueue(options *globalOptions, args []string) error {
var (
address = args[0]
name = args[1]
)
user, password := getOrReadInCredentials(options)
provider := NewProvider(&RabbitMQConfig{
Address: address,
User: user,
Password: password,
})
queue := Queue{
Name: name,
}
if err := provider.DeleteQueue(queue); err != nil {
return err
}
_, _ = options.out.WriteString("queue deleted successfully\n")
return nil
}
// versionCommand creates the `buneary version` command for printing release
// information. This data is injected by the CI pipeline.
func versionCommand(options *globalOptions) *cobra.Command {
version := &cobra.Command{
Use: "version",
Short: "Print version information",
RunE: func(cmd *cobra.Command, args []string) error {
output := fmt.Sprintf("buneary version %s\n", version)
_, _ = options.out.WriteString(output)
return nil
},
}
return version
}
// getOrReadInCredentials either returns the credentials directly from the global
// options or prompts the user to type them in.
//
// If both user and password have been set using the --user and --password flags,
// those values will be used. Otherwise, the user will be asked to type in both.
//
// Another option might be to only ask the user for the password in case the --user
// flag has been specified, but this is not implemented at the moment.
func getOrReadInCredentials(options *globalOptions) (string, string) {
user := options.user
password := options.password
if user != "" && password != "" {
return user, password
}
reader := bufio.NewReader(os.Stdin)
_, _ = options.out.WriteString("User: ")
user, _ = reader.ReadString('\n')
user = strings.TrimSpace(user)
signalCh := make(chan os.Signal)
signal.Notify(signalCh, os.Interrupt)
go func() {
<-signalCh
os.Exit(0)
}()
_, _ = options.out.WriteString("Password: ")
p, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
_, _ = options.out.WriteString("\nerror reading password from stdin")
os.Exit(1)
}
_, _ = options.out.WriteString("\n")
password = string(p)
return user, password
}
// confirm asks the user to confirm the given message or question by answering with
// "y" for yes or "n" for no. Returns true if the user confirmed the message.
func confirm(options *globalOptions, message string) bool {
reader := bufio.NewReader(os.Stdin)
output := fmt.Sprintf("%s [y/N] ", message)
_, _ = options.out.WriteString(output)
answer, _ := reader.ReadString('\n')
answer = strings.TrimSpace(answer)
_, _ = options.out.WriteString("\n")
return answer == "y" || answer == "yes"
}
// boolToString returns "yes" if the given bool is true and "no" if it is false.
func boolToString(source bool) string {
if source {
return "yes"
}
return "no"
}