GitLabgitlab-org
cli
main
1package create
3import (
4 "fmt"
5 "net/url"
6 "os"
7 "path"
8 "strings"
10 "github.com/MakeNowJust/heredoc/v2"
11 "github.com/spf13/cobra"
13 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
15 "gitlab.com/gitlab-org/cli/internal/cmdutils"
16 "gitlab.com/gitlab-org/cli/internal/config"
17 "gitlab.com/gitlab-org/cli/internal/git"
18 "gitlab.com/gitlab-org/cli/internal/glrepo"
19 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
20 "gitlab.com/gitlab-org/cli/internal/run"
21)
23var currentUser = func(client *gitlab.Client) (*gitlab.User, error) {
24 u, _, err := client.Users.CurrentUser()
25 if err != nil {
26 return nil, err
27 }
28 return u, nil
29}
31var createProject = func(client *gitlab.Client, opts *gitlab.CreateProjectOptions) (*gitlab.Project, error) {
32 project, _, err := client.Projects.CreateProject(opts)
33 if err != nil {
34 return nil, err
35 }
36 return project, nil
37}
39var addRemote = git.AddRemote
41var gitInitializer = initGit
43var repoInitializer = initializeRepo
45var repoCloner = func(cloneURL, target, remoteName string) error {
46 _, err := git.RunClone(cloneURL, target, []string{"--origin", remoteName})
47 return err
48}
50func NewCmdCreate(f cmdutils.Factory) *cobra.Command {
51 projectCreateCmd := &cobra.Command{
52 Use: "create [path] [flags]",
53 Short: `Create a new GitLab project/repository.`,
54 Long: heredoc.Docf(`
55 Creates the new project with your first configured host in your %[1]sglab%[1]s
56 configuration. The host defaults to %[1]sGitLab.com%[1]s if not set. To set a host,
57 provide either:
59 - A %[1]sGITLAB_HOST%[1]s environment variable.
60 - A full URL for the project.
62 If you don't pass %[1]s--private%[1]s, %[1]s--internal%[1]s, or %[1]s--public%[1]s, the project uses the default project visibility of your GitLab instance.
63 `, "`"),
64 Args: cobra.MaximumNArgs(1),
65 Annotations: map[string]string{
66 mcpannotations.Destructive: "true",
67 },
68 RunE: func(cmd *cobra.Command, args []string) error {
69 return runCreateProject(cmd, args, f)
70 },
71 Example: heredoc.Doc(`
72 # Create a repository under your account using the current directory name.
73 glab repo create
75 # Create a repository under a group using the current directory name.
76 glab repo create --group glab-cli
78 # Create a repository with a specific name.
79 glab repo create my-project
81 # Create a repository for a group.
82 glab repo create glab-cli/my-project
84 # Create on a host other than gitlab.com.
85 GITLAB_HOST=example.com glab repo create
86 glab repo create <host>/path/to/repository`),
87 }
89 projectCreateCmd.Flags().StringP("name", "n", "", "Name of the new project.")
90 projectCreateCmd.Flags().StringP("group", "g", "", "Namespace or group for the new project. Defaults to the current user's namespace.")
91 projectCreateCmd.Flags().StringP("description", "d", "", "Description of the new project. Set to \"-\" to open an editor.")
92 projectCreateCmd.Flags().String("defaultBranch", "", "Branch name for the new project, overriding both the GitLab instance default and your local git configuration.")
93 projectCreateCmd.Flags().String("remoteName", "origin", "Remote name for the Git repository you're in. Defaults to `origin` if not provided.")
94 projectCreateCmd.Flags().StringArrayP("tag", "t", []string{}, "The list of topics for the project.")
95 projectCreateCmd.Flags().Bool("internal", false, "Make project internal: visible to any authenticated user.")
96 projectCreateCmd.Flags().BoolP("private", "p", false, "Make project private: visible only to project members.")
97 projectCreateCmd.Flags().BoolP("public", "P", false, "Make project public: visible without any authentication.")
98 projectCreateCmd.Flags().Bool("readme", false, "Initialize project with `README.md`. The repository is cloned locally after creation to ensure the local branch matches the remote.")
99 projectCreateCmd.Flags().BoolP("skipGitInit", "s", false, "Skip local repository setup (skips both 'git init' and cloning).")
101 return projectCreateCmd
102}
104func runCreateProject(cmd *cobra.Command, args []string, f cmdutils.Factory) error {
105 var (
106 projectPath string
107 visibility gitlab.VisibilityValue
108 err error
109 isPath bool
110 namespaceID int
111 namespace string
112 )
113 c := f.IO().Color()
115 defaultBranch, err := cmd.Flags().GetString("defaultBranch")
116 if err != nil {
117 return err
118 }
119 remoteName, err := cmd.Flags().GetString("remoteName")
120 if err != nil {
121 return err
122 }
123 skipGitInit, _ := cmd.Flags().GetBool("skipGitInit")
124 readme, _ := cmd.Flags().GetBool("readme")
126 // Check if directory is already git initialized
127 gitDir := path.Join(config.GitDir(false)...)
128 stat, statErr := os.Stat(gitDir)
129 isGitInitialized := statErr == nil && stat.Mode().IsDir()
131 // Determine if we need to set up a local repository in the current directory
132 var needsGitInit bool
133 if !skipGitInit && !isGitInitialized {
134 // Default behavior depends on whether we can prompt
135 if f.IO().IsInteractive() {
136 needsGitInit = true
137 promptMsg := "Directory not Git initialized. Run `git init`?"
138 if readme {
139 promptMsg = "Directory not Git initialized. Create project on GitLab and clone to the current directory?"
140 }
141 err := f.IO().Confirm(cmd.Context(), &needsGitInit, promptMsg)
142 if err != nil {
143 return err
144 }
145 } else {
146 // In non-interactive mode, default to false for safety
147 needsGitInit = false
148 }
149 }
151 var gitlabClient *gitlab.Client
152 if len(args) == 1 {
153 var host string
154 host, namespace, projectPath = projectPathFromArgs(args, f.DefaultHostname(), f.Config())
155 client, err := f.ApiClient(host)
156 if err != nil {
157 return err
158 }
159 gitlabClient = client.Lab()
161 user, err := currentUser(gitlabClient)
162 if err != nil {
163 return err
164 }
165 if user.Username == namespace {
166 namespace = ""
167 }
168 // When a project name is provided as argument, we won't init git in current directory
169 // Instead, we'll create a subdirectory and init there (or just add remote if already in git repo)
170 needsGitInit = false
171 } else {
172 // If we're in a git repository, use the repo name
173 // Otherwise, use the current directory name
174 if isGitInitialized {
175 projectPath, err = git.ToplevelDir()
176 if err != nil {
177 return err
178 }
179 projectPath = path.Base(projectPath)
180 } else {
181 cwd, err := os.Getwd()
182 if err != nil {
183 return fmt.Errorf("cannot get current directory: %w", err)
184 }
185 projectPath = path.Base(cwd)
186 }
187 isPath = true
189 c, err := f.ApiClient(f.DefaultHostname())
190 if err != nil {
191 return err
192 }
193 gitlabClient = c.Lab()
194 }
196 group, err := cmd.Flags().GetString("group")
197 if err != nil {
198 return fmt.Errorf("could not parse group flag: %w", err)
199 }
200 if group != "" {
201 namespace = group
202 }
204 if namespace != "" {
205 group, _, err := gitlabClient.Groups.GetGroup(namespace, &gitlab.GetGroupOptions{})
206 if err != nil {
207 return fmt.Errorf("could not find group or namespace %s: %w", namespace, err)
208 }
209 namespaceID = int(group.ID)
210 }
212 name, _ := cmd.Flags().GetString("name")
214 if projectPath == "" && name == "" {
215 fmt.Println("ERROR: path or name required to create a project.")
216 return cmd.Usage()
217 } else if name == "" {
218 name = projectPath
219 }
221 description, _ := cmd.Flags().GetString("description")
223 // Handle -d- flag: open editor without template selection
224 err = cmdutils.HandleDescriptionEditor(cmd.Context(), &description, f.IO(), f.Config, nil)
225 if err != nil {
226 return err
227 }
229 if internal, _ := cmd.Flags().GetBool("internal"); internal {
230 visibility = gitlab.InternalVisibility
231 } else if private, _ := cmd.Flags().GetBool("private"); private {
232 visibility = gitlab.PrivateVisibility
233 } else if public, _ := cmd.Flags().GetBool("public"); public {
234 visibility = gitlab.PublicVisibility
235 }
237 tags, _ := cmd.Flags().GetStringArray("tag")
239 opts := &gitlab.CreateProjectOptions{
240 Name: new(name),
241 Path: new(projectPath),
242 Description: new(description),
243 DefaultBranch: new(defaultBranch),
244 Topics: &tags,
245 InitializeWithReadme: new(readme),
246 }
248 if visibility != "" {
249 opts.Visibility = new(visibility)
250 }
252 if namespaceID != 0 {
253 opts.NamespaceID = new(int64(namespaceID))
254 }
256 project, err := createProject(gitlabClient, opts)
257 if err != nil {
258 return fmt.Errorf("error creating project: %w", err)
259 }
261 greenCheck := c.Green("✓")
262 f.IO().LogInfof("%s Created project on GitLab: %s - %s\n", greenCheck, project.NameWithNamespace, project.WebURL)
264 cfg := f.Config()
265 webURL, err := url.Parse(project.WebURL)
266 if err != nil {
267 return fmt.Errorf("project created but GitLab returned an invalid web URL %q: %w", project.WebURL, err)
268 }
269 protocol, _ := cfg.Get(webURL.Host, "git_protocol")
270 remote, err := glrepo.RemoteURL(project, protocol)
271 if err != nil {
272 return fmt.Errorf("project created but GitLab returned an invalid repository URL: %w", err)
273 }
275 if isPath {
276 if needsGitInit {
277 if readme {
278 // GitLab initialized the repo server-side; clone so the local branch matches the remote.
279 if err := repoCloner(remote, ".", remoteName); err != nil {
280 f.IO().LogErrorf("Warning: Project created on GitLab but clone failed: %v\n", err)
281 f.IO().LogErrorf("You can manually clone with: git clone %s .\n", remote)
282 } else {
283 f.IO().LogInfof("%s Cloned repository\n", greenCheck)
284 }
285 } else {
286 if err := gitInitializer(); err != nil {
287 f.IO().LogErrorf("Warning: Project created on GitLab but git init failed: %v\n", err)
288 f.IO().LogErrorf("You can manually initialize the repository with: git init\n")
289 } else {
290 f.IO().LogInfof("%s Initialized git repository\n", greenCheck)
291 if _, err := addRemote(remoteName, remote); err != nil {
292 f.IO().LogErrorf("Warning: Could not add remote: %v\n", err)
293 } else {
294 f.IO().LogInfof("%s Added remote %s\n", greenCheck, remote)
295 }
296 if defaultBranch != "" {
297 gitBranch := git.GitCommand("checkout", "-b", defaultBranch)
298 gitBranch.Stdout = os.Stdout
299 gitBranch.Stdin = os.Stdin
300 if err := run.PrepareCmd(gitBranch).Run(); err != nil {
301 f.IO().LogErrorf("Warning: Failed to create branch %s: %v\n", defaultBranch, err)
302 }
303 }
304 }
305 }
306 } else if isGitInitialized {
307 // Only when the directory really is a repository. Reached both with
308 // --skipGitInit and when the user declined `git init`, and in neither
309 // case is there anywhere for a remote to go: `git remote add` would
310 // print `fatal: not a git repository` while the command still exits 0.
311 if _, err := addRemote(remoteName, remote); err != nil {
312 f.IO().LogErrorf("Warning: Could not add remote: %v\n", err)
313 } else {
314 f.IO().LogInfof("%s Added remote %s\n", greenCheck, remote)
315 }
316 }
318 return nil
319 }
321 // When a project name is provided (not working in current directory)
322 // we need to set up a local subdirectory for it.
323 // In non-interactive mode, defaults to false (only creates remote project)
324 // to prevent unexpected directory creation for AI agents.
325 var doSetup bool
326 if !skipGitInit && f.IO().IsInteractive() {
327 doSetup = true
328 if err := f.IO().Confirm(cmd.Context(), &doSetup, fmt.Sprintf("Create a local project directory for %s?", project.NameWithNamespace)); err != nil {
329 return err
330 }
331 }
333 if doSetup {
334 projectPath := project.Path
335 if readme {
336 if err := repoCloner(remote, projectPath, remoteName); err != nil {
337 f.IO().LogErrorf("Warning: Project created on GitLab but clone failed: %v\n", err)
338 f.IO().LogErrorf("You can manually clone with: git clone %s %s\n", remote, projectPath)
339 } else {
340 f.IO().LogInfof("%s Initialized repository in './%s/'\n", greenCheck, projectPath)
341 }
342 } else {
343 if err := repoInitializer(projectPath, remote); err != nil {
344 return err
345 }
346 f.IO().LogInfof("%s Initialized repository in './%s/'\n", greenCheck, projectPath)
347 }
348 }
350 return nil
351}
353func initGit() error {
354 gitDir := path.Join(config.GitDir(false)...)
355 if stat, err := os.Stat(gitDir); err == nil && stat.Mode().IsDir() {
356 return nil
357 }
359 gitInit := git.GitCommand("init")
360 gitInit.Stdout = os.Stdout
361 gitInit.Stderr = os.Stderr
362 return run.PrepareCmd(gitInit).Run()
363}
365func initializeRepo(projectPath, remoteURL string) error {
366 gitInit := git.GitCommand("init", projectPath)
367 gitInit.Stdout = os.Stdout
368 gitInit.Stderr = os.Stderr
369 err := run.PrepareCmd(gitInit).Run()
370 if err != nil {
371 return err
372 }
373 gitRemoteAdd := git.GitCommand("-C", projectPath, "remote", "add", "origin", "--", remoteURL)
374 gitRemoteAdd.Stdout = os.Stdout
375 gitRemoteAdd.Stderr = os.Stderr
376 err = run.PrepareCmd(gitRemoteAdd).Run()
377 if err != nil {
378 return err
379 }
380 return nil
381}
383func projectPathFromArgs(args []string, defaultHostname string, cfg config.Config) (string, string, string) {
384 // sanitize input by removing trailing "/"
385 project := strings.TrimSuffix(args[0], "/")
387 var host, namespace string
388 if strings.Contains(project, "/") {
389 pp, _ := glrepo.FromFullName(project, defaultHostname, cfg)
390 host = pp.RepoHost()
391 project = pp.RepoName()
392 namespace = pp.RepoOwner()
393 }
394 return host, namespace, project
395}
Diagnostics9 git calls · 395 ms
CallStatusSizeTime0395 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs 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 KiB · hit46 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=HIT git.response.duration_ms=46 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 · hit7 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=32926 git.response.cache=HIT git.response.duration_ms=7 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.1 KiB · hit5 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=1112 git.response.cache=HIT git.response.duration_ms=5 git.fetch.filter=tree:0 git.fetch.wants=fed5065f0120a857fec6fa567dcdacfd34c3187b 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=1112 git.pkt.payload.max=1085 git.sideband.band1.bytes=1085 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1085 git.pack.trailer=792a8e6885c3db50fcc6be7a28de09363c6fb5e4Open pack map
fetchtree:0200890 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=890 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=11daffb8433226c87be08ba8cfc35154e4957d77 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=890 git.pkt.payload.max=863 git.sideband.band1.bytes=863 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=863 git.pack.trailer=b909e7b7573f11b0bb74a32781c8c5e4e19277f4Open 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=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:0200614 B · 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=614 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=3a89d0cfc8e81880c982180388e42e561a0b7eee 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=614 git.pkt.payload.max=587 git.sideband.band1.bytes=587 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=587 git.pack.trailer=eb8250f8e8340ff2fafc22c5aba90db34fd906a9Open pack map
fetchtree:0200146 B · 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=146 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=36190c1e41d9d7100992fb1024e710443f9e7622 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=146 git.pkt.payload.max=119 git.sideband.band1.bytes=119 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=119 git.pack.trailer=06bc37d1848912e665a98db6e5476c114b644397Open pack map
fetch2003.9 KiB303 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=303 git.response.bytes=4009 git.response.cache=MISS git.response.duration_ms=303 git.fetch.wants=398d4e2ac0fa1579f37a31a1b85eb349b205f0c6 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=4009 git.pkt.payload.max=3982 git.sideband.band1.bytes=3982 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
- a5ea56420c8f7089
- Request
- 4a35840e…
- 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