Skip to content

Commit

Permalink
fix(usage-csv): changes from review
Browse files Browse the repository at this point in the history
Signed-off-by: Michal Wasilewski <[email protected]>
  • Loading branch information
mwasilew2 committed Jan 25, 2024
1 parent 24c879b commit f8ad2eb
Showing 1 changed file with 56 additions and 68 deletions.
124 changes: 56 additions & 68 deletions internal/cmd/profile/usage_view_csv_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
Expand All @@ -15,16 +14,9 @@ import (
"github.com/spacelift-io/spacectl/internal/cmd/authenticated"
)

type queryArgs struct {
since string
until string
aspect string
groupBy string
}

func usageViewCSVCommand() *cli.Command {
return &cli.Command{
Name: "usage-view-csv",
Name: "usage-csv",
Usage: "Prints CSV with usage data for the current account",
ArgsUsage: cmd.EmptyArgsUsage,
Flags: []cli.Flag{
Expand All @@ -35,73 +27,69 @@ func usageViewCSVCommand() *cli.Command {
flagUsageViewCSVFile,
},
Before: authenticated.Ensure,
Action: func(ctx *cli.Context) error {
// prep http query
args := &queryArgs{
since: ctx.String(flagUsageViewCSVSince.Name),
until: ctx.String(flagUsageViewCSVUntil.Name),
aspect: ctx.String(flagUsageViewCSVAspect.Name),
groupBy: ctx.String(flagUsageViewCSVGroupBy.Name),
}
params := buildQueryParams(args)
req, err := http.NewRequestWithContext(ctx.Context, http.MethodGet, "/usageanalytics/csv", nil)
if err != nil {
return fmt.Errorf("failed to create an HTTP request: %w", err)
}
q := req.URL.Query()
for k, v := range params {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
Action: usageViewCsv,
}
}

// execute http query
log.Println("Querying Spacelift for usage data...")
resp, err := authenticated.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
func usageViewCsv(ctx *cli.Context) error {
// prep http query
params := buildQueryParams(ctx)
req, err := http.NewRequestWithContext(ctx.Context, http.MethodGet, "/usageanalytics/csv", nil)
if err != nil {
return fmt.Errorf("failed to create an HTTP request: %w", err)
}
q := req.URL.Query()
for k, v := range params {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()

// save response to a file
var filePath string
if !ctx.IsSet(flagUsageViewCSVFile.Name) {
basePath, err := os.Getwd()
if err != nil {
return fmt.Errorf("failed to get base path: %w", err)
}
filePath = fmt.Sprintf(basePath+"/usage-%s-%s-%s.csv", args.aspect, args.since, args.until)
} else {
filePath = ctx.String(flagUsageViewCSVFile.Name)
}
fd, err := os.OpenFile(filepath.Clean(filePath), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
if err != nil {
return fmt.Errorf("failed to open a file descriptor: %w", err)
}
defer fd.Close()
bfd := bufio.NewWriter(fd)
defer bfd.Flush()
_, err = io.Copy(bfd, resp.Body)
if err != nil {
return fmt.Errorf("failed to write the response to a file: %w", err)
}
log.Println("Usage data saved to", filePath)
return nil
},
// execute http query
fmt.Fprint(os.Stderr, "Querying Spacelift for usage data...\n")
resp, err := authenticated.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}

// process a response
var filePath string
if ctx.IsSet(flagUsageViewCSVFile.Name) {
filePath = ctx.String(flagUsageViewCSVFile.Name)
fd, err := os.OpenFile(filepath.Clean(filePath), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
if err != nil {
return fmt.Errorf("failed to open a file descriptor: %w", err)
}
defer fd.Close()
bfd := bufio.NewWriter(fd)
defer bfd.Flush()
_, err = io.Copy(bfd, resp.Body)
if err != nil {
return fmt.Errorf("failed to write the response to a file: %w", err)
}
} else {
_, err = io.Copy(os.Stdout, resp.Body)
if err != nil {
return fmt.Errorf("failed to write the response to stdout: %w", err)
}
}

fmt.Fprint(os.Stderr, "Usage data downloaded successfully.\n")
return nil
}

func buildQueryParams(args *queryArgs) map[string]string {
func buildQueryParams(ctx *cli.Context) map[string]string {
params := make(map[string]string)

params["since"] = args.since
params["until"] = args.until
params["aspect"] = args.aspect
params["since"] = ctx.String(flagUsageViewCSVSince.Name)
params["until"] = ctx.String(flagUsageViewCSVUntil.Name)
params["aspect"] = ctx.String(flagUsageViewCSVAspect.Name)

if args.aspect == "run-minutes" {
params["groupBy"] = args.groupBy
if ctx.String(flagUsageViewCSVAspect.Name) == "run-minutes" {
params["groupBy"] = ctx.String(flagUsageViewCSVGroupBy.Name)
}

return params
Expand Down

0 comments on commit f8ad2eb

Please sign in to comment.