CLI JSON updates (#962)

See Changelog for details.
This commit is contained in:
Jeff Mitchell authored and GitHub committed 2021-02-25 12:43:17 -05:00
1 parent b967ff7f05
commit 72aa110f72
50 files changed
+489 -540

No files matched your search

+20
View File
@@ -2,6 +2,26 @@
Canonical reference for changes, improvements, and bugfixes for Boundary. Canonical reference for changes, improvements, and bugfixes for Boundary.
## Next
### Changes/Deprecations
All of these changes are from [PR
962](https://github.com/hashicorp/boundary/pull/962):
* api: A few functions have changed places. Notably, instead of `ResponseMap()`
and `ResponseBody()`, resources simply expose `Response()`. This higher-level
response object contains the map and body, and also exposes `StatusCode()` in
place of indivdidual resources.
* cli: In `json` output format, a resource item is now an object under the
top-level key `item`; a list of resource items is now an list of objects under
the top-level key `items`. This preserves the top level for putting in other
useful information later on (and the HTTP status code is included now).
* cli: In `json` output format, errors are now serialized as a JSON object with
an `error` key instead of outputting normal text
* cli: All errors, including API errors, are now written to `stderr`. Previously
in the default table format, API errors would be written to `stdout`.
## 0.1.7 (2021/02/16) ## 0.1.7 (2021/02/16)
*Note* This release fixes an upgrade issue affecting users on Postgres 11 *Note* This release fixes an upgrade issue affecting users on Postgres 11
+3 -1
View File
@@ -1,6 +1,8 @@
module github.com/hashicorp/boundary module github.com/hashicorp/boundary
go 1.14 go 1.15
replace github.com/hashicorp/boundary/api => ./api
require ( require (
github.com/armon/go-metrics v0.3.6 github.com/armon/go-metrics v0.3.6
-5
View File
@@ -568,8 +568,6 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t
github.com/grpc-ecosystem/grpc-gateway/v2 v2.2.0 h1:HlJcTiqGHvaWDG7/s85d68Kw7G7FqMz+9LlcyVauOAw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.2.0 h1:HlJcTiqGHvaWDG7/s85d68Kw7G7FqMz+9LlcyVauOAw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.2.0/go.mod h1:gRq9gZWcIFvz68EgWqy2qQpRbmtn5j2qLZ4zHjqiLpg= github.com/grpc-ecosystem/grpc-gateway/v2 v2.2.0/go.mod h1:gRq9gZWcIFvz68EgWqy2qQpRbmtn5j2qLZ4zHjqiLpg=
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed/go.mod h1:tMWxXQ9wFIaZeTI9F+hmhFiGpFmhOHzyShyFUhRm0H4= github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed/go.mod h1:tMWxXQ9wFIaZeTI9F+hmhFiGpFmhOHzyShyFUhRm0H4=
github.com/hashicorp/boundary/api v0.0.7 h1:BdDnbt4Ufp/4ylL4hTbOGAOAiotN/bMRgQ/PrPL+cCA=
github.com/hashicorp/boundary/api v0.0.7/go.mod h1:fWESFnitZg/5EHEtg8cuvT0E9rFywnBrRtGdLjhDwqU=
github.com/hashicorp/boundary/sdk v0.0.3 h1:xCj1LLvoLkJ6qP6oyn9k5uVHn8N40TGRG+iw7GdDmmU= github.com/hashicorp/boundary/sdk v0.0.3 h1:xCj1LLvoLkJ6qP6oyn9k5uVHn8N40TGRG+iw7GdDmmU=
github.com/hashicorp/boundary/sdk v0.0.3/go.mod h1:hu1j0/j9FY+G/vhl+6zoT18dCFs+wzeyTI+EuTHg4OY= github.com/hashicorp/boundary/sdk v0.0.3/go.mod h1:hu1j0/j9FY+G/vhl+6zoT18dCFs+wzeyTI+EuTHg4OY=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
@@ -1362,12 +1360,10 @@ golang.org/x/sys v0.0.0-20201029080932-201ba4db2418/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201126233918-771906719818/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201126233918-771906719818/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43 h1:SgQ6LNaYJU0JIuEHv9+s6EbhSCwYeAf5Yvj6lpYlqAE= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43 h1:SgQ6LNaYJU0JIuEHv9+s6EbhSCwYeAf5Yvj6lpYlqAE=
golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
@@ -1454,7 +1450,6 @@ golang.org/x/tools v0.0.0-20200818005847-188abfa75333/go.mod h1:njjCfa9FT2d7l9Bc
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20201125231158-b5590deeca9b/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201125231158-b5590deeca9b/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a h1:CB3a9Nez8M13wwlr/E2YtwoU+qYHKfC+JrDa45RXXoQ=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY=
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
+6 -32
View File
@@ -548,20 +548,6 @@ type {{ .Name }} struct { {{ range .Fields }}
{{ end }} {{ end }}
} }
{{ if ( or .CreateResponseTypes ( eq .Name "Error" ) ) }}
func (n {{ .Name }}) ResponseBody() *bytes.Buffer {
return n.response.Body
}
func (n {{ .Name }}) ResponseMap() map[string]interface{} {
return n.response.Map
}
func (n {{ .Name }}) ResponseStatus() int {
return n.response.HttpResponse().StatusCode
}
{{ end }}
{{ if .CreateResponseTypes }} {{ if .CreateResponseTypes }}
type {{ .Name }}ReadResult struct { type {{ .Name }}ReadResult struct {
Item *{{ .Name }} Item *{{ .Name }}
@@ -572,12 +558,8 @@ func (n {{ .Name }}ReadResult) GetItem() interface{} {
return n.Item return n.Item
} }
func (n {{ .Name }}ReadResult) GetResponseBody() *bytes.Buffer { func (n {{ .Name }}ReadResult) GetResponse() *api.Response {
return n.response.Body return n.response
}
func (n {{ .Name }}ReadResult) GetResponseMap() map[string]interface{} {
return n.response.Map
} }
type {{ .Name }}CreateResult = {{ .Name }}ReadResult type {{ .Name }}CreateResult = {{ .Name }}ReadResult
@@ -587,12 +569,8 @@ type {{ .Name }}DeleteResult struct {
response *api.Response response *api.Response
} }
func (n {{ .Name }}DeleteResult) GetResponseBody() *bytes.Buffer { func (n {{ .Name }}DeleteResult) GetResponse() *api.Response {
return n.response.Body return n.response
}
func (n {{ .Name }}DeleteResult) GetResponseMap() map[string]interface{} {
return n.response.Map
} }
type {{ .Name }}ListResult struct { type {{ .Name }}ListResult struct {
@@ -604,12 +582,8 @@ func (n {{ .Name }}ListResult) GetItems() interface{} {
return n.Items return n.Items
} }
func (n {{ .Name }}ListResult) GetResponseBody() *bytes.Buffer { func (n {{ .Name }}ListResult) GetResponse() *api.Response {
return n.response.Body return n.response
}
func (n {{ .Name }}ListResult) GetResponseMap() map[string]interface{} {
return n.response.Map
} }
{{ end }} {{ end }}
`))) `)))
+120 -44
View File
@@ -134,58 +134,134 @@ func WrapMap(prefixSpaces, maxLengthOverride int, input map[string]interface{})
return strings.Join(ret, "\n") return strings.Join(ret, "\n")
} }
func PrintApiError(in *api.Error) string { // PrintApiError prints the given API error, optionally with context
nonAttributeMap := map[string]interface{}{ // information, to the UI in the appropriate format
"Status": in.ResponseStatus(), func (c *Command) PrintApiError(in *api.Error, contextStr string) {
"Kind": in.Kind, switch Format(c.UI) {
"Message": in.Message, case "json":
} output := struct {
Context string `json:"context,omitempty"`
Status int `json:"status"`
ApiError json.RawMessage `json:"api_error"`
}{
Context: contextStr,
Status: in.Response().StatusCode(),
ApiError: in.Response().Body.Bytes(),
}
b, _ := JsonFormatter{}.Format(output)
c.UI.Error(string(b))
if in.Op != "" { default:
nonAttributeMap["Operation"] = in.Op nonAttributeMap := map[string]interface{}{
} "Status": in.Response().StatusCode(),
"Kind": in.Kind,
maxLength := MaxAttributesLength(nonAttributeMap, nil, nil) "Message": in.Message,
}
ret := []string{ if contextStr != "" {
"", nonAttributeMap["context"] = contextStr
"Error information:", }
WrapMap(2, maxLength+2, nonAttributeMap), if in.Op != "" {
} nonAttributeMap["Operation"] = in.Op
if in.Details != nil {
if len(in.Details.WrappedErrors) > 0 {
ret = append(ret,
"",
" Wrapped Errors:",
)
for _, we := range in.Details.WrappedErrors {
ret = append(ret,
fmt.Sprintf(" Message: %s", we.Message),
fmt.Sprintf(" Operation: %s", we.Op),
)
}
} }
if len(in.Details.RequestFields) > 0 { maxLength := MaxAttributesLength(nonAttributeMap, nil, nil)
ret = append(ret,
"", var output []string
" Field-specific Errors:", if contextStr != "" {
) output = append(output, contextStr)
for _, field := range in.Details.RequestFields { }
if field.Name == "update_mask" { output = append(output,
// TODO: Report useful error messages related to "update_mask". "",
continue "Error information:",
WrapMap(2, maxLength+2, nonAttributeMap),
)
if in.Details != nil {
if len(in.Details.WrappedErrors) > 0 {
output = append(output,
"",
" Wrapped Errors:",
)
for _, we := range in.Details.WrappedErrors {
output = append(output,
fmt.Sprintf(" Message: %s", we.Message),
fmt.Sprintf(" Operation: %s", we.Op),
)
} }
ret = append(ret, }
fmt.Sprintf(" Name: -%s", strings.ReplaceAll(field.Name, "_", "-")),
fmt.Sprintf(" Error: %s", field.Description), if len(in.Details.RequestFields) > 0 {
output = append(output,
"",
" Field-specific Errors:",
) )
for _, field := range in.Details.RequestFields {
if field.Name == "update_mask" {
// TODO: Report useful error messages related to "update_mask".
continue
}
output = append(output,
fmt.Sprintf(" Name: -%s", strings.ReplaceAll(field.Name, "_", "-")),
fmt.Sprintf(" Error: %s", field.Description),
)
}
} }
} }
}
return WrapForHelpText(ret) c.UI.Error(WrapForHelpText(output))
}
}
// PrintCliError prints the given CLI error to the UI in the appropriate format
func (c *Command) PrintCliError(err error) {
switch Format(c.UI) {
case "table":
c.UI.Error(err.Error())
case "json":
output := struct {
Error string `json:"error"`
}{
Error: err.Error(),
}
b, _ := JsonFormatter{}.Format(output)
c.UI.Error(string(b))
}
}
// PrintJsonItem prints the given item to the UI in JSON format
func (c *Command) PrintJsonItem(result api.GenericResult, item interface{}) int {
output := struct {
StatusCode int `json:"status_code"`
Item interface{} `json:"item"`
}{
StatusCode: result.GetResponse().HttpResponse().StatusCode,
Item: item,
}
b, err := JsonFormatter{}.Format(output)
if err != nil {
c.PrintCliError(err)
return 1
}
c.UI.Output(string(b))
return 0
}
// PrintJsonItems prints the given items to the UI in JSON format
func (c *Command) PrintJsonItems(result api.GenericListResult, items []interface{}) int {
output := struct {
StatusCode int `json:"status_code"`
Items []interface{} `json:"items"`
}{
StatusCode: result.GetResponse().HttpResponse().StatusCode,
Items: items,
}
b, err := JsonFormatter{}.Format(output)
if err != nil {
c.PrintCliError(err)
return 1
}
c.UI.Output(string(b))
return 0
} }
// An output formatter for json output of an object // An output formatter for json output of an object
@@ -2,6 +2,7 @@
package accountscmd package accountscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -131,12 +132,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -146,7 +147,7 @@ func (c *Command) Run(args []string) int {
switch c.Func { switch c.Func {
case "list": case "list":
if c.FlagAuthMethodId == "" { if c.FlagAuthMethodId == "" {
c.UI.Error("AuthMethod ID must be passed in via -auth-method-id or BOUNDARY_AUTH_METHOD_ID") c.PrintCliError(errors.New("AuthMethod ID must be passed in via -auth-method-id or BOUNDARY_AUTH_METHOD_ID"))
return 1 return 1
} }
} }
@@ -154,7 +155,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
accountsClient := accounts.NewClient(client) accountsClient := accounts.NewClient(client)
@@ -214,7 +215,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = accountsClient.Delete(c.Context, c.FlagId, opts...) _, err = accountsClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -228,16 +229,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -274,12 +275,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -296,12 +296,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package accountscmd package accountscmd
import ( import (
"errors"
"fmt" "fmt"
"github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api"
@@ -114,12 +115,12 @@ func (c *PasswordCommand) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsPasswordMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsPasswordMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -129,7 +130,7 @@ func (c *PasswordCommand) Run(args []string) int {
switch c.Func { switch c.Func {
case "create": case "create":
if c.FlagAuthMethodId == "" { if c.FlagAuthMethodId == "" {
c.UI.Error("AuthMethod ID must be passed in via -auth-method-id or BOUNDARY_AUTH_METHOD_ID") c.PrintCliError(errors.New("AuthMethod ID must be passed in via -auth-method-id or BOUNDARY_AUTH_METHOD_ID"))
return 1 return 1
} }
} }
@@ -137,7 +138,7 @@ func (c *PasswordCommand) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
accountsClient := accounts.NewClient(client) accountsClient := accounts.NewClient(client)
@@ -190,16 +191,16 @@ func (c *PasswordCommand) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomPasswordActionOutput(c) output, err := printCustomPasswordActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -215,12 +216,7 @@ func (c *PasswordCommand) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+8 -12
View File
@@ -3,6 +3,7 @@ package authenticate
import ( import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"os" "os"
"strings" "strings"
@@ -94,16 +95,16 @@ func (c *PasswordCommand) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
switch { switch {
case c.flagLoginName == "": case c.flagLoginName == "":
c.UI.Error("Login name must be provided via -login-name") c.PrintCliError(errors.New("Login name must be provided via -login-name"))
return 1 return 1
case c.FlagAuthMethodId == "": case c.FlagAuthMethodId == "":
c.UI.Error("Auth method ID must be provided via -auth-method-id") c.PrintCliError(errors.New("Auth method ID must be provided via -auth-method-id"))
return 1 return 1
} }
@@ -120,7 +121,7 @@ func (c *PasswordCommand) Run(args []string) int {
client, err := c.Client(base.WithNoTokenScope(), base.WithNoTokenValue()) client, err := c.Client(base.WithNoTokenScope(), base.WithNoTokenValue())
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %w", err))
return 2 return 2
} }
@@ -134,10 +135,10 @@ func (c *PasswordCommand) Run(args []string) int {
}) })
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing authentication: %s", base.PrintApiError(apiErr))) c.PrintApiError(apiErr, "Error from controller when performing authentication")
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to perform authentication: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error trying to perform authentication: %w", err))
return 2 return 2
} }
@@ -155,12 +156,7 @@ func (c *PasswordCommand) Run(args []string) int {
})) }))
case "json": case "json":
jsonOut, err := base.JsonFormatter{}.Format(token) return c.PrintJsonItem(result, token)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(jsonOut))
} }
var gotErr bool var gotErr bool
@@ -2,6 +2,7 @@
package authmethodscmd package authmethodscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -129,12 +130,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -144,7 +145,7 @@ func (c *Command) Run(args []string) int {
switch c.Func { switch c.Func {
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
} }
@@ -152,7 +153,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
authmethodsClient := authmethods.NewClient(client) authmethodsClient := authmethods.NewClient(client)
@@ -181,7 +182,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = authmethodsClient.Delete(c.Context, c.FlagId, opts...) _, err = authmethodsClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -195,16 +196,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -241,12 +242,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -263,12 +263,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package authmethodscmd package authmethodscmd
import ( import (
"errors"
"fmt" "fmt"
"github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api"
@@ -114,12 +115,12 @@ func (c *PasswordCommand) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsPasswordMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsPasswordMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -129,7 +130,7 @@ func (c *PasswordCommand) Run(args []string) int {
switch c.Func { switch c.Func {
case "create": case "create":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
} }
@@ -137,7 +138,7 @@ func (c *PasswordCommand) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
authmethodsClient := authmethods.NewClient(client) authmethodsClient := authmethods.NewClient(client)
@@ -195,16 +196,16 @@ func (c *PasswordCommand) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomPasswordActionOutput(c) output, err := printCustomPasswordActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -220,12 +221,7 @@ func (c *PasswordCommand) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package authtokenscmd package authtokenscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -125,12 +126,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -140,7 +141,7 @@ func (c *Command) Run(args []string) int {
switch c.Func { switch c.Func {
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
} }
@@ -148,7 +149,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
authtokensClient := authtokens.NewClient(client) authtokensClient := authtokens.NewClient(client)
@@ -177,7 +178,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = authtokensClient.Delete(c.Context, c.FlagId, opts...) _, err = authtokensClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -191,16 +192,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -237,12 +238,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -259,12 +259,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+32 -55
View File
@@ -208,15 +208,6 @@ func (c *Command) Flags() *base.FlagSets {
Usage: "Target scope name, if authorizing the session via scope parameters and target name. Mutually exclusive with -scope-id.", Usage: "Target scope name, if authorizing the session via scope parameters and target name. Mutually exclusive with -scope-id.",
}) })
f.BoolVar(&base.BoolVar{
Name: "output-json-errors",
Target: &c.outputJsonErrors,
EnvVar: "BOUNDARY_CONNECT_OUTPUT_JSON_ERRORS",
Completion: complete.PredictNothing,
Usage: "Cause errors coming from this command to be output as JSON. This is experimental only and currently only meant for internal purposes. The format may change at any time and this flag/env var may be removed or modified at any time.",
Hidden: true,
})
switch c.Func { switch c.Func {
case "connect": case "connect":
f.StringVar(&base.StringVar{ f.StringVar(&base.StringVar{
@@ -274,7 +265,7 @@ func (c *Command) Run(args []string) (retCode int) {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.Error(err.Error()) c.PrintCliError(err)
return 3 return 3
} }
@@ -282,22 +273,22 @@ func (c *Command) Run(args []string) (retCode int) {
case c.flagAuthzToken != "": case c.flagAuthzToken != "":
switch { switch {
case c.flagTargetId != "": case c.flagTargetId != "":
c.Error(`-target-id and -authz-token cannot both be specified`) c.PrintCliError(errors.New(`-target-id and -authz-token cannot both be specified`))
return 3 return 3
case c.flagTargetName != "": case c.flagTargetName != "":
c.Error(`-target-name and -authz-token cannot both be specified`) c.PrintCliError(errors.New(`-target-name and -authz-token cannot both be specified`))
return 3 return 3
} }
default: default:
if c.flagTargetId == "" && if c.flagTargetId == "" &&
(c.flagTargetName == "" || (c.flagTargetName == "" ||
(c.FlagScopeId == "" && c.FlagScopeName == "")) { (c.FlagScopeId == "" && c.FlagScopeName == "")) {
c.Error("Target ID was not passed in, but no combination of target name and scope ID/name was passed in either") c.PrintCliError(errors.New("Target ID was not passed in, but no combination of target name and scope ID/name was passed in either"))
return 3 return 3
} }
if c.flagTargetId != "" && if c.flagTargetId != "" &&
(c.flagTargetName != "" || c.FlagScopeId != "" || c.FlagScopeName != "") { (c.flagTargetName != "" || c.FlagScopeId != "" || c.FlagScopeName != "") {
c.Error("Cannot specify a target ID and also other lookup parameters") c.PrintCliError(errors.New("Cannot specify a target ID and also other lookup parameters"))
return 3 return 3
} }
} }
@@ -319,7 +310,7 @@ func (c *Command) Run(args []string) (retCode int) {
tofuToken, err := base62.Random(20) tofuToken, err := base62.Random(20)
if err != nil { if err != nil {
c.Error(fmt.Errorf("Could not derive random bytes for tofu token: %w", err).Error()) c.PrintCliError(fmt.Errorf("Could not derive random bytes for tofu token: %w", err))
return 2 return 2
} }
@@ -330,7 +321,7 @@ func (c *Command) Run(args []string) (retCode int) {
} }
listenAddr := net.ParseIP(c.flagListenAddr) listenAddr := net.ParseIP(c.flagListenAddr)
if listenAddr == nil { if listenAddr == nil {
c.Error(fmt.Sprintf("Could not successfully parse listen address of %s", c.flagListenAddr)) c.PrintCliError(fmt.Errorf("Could not successfully parse listen address of %s", c.flagListenAddr))
return 3 return 3
} }
@@ -340,18 +331,18 @@ func (c *Command) Run(args []string) (retCode int) {
if authzString == "-" { if authzString == "-" {
authBytes, err := ioutil.ReadAll(os.Stdin) authBytes, err := ioutil.ReadAll(os.Stdin)
if err != nil { if err != nil {
c.Error(fmt.Errorf("No authorization string was provided and encountered the following error attempting to read it from stdin: %w", err).Error()) c.PrintCliError(fmt.Errorf("No authorization string was provided and encountered the following error attempting to read it from stdin: %w", err))
return 3 return 3
} }
if len(authBytes) == 0 { if len(authBytes) == 0 {
c.Error("No authorization data read from stdin") c.PrintCliError(errors.New("No authorization data read from stdin"))
return 3 return 3
} }
authzString = string(authBytes) authzString = string(authBytes)
} }
if authzString == "" { if authzString == "" {
c.Error("Authorization data was empty") c.PrintCliError(errors.New("Authorization data was empty"))
return 3 return 3
} }
@@ -367,7 +358,7 @@ func (c *Command) Run(args []string) (retCode int) {
default: default:
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err))
return 2 return 2
} }
targetClient := targets.NewClient(client) targetClient := targets.NewClient(client)
@@ -389,15 +380,10 @@ func (c *Command) Run(args []string) (retCode int) {
sar, err := targetClient.AuthorizeSession(c.Context, c.flagTargetId, opts...) sar, err := targetClient.AuthorizeSession(c.Context, c.flagTargetId, opts...)
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
switch c.outputJsonErrors { c.PrintApiError(apiErr, "Error from controller when performing authorize-session action against given target")
case true:
c.Error(apiErr.ResponseBody().String())
default:
c.Error(fmt.Sprintf("Error from controller when performing authorize-session against target: %s", base.PrintApiError(apiErr)))
}
return 1 return 1
} }
c.Error(fmt.Sprintf("Error trying to authorize a session against target: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error trying to authorize a session against target: %w", err))
return 2 return 2
} }
authzString = sar.GetItem().(*targets.SessionAuthorization).AuthorizationToken authzString = sar.GetItem().(*targets.SessionAuthorization).AuthorizationToken
@@ -405,22 +391,22 @@ func (c *Command) Run(args []string) (retCode int) {
marshaled, err := base58.FastBase58Decoding(authzString) marshaled, err := base58.FastBase58Decoding(authzString)
if err != nil { if err != nil {
c.Error(fmt.Errorf("Unable to base58-decode authorization data: %w", err).Error()) c.PrintCliError(fmt.Errorf("Unable to base58-decode authorization data: %w", err))
return 3 return 3
} }
if len(marshaled) == 0 { if len(marshaled) == 0 {
c.Error("Zero length authorization information after decoding") c.PrintCliError(errors.New("Zero length authorization information after decoding"))
return 3 return 3
} }
c.sessionAuthzData = new(targetspb.SessionAuthorizationData) c.sessionAuthzData = new(targetspb.SessionAuthorizationData)
if err := proto.Unmarshal(marshaled, c.sessionAuthzData); err != nil { if err := proto.Unmarshal(marshaled, c.sessionAuthzData); err != nil {
c.Error(fmt.Errorf("Unable to proto-decode authorization data: %w", err).Error()) c.PrintCliError(fmt.Errorf("Unable to proto-decode authorization data: %w", err))
return 3 return 3
} }
if len(c.sessionAuthzData.GetWorkerInfo()) == 0 { if len(c.sessionAuthzData.GetWorkerInfo()) == 0 {
c.Error("No workers found in authorization string") c.PrintCliError(errors.New("No workers found in authorization string"))
return 3 return 3
} }
@@ -429,12 +415,12 @@ func (c *Command) Run(args []string) (retCode int) {
parsedCert, err := x509.ParseCertificate(c.sessionAuthzData.Certificate) parsedCert, err := x509.ParseCertificate(c.sessionAuthzData.Certificate)
if err != nil { if err != nil {
c.Error(fmt.Errorf("Unable to decode mTLS certificate: %w", err).Error()) c.PrintCliError(fmt.Errorf("Unable to decode mTLS certificate: %w", err))
return 3 return 3
} }
if len(parsedCert.DNSNames) != 1 { if len(parsedCert.DNSNames) != 1 {
c.Error(fmt.Errorf("mTLS certificate has invalid parameters: %w", err).Error()) c.PrintCliError(fmt.Errorf("mTLS certificate has invalid parameters: %w", err))
return 3 return 3
} }
@@ -474,7 +460,7 @@ func (c *Command) Run(args []string) (retCode int) {
Port: c.flagListenPort, Port: c.flagListenPort,
}) })
if err != nil { if err != nil {
c.Error(fmt.Errorf("Error starting listening port: %w", err).Error()) c.PrintCliError(fmt.Errorf("Error starting listening port: %w", err))
return 2 return 2
} }
@@ -482,7 +468,7 @@ func (c *Command) Run(args []string) (retCode int) {
// Forces the for loop to exist instead of spinning on errors // Forces the for loop to exist instead of spinning on errors
c.connectionsLeft.Store(0) c.connectionsLeft.Store(0)
if err := c.listener.Close(); err != nil { if err := c.listener.Close(); err != nil {
c.Error(fmt.Errorf("Error closing listener on shutdown: %w", err).Error()) c.PrintCliError(fmt.Errorf("Error closing listener on shutdown: %w", err))
retCode = 2 retCode = 2
} }
} }
@@ -510,7 +496,7 @@ func (c *Command) Run(args []string) (retCode int) {
case "json": case "json":
out, err := json.Marshal(&sessInfo) out, err := json.Marshal(&sessInfo)
if err != nil { if err != nil {
c.Error(fmt.Errorf("error marshaling session information: %w", err).Error()) c.PrintCliError(fmt.Errorf("error marshaling session information: %w", err))
return 2 return 2
} }
c.UI.Output(string(out)) c.UI.Output(string(out))
@@ -536,7 +522,7 @@ func (c *Command) Run(args []string) (retCode int) {
if c.connectionsLeft.Load() == 0 { if c.connectionsLeft.Load() == 0 {
return return
} }
c.Error(fmt.Errorf("Error accepting connection: %w", err).Error()) c.PrintCliError(fmt.Errorf("Error accepting connection: %w", err))
continue continue
} }
} }
@@ -549,10 +535,10 @@ func (c *Command) Run(args []string) (retCode int) {
workerAddr, workerAddr,
transport) transport)
if err != nil { if err != nil {
c.Error(err.Error()) c.PrintCliError(err)
} else { } else {
if err := c.runTcpProxyV1(wsConn, listeningConn, tofuToken); err != nil { if err := c.runTcpProxyV1(wsConn, listeningConn, tofuToken); err != nil {
c.Error(err.Error()) c.PrintCliError(err)
} }
} }
}() }()
@@ -620,10 +606,10 @@ func (c *Command) Run(args []string) (retCode int) {
ctx, cancel := context.WithTimeout(context.Background(), sessionCancelTimeout) ctx, cancel := context.WithTimeout(context.Background(), sessionCancelTimeout)
wsConn, err := c.getWsConn(ctx, workerAddr, transport) wsConn, err := c.getWsConn(ctx, workerAddr, transport)
if err != nil { if err != nil {
c.Error(fmt.Errorf("error fetching connection to send session teardown request to worker: %w", err).Error()) c.PrintCliError(fmt.Errorf("error fetching connection to send session teardown request to worker: %w", err))
} else { } else {
if err := c.sendSessionTeardown(ctx, wsConn, tofuToken); err != nil { if err := c.sendSessionTeardown(ctx, wsConn, tofuToken); err != nil {
c.Error(fmt.Errorf("error sending session teardown request to worker: %w", err).Error()) c.PrintCliError(fmt.Errorf("error sending session teardown request to worker: %w", err))
} }
} }
cancel() cancel()
@@ -636,7 +622,7 @@ func (c *Command) Run(args []string) (retCode int) {
case "json": case "json":
out, err := json.Marshal(&termInfo) out, err := json.Marshal(&termInfo)
if err != nil { if err != nil {
c.Error(fmt.Errorf("error marshaling termination information: %w", err).Error()) c.PrintCliError(fmt.Errorf("error marshaling termination information: %w", err))
return 2 return 2
} }
c.UI.Output(string(out)) c.UI.Output(string(out))
@@ -767,7 +753,7 @@ func (c *Command) updateConnsLeft(connsLeft int32) {
case "json": case "json":
out, err := json.Marshal(&connInfo) out, err := json.Marshal(&connInfo)
if err != nil { if err != nil {
c.Error(fmt.Errorf("error marshaling connection information: %w", err).Error()) c.PrintCliError(fmt.Errorf("error marshaling connection information: %w", err))
} }
c.UI.Output(string(out)) c.UI.Output(string(out))
} }
@@ -788,7 +774,7 @@ func (c *Command) handleExec(passthroughArgs []string) {
case "http": case "http":
httpArgs, err := c.httpFlags.buildArgs(c, port, ip, addr) httpArgs, err := c.httpFlags.buildArgs(c, port, ip, addr)
if err != nil { if err != nil {
c.Error(fmt.Sprintf("Error parsing session args: %s", err)) c.PrintCliError(fmt.Errorf("Error parsing session args: %w", err))
c.execCmdReturnValue.Store(int32(3)) c.execCmdReturnValue.Store(int32(3))
return return
} }
@@ -806,7 +792,7 @@ func (c *Command) handleExec(passthroughArgs []string) {
case "kube": case "kube":
kubeArgs, err := c.kubeFlags.buildArgs(c, port, ip, addr) kubeArgs, err := c.kubeFlags.buildArgs(c, port, ip, addr)
if err != nil { if err != nil {
c.Error(fmt.Sprintf("Error parsing session args: %s", err)) c.PrintCliError(fmt.Errorf("Error parsing session args: %w", err))
c.execCmdReturnValue.Store(int32(3)) c.execCmdReturnValue.Store(int32(3))
return return
} }
@@ -860,18 +846,9 @@ func (c *Command) handleExec(passthroughArgs []string) {
} }
} }
c.Error(fmt.Sprintf("Failed to run command: %s", err)) c.PrintCliError(fmt.Errorf("Failed to run command: %w", err))
c.execCmdReturnValue.Store(int32(exitCode)) c.execCmdReturnValue.Store(int32(exitCode))
return return
} }
c.execCmdReturnValue.Store(0) c.execCmdReturnValue.Store(0)
} }
func (c *Command) Error(err string) {
switch c.outputJsonErrors {
case true:
c.UI.Error(fmt.Sprintf(`{"error": %q}`, err))
default:
c.UI.Error(err)
}
}
+15 -20
View File
@@ -2,6 +2,7 @@
package groupscmd package groupscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -137,12 +138,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -153,13 +154,13 @@ func (c *Command) Run(args []string) int {
case "create": case "create":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
@@ -168,7 +169,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
groupsClient := groups.NewClient(client) groupsClient := groups.NewClient(client)
@@ -255,7 +256,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = groupsClient.Delete(c.Context, c.FlagId, opts...) _, err = groupsClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -269,16 +270,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -315,12 +316,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -337,12 +337,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package hostcatalogscmd package hostcatalogscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -129,12 +130,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -144,7 +145,7 @@ func (c *Command) Run(args []string) int {
switch c.Func { switch c.Func {
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
} }
@@ -152,7 +153,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
hostcatalogsClient := hostcatalogs.NewClient(client) hostcatalogsClient := hostcatalogs.NewClient(client)
@@ -181,7 +182,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = hostcatalogsClient.Delete(c.Context, c.FlagId, opts...) _, err = hostcatalogsClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -195,16 +196,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -241,12 +242,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -263,12 +263,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package hostcatalogscmd package hostcatalogscmd
import ( import (
"errors"
"fmt" "fmt"
"github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api"
@@ -112,12 +113,12 @@ func (c *StaticCommand) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsStaticMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsStaticMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -127,7 +128,7 @@ func (c *StaticCommand) Run(args []string) int {
switch c.Func { switch c.Func {
case "create": case "create":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
} }
@@ -135,7 +136,7 @@ func (c *StaticCommand) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
hostcatalogsClient := hostcatalogs.NewClient(client) hostcatalogsClient := hostcatalogs.NewClient(client)
@@ -193,16 +194,16 @@ func (c *StaticCommand) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomStaticActionOutput(c) output, err := printCustomStaticActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -218,12 +219,7 @@ func (c *StaticCommand) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+14 -19
View File
@@ -2,6 +2,7 @@
package hostscmd package hostscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -129,12 +130,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -144,7 +145,7 @@ func (c *Command) Run(args []string) int {
switch c.Func { switch c.Func {
case "list": case "list":
if c.FlagHostCatalogId == "" { if c.FlagHostCatalogId == "" {
c.UI.Error("HostCatalog ID must be passed in via -host-catalog-id or BOUNDARY_HOST_CATALOG_ID") c.PrintCliError(errors.New("HostCatalog ID must be passed in via -host-catalog-id or BOUNDARY_HOST_CATALOG_ID"))
return 1 return 1
} }
} }
@@ -152,7 +153,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
hostsClient := hosts.NewClient(client) hostsClient := hosts.NewClient(client)
@@ -192,7 +193,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = hostsClient.Delete(c.Context, c.FlagId, opts...) _, err = hostsClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -206,16 +207,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -252,12 +253,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -274,12 +274,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package hostscmd package hostscmd
import ( import (
"errors"
"fmt" "fmt"
"github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api"
@@ -114,12 +115,12 @@ func (c *StaticCommand) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsStaticMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsStaticMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -129,7 +130,7 @@ func (c *StaticCommand) Run(args []string) int {
switch c.Func { switch c.Func {
case "create": case "create":
if c.FlagHostCatalogId == "" { if c.FlagHostCatalogId == "" {
c.UI.Error("HostCatalog ID must be passed in via -host-catalog-id or BOUNDARY_HOST_CATALOG_ID") c.PrintCliError(errors.New("HostCatalog ID must be passed in via -host-catalog-id or BOUNDARY_HOST_CATALOG_ID"))
return 1 return 1
} }
} }
@@ -137,7 +138,7 @@ func (c *StaticCommand) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
hostsClient := hosts.NewClient(client) hostsClient := hosts.NewClient(client)
@@ -190,16 +191,16 @@ func (c *StaticCommand) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomStaticActionOutput(c) output, err := printCustomStaticActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -215,12 +216,7 @@ func (c *StaticCommand) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package hostsetscmd package hostsetscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -131,12 +132,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -146,7 +147,7 @@ func (c *Command) Run(args []string) int {
switch c.Func { switch c.Func {
case "list": case "list":
if c.FlagHostCatalogId == "" { if c.FlagHostCatalogId == "" {
c.UI.Error("HostCatalog ID must be passed in via -host-catalog-id or BOUNDARY_HOST_CATALOG_ID") c.PrintCliError(errors.New("HostCatalog ID must be passed in via -host-catalog-id or BOUNDARY_HOST_CATALOG_ID"))
return 1 return 1
} }
} }
@@ -154,7 +155,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
hostsetsClient := hostsets.NewClient(client) hostsetsClient := hostsets.NewClient(client)
@@ -222,7 +223,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = hostsetsClient.Delete(c.Context, c.FlagId, opts...) _, err = hostsetsClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -236,16 +237,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -282,12 +283,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -304,12 +304,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package hostsetscmd package hostsetscmd
import ( import (
"errors"
"fmt" "fmt"
"github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api"
@@ -112,12 +113,12 @@ func (c *StaticCommand) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsStaticMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsStaticMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -127,7 +128,7 @@ func (c *StaticCommand) Run(args []string) int {
switch c.Func { switch c.Func {
case "create": case "create":
if c.FlagHostCatalogId == "" { if c.FlagHostCatalogId == "" {
c.UI.Error("HostCatalog ID must be passed in via -host-catalog-id or BOUNDARY_HOST_CATALOG_ID") c.PrintCliError(errors.New("HostCatalog ID must be passed in via -host-catalog-id or BOUNDARY_HOST_CATALOG_ID"))
return 1 return 1
} }
} }
@@ -135,7 +136,7 @@ func (c *StaticCommand) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
hostsetsClient := hostsets.NewClient(client) hostsetsClient := hostsets.NewClient(client)
@@ -188,16 +189,16 @@ func (c *StaticCommand) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomStaticActionOutput(c) output, err := printCustomStaticActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -213,12 +214,7 @@ func (c *StaticCommand) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+15 -20
View File
@@ -2,6 +2,7 @@
package rolescmd package rolescmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -137,12 +138,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -153,13 +154,13 @@ func (c *Command) Run(args []string) int {
case "create": case "create":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
@@ -168,7 +169,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
rolesClient := roles.NewClient(client) rolesClient := roles.NewClient(client)
@@ -279,7 +280,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = rolesClient.Delete(c.Context, c.FlagId, opts...) _, err = rolesClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -293,16 +294,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -339,12 +340,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -361,12 +361,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+15 -20
View File
@@ -2,6 +2,7 @@
package scopescmd package scopescmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -137,12 +138,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -153,13 +154,13 @@ func (c *Command) Run(args []string) int {
case "create": case "create":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
@@ -168,7 +169,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
scopesClient := scopes.NewClient(client) scopesClient := scopes.NewClient(client)
@@ -229,7 +230,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = scopesClient.Delete(c.Context, c.FlagId, opts...) _, err = scopesClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -243,16 +244,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -289,12 +290,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -311,12 +311,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package sessionscmd package sessionscmd
import ( import (
"errors"
"fmt" "fmt"
"sync" "sync"
@@ -119,12 +120,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -134,7 +135,7 @@ func (c *Command) Run(args []string) int {
switch c.Func { switch c.Func {
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
} }
@@ -142,7 +143,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
sessionsClient := sessions.NewClient(client) sessionsClient := sessions.NewClient(client)
@@ -186,16 +187,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -213,12 +214,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -234,12 +234,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+13 -18
View File
@@ -2,6 +2,7 @@
package targetscmd package targetscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
@@ -137,7 +138,7 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
@@ -147,7 +148,7 @@ func (c *Command) Run(args []string) int {
switch c.Func { switch c.Func {
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
} }
@@ -155,7 +156,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
targetsClient := targets.NewClient(client) targetsClient := targets.NewClient(client)
@@ -228,7 +229,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = targetsClient.Delete(c.Context, c.FlagId, opts...) _, err = targetsClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -242,16 +243,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -288,12 +289,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -310,12 +310,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
@@ -2,6 +2,7 @@
package targetscmd package targetscmd
import ( import (
"errors"
"fmt" "fmt"
"github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api"
@@ -114,12 +115,12 @@ func (c *TcpCommand) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsTcpMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsTcpMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -129,7 +130,7 @@ func (c *TcpCommand) Run(args []string) int {
switch c.Func { switch c.Func {
case "create": case "create":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
} }
@@ -137,7 +138,7 @@ func (c *TcpCommand) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
targetsClient := targets.NewClient(client) targetsClient := targets.NewClient(client)
@@ -195,16 +196,16 @@ func (c *TcpCommand) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomTcpActionOutput(c) output, err := printCustomTcpActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -220,12 +221,7 @@ func (c *TcpCommand) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+15 -20
View File
@@ -2,6 +2,7 @@
package userscmd package userscmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"sync" "sync"
@@ -137,12 +138,12 @@ func (c *Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
@@ -153,13 +154,13 @@ func (c *Command) Run(args []string) int {
case "create": case "create":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
case "list": case "list":
if c.FlagScopeId == "" { if c.FlagScopeId == "" {
c.UI.Error("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID") c.PrintCliError(errors.New("Scope ID must be passed in via -scope-id or BOUNDARY_SCOPE_ID"))
return 1 return 1
} }
@@ -168,7 +169,7 @@ func (c *Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
usersClient := users.NewClient(client) usersClient := users.NewClient(client)
@@ -255,7 +256,7 @@ func (c *Command) Run(args []string) int {
case "delete": case "delete":
_, err = usersClient.Delete(c.Context, c.FlagId, opts...) _, err = usersClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -269,16 +270,16 @@ func (c *Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustomActionOutput(c) output, err := printCustomActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -315,12 +316,11 @@ func (c *Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -337,12 +337,7 @@ func (c *Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+15 -22
View File
@@ -81,16 +81,15 @@ var cmdTemplate = template.Must(template.New("").Funcs(
package {{ .Pkg }}cmd package {{ .Pkg }}cmd
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"os"
"sync" "sync"
"github.com/hashicorp/boundary/api" "github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/{{ .Pkg }}" "github.com/hashicorp/boundary/api/{{ .Pkg }}"
"github.com/hashicorp/boundary/internal/cmd/base" "github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common" "github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil" "github.com/hashicorp/boundary/sdk/strutil"
"github.com/mitchellh/cli" "github.com/mitchellh/cli"
"github.com/posener/complete" "github.com/posener/complete"
@@ -231,13 +230,13 @@ func (c *{{ camelCase .SubActionPrefix }}Command) Run(args []string) int {
f := c.Flags() f := c.Flags()
if err := f.Parse(args); err != nil { if err := f.Parse(args); err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
{{ if .HasId }} {{ if .HasId }}
if strutil.StrListContains(flags{{ camelCase .SubActionPrefix }}Map[c.Func], "id") && c.FlagId == "" { if strutil.StrListContains(flags{{ camelCase .SubActionPrefix }}Map[c.Func], "id") && c.FlagId == "" {
c.UI.Error("ID is required but not passed in via -id") c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return 1 return 1
} }
{{ end }} {{ end }}
@@ -249,14 +248,14 @@ func (c *{{ camelCase .SubActionPrefix }}Command) Run(args []string) int {
{{ if hasAction .StdActions "create" }} {{ if hasAction .StdActions "create" }}
case "create": case "create":
if c.Flag{{ .Container }}Id == "" { if c.Flag{{ .Container }}Id == "" {
c.UI.Error("{{ .Container }} ID must be passed in via -{{ kebabCase .Container }}-id or BOUNDARY_{{ envCase .Container }}_ID") c.PrintCliError(errors.New("{{ .Container }} ID must be passed in via -{{ kebabCase .Container }}-id or BOUNDARY_{{ envCase .Container }}_ID"))
return 1 return 1
} }
{{ end }} {{ end }}
{{ if hasAction .StdActions "list" }} {{ if hasAction .StdActions "list" }}
case "list": case "list":
if c.Flag{{ .Container }}Id == "" { if c.Flag{{ .Container }}Id == "" {
c.UI.Error("{{ .Container }} ID must be passed in via -{{ kebabCase .Container }}-id or BOUNDARY_{{ envCase .Container }}_ID") c.PrintCliError(errors.New("{{ .Container }} ID must be passed in via -{{ kebabCase .Container }}-id or BOUNDARY_{{ envCase .Container }}_ID"))
return 1 return 1
} }
{{ end }} {{ end }}
@@ -265,7 +264,7 @@ func (c *{{ camelCase .SubActionPrefix }}Command) Run(args []string) int {
client, err := c.Client() client, err := c.Client()
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error())) c.PrintCliError(fmt.Errorf("Error creating API client: %s", err.Error()))
return 2 return 2
} }
{{ .Pkg }}Client := {{ .Pkg }}.NewClient(client) {{ .Pkg }}Client := {{ .Pkg }}.NewClient(client)
@@ -349,7 +348,7 @@ func (c *{{ camelCase .SubActionPrefix }}Command) Run(args []string) int {
{{ if eq $action "delete" }} {{ if eq $action "delete" }}
case "delete": case "delete":
_, err = {{ $input.Pkg}}Client.Delete(c.Context, c.FlagId, opts...) _, err = {{ $input.Pkg}}Client.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.ResponseStatus() == http.StatusNotFound { if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
existed = false existed = false
err = nil err = nil
} }
@@ -365,16 +364,16 @@ func (c *{{ camelCase .SubActionPrefix }}Command) Run(args []string) int {
if err != nil { if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil { if apiErr := api.AsServerError(err); apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, c.plural, base.PrintApiError(apiErr))) c.PrintApiError(apiErr, fmt.Sprintf("Error from controller when performing %s on %s", c.Func, c.plural))
return 1 return 1
} }
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, c.plural, err.Error())) c.PrintCliError(fmt.Errorf("Error trying to %s %s: %s", c.Func, c.plural, err.Error()))
return 2 return 2
} }
output, err := printCustom{{ camelCase .SubActionPrefix }}ActionOutput(c) output, err := printCustom{{ camelCase .SubActionPrefix }}ActionOutput(c)
if err != nil { if err != nil {
c.UI.Error(err.Error()) c.PrintCliError(err)
return 1 return 1
} }
if output { if output {
@@ -413,12 +412,11 @@ func (c *{{ camelCase .SubActionPrefix }}Command) Run(args []string) int {
c.UI.Output("null") c.UI.Output("null")
default: default:
b, err := base.JsonFormatter{}.Format(listedItems) items := make([]interface{}, len(listedItems))
if err != nil { for i, v := range listedItems {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error()) items[i] = v
return 1
} }
c.UI.Output(string(b)) return c.PrintJsonItems(listResult, items)
} }
case "table": case "table":
@@ -436,12 +434,7 @@ func (c *{{ camelCase .SubActionPrefix }}Command) Run(args []string) int {
c.UI.Output(printItemTable(item)) c.UI.Output(printItemTable(item))
case "json": case "json":
b, err := base.JsonFormatter{}.Format(item) return c.PrintJsonItem(result, item)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
} }
return 0 return 0
+4 -4
View File
@@ -183,7 +183,7 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
// Create another resource with the same name. // Create another resource with the same name.
_, err = accountClient.Create(tc.Context(), amId, accounts.WithPasswordAccountLoginName("first")) _, err = accountClient.Create(tc.Context(), amId, accounts.WithPasswordAccountLoginName("first"))
@@ -195,17 +195,17 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = accountClient.Read(tc.Context(), "invalid id") _, err = accountClient.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
_, err = accountClient.Update(tc.Context(), u.Item.Id, u.Item.Version) _, err = accountClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
} }
@@ -27,5 +27,5 @@ func TestAuthenticate(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValuesf(http.StatusUnauthorized, apiErr.ResponseStatus(), "Expected unauthorized, got %q", apiErr.Message) assert.EqualValuesf(http.StatusUnauthorized, apiErr.Response().StatusCode(), "Expected unauthorized, got %q", apiErr.Message)
} }
@@ -143,11 +143,11 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = tokens.Read(tc.Context(), "invalid id") _, err = tokens.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
} }
+5 -5
View File
@@ -158,7 +158,7 @@ func TestCrud(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
}) })
} }
} }
@@ -200,7 +200,7 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
// Create another resource with the same name. // Create another resource with the same name.
_, err = groupClient.Create(tc.Context(), tt.scopeId, groups.WithName("first")) _, err = groupClient.Create(tc.Context(), tt.scopeId, groups.WithName("first"))
@@ -210,19 +210,19 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = groupClient.Read(tc.Context(), "invalid id") _, err = groupClient.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
_, err = groupClient.Update(tc.Context(), g.Item.Id, g.Item.Version) _, err = groupClient.Update(tc.Context(), g.Item.Id, g.Item.Version)
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
}) })
} }
} }
@@ -116,7 +116,7 @@ func TestCrud(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
} }
func TestErrors(t *testing.T) { func TestErrors(t *testing.T) {
@@ -141,7 +141,7 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = pc.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName("foo")) _, err = pc.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName("foo"))
require.Error(err) require.Error(err)
@@ -152,11 +152,11 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = pc.Read(tc.Context(), "invalid id") _, err = pc.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
} }
+4 -4
View File
@@ -126,7 +126,7 @@ func TestCrud(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
} }
func TestErrors(t *testing.T) { func TestErrors(t *testing.T) {
@@ -154,7 +154,7 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName("foo"), hosts.WithStaticHostAddress("someaddress")) _, err = hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName("foo"), hosts.WithStaticHostAddress("someaddress"))
require.Error(err) require.Error(err)
@@ -165,11 +165,11 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = hClient.Read(tc.Context(), "invalid id") _, err = hClient.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
} }
+4 -4
View File
@@ -163,7 +163,7 @@ func TestCrud(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
require.NotNil(apiErr) require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
} }
// TODO: Get better coverage for expected errors and error formats. // TODO: Get better coverage for expected errors and error formats.
@@ -192,7 +192,7 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
h, err = hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName("foo")) h, err = hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName("foo"))
require.Error(err) require.Error(err)
@@ -204,11 +204,11 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = hClient.Read(tc.Context(), "invalid id") _, err = hClient.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
} }
+4 -4
View File
@@ -290,7 +290,7 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
// Create another resource with the same name. // Create another resource with the same name.
_, err = roleClient.Create(tc.Context(), tt.scopeId, roles.WithName("first")) _, err = roleClient.Create(tc.Context(), tt.scopeId, roles.WithName("first"))
@@ -302,19 +302,19 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = roleClient.Read(tc.Context(), "invalid id") _, err = roleClient.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
_, err = roleClient.Update(tc.Context(), u.Item.Id, u.Item.Version) _, err = roleClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
}) })
} }
} }
+4 -4
View File
@@ -105,7 +105,7 @@ func TestCrud(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
} }
func TestErrors(t *testing.T) { func TestErrors(t *testing.T) {
@@ -129,17 +129,17 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = scps.Read(tc.Context(), "p_doesntexis") _, err = scps.Read(tc.Context(), "p_doesntexis")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = scps.Read(tc.Context(), "invalid id") _, err = scps.Read(tc.Context(), "invalid id")
assert.Error(err) assert.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
} }
+4 -4
View File
@@ -159,7 +159,7 @@ func TestCrud(t *testing.T) {
assert.Error(err) assert.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
} }
func TestSet_Errors(t *testing.T) { func TestSet_Errors(t *testing.T) {
@@ -183,7 +183,7 @@ func TestSet_Errors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
tar, err = tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo")) tar, err = tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
require.Error(err) require.Error(err)
@@ -195,11 +195,11 @@ func TestSet_Errors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = tarClient.Read(tc.Context(), "invalid id") _, err = tarClient.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
} }
+5 -5
View File
@@ -155,7 +155,7 @@ func TestCrud(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
} }
func TestErrors(t *testing.T) { func TestErrors(t *testing.T) {
@@ -178,7 +178,7 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr := api.AsServerError(err) apiErr := api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
// Create another resource with the same name. // Create another resource with the same name.
_, err = userClient.Create(tc.Context(), org.GetPublicId(), users.WithName("first")) _, err = userClient.Create(tc.Context(), org.GetPublicId(), users.WithName("first"))
@@ -190,17 +190,17 @@ func TestErrors(t *testing.T) {
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.ResponseStatus()) assert.EqualValues(http.StatusNotFound, apiErr.Response().StatusCode())
_, err = userClient.Read(tc.Context(), "invalid id") _, err = userClient.Read(tc.Context(), "invalid id")
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
_, err = userClient.Update(tc.Context(), u.Item.Id, u.Item.Version) _, err = userClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.Error(err) require.Error(err)
apiErr = api.AsServerError(err) apiErr = api.AsServerError(err)
assert.NotNil(apiErr) assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.ResponseStatus()) assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode())
} }
+1 -1
View File
@@ -16,5 +16,5 @@ function list_accounts() {
function account_id() { function account_id() {
local acct=$1 local acct=$1
strip $(list_accounts | jq -c ".[] | select(.attributes.login_name | contains(\"$acct\")) | .[\"id\"]") strip $(list_accounts | jq -c ".items[] | select(.attributes.login_name | contains(\"$acct\")) | .[\"id\"]")
} }
@@ -4,5 +4,5 @@ function has_authorized_action() {
# has_authorized_action $out authorize-session # has_authorized_action $out authorize-session
local out=$1 local out=$1
local action=$2 local action=$2
echo $out | jq -c ".authorized_actions | contains([\"$action\"])" echo $out | jq -c ".item.authorized_actions | contains([\"$action\"])"
} }
+2 -2
View File
@@ -22,12 +22,12 @@ function assoc_group_acct() {
function group_id() { function group_id() {
local group=$1 local group=$1
strip $(list_groups | jq -c ".[] | select(.name | contains(\"$group\")) | .[\"id\"]") strip $(list_groups | jq -c ".items[] | select(.name | contains(\"$group\")) | .[\"id\"]")
} }
function group_member_ids() { function group_member_ids() {
local gid=$1 local gid=$1
boundary groups read -id $gid -format json | jq '.["members"][]["id"]' boundary groups read -id $gid -format json | jq '.item["members"][]["id"]'
} }
function group_has_member_id() { function group_has_member_id() {
@@ -25,7 +25,7 @@ function list_host_catalogs() {
function host_catalog_id() { function host_catalog_id() {
local id=$1 local id=$1
local sid=$2 local sid=$2
strip $(list_host_catalogs $sid | jq -c ".[] | select(.name | contains(\"$id\")) | .[\"id\"]") strip $(list_host_catalogs $sid | jq -c ".items[] | select(.name | contains(\"$id\")) | .[\"id\"]")
} }
function has_default_host_catalog_actions() { function has_default_host_catalog_actions() {
+2 -2
View File
@@ -28,12 +28,12 @@ function assoc_host_set_host() {
function host_set_id() { function host_set_id() {
local name=$1 local name=$1
local hcid=$2 local hcid=$2
strip $(list_host_sets $hcid | jq -c ".[] | select(.name | contains(\"$name\")) | .[\"id\"]") strip $(list_host_sets $hcid | jq -c ".items[] | select(.name | contains(\"$name\")) | .[\"id\"]")
} }
function host_set_host_ids() { function host_set_host_ids() {
local id=$1 local id=$1
ids=$(read_host_set $id | jq '.["host_ids"]') ids=$(read_host_set $id | jq '.item["host_ids"]')
echo "ids $ids" echo "ids $ids"
} }
+1 -1
View File
@@ -27,7 +27,7 @@ function host_id() {
local name=$1 local name=$1
local hcid=$2 local hcid=$2
strip $(list_hosts $hcid | jq -c ".[] | select(.name | contains(\"$name\")) | .[\"id\"]") strip $(list_hosts $hcid | jq -c ".items[] | select(.name | contains(\"$name\")) | .[\"id\"]")
} }
function has_default_host_actions() { function has_default_host_actions() {
+3 -3
View File
@@ -55,12 +55,12 @@ function remove_role_principal() {
function role_id() { function role_id() {
local name=$1 local name=$1
local sid=$2 local sid=$2
strip $(list_roles $sid | jq -c ".[] | select(.name | contains(\"$name\")) | .[\"id\"]") strip $(list_roles $sid | jq -c ".items[] | select(.name | contains(\"$name\")) | .[\"id\"]")
} }
function role_principal_ids() { function role_principal_ids() {
local rid=$1 local rid=$1
strip $(read_role $rid | jq '.["principals"][]["id"]') strip $(read_role $rid | jq '.item["principals"][]["id"]')
} }
function role_has_principal_id() { function role_has_principal_id() {
@@ -77,7 +77,7 @@ function role_has_principal_id() {
function role_grants() { function role_grants() {
local rid=$1 local rid=$1
read_role $rid | jq -rc '.grant_strings | @sh' read_role $rid | jq -rc '.item.grant_strings | @sh'
} }
function role_has_grant() { function role_has_grant() {
+1 -1
View File
@@ -27,7 +27,7 @@ function scope_id() {
local name=$1 local name=$1
local sid=$2 local sid=$2
strip $(list_scopes $sid | jq -c ".[] | select(.name | contains(\"$name\")) | .[\"id\"]") strip $(list_scopes $sid | jq -c ".items[] | select(.name | contains(\"$name\")) | .[\"id\"]")
} }
function has_default_scope_actions() { function has_default_scope_actions() {
+2 -2
View File
@@ -5,7 +5,7 @@ function list_sessions() {
} }
function count_sessions() { function count_sessions() {
list_sessions $1 | jq '. | length' list_sessions $1 | jq '.items | length'
} }
function cancel_session() { function cancel_session() {
@@ -14,4 +14,4 @@ function cancel_session() {
function read_session() { function read_session() {
boundary sessions read -id $1 boundary sessions read -id $1
} }
+2 -2
View File
@@ -34,12 +34,12 @@ function assoc_host_sets() {
function target_id_from_name() { function target_id_from_name() {
local sid=$1 local sid=$1
local name=$2 local name=$2
strip $(list_targets $sid | jq -c ".[] | select(.name | contains(\"$name\")) | .[\"id\"]") strip $(list_targets $sid | jq -c ".items[] | select(.name | contains(\"$name\")) | .[\"id\"]")
} }
function target_host_set_ids() { function target_host_set_ids() {
local tid=$1 local tid=$1
boundary targets read -id $tid -format json | jq '.host_sets[].id' boundary targets read -id $tid -format json | jq '.item.host_sets[].id'
} }
function target_has_host_set_id() { function target_has_host_set_id() {
+1 -1
View File
@@ -35,5 +35,5 @@ function has_default_user_actions() {
function user_id() { function user_id() {
local user=$1 local user=$1
strip $(list_users | jq -c ".[] | select(.name | contains(\"$user\")) | .[\"id\"]") strip $(list_users | jq -c ".items[] | select(.name | contains(\"$user\")) | .[\"id\"]")
} }
+2 -2
View File
@@ -59,7 +59,7 @@ load _helpers
[ "$status" -eq 0 ] [ "$status" -eq 0 ]
run list_sessions $DEFAULT_P_ID run list_sessions $DEFAULT_P_ID
[ "$status" -eq 0 ] [ "$status" -eq 0 ]
id=$(echo "$output" | jq -r '[.[]|select(.user_id == "u_1234567890")][0].id') id=$(echo "$output" | jq -r '[.items[]|select(.user_id == "u_1234567890")][0].id')
# Check unpriv cannot read or cancel an admin's session # Check unpriv cannot read or cancel an admin's session
run login $DEFAULT_UNPRIVILEGED_LOGIN run login $DEFAULT_UNPRIVILEGED_LOGIN
@@ -86,7 +86,7 @@ load _helpers
[ "$status" -eq 0 ] [ "$status" -eq 0 ]
run list_sessions $DEFAULT_P_ID run list_sessions $DEFAULT_P_ID
[ "$status" -eq 0 ] [ "$status" -eq 0 ]
id=$(echo "$output" | jq -r '[.[]|select(.user_id == "u_0987654321")][0].id') id=$(echo "$output" | jq -r '[.items[]|select(.user_id == "u_0987654321")][0].id')
# Check unpriv can read and cancel their own session # Check unpriv can read and cancel their own session
run login $DEFAULT_UNPRIVILEGED_LOGIN run login $DEFAULT_UNPRIVILEGED_LOGIN
@@ -17,7 +17,7 @@ The examples in Getting Started all revolve around running in `dev mode`. There
1. A route to download the [Postgres Docker image](https://hub.docker.com/_/postgres) is available or a local image cache is available 1. A route to download the [Postgres Docker image](https://hub.docker.com/_/postgres) is available or a local image cache is available
1. A [Boundary binary](https://www.boundaryproject.io/downloads) in your `$PATH` 1. A [Boundary binary](https://www.boundaryproject.io/downloads) in your `$PATH`
1. Optionally, an [installation of Boundary Desktop](/docs/api-clients/desktop#install-boundary-desktop) if you want to use the 1. Optionally, an [installation of Boundary Desktop](/docs/api-clients/desktop#install-boundary-desktop) if you want to use the
desktop examples desktop examples
## What is Dev Mode? ## What is Dev Mode?