Skip to content

Commit

Permalink
fix: add output flag
Browse files Browse the repository at this point in the history
  • Loading branch information
artaasadi committed May 20, 2024
1 parent cb1db1b commit 572d5df
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 36 deletions.
23 changes: 14 additions & 9 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ func init() {
rootCmd.AddCommand(optimizeCmd)

optimizeCmd.PersistentFlags().String("preferences", "", "Path to preferences file (yaml)")
optimizeCmd.PersistentFlags().Bool("non-interactive-view", false, "Show optimization results in non-interactive mode")
optimizeCmd.PersistentFlags().Bool("csv-export", false, "Get CSV export")
optimizeCmd.PersistentFlags().Bool("json-export", false, "Get json export")
optimizeCmd.PersistentFlags().String("output", "interactive", "Show optimization results in selected output (possible values: interactive, table, csv, json. default value: interactive)")
optimizeCmd.PersistentFlags().Bool("plugin-debug-mode", false, "Enable plugin debug mode (manager wont start plugin)")
}

Expand Down Expand Up @@ -99,12 +97,19 @@ func Execute() {
return err
}

nonInteractiveFlag := utils.ReadBooleanFlag(c, "non-interactive-view")
csvExportFlag := utils.ReadBooleanFlag(c, "csv-export")
jsonExportFlag := utils.ReadBooleanFlag(c, "json-export")
nonInteractiveFlag := utils.ReadStringFlag(c, "output")
manager := plugin2.New()

if nonInteractiveFlag || csvExportFlag || jsonExportFlag {
switch nonInteractiveFlag {
case "interactive":
case "table":
case "csv":
case "json":
default:
return fmt.Errorf("output mode not recognized\npossible values: interactive, table, csv, json. default value: interactive (default \"interactive\")")
}

if nonInteractiveFlag != "interactive" {
manager.SetNonInteractiveView()
}

Expand Down Expand Up @@ -208,8 +213,8 @@ func Execute() {
return err
}

if nonInteractiveFlag || csvExportFlag || jsonExportFlag {
err := manager.NonInteractiveView.WaitAndShowResults(nonInteractiveFlag, csvExportFlag, jsonExportFlag)
if nonInteractiveFlag != "interactive" {
err := manager.NonInteractiveView.WaitAndShowResults(nonInteractiveFlag)
return err
} else {
helpController := controller.NewHelp()
Expand Down
21 changes: 20 additions & 1 deletion pkg/utils/view.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package utils

import "fmt"
import (
"fmt"
"strings"
)

func PFloat64ToString(v *float64) string {
if v == nil {
Expand Down Expand Up @@ -76,3 +79,19 @@ func SizeByteToGB(v *int32) string {
vv := *v // / 1000000000
return fmt.Sprintf("%d GB", vv)
}

func FormatFloat(number float64) string {
parts := strings.Split(fmt.Sprintf("%.2f", number), ".")
integerPart := parts[0]
decimalPart := parts[1]

var result []rune
for i, digit := range integerPart {
if i > 0 && (len(integerPart)-i)%3 == 0 {
result = append(result, ',')
}
result = append(result, rune(digit))
}

return fmt.Sprintf("%s.%s", string(result), decimalPart)
}
40 changes: 19 additions & 21 deletions view/non_interactive_view.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/jedib0t/go-pretty/v6/table"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/kaytu-io/kaytu/pkg/plugin/proto/src/golang"
"github.com/kaytu-io/kaytu/pkg/utils"
"os"
"sync"
"time"
Expand Down Expand Up @@ -122,7 +123,7 @@ func getItemString(item *golang.OptimizationItem) string {
totalSaving += dev.CurrentCost - dev.RightSizedCost
}
}
row = append(row, item.Id, item.ResourceType, item.Region, item.Platform, fmt.Sprintf("$%.2f", totalSaving))
row = append(row, item.Id, item.ResourceType, item.Region, item.Platform, fmt.Sprintf("$%s", utils.FormatFloat(totalSaving)))
t.AppendRow(row)
itemString += t.Render()
itemString += "\n " + bold.Sprint("Devices") + ":"
Expand Down Expand Up @@ -196,7 +197,7 @@ func getDeviceString(dev *golang.Device) string {
t.AppendHeader(headers)
var row table.Row
var itemString string
row = append(row, "└─ "+dev.DeviceId, dev.ResourceType, dev.Runtime, dev.CurrentCost, dev.RightSizedCost, fmt.Sprintf("$%.2f", dev.CurrentCost-dev.RightSizedCost))
row = append(row, "└─ "+dev.DeviceId, dev.ResourceType, dev.Runtime, dev.CurrentCost, dev.RightSizedCost, fmt.Sprintf("$%s", utils.FormatFloat(dev.CurrentCost-dev.RightSizedCost)))
t.AppendRow(row)
itemString += t.Render()
itemString += "\n " + bold.Sprint("Properties") + ":\n" + getPropertiesString(dev.Properties)
Expand Down Expand Up @@ -281,29 +282,25 @@ func (v *NonInteractiveView) PublishResultsReady(ready *golang.ResultsReady) {
v.resultsReady <- ready.Ready
}

func (v *NonInteractiveView) WaitAndShowResults(showResults bool, csvExport bool, jsonExport bool) error {
func (v *NonInteractiveView) WaitAndShowResults(nonInteractiveFlag string) error {
go v.WaitForAllItems()
go v.WaitForJobs()
for {
select {
case ready := <-v.resultsReady:
if ready == true {
if showResults {
if nonInteractiveFlag == "table" {
str, err := v.OptimizationsString()
if err != nil {
return err
}
os.Stderr.WriteString(str)
}
if csvExport {
os.Stdout.WriteString(str)
} else if nonInteractiveFlag == "csv" {
csvHeaders, csvRows := exportCsv(v.items)
file, err := os.Create("export.csv")
if err != nil {
return err
}
writer := csv.NewWriter(file)
out := os.Stdout
writer := csv.NewWriter(out)

err = writer.Write(csvHeaders)
err := writer.Write(csvHeaders)
if err != nil {
return err
}
Expand All @@ -315,12 +312,11 @@ func (v *NonInteractiveView) WaitAndShowResults(showResults bool, csvExport bool
}
}
writer.Flush()
err = file.Close()
err = out.Close()
if err != nil {
return err
}
}
if jsonExport {
} else if nonInteractiveFlag == "json" {
jsonValue := struct {
Items []*golang.OptimizationItem
}{
Expand All @@ -331,19 +327,21 @@ func (v *NonInteractiveView) WaitAndShowResults(showResults bool, csvExport bool
return err
}

file, err := os.Create("export.json")
out := os.Stdout
if err != nil {
return err
}

_, err = file.Write(jsonData)
_, err = out.Write(jsonData)
if err != nil {
return err
}
err = file.Close()
err = out.Close()
if err != nil {
return err
}
} else {
os.Stderr.WriteString("output mode not recognized!")
}
return nil
}
Expand Down Expand Up @@ -427,8 +425,8 @@ func exportCsv(items []*golang.OptimizationItem) ([]string, [][]string) {
for _, d := range i.Devices {
for _, p := range d.Properties {
rows = append(rows, []string{
i.Id, i.ResourceType, i.Region, i.Platform, fmt.Sprintf("$%.2f", totalSaving),
d.DeviceId, d.ResourceType, d.Runtime, fmt.Sprintf("$%.2f", d.CurrentCost), fmt.Sprintf("$%.2f", d.RightSizedCost), fmt.Sprintf("$%.2f", d.CurrentCost-d.RightSizedCost),
i.Id, i.ResourceType, i.Region, i.Platform, fmt.Sprintf("$%s", utils.FormatFloat(totalSaving)),
d.DeviceId, d.ResourceType, d.Runtime, fmt.Sprintf("$%s", utils.FormatFloat(d.CurrentCost)), fmt.Sprintf("$%s", utils.FormatFloat(d.RightSizedCost)), fmt.Sprintf("$%s", utils.FormatFloat(d.CurrentCost-d.RightSizedCost)),
p.Key, p.Current, p.Average, p.Max, p.Recommended,
})
}
Expand Down
5 changes: 3 additions & 2 deletions view/page_optimization.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/evertras/bubble-table/table"
"github.com/kaytu-io/kaytu/controller"
"github.com/kaytu-io/kaytu/pkg/style"
"github.com/kaytu-io/kaytu/pkg/utils"
"github.com/kaytu-io/kaytu/view/responsive"
)

Expand Down Expand Up @@ -90,7 +91,7 @@ func (m OptimizationsPage) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
i.ResourceType,
i.Region,
i.Platform,
fmt.Sprintf("$%.2f (%%%.2f)", totalSaving, (totalSaving/totalCurrentCost)*100),
fmt.Sprintf("$%s (%%%.2f)", utils.FormatFloat(totalSaving), (totalSaving/totalCurrentCost)*100),
}
if i.Skipped {
row[5] = "skipped"
Expand Down Expand Up @@ -209,7 +210,7 @@ func (m OptimizationsPage) View() string {
}

return fmt.Sprintf("Current runtime cost: %s, Savings: %s\n%s\n%s",
style.CostStyle.Render(fmt.Sprintf("$%.2f", totalCost)), style.SavingStyle.Render(fmt.Sprintf("$%.2f", savings)),
style.CostStyle.Render(fmt.Sprintf("$%s", utils.FormatFloat(totalCost))), style.SavingStyle.Render(fmt.Sprintf("$%s", utils.FormatFloat(savings))),
m.table.View(),
m.statusBar.View(),
)
Expand Down
7 changes: 4 additions & 3 deletions view/page_optimization_details.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/kaytu-io/kaytu/controller"
"github.com/kaytu-io/kaytu/pkg/plugin/proto/src/golang"
"github.com/kaytu-io/kaytu/pkg/style"
"github.com/kaytu-io/kaytu/pkg/utils"
"github.com/kaytu-io/kaytu/view/responsive"
"github.com/muesli/reflow/wordwrap"
"strings"
Expand Down Expand Up @@ -124,12 +125,12 @@ func (m OptimizationDetailsPage) OnOpen() Page {
dev.DeviceId,
dev.ResourceType,
dev.Runtime,
fmt.Sprintf("$%.2f", dev.CurrentCost),
fmt.Sprintf("$%s", utils.FormatFloat(dev.CurrentCost)),
ifRecommendationExists(func() string {
return fmt.Sprintf("$%.2f", dev.RightSizedCost)
return fmt.Sprintf("$%s", utils.FormatFloat(dev.RightSizedCost))
}),
ifRecommendationExists(func() string {
return fmt.Sprintf("$%.2f", dev.CurrentCost-dev.RightSizedCost)
return fmt.Sprintf("$%s", utils.FormatFloat(dev.CurrentCost-dev.RightSizedCost))
}),
})
}
Expand Down

0 comments on commit 572d5df

Please sign in to comment.