github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/issue/pin/pin.go (about) 1 package pin 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/MakeNowJust/heredoc" 8 "github.com/ungtb10d/cli/v2/api" 9 "github.com/ungtb10d/cli/v2/internal/config" 10 "github.com/ungtb10d/cli/v2/internal/ghrepo" 11 "github.com/ungtb10d/cli/v2/pkg/cmd/issue/shared" 12 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 13 "github.com/ungtb10d/cli/v2/pkg/iostreams" 14 "github.com/shurcooL/githubv4" 15 "github.com/spf13/cobra" 16 ) 17 18 type PinOptions struct { 19 HttpClient func() (*http.Client, error) 20 Config func() (config.Config, error) 21 IO *iostreams.IOStreams 22 BaseRepo func() (ghrepo.Interface, error) 23 SelectorArg string 24 } 25 26 func NewCmdPin(f *cmdutil.Factory, runF func(*PinOptions) error) *cobra.Command { 27 opts := &PinOptions{ 28 IO: f.IOStreams, 29 HttpClient: f.HttpClient, 30 Config: f.Config, 31 BaseRepo: f.BaseRepo, 32 } 33 34 cmd := &cobra.Command{ 35 Use: "pin {<number> | <url>}", 36 Short: "Pin a issue", 37 Long: heredoc.Doc(` 38 Pin an issue to a repository. 39 40 The issue can be specified by issue number or URL. 41 `), 42 Example: heredoc.Doc(` 43 # Pin an issue to the current repository 44 $ gh issue pin 23 45 46 # Pin an issue by URL 47 $ gh issue pin https://github.com/owner/repo/issues/23 48 49 # Pin an issue to specific repository 50 $ gh issue pin 23 --repo owner/repo 51 `), 52 Args: cobra.ExactArgs(1), 53 RunE: func(cmd *cobra.Command, args []string) error { 54 opts.BaseRepo = f.BaseRepo 55 opts.SelectorArg = args[0] 56 57 if runF != nil { 58 return runF(opts) 59 } 60 61 return pinRun(opts) 62 }, 63 } 64 65 return cmd 66 } 67 68 func pinRun(opts *PinOptions) error { 69 cs := opts.IO.ColorScheme() 70 71 httpClient, err := opts.HttpClient() 72 if err != nil { 73 return err 74 } 75 76 issue, baseRepo, err := shared.IssueFromArgWithFields(httpClient, opts.BaseRepo, opts.SelectorArg, []string{"id", "number", "title", "isPinned"}) 77 if err != nil { 78 return err 79 } 80 81 if issue.IsPinned { 82 fmt.Fprintf(opts.IO.ErrOut, "%s Issue #%d (%s) is already pinned to %s\n", cs.Yellow("!"), issue.Number, issue.Title, ghrepo.FullName(baseRepo)) 83 return nil 84 } 85 86 err = pinIssue(httpClient, baseRepo, issue) 87 if err != nil { 88 return err 89 } 90 91 fmt.Fprintf(opts.IO.ErrOut, "%s Pinned issue #%d (%s) to %s\n", cs.SuccessIcon(), issue.Number, issue.Title, ghrepo.FullName(baseRepo)) 92 93 return nil 94 } 95 96 func pinIssue(httpClient *http.Client, repo ghrepo.Interface, issue *api.Issue) error { 97 var mutation struct { 98 PinIssue struct { 99 Issue struct { 100 ID githubv4.ID 101 } 102 } `graphql:"pinIssue(input: $input)"` 103 } 104 105 variables := map[string]interface{}{ 106 "input": githubv4.PinIssueInput{ 107 IssueID: issue.ID, 108 }, 109 } 110 111 gql := api.NewClientFromHTTP(httpClient) 112 113 return gql.Mutate(repo.RepoHost(), "IssuePin", &mutation, variables) 114 }