GitLabgitlab-org
cli
main
1package ask
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net/http"
8 "os/exec"
9 "regexp"
10 "strings"
12 "github.com/MakeNowJust/heredoc/v2"
13 "github.com/google/shlex"
14 "github.com/spf13/cobra"
16 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
18 "gitlab.com/gitlab-org/cli/internal/api"
19 "gitlab.com/gitlab-org/cli/internal/cmdutils"
20 "gitlab.com/gitlab-org/cli/internal/glrepo"
21 "gitlab.com/gitlab-org/cli/internal/iostreams"
22 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
23 "gitlab.com/gitlab-org/cli/internal/run"
24)
26type request struct {
27 Prompt string `json:"prompt"`
28 Model string `json:"model"`
29}
31type response struct {
32 Predictions []struct {
33 Candidates []struct {
34 Content string `json:"content"`
35 } `json:"candidates"`
36 } `json:"predictions"`
37}
39type result struct {
40 Commands []string `json:"commands"`
41 Explanation string `json:"explanation"`
42}
44type opts struct {
45 Prompt string
46 IO *iostreams.IOStreams
47 apiClient func(repoHost string) (*api.Client, error)
48 Git bool
49 BaseRepo func() (glrepo.Interface, error)
50}
52var (
53 cmdHighlightRegexp = regexp.MustCompile("`+\n?([^`]*)\n?`+\n?")
54 cmdExecRegexp = regexp.MustCompile("```([^`]*)```")
55 vertexAI = "vertexai"
56)
58const (
59 runCmdsQuestion = "Would you like to run these Git commands?"
60 gitCmd = "git"
61 gitCmdAPIPath = "ai/llm/git_command"
62 spinnerText = "Generating Git commands..."
63 aiResponseErr = "AI response has not been generated correctly"
64 apiUnreachableErr = "API is unreachable"
65)
67func NewCmdAsk(f cmdutils.Factory) *cobra.Command {
68 opts := &opts{
69 IO: f.IO(),
70 apiClient: f.ApiClient,
71 BaseRepo: f.BaseRepo,
72 }
74 duoAskCmd := &cobra.Command{
75 Use: "ask <prompt>",
76 Short: "Generate Git commands from natural language.",
77 Hidden: true,
78 Long: heredoc.Doc(`
79 Generate Git commands from natural language using AI assistance.
81 Describe what you want to do in plain language, and GitLab Duo suggests
82 the appropriate Git commands. You receive both the commands and an explanation.
84 After you receive the suggested commands, you can run them directly from
85 the CLI. You must confirm each command before it runs.
87 Use this command to:
89 - Retrieve forgotten Git commands.
90 - Learn how to accomplish specific Git operations.
91 - Get guidance on complex Git workflows.
92 - Reduce context switching during development.
93 `),
94 Example: heredoc.Doc(`
95 # Explain how to display the titles of the last 10 commits
96 glab duo ask how to list last 10 commit titles
98 # Explain how to undo the last commit
99 glab duo ask how do I undo my last commit
101 # Explain how to display files changed in the last commit
102 glab duo ask show me files changed in the last commit`),
103 Args: cobra.ArbitraryArgs,
104 Annotations: map[string]string{
105 mcpannotations.Destructive: "true",
106 },
107 RunE: func(cmd *cobra.Command, args []string) error {
108 if !opts.Git {
109 return nil
110 }
112 if len(args) == 0 {
113 return nil
114 }
116 opts.Prompt = strings.Join(args, " ")
118 result, err := opts.Result()
119 if err != nil {
120 return err
121 }
123 opts.displayResult(result)
125 if len(result.Commands) > 0 {
126 if err := opts.executeCommands(cmd.Context(), result.Commands); err != nil {
127 return err
128 }
129 }
130 return nil
131 },
132 }
134 duoAskCmd.Flags().BoolVarP(&opts.Git, "git", "", true, "Ask a question about Git.")
136 return duoAskCmd
137}
139func (opts *opts) Result() (*result, error) {
140 opts.IO.StartSpinner(spinnerText)
141 defer opts.IO.StopSpinner("")
143 var repoHost string
144 if baseRepo, err := opts.BaseRepo(); err == nil {
145 repoHost = baseRepo.RepoHost()
146 }
148 c, err := opts.apiClient(repoHost)
149 if err != nil {
150 return nil, cmdutils.WrapError(err, "failed to get HTTP client.")
151 }
152 client := c.Lab()
154 body := request{Prompt: opts.Prompt, Model: vertexAI}
155 request, err := client.NewRequest(http.MethodPost, gitCmdAPIPath, body, []gitlab.RequestOptionFunc{api.WithSafeRetries()})
156 if err != nil {
157 return nil, cmdutils.WrapError(err, "failed to create a request.")
158 }
160 var r response
161 _, err = client.Do(request, &r)
162 if err != nil {
163 return nil, cmdutils.WrapError(err, apiUnreachableErr)
164 }
166 if len(r.Predictions) == 0 || len(r.Predictions[0].Candidates) == 0 {
167 return nil, errors.New(aiResponseErr)
168 }
170 content := r.Predictions[0].Candidates[0].Content
172 var cmds []string
173 for _, cmd := range cmdExecRegexp.FindAllString(content, -1) {
174 cmds = append(cmds, strings.Trim(cmd, "\n`"))
175 }
177 return &result{
178 Commands: cmds,
179 Explanation: content,
180 }, nil
181}
183func (opts *opts) displayResult(result *result) {
184 color := opts.IO.Color()
186 opts.IO.LogInfo(color.Bold("Commands:\n"))
188 for _, cmd := range result.Commands {
189 opts.IO.LogInfo(color.Green(cmd))
190 }
192 opts.IO.LogInfo(color.Bold("\nExplanation:\n"))
193 explanation := cmdHighlightRegexp.ReplaceAllString(result.Explanation, color.Green("$1"))
194 opts.IO.LogInfo(explanation + "\n")
195}
197func (opts *opts) executeCommands(ctx context.Context, commands []string) error {
198 color := opts.IO.Color()
200 confirmed := true
201 question := color.Bold(runCmdsQuestion)
202 if err := opts.IO.Confirm(ctx, &confirmed, question); err != nil {
203 return err
204 }
206 if !confirmed {
207 return nil
208 }
210 for _, command := range commands {
211 if err := opts.executeCommand(ctx, command); err != nil {
212 return err
213 }
214 }
216 return nil
217}
219func (opts *opts) executeCommand(ctx context.Context, cmd string) error {
220 gitArgs, err := shlex.Split(cmd)
221 if err != nil {
222 return nil
223 }
225 if gitArgs[0] != gitCmd {
226 return nil
227 }
229 color := opts.IO.Color()
230 question := "Run `" + color.Green(cmd) + "`"
231 confirmed := true
232 if err := opts.IO.Confirm(ctx, &confirmed, question); err != nil {
233 return err
234 }
236 if !confirmed {
237 return nil
238 }
240 execCmd := exec.CommandContext(ctx, "git", gitArgs[1:]...)
241 output, err := run.PrepareCmd(execCmd).Output()
242 if err != nil {
243 return err
244 }
246 if len(output) == 0 {
247 return nil
248 }
250 if err := opts.IO.StartPager(); err != nil {
251 return fmt.Errorf("failed to start pager: %w", err)
252 }
253 defer opts.IO.StopPager()
255 opts.IO.LogInfo(string(output))
257 return nil
258}
Diagnostics8 git calls · 234 ms
CallStatusSizeTime0234 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=5 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit5 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=5 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:02001.8 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=1857 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=1857 git.pkt.payload.max=1830 git.sideband.band1.bytes=1830 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1830 git.pack.trailer=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200191 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=191 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=c3602e112f33dfaff92a8559e2993279d5c2f1ac git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=191 git.pkt.payload.max=164 git.sideband.band1.bytes=164 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=164 git.pack.trailer=43874cd66e8aba9ccffcac699b3b9f515e08cf67Open pack map
fetchtree:0200172 B · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=216 git.response.bytes=172 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=97a3b7ac4cdd1f4e2351ca134b012a56159b11b8 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=172 git.pkt.payload.max=145 git.sideband.band1.bytes=145 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=145 git.pack.trailer=2fbaff8815b3fcfce9ac505b9b02062f6ca8a3daOpen pack map
fetch2002.3 KiB216 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2310 git.response.cache=MISS git.response.duration_ms=216 git.fetch.wants=f9422f41c0f3421f3c11d62ae92e2269bf350d52 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=2310 git.pkt.payload.max=2283 git.sideband.band1.bytes=2283 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://gitlab.com/gitlab-org/cli
- Ref
- refs/heads/main
- Commit
- 0dd7574dce9e385c5c30540e6c15657adc6bdce9
- cf-ray
- a5e2b222feffe6b0
- Request
- 1c7792cc…
- Protocol
- v2 · sha1
- Agent
- git/2.56.g1891de4-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format