github.com/zaquestion/lab@v0.25.1/cmd/label_list.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/MakeNowJust/heredoc/v2"
     8  	"github.com/pkg/errors"
     9  	"github.com/rsteube/carapace"
    10  	"github.com/spf13/cobra"
    11  	"github.com/zaquestion/lab/internal/action"
    12  	lab "github.com/zaquestion/lab/internal/gitlab"
    13  )
    14  
    15  var labelListCmd = &cobra.Command{
    16  	Use:     "list [remote] [search]",
    17  	Aliases: []string{"ls", "search"},
    18  	Short:   "List labels",
    19  	Example: heredoc.Doc(`
    20  		lab label list
    21  		lab label list "search term"
    22  		lab label list remote "search term"`),
    23  	PersistentPreRun: labPersistentPreRun,
    24  	Run: func(cmd *cobra.Command, args []string) {
    25  		rn, labelSearch, err := parseArgsRemoteAndProject(args)
    26  		if err != nil {
    27  			log.Fatal(err)
    28  		}
    29  
    30  		nameOnly, err := cmd.Flags().GetBool("name-only")
    31  		if err != nil {
    32  			log.Fatal(err)
    33  		}
    34  
    35  		labelSearch = strings.ToLower(labelSearch)
    36  
    37  		labels, err := lab.LabelList(rn)
    38  		if err != nil {
    39  			log.Fatal(err)
    40  		}
    41  
    42  		pager := newPager(cmd.Flags())
    43  		defer pager.Close()
    44  
    45  		for _, label := range labels {
    46  			// GitLab API has no search for labels, so we do it ourselves
    47  			if labelSearch != "" &&
    48  				!(strings.Contains(strings.ToLower(label.Name), labelSearch) || strings.Contains(strings.ToLower(label.Description), labelSearch)) {
    49  				continue
    50  			}
    51  
    52  			description := ""
    53  			if !nameOnly && label.Description != "" {
    54  				description = " - " + label.Description
    55  			}
    56  
    57  			fmt.Printf("%s%s\n", label.Name, description)
    58  		}
    59  	},
    60  }
    61  
    62  func mapLabels(rn string, labelTerms []string) ([]string, error) {
    63  	// Don't bother fetching project labels if nothing is being really requested
    64  	if len(labelTerms) == 0 {
    65  		return []string{}, nil
    66  	}
    67  
    68  	labels, err := lab.LabelList(rn)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  
    73  	labelNames := make([]string, len(labels))
    74  	for _, label := range labels {
    75  		labelNames = append(labelNames, label.Name)
    76  	}
    77  
    78  	matches, err := matchTerms(labelTerms, labelNames)
    79  	if err != nil {
    80  		return nil, errors.Errorf("Label %s\n", err.Error())
    81  	}
    82  
    83  	return matches, nil
    84  }
    85  
    86  func init() {
    87  	labelListCmd.Flags().Bool("name-only", false, "only list label names, not descriptions")
    88  	labelCmd.AddCommand(labelListCmd)
    89  	carapace.Gen(labelCmd).PositionalCompletion(
    90  		action.Remotes(),
    91  	)
    92  }