feat: add the ability to specify the output format when listing ports

This commit is contained in:
Jose Diaz-Gonzalez
2024-01-17 18:03:36 -05:00
parent 44054ac993
commit 78d24ead09
4 changed files with 26 additions and 6 deletions

View File

@@ -1371,7 +1371,7 @@ set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x
- Description: Returns a list of port mappings, newline delimited
- Invoked by: Various networking plugins
- Arguments: `$APP`
- Arguments: `$APP $FORMAT`
- Example:
```shell

View File

@@ -6,9 +6,9 @@ import (
// PortMap is a struct that contains a scheme:host-port:container-port mapping
type PortMap struct {
ContainerPort int
HostPort int
Scheme string
ContainerPort int `json:"container_port"`
HostPort int `json:"host_port"`
Scheme string `json:"scheme"`
}
func (p PortMap) String() string {

View File

@@ -28,7 +28,8 @@ func main() {
err = ports.TriggerPortsConfigure(appName)
case "ports-get":
appName := flag.Arg(0)
err = ports.TriggerPortsGet(appName)
format := flag.Arg(1)
err = ports.TriggerPortsGet(appName, format)
case "ports-get-available":
err = ports.TriggerPortsGetAvailable()
case "ports-get-property":

View File

@@ -1,6 +1,7 @@
package ports
import (
"encoding/json"
"fmt"
"sort"
@@ -64,17 +65,35 @@ func TriggerPortsConfigure(appName string) error {
}
// TriggerPortsGet prints out the port mapping for a given app
func TriggerPortsGet(appName string) error {
func TriggerPortsGet(appName string, format string) error {
if format != "json" && format != "stdout" {
return fmt.Errorf("Invalid format specified: %s", format)
}
portMaps := getPortMaps(appName)
if len(portMaps) == 0 {
portMaps = getDetectedPortMaps(appName)
}
persisted := []PortMap{}
for _, portMap := range portMaps {
if portMap.AllowsPersistence() {
continue
}
persisted = append(persisted, portMap)
}
if format == "json" {
b, err := json.Marshal(persisted)
if err != nil {
return fmt.Errorf("Unable to marshal port mapping: %s", err.Error())
}
fmt.Println(string(b))
return nil
}
for _, portMap := range persisted {
fmt.Println(portMap)
}