/
main.go
83 lines (70 loc) · 2.25 KB
/
main.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
package list
import (
"encoding/json"
"errors"
"fmt"
"github.com/jszwec/csvutil"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"go.bug.st/serial"
"strings"
)
var CommandDefinition = &cobra.Command{
Use: "list",
Short: "List all serial ports",
Long: `List all serial ports available on the system, in various forms.`,
RunE: main,
}
var configPrint0 bool // print with "\0" as the separator; useful when running with Linux philosophy
var configPrintFormat string
var configPrintSerializeWrapInObject bool
var configPrintSerializeDoNotPretty bool
func init() {
CommandDefinition.PersistentFlags().BoolVar(&configPrint0, "print0", false, "Use '\\0' as the separator")
CommandDefinition.PersistentFlags().StringVar(&configPrintFormat, "format", "table", "Print detailed information in the specified format (supported formats: simple, table, json, csv)")
CommandDefinition.PersistentFlags().BoolVar(&configPrintSerializeWrapInObject, "json-wrap-in-object", false, "JSON: Wrap the array in an object (a compatibility option for some weak JSON parsers)")
CommandDefinition.PersistentFlags().BoolVar(&configPrintSerializeDoNotPretty, "json-do-not-pretty", false, "JSON: Do not pretty print")
}
func main(cmd *cobra.Command, args []string) error {
log.Traceln("serial list main()")
serialPortList, err := serial.GetPortsList()
if err != nil {
log.WithError(err).Errorln("error getting serial port list")
return err
}
separator := "\n"
if configPrint0 {
separator = "\x00"
}
switch strings.ToLower(configPrintFormat) {
case "simple":
fmt.Print(strings.Join(serialPortList, separator))
case "table":
formatTable()
case "detail", "detailed", "table-wide":
formatTableWide()
case "json":
var d interface{}
if configPrintSerializeWrapInObject {
d = serialPortEnvelope{
Ports: getPortDetail(),
}
} else {
d = getPortDetail()
}
return portDetailDump(d, func(d interface{}) ([]byte, error) {
if configPrintSerializeDoNotPretty {
return json.Marshal(d)
} else {
return json.MarshalIndent(d, "", " ")
}
})
case "csv":
d := getPortDetail()
return portDetailDump(d, csvutil.Marshal)
default:
log.Errorf("unknown format: %s", configPrintFormat)
return errors.New("unknown format")
}
return nil
}