Refactored the map to a struct because maps are for some reason not sortable, added sorting

This commit is contained in:
2025-10-18 00:34:39 +02:00
parent b4f7007a9f
commit 43b1fbb64c
3 changed files with 93 additions and 58 deletions
+75 -5
View File
@@ -4,8 +4,32 @@ import (
"fmt"
"os"
"flag"
"encoding/json"
"log"
"sort"
)
type CmdGroup struct {
Category string
Commands []CmdItem
}
type CmdList []CmdGroup
type CmdItem struct {
CommandName string `json:"command"`
CommandDescription string `json:"desc"`
}
func (list CmdList) Get(category string) []CmdItem {
for _, group := range list {
if group.Category == category {
return group.Commands
}
}
return nil
}
func main() {
@@ -15,22 +39,41 @@ func main() {
flag.Parse()
if len(os.Args) == 1 {
StartTui()
configFile := "/etc/cheatsh/commands.json"
var commands CmdList
var err error
if *configFlag != "" {
commands, err = loadCommands(*configFlag)
if err != nil {
log.Fatalf("Cannot load commands file: %v", err)
}
StartTui(commands)
return
} else if len(os.Args) == 1 {
commands, err = loadCommands(configFile)
if err != nil {
log.Fatalf("Cannot load commands file: %v", err)
}
StartTui(commands)
return
}
switch {
case *helpFlag:
printHelp()
case *configFlag != "":
StartTui(*configFlag)
case *newFlag:
HandleInput()
default:
printHelp()
os.Exit(1)
}
}
func printHelp() {
@@ -38,5 +81,32 @@ func printHelp() {
Options:
--config <file> Specify a config file
--help Show this help message
--new Add a new command to the config file`)
--new Add a new command to the config file`)
}
func loadCommands(path string) (CmdList, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var raw map[string][]CmdItem
err = json.Unmarshal(data, &raw)
if err != nil {
return nil, err
}
cmdList := make(CmdList, 0, len(raw))
for category, commands := range raw {
cmdList = append(cmdList, CmdGroup{
Category: category,
Commands: commands,
})
}
sort.Slice(cmdList, func(i, j int) bool {
return cmdList[i].Category < cmdList[j].Category
})
return cmdList, nil
}