feat(cmd): add list command to display tracked units
This commit is contained in:
89
cmd/list.go
Normal file
89
cmd/list.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/warkanum/unitdore/config"
|
||||
"github.com/warkanum/unitdore/systemd"
|
||||
)
|
||||
|
||||
var listCmd = &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List all tracked units with service file locations",
|
||||
RunE: runList,
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(listCmd)
|
||||
}
|
||||
|
||||
func runList(cmd *cobra.Command, args []string) error {
|
||||
cfg, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(cfg.Units) == 0 {
|
||||
fmt.Println("No units tracked. Run 'unitdore syncup' to discover containers.")
|
||||
return nil
|
||||
}
|
||||
|
||||
units := make([]config.Unit, len(cfg.Units))
|
||||
copy(units, cfg.Units)
|
||||
sort.Slice(units, func(i, j int) bool {
|
||||
if units[i].Order != units[j].Order {
|
||||
return units[i].Order < units[j].Order
|
||||
}
|
||||
return units[i].Name < units[j].Name
|
||||
})
|
||||
|
||||
prefix, suffix := cfg.Prefix, cfg.Suffix
|
||||
|
||||
type row struct{ name, runtime, enabled, installed, path string }
|
||||
|
||||
rows := make([]row, 0, len(units))
|
||||
for _, u := range units {
|
||||
enabled := "yes"
|
||||
if !u.Enabled {
|
||||
enabled = "no"
|
||||
}
|
||||
|
||||
installed := "no"
|
||||
unitPath := "—"
|
||||
if p, err := systemd.UnitPath(u, prefix, suffix); err == nil {
|
||||
unitPath = p
|
||||
if systemd.IsInstalled(u, prefix, suffix) {
|
||||
installed = "yes"
|
||||
}
|
||||
}
|
||||
|
||||
rows = append(rows, row{u.Name, u.Runtime, enabled, installed, unitPath})
|
||||
}
|
||||
|
||||
cols := []string{"NAME", "RUNTIME", "ENABLED", "INSTALLED", "SERVICE FILE"}
|
||||
widths := make([]int, len(cols))
|
||||
for i, c := range cols {
|
||||
widths[i] = len(c)
|
||||
}
|
||||
for _, r := range rows {
|
||||
vals := []string{r.name, r.runtime, r.enabled, r.installed, r.path}
|
||||
for i, v := range vals {
|
||||
if len(v) > widths[i] {
|
||||
widths[i] = len(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
printRow(cols, widths)
|
||||
fmt.Println(strings.Repeat("─", totalWidth(widths)))
|
||||
for _, r := range rows {
|
||||
printRow([]string{r.name, r.runtime, r.enabled, r.installed, r.path}, widths)
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user