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 }