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 - Description: Returns a list of port mappings, newline delimited
- Invoked by: Various networking plugins - Invoked by: Various networking plugins
- Arguments: `$APP` - Arguments: `$APP $FORMAT`
- Example: - Example:
```shell ```shell

View File

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

View File

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

View File

@@ -1,6 +1,7 @@
package ports package ports
import ( import (
"encoding/json"
"fmt" "fmt"
"sort" "sort"
@@ -64,17 +65,35 @@ func TriggerPortsConfigure(appName string) error {
} }
// TriggerPortsGet prints out the port mapping for a given app // 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) portMaps := getPortMaps(appName)
if len(portMaps) == 0 { if len(portMaps) == 0 {
portMaps = getDetectedPortMaps(appName) portMaps = getDetectedPortMaps(appName)
} }
persisted := []PortMap{}
for _, portMap := range portMaps { for _, portMap := range portMaps {
if portMap.AllowsPersistence() { if portMap.AllowsPersistence() {
continue 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) fmt.Println(portMap)
} }