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

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/MakeNowJust/heredoc/v2"
     6  	"strconv"
     7  
     8  	"github.com/rsteube/carapace"
     9  	"github.com/spf13/cobra"
    10  	gitlab "github.com/xanzy/go-gitlab"
    11  	"github.com/zaquestion/lab/internal/action"
    12  	lab "github.com/zaquestion/lab/internal/gitlab"
    13  )
    14  
    15  var snippetListConfig struct {
    16  	Number string
    17  	All    bool
    18  }
    19  
    20  // snippetListCmd represents the snippetList command
    21  var snippetListCmd = &cobra.Command{
    22  	Use:     "list [remote]",
    23  	Aliases: []string{"ls"},
    24  	Short:   "List personal or project snippets",
    25  	Example: heredoc.Doc(`
    26  		lab snippet list
    27  		lab snippet list -a
    28  		lab snippet list -n 10
    29  		lab snippet list -m "Snippet example" -M "Description message"
    30  		lab snippet list upstream --private
    31  		lab snippet list origin --public`),
    32  	PersistentPreRun: labPersistentPreRun,
    33  	Run: func(cmd *cobra.Command, args []string) {
    34  		snips, err := snippetList(args)
    35  		if err != nil {
    36  			log.Fatal(err)
    37  		}
    38  		pager := newPager(cmd.Flags())
    39  		defer pager.Close()
    40  		for _, snip := range snips {
    41  			fmt.Printf("#%d %s\n", snip.ID, snip.Title)
    42  		}
    43  	},
    44  }
    45  
    46  func snippetList(args []string) ([]*gitlab.Snippet, error) {
    47  	rn, _, err := parseArgsRemoteAndID(args)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	num, err := strconv.Atoi(snippetListConfig.Number)
    53  	if snippetListConfig.All || (err != nil) {
    54  		num = -1
    55  	}
    56  
    57  	listOpts := gitlab.ListOptions{
    58  		PerPage: num,
    59  	}
    60  
    61  	// See if we're in a git repo or if global is set to determine
    62  	// if this should be a personal snippet
    63  	if global || rn == "" {
    64  		opts := gitlab.ListSnippetsOptions(listOpts)
    65  		return lab.SnippetList(opts, num)
    66  	}
    67  
    68  	opts := gitlab.ListProjectSnippetsOptions(listOpts)
    69  	return lab.ProjectSnippetList(rn, opts, num)
    70  }
    71  
    72  func init() {
    73  	snippetListCmd.Flags().StringVarP(&snippetListConfig.Number, "number", "n", "10", "Number of snippets to return")
    74  	snippetListCmd.Flags().BoolVarP(&snippetListConfig.All, "all", "a", false, "list all snippets")
    75  
    76  	snippetCmd.AddCommand(snippetListCmd)
    77  	carapace.Gen(snippetListCmd).PositionalCompletion(
    78  		action.Remotes(),
    79  	)
    80  }