forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
49 lines (41 loc) · 1.08 KB
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package vehicle
import (
"fmt"
"strings"
"github.com/samber/lo"
)
// ensureVehicle extracts VIN from list of VINs returned from `list` function
func ensureVehicle(vin string, list func() ([]string, error)) (string, error) {
return ensureVehicleEx(vin, list, func(v string) string {
return v
})
}
// ensureVehicleEx extracts vehicle with matching VIN from list of vehicles
func ensureVehicleEx[Vehicle any](
vin string,
list func() ([]Vehicle, error),
extract func(Vehicle) string,
) (Vehicle, error) {
vehicles, err := list()
if err != nil {
return *new(Vehicle), fmt.Errorf("cannot get vehicles: %w", err)
}
if vin = strings.ToUpper(vin); vin != "" {
for _, vehicle := range vehicles {
if vin == extract(vehicle) {
return vehicle, nil
}
}
// vin defined but doesn't exist
err = fmt.Errorf("cannot find vehicle: %s", vin)
} else {
// vin empty
if len(vehicles) == 1 {
return vehicles[0], nil
}
err = fmt.Errorf("cannot find vehicle, got: %v", lo.Map(vehicles, func(v Vehicle, _ int) string {
return extract(v)
}))
}
return *new(Vehicle), err
}