|
| 1 | +package thing |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/arduino/arduino-cli/cli/feedback" |
| 8 | + "github.com/arduino/arduino-cli/table" |
| 9 | + "github.com/arduino/iot-cloud-cli/command/thing" |
| 10 | + "github.com/spf13/cobra" |
| 11 | +) |
| 12 | + |
| 13 | +var listFlags struct { |
| 14 | + ids []string |
| 15 | + deviceID string |
| 16 | + properties bool |
| 17 | +} |
| 18 | + |
| 19 | +func initListCommand() *cobra.Command { |
| 20 | + listCommand := &cobra.Command{ |
| 21 | + Use: "list", |
| 22 | + Short: "List things", |
| 23 | + Long: "List things on Arduino IoT Cloud", |
| 24 | + RunE: runListCommand, |
| 25 | + } |
| 26 | + // list only the things corresponding to the passed ids |
| 27 | + listCommand.Flags().StringSliceVarP(&listFlags.ids, "ids", "i", []string{}, "List of thing IDs to be retrieved") |
| 28 | + // list only the thing associated to the passed device id |
| 29 | + listCommand.Flags().StringVarP(&listFlags.deviceID, "device-id", "d", "", "ID of Device associated to the thing to be retrieved") |
| 30 | + listCommand.Flags().BoolVarP(&listFlags.properties, "properties", "p", false, "Show thing properties") |
| 31 | + return listCommand |
| 32 | +} |
| 33 | + |
| 34 | +func runListCommand(cmd *cobra.Command, args []string) error { |
| 35 | + fmt.Println("Listing things") |
| 36 | + |
| 37 | + params := &thing.ListParams{ |
| 38 | + IDs: listFlags.ids, |
| 39 | + Properties: listFlags.properties, |
| 40 | + } |
| 41 | + if listFlags.deviceID != "" { |
| 42 | + params.DeviceID = &listFlags.deviceID |
| 43 | + } |
| 44 | + |
| 45 | + things, err := thing.List(params) |
| 46 | + if err != nil { |
| 47 | + return err |
| 48 | + } |
| 49 | + |
| 50 | + feedback.PrintResult(result{things}) |
| 51 | + return nil |
| 52 | +} |
| 53 | + |
| 54 | +type result struct { |
| 55 | + things []thing.ThingInfo |
| 56 | +} |
| 57 | + |
| 58 | +func (r result) Data() interface{} { |
| 59 | + return r.things |
| 60 | +} |
| 61 | + |
| 62 | +func (r result) String() string { |
| 63 | + if len(r.things) == 0 { |
| 64 | + return "No things found." |
| 65 | + } |
| 66 | + t := table.New() |
| 67 | + |
| 68 | + h := []interface{}{"Name", "ID", "Device"} |
| 69 | + if listFlags.properties { |
| 70 | + h = append(h, "Properties") |
| 71 | + } |
| 72 | + t.SetHeader(h...) |
| 73 | + |
| 74 | + for _, thing := range r.things { |
| 75 | + r := []interface{}{thing.Name, thing.ID, thing.DeviceID} |
| 76 | + if listFlags.properties { |
| 77 | + r = append(r, strings.Join(thing.Properties, ", ")) |
| 78 | + } |
| 79 | + t.AddRow(r...) |
| 80 | + } |
| 81 | + return t.Render() |
| 82 | +} |
0 commit comments