github.com/arduino/arduino-cloud-cli@v0.0.0-20240517070944-e7a449561083/command/thing/clone.go (about) 1 // This file is part of arduino-cloud-cli. 2 // 3 // Copyright (C) 2021 ARDUINO SA (http://www.arduino.cc/) 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published 7 // by the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <https://www.gnu.org/licenses/>. 17 18 package thing 19 20 import ( 21 "context" 22 "fmt" 23 24 "github.com/arduino/arduino-cloud-cli/config" 25 "github.com/arduino/arduino-cloud-cli/internal/iot" 26 iotclient "github.com/arduino/iot-client-go" 27 ) 28 29 // CloneParams contains the parameters needed to clone a thing. 30 type CloneParams struct { 31 Name string // Name of the new thing 32 CloneID string // ID of thing to be cloned 33 } 34 35 // Clone allows to create a new thing from an already existing one. 36 func Clone(ctx context.Context, params *CloneParams, cred *config.Credentials) (*ThingInfo, error) { 37 iotClient, err := iot.NewClient(cred) 38 if err != nil { 39 return nil, err 40 } 41 42 thing, err := retrieve(ctx, iotClient, params.CloneID) 43 if err != nil { 44 return nil, err 45 } 46 47 thing.Name = params.Name 48 force := true 49 newThing, err := iotClient.ThingCreate(ctx, thing, force) 50 if err != nil { 51 return nil, err 52 } 53 54 t, err := getThingInfo(newThing) 55 if err != nil { 56 return nil, fmt.Errorf("parsing thing %s from cloud: %w", newThing.Id, err) 57 } 58 return t, nil 59 } 60 61 type thingFetcher interface { 62 ThingShow(ctx context.Context, id string) (*iotclient.ArduinoThing, error) 63 } 64 65 func retrieve(ctx context.Context, fetcher thingFetcher, thingID string) (*iotclient.ThingCreate, error) { 66 clone, err := fetcher.ThingShow(ctx, thingID) 67 if err != nil { 68 return nil, fmt.Errorf("%s: %w", "retrieving the thing to be cloned", err) 69 } 70 71 thing := &iotclient.ThingCreate{} 72 73 // Copy variables 74 for _, p := range clone.Properties { 75 thing.Properties = append(thing.Properties, iotclient.Property{ 76 Name: p.Name, 77 Permission: p.Permission, 78 UpdateParameter: p.UpdateParameter, 79 UpdateStrategy: p.UpdateStrategy, 80 Type: p.Type, 81 VariableName: p.VariableName, 82 }) 83 } 84 85 return thing, nil 86 }