github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/repo/deploy-key/list/list.go (about) 1 package list 2 3 import ( 4 "fmt" 5 "net/http" 6 "strconv" 7 "time" 8 9 "github.com/ungtb10d/cli/v2/internal/ghrepo" 10 "github.com/ungtb10d/cli/v2/internal/text" 11 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 12 "github.com/ungtb10d/cli/v2/pkg/iostreams" 13 "github.com/ungtb10d/cli/v2/utils" 14 "github.com/spf13/cobra" 15 ) 16 17 type ListOptions struct { 18 IO *iostreams.IOStreams 19 HTTPClient func() (*http.Client, error) 20 BaseRepo func() (ghrepo.Interface, error) 21 } 22 23 func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { 24 opts := &ListOptions{ 25 IO: f.IOStreams, 26 HTTPClient: f.HttpClient, 27 } 28 29 cmd := &cobra.Command{ 30 Use: "list", 31 Short: "List deploy keys in a GitHub repository", 32 Aliases: []string{"ls"}, 33 Args: cobra.ExactArgs(0), 34 RunE: func(cmd *cobra.Command, args []string) error { 35 opts.BaseRepo = f.BaseRepo 36 37 if runF != nil { 38 return runF(opts) 39 } 40 return listRun(opts) 41 }, 42 } 43 44 return cmd 45 } 46 47 func listRun(opts *ListOptions) error { 48 apiClient, err := opts.HTTPClient() 49 if err != nil { 50 return err 51 } 52 53 repo, err := opts.BaseRepo() 54 if err != nil { 55 return err 56 } 57 58 deployKeys, err := repoKeys(apiClient, repo) 59 if err != nil { 60 return err 61 } 62 63 if len(deployKeys) == 0 { 64 return cmdutil.NewNoResultsError(fmt.Sprintf("no deploy keys found in %s", ghrepo.FullName(repo))) 65 } 66 67 //nolint:staticcheck // SA1019: utils.NewTablePrinter is deprecated: use internal/tableprinter 68 t := utils.NewTablePrinter(opts.IO) 69 cs := opts.IO.ColorScheme() 70 now := time.Now() 71 72 for _, deployKey := range deployKeys { 73 sshID := strconv.Itoa(deployKey.ID) 74 t.AddField(sshID, nil, nil) 75 t.AddField(deployKey.Title, nil, nil) 76 77 sshType := "read-only" 78 if !deployKey.ReadOnly { 79 sshType = "read-write" 80 } 81 t.AddField(sshType, nil, nil) 82 t.AddField(deployKey.Key, truncateMiddle, nil) 83 84 createdAt := deployKey.CreatedAt.Format(time.RFC3339) 85 if t.IsTTY() { 86 createdAt = text.FuzzyAgoAbbr(now, deployKey.CreatedAt) 87 } 88 t.AddField(createdAt, nil, cs.Gray) 89 t.EndRow() 90 } 91 92 return t.Render() 93 } 94 95 func truncateMiddle(maxWidth int, t string) string { 96 if len(t) <= maxWidth { 97 return t 98 } 99 100 ellipsis := "..." 101 if maxWidth < len(ellipsis)+2 { 102 return t[0:maxWidth] 103 } 104 105 halfWidth := (maxWidth - len(ellipsis)) / 2 106 remainder := (maxWidth - len(ellipsis)) % 2 107 return t[0:halfWidth+remainder] + ellipsis + t[len(t)-halfWidth:] 108 }