init: cctuip is a go

This commit is contained in:
decentral1se 2023-04-11 12:09:00 +02:00
commit 60451aab45
Signed by: decentral1se
GPG Key ID: 03789458B3D0C410
6 changed files with 2271 additions and 0 deletions

15
LICENSE Normal file
View File

@ -0,0 +1,15 @@
cctuip: Co-op Cloud TUI prototype.
Copyright (C) 2023 Co-op Cloud <helo@coopcloud.tech>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

30
README.md Normal file
View File

@ -0,0 +1,30 @@
# cctuip
> Co-op Cloud TUI prototype 🎉
## Features
* `abra app ls` compatibility. It does not query `-S` unless you press
`s` (like passing `-S` on the CLI) so that initial loading times are
real fast (because we only query local-first data in `~/.abra`).
* Fuzzy search against domain, server and recipe.
## Controls
* `up/down`: scroll up / down (`jk` vim bindings also work)
* `page up/down`: ;page up down (`ctrl+u/d` vim binding also work)
* `/`: fuzzy filter against domain, server & recipe
* `enter`: focus on table, select row, confirm
* `esc`: reset filter
* `s`: retrieve app deployment status (filter first to reduce scope)
## Install
(Only `x86_64` supported atm for alpha testing)
```
curl https://git.coopcloud.tech/decentral1se/cctuip/raw/branch/main/cctuip -o cctuip
chmod +x cctuip
./cctuip
```

BIN
cctuip Executable file

Binary file not shown.

405
cctuip.go Normal file
View File

@ -0,0 +1,405 @@
// cctuip is a Co-op Cloud TUI.
package main
import (
"flag"
"fmt"
"log"
"os"
"sort"
"strings"
abraClient "coopcloud.tech/abra/pkg/client"
"coopcloud.tech/abra/pkg/config"
"coopcloud.tech/abra/pkg/recipe"
"coopcloud.tech/tagcmp"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
dockerClient "github.com/docker/docker/client"
"github.com/evertras/bubble-table/table"
"golang.org/x/exp/slices"
"golang.org/x/term"
)
// help is the cctuip CLI help output.
const help = `cctuip [options]
cctuip is a Co-op Cloud TUI.
Options:
-h output help
`
var helpFlag bool
// handleCliFlags parses CLI flags.
func handleCliFlags() error {
flag.BoolVar(&helpFlag, "h", false, "output help")
flag.Parse()
return nil
}
// getClient retrieves a docker client from the abra API.
func getClient(server string) (*dockerClient.Client, error) {
cl, err := abraClient.New(server)
if err != nil {
return nil, fmt.Errorf("getClient: %s", err)
}
return cl, nil
}
// getApps retrieves app metadata from the abra API.
func getApps() ([]config.App, error) {
appFiles, err := config.LoadAppFiles("")
if err != nil {
return []config.App{}, fmt.Errorf("getApps: %s", err)
}
apps, err := config.GetApps(appFiles, "")
if err != nil {
return []config.App{}, fmt.Errorf("getApps: %s", err)
}
sort.Sort(config.ByName(apps))
return apps, nil
}
// getNumServersAndRecipes totals servers and recipes.
func getNumServersAndRecipes(apps []config.App) (int, int) {
var (
servers []string
recipes []string
)
for _, app := range apps {
if !slices.Contains(servers, app.Server) {
servers = append(servers, app.Server)
}
if !slices.Contains(recipes, app.Recipe) {
recipes = append(recipes, app.Recipe)
}
}
return len(servers), len(recipes)
}
// errorMsg delivers errors to the UI.
type errorMsg struct{ err error }
// Error implements error output rendering.
func (e errorMsg) Error() string { return e.err.Error() }
// appsDeployStatusMsg delivers the deployment status of all apps to the UI.
type appsDeployStatusMsg map[string]map[string]string
// getAppsDeployStatus retrieves apps deployment status from a server.
func getAppsDeployStatus(m model) tea.Msg {
var apps []config.App
for _, row := range m.table.GetVisibleRows() {
apps = append(apps, row.Data["app"].(config.App))
}
statuses, err := config.GetAppStatuses(apps, true)
if err != nil {
return errorMsg{err}
}
catl, err := recipe.ReadRecipeCatalogue()
if err != nil {
return errorMsg{err}
}
for _, app := range apps {
var newUpdates []string
if status, ok := statuses[app.StackName()]; ok {
if version, ok := status["version"]; ok {
updates, err := recipe.GetRecipeCatalogueVersions(app.Recipe, catl)
if err != nil {
return errorMsg{err}
}
parsedVersion, err := tagcmp.Parse(version)
if err != nil {
statuses[app.StackName()]["updates"] = "🤷"
continue
}
for _, update := range updates {
parsedUpdate, err := tagcmp.Parse(update)
if err != nil {
statuses[app.StackName()]["updates"] = "🤷"
continue
}
if update != version && parsedUpdate.IsGreaterThan(parsedVersion) {
newUpdates = append(newUpdates, update)
}
}
if len(newUpdates) == 0 {
statuses[app.StackName()]["updates"] = "✅"
} else {
statuses[app.StackName()]["updates"] = fmt.Sprintf("%v", len(newUpdates))
}
}
}
}
return appsDeployStatusMsg(statuses)
}
func renderAppsDeployStatus(m *model, appStatuses appsDeployStatusMsg) table.Model {
for _, row := range m.table.GetVisibleRows() {
app := row.Data["app"].(config.App)
appStatus := appStatuses[app.StackName()]
var (
version = appStatus["version"]
updates = appStatus["updates"]
status = appStatus["status"]
chaos = appStatus["chaos"]
chaosVersion = appStatus["chaosVersion"]
autoUpdate = appStatus["autoUpdate"]
)
if status == "" {
row.Data["status"] = "🤷"
} else {
row.Data["status"] = status
}
if version == "" {
row.Data["version"] = "🤷"
} else {
row.Data["version"] = version
row.Data["updates"] = updates
}
if chaos == "" {
row.Data["chaos"] = "🤷"
} else {
row.Data["chaos"] = chaos
}
if chaosVersion == "" {
row.Data["chaos-version"] = "🤷"
} else {
row.Data["chaos-version"] = chaosVersion
}
if autoUpdate == "" {
row.Data["autoUpdate"] = "🤷"
} else {
row.Data["autoUpdate"] = autoUpdate
}
}
return m.table
}
type initTableMsg struct{ table table.Model }
// initTable loads the table layout from local-first data sources (~/.abra).
func initTable(m model) tea.Msg {
var rows []table.Row
for _, app := range m.apps {
rows = append(rows, table.NewRow(table.RowData{
"domain": app.Domain,
"server": app.Server,
"recipe": app.Recipe,
"status": "🤷",
"version": "🤷",
"updates": "🤷",
"chaos": "🤷",
"chaos-version": "🤷",
"auto-update": "🤷",
"app": app, // attach app itself for faster lookups
}))
}
colStyle := lipgloss.NewStyle().Align(lipgloss.Left)
columns := []table.Column{
table.NewFlexColumn("domain", "Domain", 2).WithFiltered(true).WithStyle(colStyle),
table.NewFlexColumn("server", "Server", 1).WithFiltered(true).WithStyle(colStyle),
table.NewFlexColumn("recipe", "Recipe", 1).WithFiltered(true).WithStyle(colStyle),
table.NewFlexColumn("status", "Status", 1).WithStyle(colStyle),
table.NewFlexColumn("version", "Version", 2).WithStyle(colStyle),
table.NewFlexColumn("updates", "Updates", 2).WithStyle(colStyle),
table.NewFlexColumn("chaos", "Chaos", 1).WithStyle(colStyle),
table.NewFlexColumn("chaos-version", "Chaos version", 2).WithStyle(colStyle),
table.NewFlexColumn("auto-update", "Auto-update", 1).WithStyle(colStyle),
}
width, height, err := term.GetSize(0)
if err != nil {
log.Fatal(err) // TODO
}
keymap := table.DefaultKeyMap()
keymap.Filter = key.NewBinding(key.WithKeys("/", "f"))
keymap.PageDown = key.NewBinding(key.WithKeys("right", "l", "pgdown", "ctrl+d"))
keymap.PageUp = key.NewBinding(key.WithKeys("left", "h", "pgup", "ctrl+u"))
t := table.
New(columns).
Filtered(true).
Focused(true).
WithPageSize(height - 10).
WithRows([]table.Row(rows)).
WithTargetWidth(width).
WithKeyMap(keymap)
return initTableMsg{table: t}
}
// model is the TUI application state.
type model struct {
apps []config.App
numApps int
numServers int
numRecipes int
numFilteredApps int
numFilteredServers int
numFilteredRecipes int
table table.Model
spinner spinner.Model
pollingStatus bool
err error
}
// getFilteredApps retrieves all visible apps.
func (m model) getFilteredApps() []config.App {
var servers []config.App
for _, row := range m.table.GetVisibleRows() {
servers = append(servers, row.Data["app"].(config.App))
}
return servers
}
// updateCount updates the apps/servers/recipes count.
func (m *model) updateCount() {
if m.table.GetIsFilterActive() {
apps := m.getFilteredApps()
m.numFilteredApps = len(apps)
m.numFilteredServers, m.numFilteredRecipes = getNumServersAndRecipes(apps)
} else {
m.numFilteredApps = m.numApps
m.numFilteredServers = m.numServers
m.numFilteredRecipes = m.numRecipes
}
}
// Init initialises a new model. All I/O happens here and the results are fed
// into the UI for further updates and rendering.
func (m model) Init() tea.Cmd {
return tea.Batch(
func() tea.Msg { return initTable(m) },
m.spinner.Tick,
)
}
// Update handles updates to the TUI via I/O and the user.
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
var cmds []tea.Cmd
m.table, cmd = m.table.Update(msg)
cmds = append(cmds, cmd)
m.spinner, cmd = m.spinner.Update(msg)
cmds = append(cmds, cmd)
switch msg := msg.(type) {
case tea.KeyMsg:
m.updateCount()
switch msg.String() {
case "q":
return m, tea.Quit
case "s":
if !m.table.GetIsFilterInputFocused() {
m.pollingStatus = true
return m, func() tea.Msg { return getAppsDeployStatus(m) }
}
}
case initTableMsg:
m.table = msg.table
case appsDeployStatusMsg:
m.pollingStatus = false
m.table = renderAppsDeployStatus(&m, msg)
case tea.WindowSizeMsg:
m.table = m.table.WithTargetWidth(msg.Width)
m.table = m.table.WithPageSize(msg.Height - 10)
case errorMsg:
m.err = msg // TODO
}
return m, tea.Batch(cmds...)
}
// View renders the UI.
func (m model) View() string {
if m.err != nil {
// TODO
return fmt.Sprintf("\nWe had some trouble: %v\n\n", m.err)
}
body := strings.Builder{}
body.WriteString(fmt.Sprintf(
"Servers: %v, Apps: %v, Recipes: %v\n",
m.numFilteredServers, m.numFilteredApps, m.numFilteredRecipes,
))
body.WriteString(m.table.View() + "\n")
body.WriteString("cctuip v0.1.0")
if m.pollingStatus {
body.WriteString(fmt.Sprintf(" %s querying app status...", m.spinner.View()))
}
return body.String()
}
// main is the command-line entrypoint.
func main() {
handleCliFlags()
if helpFlag {
fmt.Print(help)
os.Exit(0)
}
apps, err := getApps()
if err != nil {
log.Fatal(err)
}
numServers, numRecipes := getNumServersAndRecipes(apps)
if err != nil {
log.Fatal(err)
}
s := spinner.New()
s.Spinner = spinner.Dot
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
numApps := len(apps)
m := model{
apps: apps,
numApps: numApps,
numServers: numServers,
numRecipes: numRecipes,
numFilteredApps: numApps,
numFilteredServers: numServers,
numFilteredRecipes: numRecipes,
spinner: s,
}
p := tea.NewProgram(m, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
log.Fatalf("oops, cctuip exploded: %s", err)
}
}

102
go.mod Normal file
View File

@ -0,0 +1,102 @@
module coopcloud.tech/cctuip
go 1.20
require (
coopcloud.tech/abra v0.0.0-20230406152233-9e0500047628
coopcloud.tech/tagcmp v0.0.0-20211103052201-885b22f77d52
github.com/charmbracelet/bubbles v0.15.0
github.com/charmbracelet/bubbletea v0.23.2
github.com/charmbracelet/lipgloss v0.6.0
github.com/docker/docker v20.10.24+incompatible
github.com/evertras/bubble-table v0.15.2
golang.org/x/exp v0.0.0-20230321023759-10a507213a29
golang.org/x/term v0.6.0
)
require (
github.com/Autonomic-Cooperative/godotenv v1.3.1-0.20210731094149-b031ea1211e7 // indirect
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
github.com/BurntSushi/toml v1.0.0 // indirect
github.com/Microsoft/go-winio v0.5.2 // indirect
github.com/Microsoft/hcsshim v0.9.2 // indirect
github.com/ProtonMail/go-crypto v0.0.0-20230217124315-7d5c6f04bbb8 // indirect
github.com/acomagu/bufpipe v1.0.4 // indirect
github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymanbagabas/go-osc52 v1.2.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/cloudflare/circl v1.1.0 // indirect
github.com/containerd/console v1.0.3 // indirect
github.com/containers/image v3.0.2+incompatible // indirect
github.com/docker/cli v20.10.24+incompatible // indirect
github.com/docker/distribution v2.8.1+incompatible // indirect
github.com/docker/docker-credential-helpers v0.6.4 // indirect
github.com/docker/go v1.5.1-1.0.20160303222718-d30aec9fd63c // indirect
github.com/docker/go-connections v0.4.0 // indirect
github.com/docker/go-metrics v0.0.1 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/fvbommel/sortorder v1.0.2 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/go-git/gcfg v1.5.0 // indirect
github.com/go-git/go-billy/v5 v5.4.1 // indirect
github.com/go-git/go-git/v5 v5.6.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/gorilla/mux v1.8.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-retryablehttp v0.7.2 // indirect
github.com/imdario/mergo v0.3.13 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/miekg/pkcs11 v1.0.3 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/moby/sys/mount v0.2.0 // indirect
github.com/moby/sys/mountinfo v0.5.0 // indirect
github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/muesli/ansi v0.0.0-20221106050444-61f0cd9a192a // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.14.0 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.0.3-0.20211202193544-a5463b7f9c84 // indirect
github.com/pjbgf/sha1cd v0.3.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_golang v1.14.0 // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.37.0 // indirect
github.com/prometheus/procfs v0.8.0 // indirect
github.com/rivo/uniseg v0.4.3 // indirect
github.com/schollz/progressbar/v3 v3.13.1 // indirect
github.com/sergi/go-diff v1.2.0 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/skeema/knownhosts v1.1.0 // indirect
github.com/spf13/cobra v1.3.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/theupdateframework/notary v0.7.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190809123943-df4f5c81cb3b // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
golang.org/x/crypto v0.6.0 // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.8.0 // indirect
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

1719
go.sum Normal file

File diff suppressed because it is too large Load Diff