Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interactive table sorting, trimming, and filtering #152

Merged
merged 18 commits into from
Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,12 @@ t3.medium 2 4 nitro true true
t3a.medium 2 4 nitro true true x86_64 Up to 5 Gigabit 3 0 0 none -Not Fetched- $0.01246
```

**Interactive Output**
```
$ ec2-instance-selector -o interactive
```
https://user-images.githubusercontent.com/68402662/184218343-6b236d4a-3fe6-42ae-9fe3-3fd3ee92a4b5.mov

**Sort by memory in ascending order using shorthand**
```
$ ec2-instance-selector -r us-east-1 -o table-wide --max-results 10 --sort-by memory --sort-direction asc
Expand Down
27 changes: 27 additions & 0 deletions THIRD_PARTY_LICENSES
Original file line number Diff line number Diff line change
Expand Up @@ -1445,6 +1445,33 @@ furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

------

** github.com/sahilm/fuzzy; v0.1.0 --
https://github.com/sahilm/fuzzy

The MIT License (MIT)

Copyright (c) 2017 Sahil Muthoo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Expand Down
61 changes: 8 additions & 53 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ const (
tableWideOutput = "table-wide"
oneLine = "one-line"
bubbleTeaOutput = "interactive"

// Sort filter default
instanceNamePath = ".InstanceType"
)

// Filter Flag Constants
Expand Down Expand Up @@ -120,33 +123,6 @@ const (
sortBy = "sort-by"
)

// Sorting Constants
const (
// Direction

sortAscending = "ascending"
sortAsc = "asc"
sortDescending = "descending"
sortDesc = "desc"

// Sorting Fields
spotPrice = "spot-price"
odPrice = "on-demand-price"

// JSON field paths
instanceNamePath = ".InstanceType"
vcpuPath = ".VCpuInfo.DefaultVCpus"
memoryPath = ".MemoryInfo.SizeInMiB"
gpuMemoryTotalPath = ".GpuInfo.TotalGpuMemoryInMiB"
networkInterfacesPath = ".NetworkInfo.MaximumNetworkInterfaces"
spotPricePath = ".SpotPrice"
odPricePath = ".OndemandPricePerHour"
instanceStoragePath = ".InstanceStorageInfo.TotalSizeInGB"
ebsOptimizedBaselineBandwidthPath = ".EbsInfo.EbsOptimizedInfo.BaselineBandwidthInMbps"
ebsOptimizedBaselineThroughputPath = ".EbsInfo.EbsOptimizedInfo.BaselineThroughputInMBps"
ebsOptimizedBaselineIOPSPath = ".EbsInfo.EbsOptimizedInfo.BaselineIops"
)

var (
// versionID is overridden at compilation with the version based on the git tag
versionID = "dev"
Expand Down Expand Up @@ -177,26 +153,10 @@ Full docs can be found at github.com/aws/amazon-` + binName
resultsOutputFn := outputs.SimpleInstanceTypeOutput

cliSortDirections := []string{
sortAscending,
sortAsc,
sortDescending,
sortDesc,
}

// map quantity cli flags to json paths for easier cli sorting
sortingKeysMap := map[string]string{
vcpus: vcpuPath,
memory: memoryPath,
gpuMemoryTotal: gpuMemoryTotalPath,
networkInterfaces: networkInterfacesPath,
spotPrice: spotPricePath,
odPrice: odPricePath,
instanceStorage: instanceStoragePath,
ebsOptimizedBaselineBandwidth: ebsOptimizedBaselineBandwidthPath,
ebsOptimizedBaselineThroughput: ebsOptimizedBaselineThroughputPath,
ebsOptimizedBaselineIOPS: ebsOptimizedBaselineIOPSPath,
gpus: gpus,
inferenceAccelerators: inferenceAccelerators,
sorter.SortAscending,
sorter.SortAsc,
sorter.SortDescending,
sorter.SortDesc,
}

// Registers flags with specific input types from the cli pkg
Expand Down Expand Up @@ -263,7 +223,7 @@ Full docs can be found at github.com/aws/amazon-` + binName
cli.ConfigBoolFlag(verbose, cli.StringMe("v"), nil, "Verbose - will print out full instance specs")
cli.ConfigBoolFlag(help, cli.StringMe("h"), nil, "Help")
cli.ConfigBoolFlag(version, nil, nil, "Prints CLI version")
cli.ConfigStringOptionsFlag(sortDirection, nil, cli.StringMe(sortAscending), fmt.Sprintf("Specify the direction to sort in (%s)", strings.Join(cliSortDirections, ", ")), cliSortDirections)
cli.ConfigStringOptionsFlag(sortDirection, nil, cli.StringMe(sorter.SortAscending), fmt.Sprintf("Specify the direction to sort in (%s)", strings.Join(cliSortDirections, ", ")), cliSortDirections)
cli.ConfigStringFlag(sortBy, nil, cli.StringMe(instanceNamePath), "Specify the field to sort by. Quantity flags present in this CLI (memory, gpus, etc.) or a JSON path to the appropriate instance type field (Ex: \".MemoryInfo.SizeInMiB\") is acceptable.", nil)

// Parses the user input with the registered flags and runs type specific validation on the user input
Expand Down Expand Up @@ -419,11 +379,6 @@ Full docs can be found at github.com/aws/amazon-` + binName
}
}

// determine if user used a shorthand for sorting flag
if sortFieldShorthandPath, ok := sortingKeysMap[*sortField]; ok {
sortField = &sortFieldShorthandPath
}

// fetch instance types without truncating results
prevMaxResults := filters.MaxResults
filters.MaxResults = nil
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.18
require (
github.com/aws/aws-sdk-go v1.44.59
github.com/blang/semver/v4 v4.0.0
github.com/charmbracelet/bubbles v0.11.0
github.com/charmbracelet/bubbles v0.13.0
github.com/charmbracelet/bubbletea v0.21.0
github.com/charmbracelet/lipgloss v0.5.0
github.com/evertras/bubble-table v0.14.4
Expand All @@ -32,6 +32,7 @@ require (
github.com/muesli/cancelreader v0.2.0 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/sahilm/fuzzy v0.1.0 // indirect
github.com/smartystreets/goconvey v1.6.4 // indirect
go.uber.org/atomic v1.4.0 // indirect
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2y
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/charmbracelet/bubbles v0.11.0 h1:fBLyY0PvJnd56Vlu5L84JJH6f4axhgIJ9P3NET78f0Q=
github.com/charmbracelet/bubbles v0.11.0/go.mod h1:bbeTiXwPww4M031aGi8UK2HT9RDWoiNibae+1yCMtcc=
github.com/charmbracelet/bubbles v0.13.0 h1:zP/ROH3wJEBqZWKIsD50ZKKlx3ydLInq3LdD/Nrlb8w=
github.com/charmbracelet/bubbles v0.13.0/go.mod h1:bbeTiXwPww4M031aGi8UK2HT9RDWoiNibae+1yCMtcc=
github.com/charmbracelet/bubbletea v0.21.0 h1:f3y+kanzgev5PA916qxmDybSHU3N804uOnKnhRPXTcI=
github.com/charmbracelet/bubbletea v0.21.0/go.mod h1:GgmJMec61d08zXsOhqRC/AiOx4K4pmz+VIcRIm1FKr4=
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
Expand Down Expand Up @@ -126,6 +128,7 @@ github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=
github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
Expand Down
109 changes: 91 additions & 18 deletions pkg/selector/outputs/bubbletea.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,29 @@ package outputs

import (
"github.com/aws/amazon-ec2-instance-selector/v2/pkg/instancetypes"
"github.com/aws/amazon-ec2-instance-selector/v2/pkg/sorter"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv"
)

const (
// can't get terminal dimensions on startup, so use this
initialDimensionVal = 30

instanceTypeKey = "instance type"
selectedKey = "selected"
)

const (
// table states
stateTable = "table"
stateVerbose = "verbose"
stateSorting = "sorting"
)

var (
controlsStyle = lipgloss.NewStyle().Faint(true)
)

// BubbleTeaModel is used to hold the state of the bubble tea TUI
Expand All @@ -40,6 +50,9 @@ type BubbleTeaModel struct {

// holds state for the verbose view
verboseModel verboseModel

// holds the state for the sorting view
sortingModel sortingModel
}

// NewBubbleTeaModel initializes a new bubble tea Model which represents
Expand All @@ -49,6 +62,7 @@ func NewBubbleTeaModel(instanceTypes []*instancetypes.Details) BubbleTeaModel {
currentState: stateTable,
tableModel: *initTableModel(instanceTypes),
verboseModel: *initVerboseModel(instanceTypes),
sortingModel: *initSortingModel(instanceTypes),
}
}

Expand All @@ -62,28 +76,87 @@ func (m BubbleTeaModel) Init() tea.Cmd {
func (m BubbleTeaModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
// don't listen for input if currently typing into text field
if m.tableModel.filterTextInput.Focused() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about moving this table- and sorting-related logic to the respective view files, and then forwarding the key msg to the Update() of tableView and sortingView? Similar to the other "in focus" handling you do there.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These if statements exist to prevent the keys used to switch between states from causing a state switch while typing in a text field.

break
} else if m.sortingModel.sortTextInput.Focused() {
// see if we should sort and switch states to table
if m.currentState == stateSorting && msg.String() == "enter" {
jsonPath := m.sortingModel.sortTextInput.Value()

sortDirection := sorter.SortAscending
if m.sortingModel.isDescending {
sortDirection = sorter.SortDescending
}

var err error
m.tableModel, err = m.tableModel.sortTable(jsonPath, sortDirection)
if err != nil {
m.sortingModel.sortTextInput.SetValue(jsonPathError)
break
}

m.currentState = stateTable

m.sortingModel.sortTextInput.Blur()
}

break
}

// check for quit or change in state
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
case "enter":
switch m.currentState {
case stateTable:
// switch from table state to verbose state
m.currentState = stateVerbose

case "e":
// switch from table state to verbose state
if m.currentState == stateTable {
// get focused instance type
rowIndex := m.tableModel.table.GetHighlightedRowIndex()
focusedInstance := m.verboseModel.instanceTypes[rowIndex]
focusedRow := m.tableModel.table.HighlightedRow()
focusedInstance, ok := focusedRow.Data[instanceTypeKey].(*instancetypes.Details)
if !ok {
break
}

// set content of view
m.verboseModel.focusedInstanceName = focusedInstance.InstanceType
m.verboseModel.viewport.SetContent(VerboseInstanceTypeOutput([]*instancetypes.Details{focusedInstance})[0])

// move viewport to top of printout
m.verboseModel.viewport.SetYOffset(0)
case stateVerbose:
// switch from verbose state to table state

// switch from table state to verbose state
m.currentState = stateVerbose
}
case "s":
// switch from table view to sorting view
if m.currentState == stateTable {
m.currentState = stateSorting
}
case "enter":
// sort and switch states to table
if m.currentState == stateSorting {
sortFilter := string(m.sortingModel.shorthandList.SelectedItem().(item))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly here, once we know we're in the sortingView state, we should pass the key msg to sortingView's update() and etc. to group all of the actual sorting logic together.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the sorting, information from the sorting state must be retrieved and then passed on to the table state before the state switch occurs. This requires access to both sortingModel and tableModel which are not currently reachable within the update() functions of each view.

I tried to keep all logic which dealt with "inter-state" affairs (such as switching states) in the Update() found in bubbletea.go, which is why the sorting logic currently lies there.


sortDirection := sorter.SortAscending
if m.sortingModel.isDescending {
sortDirection = sorter.SortDescending
}

var err error
m.tableModel, err = m.tableModel.sortTable(sortFilter, sortDirection)
if err != nil {
m.sortingModel.sortTextInput.SetValue("INVALID SHORTHAND VALUE")
break
}

m.currentState = stateTable

m.sortingModel.sortTextInput.Blur()
}
case "esc":
// switch from sorting state or verbose state to table state
if m.currentState == stateSorting || m.currentState == stateVerbose {
m.currentState = stateTable
}
}
Expand All @@ -95,23 +168,21 @@ func (m BubbleTeaModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// handle screen resizing
m.tableModel = m.tableModel.resizeView(msg)
m.verboseModel = m.verboseModel.resizeView(msg)
m.sortingModel = m.sortingModel.resizeView(msg)
}

var cmd tea.Cmd
// update currently active state
switch m.currentState {
case stateTable:
// update table
var cmd tea.Cmd
m.tableModel, cmd = m.tableModel.update(msg)

return m, cmd
case stateVerbose:
// update viewport
var cmd tea.Cmd
m.verboseModel, cmd = m.verboseModel.update(msg)
return m, cmd
case stateSorting:
m.sortingModel, cmd = m.sortingModel.update(msg)
}

return m, nil
return m, cmd
}

// View is used by bubble tea to render the bubble tea model
Expand All @@ -121,6 +192,8 @@ func (m BubbleTeaModel) View() string {
return m.tableModel.view()
case stateVerbose:
return m.verboseModel.view()
case stateSorting:
return m.sortingModel.view()
}

return ""
Expand Down
Loading