Skip to content
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
2 changes: 1 addition & 1 deletion cmd/pre.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func PreRunDefaultProfile(cmd *cobra.Command, args []string) error {
conf, err := config.ReadConfigFromFile()
if err != nil {
if os.IsNotExist(err) {
return errors.New("No config found to run this command. Add a profile using pb profile command")
return errors.New("no config found to run this command. add a profile using pb profile command")
} else {
return err
}
Expand Down
62 changes: 31 additions & 31 deletions cmd/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,35 @@ import (
"pb/pkg/config"
"pb/pkg/model"

"github.com/charmbracelet/bubbles/table"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/spf13/cobra"
)

type ProfileListItem struct {
title, url, user string
}

func (item *ProfileListItem) Render(highlight bool) string {
if highlight {
render := fmt.Sprintf(
"%s\n%s\n%s",
selectedStyle.Render(item.title),
selectedStyleAlt.Render(fmt.Sprintf("url: %s", item.url)),
selectedStyleAlt.Render(fmt.Sprintf("user: %s", item.user)),
)
return selectedItemOuter.Render(render)
} else {
render := fmt.Sprintf(
"%s\n%s\n%s",
standardStyle.Render(item.title),
standardStyleAlt.Render(fmt.Sprintf("url: %s", item.url)),
standardStyleAlt.Render(fmt.Sprintf("user: %s", item.user)),
)
return itemOuter.Render(render)
}
}

var AddProfileCmd = &cobra.Command{
Use: "add name url <username?> <password?>",
Example: "add local_logs http://0.0.0.0:8000 admin admin",
Expand Down Expand Up @@ -163,40 +186,17 @@ var ListProfileCmd = &cobra.Command{
return nil
}

cols := []table.Column{
{Title: "PROFILE", Width: 7},
{Title: "URL", Width: 5},
{Title: "USER", Width: 8},
if len(file_config.Profiles) != 0 {
println()
}

rows := make([]table.Row, len(file_config.Profiles))
row_idx := 0
selected_row := 0
row := 0
for key, value := range file_config.Profiles {
if file_config.Default_profile == key {
selected_row = row_idx
}

rows[row_idx] = table.Row{key, value.Url, value.Username}
row_idx += 1

// update max width for table
cols[0].Width = Max(cols[0].Width, len(key))
cols[1].Width = Max(cols[1].Width, len(value.Url))
cols[2].Width = Max(cols[2].Width, len(value.Password))
item := ProfileListItem{key, value.Url, value.Username}
fmt.Println(item.Render(file_config.Default_profile == key))
row += 1
fmt.Println()
}

tbl := table.New(
table.WithColumns(cols),
table.WithRows(rows),
table.WithHeight(len(rows)),
table.WithStyles(listingTableStyle()),
)

tbl.SetCursor(selected_row)

fmt.Println(tbl.View())

return nil
},
}
Expand Down
12 changes: 9 additions & 3 deletions cmd/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,25 @@ import (
"fmt"
"os"
"pb/pkg/model"
"strconv"

tea "github.com/charmbracelet/bubbletea"
"github.com/spf13/cobra"
)

var QueryProfileCmd = &cobra.Command{
Use: "query name",
Use: "query name minutes",
Example: "query local_logs 20",
Short: "Open Query TUI",
Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(2),
PreRunE: PreRunDefaultProfile,
RunE: func(cmd *cobra.Command, args []string) error {
stream := args[0]
p := tea.NewProgram(model.NewQueryModel(DefaultProfile, stream), tea.WithAltScreen())
duration, err := strconv.Atoi(args[1])
if err != nil {
return err
}
p := tea.NewProgram(model.NewQueryModel(DefaultProfile, stream, uint(duration)), tea.WithAltScreen())
if _, err := p.Run(); err != nil {
fmt.Printf("Alas, there's been an error: %v", err)
os.Exit(1)
Expand Down
26 changes: 16 additions & 10 deletions cmd/style.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,26 @@
package cmd

import (
"github.com/charmbracelet/bubbles/table"
"github.com/charmbracelet/lipgloss"
)

// styling for cli outputs
var (
selectedStyle = lipgloss.NewStyle().
Foreground(lipgloss.AdaptiveColor{Light: "4", Dark: "11"}).Bold(true)
FocusPrimary = lipgloss.AdaptiveColor{Light: "16", Dark: "226"}
FocusSecondry = lipgloss.AdaptiveColor{Light: "18", Dark: "220"}

standardPrimary = lipgloss.AdaptiveColor{Light: "235", Dark: "255"}
standardSecondry = lipgloss.AdaptiveColor{Light: "238", Dark: "254"}

standardStyle = lipgloss.NewStyle().Foreground(standardPrimary)
standardStyleBold = lipgloss.NewStyle().Foreground(standardPrimary).Bold(true)
standardStyleAlt = lipgloss.NewStyle().Foreground(standardSecondry)

selectedStyle = lipgloss.NewStyle().Foreground(FocusPrimary).Bold(true)
selectedStyleAlt = lipgloss.NewStyle().Foreground(FocusSecondry)

selectedItemOuter = lipgloss.NewStyle().BorderStyle(lipgloss.NormalBorder()).BorderLeft(true).PaddingLeft(1).BorderForeground(FocusPrimary)
itemOuter = lipgloss.NewStyle().PaddingLeft(1)

styleBold = lipgloss.NewStyle().Bold(true)
)

func listingTableStyle() table.Styles {
s := table.DefaultStyles()
s.Header = s.Header.Border(lipgloss.NormalBorder(), false, false, true, false)
s.Selected = selectedStyle
return s
}
87 changes: 83 additions & 4 deletions cmd/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,44 @@ import (
"encoding/json"
"fmt"
"io"
"net/http"
"pb/pkg/config"
"strings"
"sync"

"github.com/spf13/cobra"
)

type UserRoleData struct {
Privilege string `json:"privilege"`
Resource struct {
Stream string `json:"stream"`
Tag string `json:"tag"`
} `json:"resource"`
}

func (user *UserRoleData) Render() string {
var s strings.Builder
s.WriteString(standardStyle.Render(user.Privilege))

if user.Resource.Stream != "" {
s.WriteString(" - ")
s.WriteString(standardStyleAlt.Render(user.Resource.Stream))
}
if user.Resource.Tag != "" {
s.WriteString(" ( ")
s.WriteString(standardStyleAlt.Render(user.Resource.Tag))
s.WriteString(" )")
}

return s.String()
}

type FetchUserRoleRes struct {
data []UserRoleData
err error
}

var AddUserCmd = &cobra.Command{
Use: "add name",
Example: "add bob",
Expand Down Expand Up @@ -117,14 +151,38 @@ var ListUserCmd = &cobra.Command{
defer resp.Body.Close()

if resp.StatusCode == 200 {
items := []string{}
err = json.Unmarshal(bytes, &items)
users := []string{}
err = json.Unmarshal(bytes, &users)
if err != nil {
return err
}
for _, item := range items {
fmt.Println(item)

client = DefaultClient()
role_responses := make([]FetchUserRoleRes, len(users))

wsg := sync.WaitGroup{}
wsg.Add(len(users))
for idx, user := range users {
idx := idx
user := user
go func() {
role_responses[idx] = fetchUserRoles(&client.client, &DefaultProfile, user)
wsg.Done()
}()
}
wsg.Wait()
fmt.Println()
for idx, user := range users {
roles := role_responses[idx]
fmt.Println(standardStyleBold.Bold(true).Render(user))
if roles.err == nil {
for _, role := range roles.data {
fmt.Printf(" %s\n", role.Render())
}
}
println()
}

} else {
body := string(bytes)
fmt.Printf("Request Failed\nStatus Code: %s\nResponse: %s\n", resp.Status, body)
Expand All @@ -133,3 +191,24 @@ var ListUserCmd = &cobra.Command{
return nil
},
}

func fetchUserRoles(client *http.Client, profile *config.Profile, user string) (res FetchUserRoleRes) {
endpoint := fmt.Sprintf("%s/%s", profile.Url, fmt.Sprintf("api/v1/user/%s/role", user))
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return
}
req.SetBasicAuth(profile.Username, profile.Password)
resp, err := client.Do(req)
if err != nil {
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return
}
defer resp.Body.Close()

res.err = json.Unmarshal(body, &res.data)
return
}
67 changes: 67 additions & 0 deletions pkg/model/help.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package model

import (
"github.com/charmbracelet/bubbles/key"
)

type TableKeyMap struct {
Up key.Binding
Down key.Binding
PageUp key.Binding
PageDown key.Binding
ScrollRight key.Binding
ScrollLeft key.Binding
Filter key.Binding
ClearFilter key.Binding
}

// ShortHelp returns keybindings to be shown in the mini help view. It's part
// of the key.Map interface.
func (k TableKeyMap) ShortHelp() []key.Binding {
return []key.Binding{k.ScrollRight, k.ScrollRight, k.Filter, k.ClearFilter}
}

// FullHelp returns keybindings for the expanded help view. It's part of the
// key.Map interface.
func (k TableKeyMap) FullHelp() [][]key.Binding {
return [][]key.Binding{
{k.Up, k.Down, k.PageUp, k.PageDown}, // first column
{k.ScrollLeft, k.ScrollRight},
{k.ClearFilter, k.Filter}, // second column
}
}

var tableKeys = TableKeyMap{
Up: key.NewBinding(
key.WithKeys("up", "k"),
key.WithHelp("↑/k", "move up"),
),
Down: key.NewBinding(
key.WithKeys("down", "j"),
key.WithHelp("↓/j", "move down"),
),
PageUp: key.NewBinding(
key.WithKeys("right", "l", "pgdown"),
key.WithHelp("→/l", "prev page"),
),
PageDown: key.NewBinding(
key.WithKeys("left", "h", "pgup"),
key.WithHelp("←/h", "next page"),
),
ScrollLeft: key.NewBinding(
key.WithKeys("shift+left", "shift+h"),
key.WithHelp("shift ←/h", "scroll left"),
),
ScrollRight: key.NewBinding(
key.WithKeys("shift+right", "shift+l"),
key.WithHelp("shift →/l", "scroll right"),
),
Filter: key.NewBinding(
key.WithKeys("/"),
key.WithHelp("/ .. <enter>", "Filter"),
),
ClearFilter: key.NewBinding(
key.WithKeys("esc"),
key.WithHelp("esc", "remove filter"),
),
}
Loading