github.com/arduino/arduino-cloud-cli@v0.0.0-20240517070944-e7a449561083/cli/dashboard/extract.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 dashboard 19 20 import ( 21 "context" 22 "fmt" 23 "os" 24 25 "github.com/arduino/arduino-cli/cli/errorcodes" 26 "github.com/arduino/arduino-cli/cli/feedback" 27 "github.com/arduino/arduino-cloud-cli/command/dashboard" 28 "github.com/arduino/arduino-cloud-cli/config" 29 "github.com/sirupsen/logrus" 30 "github.com/spf13/cobra" 31 "gopkg.in/yaml.v3" 32 ) 33 34 type extractFlags struct { 35 id string 36 } 37 38 func initExtractCommand() *cobra.Command { 39 flags := &extractFlags{} 40 extractCommand := &cobra.Command{ 41 Use: "extract", 42 Short: "Extract a template from a dashboard", 43 Long: "Extract a template from a Arduino IoT Cloud dashboard", 44 Run: func(cmd *cobra.Command, args []string) { 45 if err := runExtractCommand(flags); err != nil { 46 feedback.Errorf("Error during dashboard extract: %v", err) 47 os.Exit(errorcodes.ErrGeneric) 48 } 49 }, 50 } 51 extractCommand.Flags().StringVarP(&flags.id, "id", "i", "", "Dashboard ID") 52 extractCommand.MarkFlagRequired("id") 53 return extractCommand 54 } 55 56 func runExtractCommand(flags *extractFlags) error { 57 logrus.Infof("Extracting template from dashboard %s", flags.id) 58 59 cred, err := config.RetrieveCredentials() 60 if err != nil { 61 return fmt.Errorf("retrieving credentials: %w", err) 62 } 63 64 params := &dashboard.ExtractParams{ 65 ID: flags.id, 66 } 67 68 template, err := dashboard.Extract(context.TODO(), params, cred) 69 if err != nil { 70 return err 71 } 72 73 feedback.PrintResult(extractResult{template}) 74 return nil 75 } 76 77 type extractResult struct { 78 template map[string]interface{} 79 } 80 81 func (r extractResult) Data() interface{} { 82 return r.template 83 } 84 85 func (r extractResult) String() string { 86 t, err := yaml.Marshal(r.template) 87 if err != nil { 88 feedback.Errorf("Error during template parsing: %v", err) 89 os.Exit(errorcodes.ErrGeneric) 90 } 91 return string(t) 92 }