GitLabgitlab-org

cli

main
ply8 git calls245 ms100 KiB6 cachedprotocol v2
268 lines7.8 KiBRaw
1package save
3import (
4 "errors"
5 "fmt"
6 "os"
7 "strings"
8 "time"
10 "github.com/MakeNowJust/heredoc/v2"
11 "github.com/briandowns/spinner"
12 "github.com/spf13/cobra"
14 "gitlab.com/gitlab-org/cli/internal/cmdutils"
15 "gitlab.com/gitlab-org/cli/internal/commands/stack/stackutils"
16 "gitlab.com/gitlab-org/cli/internal/git"
17 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
18 "gitlab.com/gitlab-org/cli/internal/run"
19 "gitlab.com/gitlab-org/cli/internal/text"
22var description string
24func NewCmdSaveStack(f cmdutils.Factory, gr git.GitRunner, getText cmdutils.GetTextUsingEditor) *cobra.Command {
25 var stageAll bool
26 var noVerify bool
27 stackSaveCmd := &cobra.Command{
28 Use: "save",
29 Short: `Save your changes as a new diff. (EXPERIMENTAL)`,
30 Long: heredoc.Docf(`
31 Adds a new diff to the end of the stack. It becomes a new merge request the next time you run %[1]sglab stack sync%[1]s.
33 To add your changes to the diff you have checked out instead, use %[1]sglab stack amend%[1]s.
34 `, "`") + text.ExperimentalString,
35 Example: heredoc.Doc(`
36 # Save currently staged changes as diff with description
37 glab stack save -m "added a function"
39 # Add specified file to staged changes and save diff
40 glab stack save added_file
42 # Add all tracked files to staged changes and save diff
43 glab stack save -a -m "added a function to exisiting file"
45 # Add all tracked and untracked files to staged changes and save diff
46 glab stack save . -m "added new file"`),
47 Annotations: map[string]string{
48 mcpannotations.Destructive: "true",
49 },
50 RunE: func(cmd *cobra.Command, args []string) error {
51 if cmd.Flags().Changed("message") && cmd.Flags().Changed("description") {
52 return &cmdutils.FlagError{Err: errors.New("specify either of --message or --description")}
53 }
55 if err := stackutils.CheckNoRebaseInProgress(); err != nil {
56 return err
57 }
59 // check if there are even any changes before we start
60 err := checkForChanges()
61 if err != nil {
62 return fmt.Errorf("could not save: %w", err)
63 }
65 // a description is required, so ask if one is not provided
66 if description == "" {
67 description, err = promptForCommit(cmd.Context(), f, getText, "")
68 if err != nil {
69 return fmt.Errorf("error getting commit message: %w", err)
70 }
71 }
73 s := spinner.New(spinner.CharSets[11], 100*time.Millisecond)
75 // git add files
76 err = addFiles(args[0:], stageAll)
77 if err != nil {
78 return fmt.Errorf("error adding files: %w", err)
79 }
81 title, err := git.GetCurrentStackTitle()
82 if err != nil {
83 return fmt.Errorf("error running Git command: %w", err)
84 }
86 stack, err := git.GatherStackRefs(title)
87 if err != nil {
88 return fmt.Errorf("error getting refs from file system: %w", err)
89 }
91 if !stack.Empty() {
92 currentRef, err := git.CurrentStackRefFromCurrentBranch(title)
93 if err == nil && !currentRef.Empty() && !currentRef.IsLast() {
94 color := f.IO().Color()
95 f.IO().LogErrorf("%s warning: you are not on the last diff of the stack. Consider using 'glab stack amend' to modify the diff you have checked out. New changes will be appended to the end of the stack.\n", color.WarnIcon())
96 }
97 }
99 author, err := git.GitUserName()
100 if err != nil {
101 return fmt.Errorf("error getting Git author: %w", err)
102 }
104 // generate a SHA based on: commit message, stack title, Git author name
105 sha, err := stackutils.GenerateStackSha(description, title, string(author), time.Now())
106 if err != nil {
107 return fmt.Errorf("error generating hash for stack branch name: %w", err)
108 }
110 // create branch name from SHA
111 branch, err := stackutils.CreateShaBranch(f, sha, title)
112 if err != nil {
113 return fmt.Errorf("error creating branch name: %w", err)
114 }
116 // create the branch prefix-stack_title-SHA
117 err = git.CheckoutNewBranch(branch)
118 if err != nil {
119 return fmt.Errorf("error running branch checkout: %w", err)
120 }
122 // commit files to branch
123 _, err = commitFiles(description, noVerify)
124 if err != nil {
125 return fmt.Errorf("error committing files: %w", err)
126 }
128 var stackRef git.StackRef
129 if !stack.Empty() {
130 lastRef := stack.Last()
132 // update the ref before it (the current last ref)
133 err = git.UpdateStackRefFile(title, git.StackRef{
134 Prev: lastRef.Prev,
135 MR: lastRef.MR,
136 Description: lastRef.Description,
137 SHA: lastRef.SHA,
138 Branch: lastRef.Branch,
139 Next: sha,
140 })
141 if err != nil {
142 return fmt.Errorf("error updating old ref: %w", err)
143 }
145 stackRef = git.StackRef{Prev: lastRef.SHA, SHA: sha, Branch: branch, Description: description}
146 } else {
147 stackRef = git.StackRef{SHA: sha, Branch: branch, Description: description}
148 }
150 err = git.AddStackRefFile(title, stackRef)
151 if err != nil {
152 return fmt.Errorf("error creating stack file: %w", err)
153 }
155 if f.IO().IsOutputTTY() {
156 color := f.IO().Color()
158 f.IO().LogInfof(
159 "%s %s: Saved with message: \"%s\".\n",
160 color.ProgressIcon(),
161 color.Blue(title),
162 description,
163 )
164 }
166 s.Stop()
168 return nil
169 },
170 }
171 stackSaveCmd.Flags().StringVarP(&description, "description", "d", "", "Description of the change.")
172 stackSaveCmd.Flags().StringVarP(&description, "message", "m", "", "Alias for the description flag.")
173 stackSaveCmd.Flags().BoolVarP(&stageAll, "all", "a", false, "Automatically stage modified and deleted tracked files.")
174 stackSaveCmd.Flags().BoolVar(&noVerify, "no-verify", false, "Bypass the pre-commit and commit-msg hooks of git-commit(1).")
176 return stackSaveCmd
179func checkForChanges() error {
180 gitCmd := git.GitCommand("status", "--porcelain")
181 output, err := run.PrepareCmd(gitCmd).Output()
182 if err != nil {
183 return fmt.Errorf("error running Git status: %w", err)
184 }
186 if string(output) == "" {
187 return fmt.Errorf("no changes to save")
188 }
190 return nil
193func checkForStagedChanges() (bool, error) {
194 gitCmd := git.GitCommand("diff", "--cached", "--name-only")
195 output, err := run.PrepareCmd(gitCmd).Output()
196 if err != nil {
197 return false, fmt.Errorf("error checking for staged changes: %w", err)
198 }
200 return strings.TrimSpace(string(output)) != "", nil
203// addFiles adds files to git (git add args...)
204func addFiles(args []string, stageAll bool) error {
205 // If stageAll flag is set, stage tracked files only (like git commit -a)
206 if stageAll {
207 gitCmd := git.GitCommand("add", "--update")
208 _, err := run.PrepareCmd(gitCmd).Output()
209 if err != nil {
210 return fmt.Errorf("error running Git add --update: %w", err)
211 }
212 hasStagedChanges, err := checkForStagedChanges()
213 if err != nil {
214 return err
215 }
216 if !hasStagedChanges {
217 return fmt.Errorf("no staged changes after 'git add --update'. Are there any tracked modified files?")
218 }
219 return nil
220 }
222 // If explicit files are provided, stage those files
223 if len(args) > 0 {
224 for _, file := range args {
225 _, err := os.Stat(file)
226 if err != nil {
227 return err
228 }
229 }
231 cmdargs := append([]string{"add"}, args...)
232 gitCmd := git.GitCommand(cmdargs...)
234 _, err := run.PrepareCmd(gitCmd).Output()
235 if err != nil {
236 return fmt.Errorf("error running Git add: %w", err)
237 }
239 return nil
240 }
242 // No args and no flags: check if there are staged changes
243 hasStagedChanges, err := checkForStagedChanges()
244 if err != nil {
245 return err
246 }
248 if !hasStagedChanges {
249 return fmt.Errorf("no staged changes. Stage files manually with 'git add', use -a flag to automatically stage tracked files, or specify files explicitly")
250 }
252 // If there are staged changes, proceed without staging anything
253 return nil
256func commitFiles(message string, noVerify bool) (string, error) {
257 args := []string{"commit", "-m", message}
258 if noVerify {
259 args = append(args, "--no-verify")
260 }
261 commitCmd := git.GitCommand(args...)
262 output, err := run.PrepareCmd(commitCmd).Output()
263 if err != nil {
264 return "", fmt.Errorf("error running Git command: %w", err)
265 }
267 return string(output), nil
Diagnostics8 git calls · 245 ms
CallStatusSizeTime0245 ms
discover200185 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
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 KiB · hit8 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=59849
git.response.cache=HIT
git.response.duration_ms=8
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
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 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=4273
git.response.cache=HIT
git.response.duration_ms=4
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:0 · deepen 1020032 KiB · hit4 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=32926
git.response.cache=HIT
git.response.duration_ms=4
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=44
Open pack map
fetchtree:02001.8 KiB · hit1 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=1
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=1
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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200432 B · 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=432
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=ff2d1e7abc74964e5679ebdb51f1ac0d0dc3aff0
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=432
git.pkt.payload.max=405
git.sideband.band1.bytes=405
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=405
git.pack.trailer=8f3029a269217d94d12d0671e0490fe3d5506303
Open pack map
fetchtree:0200254 B · 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=254
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=1bddb68dc447e75c7fc2f3cd02e93e572448d630
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=254
git.pkt.payload.max=227
git.sideband.band1.bytes=227
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=227
git.pack.trailer=5113828f2359f89a3269ef1119ad801c584c57a8
Open pack map
fetch2002.6 KiB226 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=226
git.response.bytes=2636
git.response.cache=MISS
git.response.duration_ms=226
git.fetch.wants=b490390792498a0ee231a994e69a35289478f54f
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=2636
git.pkt.payload.max=2609
git.sideband.band1.bytes=2609
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
a5e15a836f0ecf6a
Request
06b8286c…
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