Skip to content

Commit

Permalink
chore: refactor selection by name
Browse files Browse the repository at this point in the history
  • Loading branch information
andig committed Mar 15, 2022
1 parent 7a7f787 commit e1902c1
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 22 deletions.
9 changes: 2 additions & 7 deletions cmd/charger.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,8 @@ func runCharger(cmd *cobra.Command, args []string) {
}

// select single charger
if name := cmd.PersistentFlags().Lookup(flagName).Value.String(); name != "" {
for _, cfg := range conf.Chargers {
if cfg.Name == name {
conf.Chargers = []qualifiedConfig{cfg}
break
}
}
if err := selectByName(cmd, &conf.Chargers); err != nil {
log.FATAL.Fatal(err)
}

if err := cp.configureChargers(conf); err != nil {
Expand Down
24 changes: 24 additions & 0 deletions cmd/flags.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

const (
flagHeaders = "log-headers"
flagHeadersDescription = "Log headers"
Expand All @@ -22,3 +28,21 @@ const (
flagStop = "stop"
flagStopDescription = "Stop charging"
)

func selectByName(cmd *cobra.Command, conf *[]qualifiedConfig) error {
flag := cmd.PersistentFlags().Lookup(flagName)
if !flag.Changed {
return nil
}

name := flag.Value.String()

for _, cfg := range *conf {
if cfg.Name == name {
*conf = []qualifiedConfig{cfg}
return nil
}
}

return fmt.Errorf("%s not found", name)
}
9 changes: 2 additions & 7 deletions cmd/meter.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,8 @@ func runMeter(cmd *cobra.Command, args []string) {
}

// select single meter
if name := cmd.PersistentFlags().Lookup("name").Value.String(); name != "" {
for _, cfg := range conf.Meters {
if cfg.Name == name {
conf.Meters = []qualifiedConfig{cfg}
break
}
}
if err := selectByName(cmd, &conf.Meters); err != nil {
log.FATAL.Fatal(err)
}

if err := cp.configureMeters(conf); err != nil {
Expand Down
11 changes: 3 additions & 8 deletions cmd/vehicle.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,9 @@ func runVehicle(cmd *cobra.Command, args []string) {
request.LogHeaders = true
}

// select single charger
if name := cmd.PersistentFlags().Lookup(flagName).Value.String(); name != "" {
for _, cfg := range conf.Vehicles {
if cfg.Name == name {
conf.Vehicles = []qualifiedConfig{cfg}
break
}
}
// select single vehicle
if err := selectByName(cmd, &conf.Vehicles); err != nil {
log.FATAL.Fatal(err)
}

if err := cp.configureVehicles(conf); err != nil {
Expand Down

0 comments on commit e1902c1

Please sign in to comment.