github.com/gfleury/gobbs@v0.0.0-20200831213239-44ca2b94c1a1/users/list.go (about)

     1  package users
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net"
     8  	"net/http"
     9  	"sort"
    10  	"time"
    11  
    12  	"github.com/gfleury/gobbs/common"
    13  	"github.com/gfleury/gobbs/common/log"
    14  
    15  	bitbucketv1 "github.com/gfleury/go-bitbucket-v1"
    16  	"github.com/spf13/cobra"
    17  )
    18  
    19  // List is the cmd implementation for Listing Users
    20  var List = &cobra.Command{
    21  	Use:     "list",
    22  	Aliases: []string{"ls"},
    23  	Short:   "List users",
    24  	Args:    cobra.MinimumNArgs(0),
    25  	RunE: func(cmd *cobra.Command, args []string) error {
    26  		var users []bitbucketv1.User
    27  
    28  		opts := map[string]interface{}{
    29  			// "state": *listState,
    30  			"limit": 1000,
    31  		}
    32  
    33  		for {
    34  			var hasNext bool
    35  			apiClient, cancel, err := common.APIClient(cmd)
    36  			defer cancel()
    37  
    38  			if err != nil {
    39  				cmd.SilenceUsage = true
    40  				return err
    41  			}
    42  
    43  			response, err := apiClient.DefaultApi.GetUsers(opts)
    44  
    45  			if netError, ok := err.(net.Error); (!ok || (ok && !netError.Timeout())) &&
    46  				!errors.Is(err, context.Canceled) &&
    47  				!errors.Is(err, context.DeadlineExceeded) &&
    48  				response != nil && response.Response != nil &&
    49  				response.Response.StatusCode >= http.StatusMultipleChoices {
    50  				common.PrintApiError(response.Values)
    51  				cmd.SilenceUsage = true
    52  				log.Debugf(err.Error())
    53  				return fmt.Errorf("Unable to process request, API Error")
    54  			} else if err != nil {
    55  				cmd.SilenceUsage = true
    56  				return err
    57  			}
    58  
    59  			pagedUsers, err := bitbucketv1.GetUsersResponse(response)
    60  			if err != nil {
    61  				cmd.SilenceUsage = true
    62  				return err
    63  			}
    64  			users = append(users, pagedUsers...)
    65  
    66  			hasNext, opts["start"] = bitbucketv1.HasNextPage(response)
    67  			if !hasNext {
    68  				break
    69  			}
    70  		}
    71  
    72  		sort.Slice(users, func(i, j int) bool {
    73  			return users[i].Slug < users[j].Slug
    74  		})
    75  
    76  		header := []string{"ID", "Slug", "Email", "Name", "Last Login"}
    77  		table := common.Table(header)
    78  
    79  		for _, user := range users {
    80  			table.Append([]string{
    81  				fmt.Sprintf("%d", user.ID),
    82  				user.Slug,
    83  				user.EmailAddress,
    84  				user.DisplayName,
    85  				fmt.Sprint(time.Unix(user.LastAuthenticationTimestamp/1000, 0).Format("2006-01-02T15:04:05-0700")),
    86  			})
    87  		}
    88  		table.Render()
    89  
    90  		return nil
    91  	},
    92  }