Skip to content

Commit

Permalink
feat(catalog): implement entities get-by-uid command
Browse files Browse the repository at this point in the history
  • Loading branch information
odsod committed Mar 30, 2023
1 parent 8d4de25 commit 0c16069
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
45 changes: 45 additions & 0 deletions catalog/client_entities_getbyid.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package catalog

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)

// GetEntityByUIDRequest is the request to the [Client.GetEntityByUID] method.
type GetEntityByUIDRequest struct {
// UID of the entity to get.
UID string
}

// GetEntityByUID gets an entity by its kind, namespace and name.
//
// See: https://backstage.io/docs/features/software-catalog/software-catalog-api/#get-entitiesby-uiduid
func (c *Client) GetEntityByUID(ctx context.Context, request *GetEntityByUIDRequest) (*Entity, error) {
const pathTemplate = "/api/catalog/entities/by-uid/%s"
path := fmt.Sprintf(
pathTemplate,
url.PathEscape(request.UID),
)
var rawEntity json.RawMessage
if err := c.get(ctx, path, nil, func(response *http.Response) error {
data, err := io.ReadAll(response.Body)
if err != nil {
return err
}
rawEntity = data
return nil
}); err != nil {
return nil, err
}
entity := Entity{
Raw: rawEntity,
}
if err := json.Unmarshal(rawEntity, &entity); err != nil {
return nil, err
}
return &entity, nil
}
24 changes: 24 additions & 0 deletions cmd/backstage/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ func newEntitiesCommand() *cobra.Command {
cmd.Use = "entities"
cmd.Short = "Read entities from the Backstage catalog"
cmd.AddCommand(newEntitiesListCommand())
cmd.AddCommand(newEntitiesGetByUIDCommand())
cmd.AddCommand(newEntitiesGetByNameCommand())
return cmd
}
Expand Down Expand Up @@ -174,6 +175,29 @@ func newEntitiesGetByNameCommand() *cobra.Command {
return cmd
}

func newEntitiesGetByUIDCommand() *cobra.Command {
cmd := newCommand()
cmd.Use = "get-by-uid"
cmd.Short = "Get an entity by its UID"
uid := cmd.Flags().String("uid", "", "UID of the entity to get")
_ = cmd.MarkFlagRequired("uid")
cmd.RunE = func(cmd *cobra.Command, args []string) error {
client, err := newCatalogClient()
if err != nil {
return err
}
entity, err := client.GetEntityByUID(cmd.Context(), &catalog.GetEntityByUIDRequest{
UID: *uid,
})
if err != nil {
return err
}
printRawJSON(cmd, entity.Raw)
return nil
}
return cmd
}

func printRawJSON(cmd *cobra.Command, raw json.RawMessage) {
var indented bytes.Buffer
indented.Grow(len(raw) * 2)
Expand Down

0 comments on commit 0c16069

Please sign in to comment.