Skip to content

Commit 358eb58

Browse files
authored
Merge pull request #2559 from alexissellier/list-port-json-output
feat: add a json output for list port command
2 parents 9483c4f + 554d4ce commit 358eb58

1 file changed

Lines changed: 35 additions & 5 deletions

File tree

cmd/list/ports.go

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package list
22

33
import (
44
"context"
5+
"encoding/json"
6+
"fmt"
57

68
"github.com/loft-sh/devspace/cmd/flags"
79
"github.com/loft-sh/devspace/pkg/util/factory"
@@ -13,6 +15,14 @@ import (
1315

1416
type portsCmd struct {
1517
*flags.GlobalFlags
18+
19+
Output string
20+
}
21+
22+
type jsonOutput struct {
23+
ImageSelector string `json:"imageSelector"`
24+
LabelSelector string `json:"labelSelector"`
25+
Port string `json:"port"`
1626
}
1727

1828
func newPortsCmd(f factory.Factory, globalFlags *flags.GlobalFlags) *cobra.Command {
@@ -33,6 +43,7 @@ Lists the port forwarding configurations
3343
return cmd.RunListPort(f, cobraCmd, args)
3444
}}
3545

46+
portsCmd.Flags().StringVarP(&cmd.Output, "output", "o", "", "The output format of the command. Can be either empty or json")
3647
return portsCmd
3748
}
3849

@@ -80,11 +91,30 @@ func (cmd *portsCmd) RunListPort(f factory.Factory, cobraCmd *cobra.Command, arg
8091
logger.Info("No ports are forwarded.\n")
8192
return nil
8293
}
83-
headerColumnNames := []string{
84-
"ImageSelector",
85-
"LabelSelector",
86-
"Ports (Local:Remote)",
94+
95+
switch cmd.Output {
96+
case "":
97+
headerColumnNames := []string{
98+
"ImageSelector",
99+
"LabelSelector",
100+
"Ports (Local:Remote)",
101+
}
102+
log.PrintTable(logger, headerColumnNames, portForwards)
103+
case "json":
104+
output := make([]jsonOutput, 0)
105+
for _, portFoward := range portForwards {
106+
output = append(output, jsonOutput{
107+
ImageSelector: portFoward[0],
108+
LabelSelector: portFoward[1],
109+
Port: portFoward[2],
110+
})
111+
}
112+
113+
out, err := json.MarshalIndent(output, "", " ")
114+
if err != nil {
115+
return err
116+
}
117+
fmt.Print(string(out))
87118
}
88-
log.PrintTable(logger, headerColumnNames, portForwards)
89119
return nil
90120
}

0 commit comments

Comments
 (0)