GitLabgitlab-org
cli
main
1package create
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "strings"
11 "github.com/MakeNowJust/heredoc/v2"
12 "github.com/spf13/cobra"
14 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
16 "gitlab.com/gitlab-org/cli/internal/cmdutils"
17 "gitlab.com/gitlab-org/cli/internal/config"
18 "gitlab.com/gitlab-org/cli/internal/dbg"
19 "gitlab.com/gitlab-org/cli/internal/glrepo"
20 "gitlab.com/gitlab-org/cli/internal/iostreams"
21 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
22)
24type options struct {
25 title string
26 description string
27 displayFilename string
28 visibility string
29 personal bool
31 files []*gitlab.CreateSnippetFileOptions
33 io *iostreams.IOStreams
34 config func() config.Config
35 gitlabClient func() (*gitlab.Client, error)
36 baseRepo func() (glrepo.Interface, error)
37}
39func (opts *options) addFile(path, content *string) {
40 opts.files = append(opts.files, &gitlab.CreateSnippetFileOptions{
41 FilePath: path,
42 Content: content,
43 })
44}
46func hasStdIn() bool {
47 fi, err := os.Stdin.Stat()
48 if err != nil {
49 return false
50 }
52 // Check if stdin is a pipe or redirected file (not a character device/TTY).
53 // Note: fi.Size() is always 0 for pipes, so we check the mode instead.
54 return (fi.Mode() & os.ModeCharDevice) == 0
55}
57func NewCmdCreate(f cmdutils.Factory) *cobra.Command {
58 opts := &options{
59 io: f.IO(),
60 config: f.Config,
61 gitlabClient: f.GitLabClient,
62 baseRepo: f.BaseRepo,
63 }
64 snippetCreateCmd := &cobra.Command{
65 Use: `create -t <title> <file1> [<file2>...] [flags]`,
66 Short: `Create a new snippet.`,
67 Long: heredoc.Docf(`
68 Provide one or more file paths to upload, or pass %[1]s--filename%[1]s and
69 pipe content from standard input.
71 Snippets are created in the current project by default. Use
72 %[1]s--personal%[1]s to create the snippet in your personal account instead,
73 and %[1]s--visibility%[1]s to control who can see it.
74 `, "`"),
75 Aliases: []string{"new"},
76 Example: heredoc.Doc(`
77 glab snippet create script.py --title "Title of the snippet"
78 echo "package main" | glab snippet new --title "Title of the snippet" --filename "main.go"
79 glab snippet create -t Title -f "different.go" -d Description main.go
80 glab snippet create -t Title -f "different.go" -d Description --filename different.go main.go
81 glab snippet create --personal --title "Personal snippet" script.py`),
82 Annotations: map[string]string{
83 mcpannotations.Destructive: "true",
84 },
85 RunE: func(cmd *cobra.Command, args []string) error {
86 if err := opts.complete(args); err != nil {
87 return err
88 }
90 if err := opts.validate(); err != nil {
91 return err
92 }
94 return opts.run(cmd.Context())
95 },
96 }
98 snippetCreateCmd.Flags().StringVarP(&opts.title, "title", "t", "", "(required) Title of the snippet.")
99 snippetCreateCmd.Flags().StringVarP(&opts.displayFilename, "filename", "f", "", "Filename of the snippet in GitLab.")
100 snippetCreateCmd.Flags().StringVarP(&opts.description, "description", "d", "", "Description of the snippet. Set to \"-\" to open an editor.")
101 snippetCreateCmd.Flags().StringVarP(&opts.visibility, "visibility", "v", "private", "Limit by visibility: 'public', 'internal', or 'private'.")
102 snippetCreateCmd.Flags().BoolVarP(&opts.personal, "personal", "p", false, "Create a personal snippet.")
104 return snippetCreateCmd
105}
107func (o *options) complete(args []string) error {
108 if len(args) == 0 {
109 if o.displayFilename == "" {
110 return &cmdutils.FlagError{Err: errors.New("if 'path' is not provided, 'filename' and stdin are required")}
111 }
112 if !o.io.IsInTTY && !hasStdIn() {
113 return errors.New("stdin required if no 'path' is provided")
114 }
115 o.io.LogInfo("reading from stdin (Ctrl+D to finish, Ctrl+C to abort):")
116 content, err := readFromSTDIN(o.io)
117 if err != nil {
118 return err
119 }
120 o.addFile(&o.displayFilename, &content)
121 } else {
122 for _, path := range args {
123 filename := path
124 if len(args) == 1 && o.displayFilename != "" {
125 filename = o.displayFilename
126 }
128 content, err := readFromFile(path)
129 if err != nil {
130 return err
131 }
132 dbg.Debug("Adding:", filename)
133 o.addFile(&filename, &content)
134 }
135 }
137 return nil
138}
140func (o *options) validate() error {
141 if o.title == "" {
142 return &cmdutils.FlagError{
143 Err: errors.New("--title required for snippets"),
144 }
145 }
147 return nil
148}
150func (o *options) run(ctx context.Context) error {
151 // Handle -d- flag: open editor without template selection
152 err := cmdutils.HandleDescriptionEditor(ctx, &o.description, o.io, o.config, nil)
153 if err != nil {
154 return err
155 }
157 client, err := o.gitlabClient()
158 if err != nil {
159 return err
160 }
162 var repo glrepo.Interface
163 if !o.personal {
164 repo, err = o.baseRepo()
165 if err != nil {
166 redCheck := o.io.Color().FailedIcon()
167 return fmt.Errorf("%s Project snippet needs a repository. Do you want --personal?", redCheck)
168 }
169 }
171 var snippet *gitlab.Snippet
172 if o.personal {
173 o.io.LogError("- Creating snippet in personal space")
174 snippet, _, err = client.Snippets.CreateSnippet(&gitlab.CreateSnippetOptions{
175 Title: &o.title,
176 Description: &o.description,
177 Visibility: new(gitlab.VisibilityValue(o.visibility)),
178 Files: &o.files,
179 })
180 } else {
181 o.io.LogError("- Creating snippet in", repo.FullName())
182 snippet, _, err = client.ProjectSnippets.CreateSnippet(repo.FullName(), &gitlab.CreateProjectSnippetOptions{
183 Title: &o.title,
184 Description: &o.description,
185 Visibility: new(gitlab.VisibilityValue(o.visibility)),
186 Files: &o.files,
187 })
188 }
189 if err != nil {
190 return fmt.Errorf("failed to create snippet: %w", err)
191 }
192 snippetID := o.io.Color().Green(fmt.Sprintf("$%d", snippet.ID))
193 var files []string
194 for _, file := range o.files {
195 files = append(files, *file.FilePath)
196 }
197 names := strings.Join(files, " ")
198 if o.io.IsaTTY {
199 o.io.LogInfof("%s %s (%s)\n %s\n", snippetID, snippet.Title, names, snippet.WebURL)
200 } else {
201 o.io.LogInfo(snippet.WebURL)
202 }
204 return nil
205}
207func readFromSTDIN(ioStream *iostreams.IOStreams) (string, error) {
208 content, err := io.ReadAll(ioStream.In)
209 if err != nil {
210 return "", fmt.Errorf("failed to read snippet from STDIN: %w", err)
211 }
212 return string(content), nil
213}
215func readFromFile(filename string) (string, error) {
216 content, err := os.ReadFile(filename)
217 if err != nil {
218 return "", fmt.Errorf("failed to read snippet from file %q: %w", filename, err)
219 }
220 return string(content), nil
221}
Diagnostics8 git calls · 185 ms
CallStatusSizeTime0185 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=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 KiB2 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=UPDATING git.response.duration_ms=2 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 · 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=4273 git.response.cache=HIT git.response.duration_ms=1 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=3 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=44Open pack map
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=2 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:0200169 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=169 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=a80c002fcd583cc74c217cd1e1ee16aea4e7e70b 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=169 git.pkt.payload.max=142 git.sideband.band1.bytes=142 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=142 git.pack.trailer=8ba52b73a78950e6664cb65379b8cd65fc810d6eOpen pack map
fetchtree:0200173 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=173 git.response.bytes=173 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=28c64b6cda6e3263690e25cda1aa7c9912d186c9 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=173 git.pkt.payload.max=146 git.sideband.band1.bytes=146 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=146 git.pack.trailer=c5e9e7bf1570c18966f9c942c9de39e737a3f60dOpen pack map
fetch2002.3 KiB173 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2341 git.response.cache=MISS git.response.duration_ms=173 git.fetch.wants=b7ee0d79287ca5d477cb9a3cf6ecf1c7bdca3f34 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=2341 git.pkt.payload.max=2314 git.sideband.band1.bytes=2314 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
- a5e2c7204e1e4afc
- Request
- 03d98a0c…
- 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