From 4bd52b42eefa700a1c13076e17e4e17b9f3b0a7e Mon Sep 17 00:00:00 2001 From: Tom Romeo Doil Date: Tue, 10 Feb 2026 17:53:35 +0100 Subject: [PATCH 1/4] fix: use CF v3 API instead of old cf cli interface --- DefaultEnv_plugin.go | 62 +++++++++++++++++++++++- go.mod | 18 ++++++- go.sum | 110 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 187 insertions(+), 3 deletions(-) diff --git a/DefaultEnv_plugin.go b/DefaultEnv_plugin.go index 26c5d53..215a928 100644 --- a/DefaultEnv_plugin.go +++ b/DefaultEnv_plugin.go @@ -1,12 +1,16 @@ package main import ( + "context" "encoding/json" "fmt" "os" "strings" "code.cloudfoundry.org/cli/plugin" + cfClient "github.com/cloudfoundry/go-cfclient/v3/client" + cfClientConfig "github.com/cloudfoundry/go-cfclient/v3/config" + "github.com/cloudfoundry/go-cfclient/v3/resource" ) // DefaultEnvPlugin allows users to export environment variables of an app into a JSON file @@ -107,12 +111,28 @@ func runDefaultEnv(cliConnection plugin.CliConnection, args []string) error { return ErrAppNotSpecified } - app, err := cliConnection.GetApp(args[1]) + accessToken, err := cliConnection.AccessToken() if err != nil { return err } - url := fmt.Sprintf("/v3/apps/%s/env", app.Guid) + connAPIURL, err := cliConnection.ApiEndpoint() + if err != nil { + return err + } + + cliConnection.GetApps() + currentSpace, err := cliConnection.GetCurrentSpace() + if err != nil { + return err + } + + app, err := GetApp(connAPIURL, accessToken, args[1], currentSpace.Guid) + if err != nil { + return err + } + + url := fmt.Sprintf("/v3/apps/%s/env", app.GUID) env, err := cliConnection.CliCommandWithoutTerminalOutput("curl", url) if err != nil { return err @@ -130,3 +150,41 @@ func runDefaultEnv(cliConnection plugin.CliConnection, args []string) error { fmt.Println("Environment variables for " + args[1] + " written to default-env.json") return nil } + +// GetApp retrieves a Cloud Foundry application resource by its name and space GUID. +// +// It connects to the Cloud Foundry API using the provided API endpoint and access token, +// then searches for the application with the specified name within the given space. +// If the application is found, it returns a pointer to the resource.App object. +// If the application is not found or an error occurs during the process, an error is returned. +func GetApp(connAPIEndpoint string, accessToken string, appName string, currentSpaceGUID string) (*resource.App, error) { + // A refresh token is not provided by the CF CLI Plugin API and is not required as + // "AccessToken() now provides a refreshed o-auth token.", + // see https://github.com/cloudfoundry/cli/blob/main/plugin/plugin_examples/CHANGELOG.md#changes-in-v614 + refreshToken := "" + + cfg, err := cfClientConfig.New(connAPIEndpoint, cfClientConfig.Token(accessToken, refreshToken)) + if err != nil { + return nil, err + } + cf, err := cfClient.New(cfg) + if err != nil { + return nil, err + } + + appFilter := &cfClient.AppListOptions{ + Names: cfClient.Filter{Values: []string{appName}}, + SpaceGUIDs: cfClient.Filter{Values: []string{currentSpaceGUID}}, + } + apps, err := cf.Applications.ListAll(context.Background(), appFilter) + if err != nil { + return nil, err + } + + if len(apps) == 0 { + return nil, fmt.Errorf("app '%s' not found", appName) + } + + app := apps[0] + return app, nil +} diff --git a/go.mod b/go.mod index 76282a8..afb4a71 100644 --- a/go.mod +++ b/go.mod @@ -1,7 +1,23 @@ module github.com/saphanaacademy/DefaultEnv -go 1.20 +go 1.25.5 require ( code.cloudfoundry.org/cli v7.1.0+incompatible + github.com/cloudfoundry/go-cfclient/v3 v3.0.0-alpha.17 +) + +require ( + github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab // indirect + github.com/martini-contrib/render v0.0.0-20150707142108-ec18f8345a11 // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/gomega v1.39.1 // indirect + github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.11.1 // indirect + golang.org/x/oauth2 v0.30.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index a18b0b5..22a53a3 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,112 @@ code.cloudfoundry.org/cli v7.1.0+incompatible h1:1Zn3I+epQBaBvnZAaTudCQQ0WdqcWtjtjEV9MBZP08Y= code.cloudfoundry.org/cli v7.1.0+incompatible/go.mod h1:e4d+EpbwevNhyTZKybrLlyTvpH+W22vMsmdmcTxs/Fo= +github.com/cloudfoundry/go-cfclient/v3 v3.0.0-alpha.17 h1:JFsm6gxUOpWy57Z9viqaK4Fz771icckFEptpVTQ3H8w= +github.com/cloudfoundry/go-cfclient/v3 v3.0.0-alpha.17/go.mod h1:cwg8bywOst/2c5huQgBIbA5gcI4g8DLov00cJaDaFy0= +github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0 h1:sDMmm+q/3+BukdIpxwO365v/Rbspp2Nt5XntgQRXq8Q= +github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab h1:xveKWz2iaueeTaUgdetzel+U7exyigDYBryyVfV/rZk= +github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/martini-contrib/render v0.0.0-20150707142108-ec18f8345a11 h1:YFh+sjyJTMQSYjKwM4dFKhJPJC/wfo98tPUc17HdoYw= +github.com/martini-contrib/render v0.0.0-20150707142108-ec18f8345a11/go.mod h1:Ah2dBMoxZEqk118as2T4u4fjfXarE0pPnMJaArZQZsI= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= +github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= +github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw= +github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= +golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= +golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From 0104eab4926fd606cad1a8e917d16217435644c3 Mon Sep 17 00:00:00 2001 From: darmiel <71837281+darmiel@users.noreply.github.com> Date: Wed, 11 Feb 2026 10:37:47 +0100 Subject: [PATCH 2/4] feat: use API instead of CLI connection to retrieve environment --- DefaultEnv_plugin.go | 226 ++++++++++++++++++++++++++----------------- 1 file changed, 138 insertions(+), 88 deletions(-) diff --git a/DefaultEnv_plugin.go b/DefaultEnv_plugin.go index 215a928..4838015 100644 --- a/DefaultEnv_plugin.go +++ b/DefaultEnv_plugin.go @@ -3,13 +3,15 @@ package main import ( "context" "encoding/json" + "flag" "fmt" + "net/http" + "net/url" "os" - "strings" "code.cloudfoundry.org/cli/plugin" - cfClient "github.com/cloudfoundry/go-cfclient/v3/client" - cfClientConfig "github.com/cloudfoundry/go-cfclient/v3/config" + cfclient "github.com/cloudfoundry/go-cfclient/v3/client" + cfconfig "github.com/cloudfoundry/go-cfclient/v3/config" "github.com/cloudfoundry/go-cfclient/v3/resource" ) @@ -26,7 +28,7 @@ func (*DefaultEnvPlugin) Run(cliConnection plugin.CliConnection, args []string) return } if err := runDefaultEnv(cliConnection, args); err != nil { - _, _ = fmt.Fprintln(os.Stderr, "Error:", err) + _, _ = fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) } } @@ -35,9 +37,9 @@ func (c *DefaultEnvPlugin) GetMetadata() plugin.PluginMetadata { return plugin.PluginMetadata{ Name: "DefaultEnv", Version: plugin.VersionType{ - Major: 1, - Minor: 1, - Build: 1, + Major: 2, + Minor: 0, + Build: 0, }, MinCliVersion: plugin.VersionType{ Major: 7, @@ -51,6 +53,11 @@ func (c *DefaultEnvPlugin) GetMetadata() plugin.PluginMetadata { HelpText: "Create default-env.json file with environment variables of an app.", UsageDetails: plugin.Usage{ Usage: "cf default-env APP", + Options: map[string]string{ + "f": "output file name (default: default-env.json)", + "guid": "specify the app GUID directly instead of app name", + "stdout": "write output to stdout instead of a file", + }, }, }, }, @@ -61,130 +68,173 @@ func main() { plugin.Start(new(DefaultEnvPlugin)) } -// environmentResponse from /v3/apps/:guid/env -type environmentResponse struct { - SystemEnvJson map[string]interface{} `json:"system_env_json"` - ApplicationEnvJson map[string]interface{} `json:"application_env_json"` - EnvironmentVariables map[string]interface{} `json:"environment_variables"` -} +// createClient creates a new CF client using the access token and API endpoint from the CLI connection +func createClient(connection plugin.CliConnection) (*cfclient.Client, error) { + accessToken, err := connection.AccessToken() + if err != nil { + return nil, fmt.Errorf("failed to retrieve access token: %w", err) + } -// Merge all environment variables into one map -func (e environmentResponse) Merge() map[string]interface{} { - content := make(map[string]interface{}) - for k, v := range e.SystemEnvJson { - content[k] = v + endpoint, err := connection.ApiEndpoint() + if err != nil { + return nil, fmt.Errorf("failed to retrieve API endpoint: %w", err) } - for k, v := range e.ApplicationEnvJson { - content[k] = v + + cfg, err := cfconfig.New(endpoint, cfconfig.Token(accessToken, "")) + if err != nil { + return nil, fmt.Errorf("failed to create CF client config: %w", err) } - for k, v := range e.EnvironmentVariables { - content[k] = v + + client, err := cfclient.New(cfg) + if err != nil { + return nil, fmt.Errorf("failed to create CF client: %w", err) } - return content + + return client, nil } -// marshalAndWrite marshals v (any) into JSON and writes it to a file -func marshalAndWrite(v interface{}, filename string) error { - f, err := os.Create(filename) +// findAppByName retrieves the app with the specified name in the given space +func findAppByName(ctx context.Context, client *cfclient.Client, appName, spaceGUID string) (*resource.App, error) { + app, err := client.Applications.Single(ctx, &cfclient.AppListOptions{ + Names: cfclient.Filter{Values: []string{appName}}, + SpaceGUIDs: cfclient.Filter{Values: []string{spaceGUID}}, + }) if err != nil { - return err + return nil, fmt.Errorf("failed to retrieve app: %w", err) } - defer func(f *os.File) { - _ = f.Close() - }(f) + return app, nil +} - data, err := json.Marshal(v) +func findEnvironmentByAppGUID(ctx context.Context, client *cfclient.Client, appGUID string) (*AppEnvironment, error) { + seg := url.PathEscape(appGUID) + p, err := url.JoinPath("/v3/apps", seg, "env") if err != nil { - return err + return nil, fmt.Errorf("failed to construct API path: %w", err) } - if _, err = f.Write(data); err != nil { - return err + var environment AppEnvironment + req, err := http.NewRequestWithContext(ctx, "GET", client.ApiURL(p), nil) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + resp, err := client.ExecuteAuthRequest(req) + if err != nil { + return nil, fmt.Errorf("failed to execute request: %w", err) } + defer func() { + _ = resp.Body.Close() + }() - return nil + if err := json.NewDecoder(resp.Body).Decode(&environment); err != nil { + return nil, fmt.Errorf("failed to decode response: %w", err) + } + + return &environment, nil } // runDefaultEnv fetches and merges the environment variables of a specified CF app into a JSON file func runDefaultEnv(cliConnection plugin.CliConnection, args []string) error { - if len(args) != 2 { - return ErrAppNotSpecified + fs := flag.NewFlagSet("cf-defaultenv-plugin", flag.ExitOnError) + outFileFlag := fs.String("f", "default-env.json", "output file name") + appGUIDFlag := fs.String("guid", "", "specify the app GUID directly instead of app name") + writeStdoutFlag := fs.Bool("stdout", false, "write output to stdout instead of a file") + if err := fs.Parse(args[1:]); err != nil { + return fmt.Errorf("failed to parse flags: %w", err) } - accessToken, err := cliConnection.AccessToken() - if err != nil { - return err - } + ctx := context.Background() - connAPIURL, err := cliConnection.ApiEndpoint() + client, err := createClient(cliConnection) if err != nil { return err } - cliConnection.GetApps() currentSpace, err := cliConnection.GetCurrentSpace() if err != nil { - return err + return fmt.Errorf("failed to retrieve current space: %w", err) } - app, err := GetApp(connAPIURL, accessToken, args[1], currentSpace.Guid) - if err != nil { - return err + var appGUID string + if *appGUIDFlag != "" { + // if the user specified the app GUID directly, use it instead of looking up the app by name + appGUID = *appGUIDFlag + + _, _ = fmt.Fprintln(os.Stderr, "info: using provided app GUID", appGUID) + } else { + appName := fs.Arg(0) + if appName == "" { + _, _ = fmt.Fprintln(os.Stderr, "error: app name or -guid flag must be specified") + fs.Usage() + return nil + } + + app, err := findAppByName(ctx, client, appName, currentSpace.Guid) + if err != nil { + return err + } + appGUID = app.GUID + + _, _ = fmt.Fprintln(os.Stderr, "info: retrieved app", appName, "with GUID", appGUID) } - url := fmt.Sprintf("/v3/apps/%s/env", app.GUID) - env, err := cliConnection.CliCommandWithoutTerminalOutput("curl", url) + env, err := findEnvironmentByAppGUID(ctx, client, appGUID) if err != nil { - return err + return fmt.Errorf("failed to retrieve app environment: %w", err) } - var data environmentResponse - if err = json.Unmarshal([]byte(strings.Join(env, "")), &data); err != nil { - return err - } + result := Merge(env.SystemEnvVars, env.AppEnvVars, env.EnvVars) - if err = marshalAndWrite(data.Merge(), "default-env.json"); err != nil { - return err + if *writeStdoutFlag { + if err := marshalAndWriteStdout(result); err != nil { + return err + } + _, _ = fmt.Fprintln(os.Stderr, "success: environment variables written to stdout") + } else { + if err := marshalAndWrite(result, *outFileFlag); err != nil { + return err + } + _, _ = fmt.Fprintln(os.Stderr, "success: environment variables written to", *outFileFlag) } - - fmt.Println("Environment variables for " + args[1] + " written to default-env.json") return nil } -// GetApp retrieves a Cloud Foundry application resource by its name and space GUID. -// -// It connects to the Cloud Foundry API using the provided API endpoint and access token, -// then searches for the application with the specified name within the given space. -// If the application is found, it returns a pointer to the resource.App object. -// If the application is not found or an error occurs during the process, an error is returned. -func GetApp(connAPIEndpoint string, accessToken string, appName string, currentSpaceGUID string) (*resource.App, error) { - // A refresh token is not provided by the CF CLI Plugin API and is not required as - // "AccessToken() now provides a refreshed o-auth token.", - // see https://github.com/cloudfoundry/cli/blob/main/plugin/plugin_examples/CHANGELOG.md#changes-in-v614 - refreshToken := "" - - cfg, err := cfClientConfig.New(connAPIEndpoint, cfClientConfig.Token(accessToken, refreshToken)) - if err != nil { - return nil, err - } - cf, err := cfClient.New(cfg) - if err != nil { - return nil, err - } +// AppEnvironment is a stripped down version of [cfclient.Environment] +// that only contains the fields we care about for this plugin with a slightly different structure to make it easier +// to merge into a single map. +type AppEnvironment struct { + EnvVars map[string]any `json:"environment_variables,omitempty"` + SystemEnvVars map[string]any `json:"system_env_json,omitempty"` // VCAP_SERVICES + AppEnvVars map[string]any `json:"application_env_json,omitempty"` // VCAP_APPLICATION +} - appFilter := &cfClient.AppListOptions{ - Names: cfClient.Filter{Values: []string{appName}}, - SpaceGUIDs: cfClient.Filter{Values: []string{currentSpaceGUID}}, +// Merge merges multiple maps into a single map +func Merge[Map ~map[K]V, K comparable, V any](maps ...Map) Map { + result := make(Map) + for _, m := range maps { + for k, v := range m { + result[k] = v + } } - apps, err := cf.Applications.ListAll(context.Background(), appFilter) + return result +} + +// marshalAndWrite marshals v (any) into JSON and writes it to a file +func marshalAndWrite(v any, filename string) error { + f, err := os.Create(filename) if err != nil { - return nil, err + return err } - - if len(apps) == 0 { - return nil, fmt.Errorf("app '%s' not found", appName) + defer func(f *os.File) { + _ = f.Close() + }(f) + if err := json.NewEncoder(f).Encode(v); err != nil { + return err } + return nil +} - app := apps[0] - return app, nil +func marshalAndWriteStdout(v any) error { + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + return encoder.Encode(v) } From f7da56e2a913e4e625e04e55b250eabe2c53e5a8 Mon Sep 17 00:00:00 2001 From: darmiel <71837281+darmiel@users.noreply.github.com> Date: Wed, 11 Feb 2026 10:48:02 +0100 Subject: [PATCH 3/4] chore: update Go version --- .github/workflows/pull-request-test.yaml | 8 ++++---- .github/workflows/tag-release.yaml | 6 +++--- go.mod | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/pull-request-test.yaml b/.github/workflows/pull-request-test.yaml index 078ebae..8f2dc9f 100644 --- a/.github/workflows/pull-request-test.yaml +++ b/.github/workflows/pull-request-test.yaml @@ -2,14 +2,14 @@ name: "Test Pull Request" on: pull_request: - + jobs: test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 + - uses: actions/checkout@v6 + - uses: actions/setup-go@v6 with: - go-version: '1.20' + go-version: '1.25' - run: go get -t -v ./... - run: go test -v -race ./... diff --git a/.github/workflows/tag-release.yaml b/.github/workflows/tag-release.yaml index bbba111..dd376df 100644 --- a/.github/workflows/tag-release.yaml +++ b/.github/workflows/tag-release.yaml @@ -9,10 +9,10 @@ jobs: test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 + - uses: actions/checkout@v6 + - uses: actions/setup-go@v6 with: - go-version: '1.20' + go-version: '1.25' - run: go get -t -v ./... - run: go test -v -race ./... diff --git a/go.mod b/go.mod index afb4a71..8f61502 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/saphanaacademy/DefaultEnv -go 1.25.5 +go 1.25 require ( code.cloudfoundry.org/cli v7.1.0+incompatible From 2c49313c5aea003129ae11431edd86a1f8b1f007 Mon Sep 17 00:00:00 2001 From: darmiel <71837281+darmiel@users.noreply.github.com> Date: Thu, 12 Feb 2026 10:56:49 +0100 Subject: [PATCH 4/4] chore: remove dead code --- DefaultEnv_plugin.go | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/DefaultEnv_plugin.go b/DefaultEnv_plugin.go index 4838015..b55316c 100644 --- a/DefaultEnv_plugin.go +++ b/DefaultEnv_plugin.go @@ -18,11 +18,6 @@ import ( // DefaultEnvPlugin allows users to export environment variables of an app into a JSON file type DefaultEnvPlugin struct{} -var ( - // ErrAppNotSpecified is returned when the app name is not provided by the user - ErrAppNotSpecified = fmt.Errorf("please specify an app") -) - func (*DefaultEnvPlugin) Run(cliConnection plugin.CliConnection, args []string) { if args[0] != "default-env" { return @@ -105,6 +100,7 @@ func findAppByName(ctx context.Context, client *cfclient.Client, appName, spaceG return app, nil } +// findEnvironmentByAppGUID retrieves the environment variables of the app with the specified GUID func findEnvironmentByAppGUID(ctx context.Context, client *cfclient.Client, appGUID string) (*AppEnvironment, error) { seg := url.PathEscape(appGUID) p, err := url.JoinPath("/v3/apps", seg, "env") @@ -218,7 +214,7 @@ func Merge[Map ~map[K]V, K comparable, V any](maps ...Map) Map { return result } -// marshalAndWrite marshals v (any) into JSON and writes it to a file +// marshalAndWrite marshals [v] into JSON and writes it to a file func marshalAndWrite(v any, filename string) error { f, err := os.Create(filename) if err != nil { @@ -233,6 +229,7 @@ func marshalAndWrite(v any, filename string) error { return nil } +// marshalAndWriteStdout [v] into JSON and writes it to stdout func marshalAndWriteStdout(v any) error { encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("", " ")