refactoring, adding cli to edit config

This commit is contained in:
2025-08-26 21:59:50 +02:00
parent e36b15e271
commit 2c109b945e
14 changed files with 503 additions and 20 deletions

View File

@@ -0,0 +1,99 @@
package edit
import (
"context"
"downloadhub/pkg/data"
"flag"
"fmt"
"os"
"github.com/google/subcommands"
)
type (
EditCmd struct {
slug string
name string
description string
version string
iconURL string
out string
}
)
func (*EditCmd) Name() string { return "edit" }
func (*EditCmd) Synopsis() string { return "edit an entry" }
func (*EditCmd) Usage() string {
return `Usage: ./cli edit [OPTIONS] SLUG
Options:
`
}
func (p *EditCmd) SetFlags(f *flag.FlagSet) {
f.StringVar(&p.slug, "slug", "", "")
f.StringVar(&p.name, "name", "", "")
f.StringVar(&p.description, "description", "", "")
f.StringVar(&p.version, "version", "0.0.0", "")
f.StringVar(&p.iconURL, "icon", "", "an url or a path to the icon")
f.StringVar(&p.out, "out", "./config.json", "path to the configuration file")
}
func (p *EditCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
if f.NArg() == 0 {
fmt.Fprintln(os.Stderr, "error: slug cannot be empty")
return subcommands.ExitUsageError
}
if f.NArg() > 1 {
fmt.Fprintln(os.Stderr, "error: this command cannot take more than 1 argument")
return subcommands.ExitUsageError
}
d, err := data.Load(p.out)
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
return subcommands.ExitFailure
}
var found bool
for i, soft := range d.Softwares {
if soft.Slug == f.Arg(0) {
if len(p.slug) > 0 {
soft.Slug = p.slug
}
if len(p.name) > 0 {
soft.Name = p.name
}
if len(p.description) > 0 {
soft.Description = p.description
}
if len(p.version) > 0 {
soft.Version = p.version
}
if len(p.iconURL) > 0 {
soft.IconURL = p.iconURL
}
d.Softwares[i] = soft
found = true
break
}
}
if !found {
fmt.Fprintf(os.Stderr, "error: slug '%s' cannot be found\n", f.Arg(0))
return subcommands.ExitFailure
}
if err := data.Save(d, p.out); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
return subcommands.ExitFailure
}
return subcommands.ExitSuccess
}