github.com/matthewdale/lab@v0.14.0/cmd/mr_browse.go (about)

     1  package cmd
     2  
     3  import (
     4  	"log"
     5  	"net/url"
     6  	"path"
     7  	"strconv"
     8  
     9  	"github.com/spf13/cobra"
    10  	"github.com/spf13/viper"
    11  	"github.com/xanzy/go-gitlab"
    12  	git "github.com/zaquestion/lab/internal/git"
    13  	lab "github.com/zaquestion/lab/internal/gitlab"
    14  )
    15  
    16  var mrBrowseCmd = &cobra.Command{
    17  	Use:     "browse [remote] <id>",
    18  	Aliases: []string{"b"},
    19  	Short:   "View merge request in a browser",
    20  	Long:    ``,
    21  	Run: func(cmd *cobra.Command, args []string) {
    22  		rn, num, err := parseArgs(args)
    23  		if err != nil {
    24  			log.Fatal(err)
    25  		}
    26  
    27  		c := viper.AllSettings()["core"]
    28  		config := c.([]map[string]interface{})[0]
    29  		host := config["host"].(string)
    30  
    31  		hostURL, err := url.Parse(host)
    32  		if err != nil {
    33  			log.Fatal(err)
    34  		}
    35  		hostURL.Path = path.Join(hostURL.Path, rn, "merge_requests")
    36  		if num > 0 {
    37  			hostURL.Path = path.Join(hostURL.Path, strconv.FormatInt(num, 10))
    38  		} else {
    39  			currentBranch, err := git.CurrentBranch()
    40  			if err != nil {
    41  				log.Fatal(err)
    42  			}
    43  			mrs, err := lab.MRList(rn, gitlab.ListProjectMergeRequestsOptions{
    44  				ListOptions: gitlab.ListOptions{
    45  					PerPage: 10,
    46  				},
    47  				Labels:       mrLabels,
    48  				State:        &mrState,
    49  				OrderBy:      gitlab.String("updated_at"),
    50  				SourceBranch: gitlab.String(currentBranch),
    51  			}, -1)
    52  			if err != nil {
    53  				log.Fatal(err)
    54  			}
    55  			if len(mrs) > 0 {
    56  				num = int64(mrs[0].IID)
    57  				hostURL.Path = path.Join(hostURL.Path, strconv.FormatInt(num, 10))
    58  			}
    59  		}
    60  
    61  		err = browse(hostURL.String())
    62  		if err != nil {
    63  			log.Fatal(err)
    64  		}
    65  	},
    66  }
    67  
    68  func init() {
    69  	mrCmd.AddCommand(mrBrowseCmd)
    70  }