GitLabgitlab-org

cli

main
ply8 git calls222 ms100 KiB6 cachedprotocol v2
301 lines8.1 KiBRaw
1package view
3import (
4 "encoding/base64"
5 "fmt"
6 "net/url"
7 "strings"
9 "github.com/MakeNowJust/heredoc/v2"
10 "github.com/spf13/cobra"
12 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
14 "gitlab.com/gitlab-org/cli/internal/api"
15 "gitlab.com/gitlab-org/cli/internal/cmdutils"
16 "gitlab.com/gitlab-org/cli/internal/config"
17 "gitlab.com/gitlab-org/cli/internal/glrepo"
18 "gitlab.com/gitlab-org/cli/internal/iostreams"
19 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
20 "gitlab.com/gitlab-org/cli/internal/utils"
23type options struct {
24 projectID string
25 client *gitlab.Client
26 web bool
27 outputFormat string
28 branch string
29 browser string
30 glamourStyle string
32 io *iostreams.IOStreams
33 repo glrepo.Interface
34 config config.Config
35 apiClient func(repoHost string) (*api.Client, error)
36 gitlabClient func() (*gitlab.Client, error)
37 baseRepo func() (glrepo.Interface, error)
38 branchFactory func() (string, error)
39 defaultHostname string
42func NewCmdView(f cmdutils.Factory) *cobra.Command {
43 opts := options{
44 io: f.IO(),
45 config: f.Config(),
46 baseRepo: f.BaseRepo,
47 branchFactory: f.Branch,
48 apiClient: f.ApiClient,
49 gitlabClient: f.GitLabClient,
50 defaultHostname: f.DefaultHostname(),
51 }
53 projectViewCmd := &cobra.Command{
54 Use: "view [repository] [flags]",
55 Short: "View a project or repository.",
56 Long: heredoc.Doc(`Display the description and README of a project, or open it in the browser.
57 `),
58 Args: cobra.MaximumNArgs(1),
59 Example: heredoc.Doc(`
60 # View project information for the current directory.
61 # Must be a Git repository.
62 glab repo view
64 # View project information of specified name.
65 # glab repo view my-project
66 glab repo view user/repo
67 glab repo view group/namespace/repo
69 # Specify repository by full [Git] URL.
70 glab repo view git@gitlab.com:user/repo.git
71 glab repo view https://gitlab.company.org/user/repo
72 glab repo view https://gitlab.company.org/user/repo.git`),
73 Annotations: map[string]string{
74 mcpannotations.Safe: "true",
75 },
76 RunE: func(cmd *cobra.Command, args []string) error {
77 if err := opts.complete(args); err != nil {
78 return err
79 }
81 return opts.run()
82 },
83 }
85 projectViewCmd.Flags().BoolVarP(&opts.web, "web", "w", false, "Open a project in the browser.")
86 cmdutils.EnableJSONOutput(projectViewCmd, opts.io, &opts.outputFormat)
87 projectViewCmd.Flags().StringVarP(&opts.branch, "branch", "b", "", "View a specific branch of the repository.")
89 return projectViewCmd
92func (o *options) complete(args []string) error {
93 o.branch = strings.TrimSpace(o.branch)
95 if len(args) == 1 {
96 o.projectID = args[0]
97 }
99 // No project argument - use current repository
100 if o.projectID == "" {
101 baseRepo, err := o.baseRepo()
102 if err != nil {
103 return cmdutils.WrapError(err, "`repository` is required when not running in a Git repository.")
104 }
105 o.repo = baseRepo
107 // Configure client to have host of current repository
108 client, err := o.apiClient(o.repo.RepoHost())
109 if err != nil {
110 return err
111 }
112 o.client = client.Lab()
114 if o.branch == "" {
115 o.branch, _ = o.branchFactory()
116 }
117 } else {
118 // If the ProjectID is a single token, use current user's namespace
119 if !strings.Contains(o.projectID, "/") {
120 apiClient, err := o.gitlabClient()
121 if err != nil {
122 return err
123 }
124 currentUser, _, err := apiClient.Users.CurrentUser()
125 if err != nil {
126 return cmdutils.WrapError(err, "Failed to retrieve your current user.")
127 }
129 o.projectID = currentUser.Username + "/" + o.projectID
130 }
132 // Get the repo full name from the ProjectID which can be a full URL or a group/repo format
133 repo, err := glrepo.FromFullName(o.projectID, o.defaultHostname, o.config)
134 if err != nil {
135 return err
136 }
137 o.repo = repo
138 client, err := o.apiClient(o.repo.RepoHost())
139 if err != nil {
140 return err
141 }
142 o.client = client.Lab()
143 }
145 browser, _ := o.config.Get(o.repo.RepoHost(), "browser")
146 o.browser = browser
148 o.glamourStyle, _ = o.config.Get(o.repo.RepoHost(), "glamour_style")
149 return nil
152func (o *options) run() error {
153 project, err := o.repo.Project(o.client)
154 if err != nil {
155 return cmdutils.WrapError(err, "Failed to retrieve project information.")
156 }
158 switch {
159 case o.web:
160 projectURL := project.WebURL
162 if o.io.IsaTTY {
163 o.io.LogInfof(
164 "Opening %s in your browser.\n",
165 generateProjectOpenURL(utils.DisplayURL(projectURL), project.DefaultBranch, o.branch),
166 )
167 }
169 return utils.OpenInBrowser(
170 generateProjectOpenURL(projectURL, project.DefaultBranch, o.branch),
171 o.browser,
172 )
173 case o.outputFormat == "json":
174 return printProjectContentJSON(o, project)
175 default:
176 readmeFile, err := getReadmeFile(o, project)
177 if err != nil {
178 return err
179 }
181 if o.io.IsaTTY {
182 if err := o.io.StartPager(); err != nil {
183 return err
184 }
185 defer o.io.StopPager()
187 printProjectContentTTY(o, project, readmeFile)
188 } else {
189 printProjectContentRaw(o, project, readmeFile)
190 }
191 }
193 return nil
196func getReadmeFile(opts *options, project *gitlab.Project) (*gitlab.File, error) {
197 if project.ReadmeURL == "" {
198 return nil, nil
199 }
201 readmePath, found := strings.CutPrefix(project.ReadmeURL, project.WebURL+"/-/blob/")
202 if !found {
203 return nil, fmt.Errorf("invalid README URL: %q", project.ReadmeURL)
204 }
206 // GitLab builds the README URL from the default branch, whose name can
207 // contain slashes (for example "release/main"), so split there first.
208 var readmeRef, readmeFileName string
209 if fileName, ok := strings.CutPrefix(readmePath, project.DefaultBranch+"/"); ok {
210 readmeRef, readmeFileName = project.DefaultBranch, fileName
211 } else {
212 readmePathComponents := strings.SplitN(readmePath, "/", 2)
213 if len(readmePathComponents) != 2 {
214 return nil, fmt.Errorf("invalid README URL: %q", project.ReadmeURL)
215 }
216 readmeRef = readmePathComponents[0]
217 readmeFileName = readmePathComponents[1]
218 }
220 if opts.branch == "" {
221 opts.branch = readmeRef
222 }
224 readmeFile, _, err := opts.client.RepositoryFiles.GetFile(project.PathWithNamespace, readmeFileName, &gitlab.GetFileOptions{Ref: new(opts.branch)})
225 if err != nil {
226 return nil, cmdutils.WrapError(err, fmt.Sprintf("Failed to retrieve README file on the %s branch.", opts.branch))
227 }
229 decoded, err := base64.StdEncoding.DecodeString(readmeFile.Content)
230 if err != nil {
231 return nil, cmdutils.WrapError(err, "Failed to decode README file.")
232 }
234 readmeFile.Content = string(decoded)
236 return readmeFile, nil
239func generateProjectOpenURL(projectWebURL string, defaultBranch string, branch string) string {
240 if branch != "" && defaultBranch != branch {
241 return projectWebURL + "/-/tree/" + url.PathEscape(branch)
242 }
244 return projectWebURL
247func printProjectContentTTY(opts *options, project *gitlab.Project, readme *gitlab.File) {
248 var description string
249 var readmeContent string
250 var err error
252 fullName := project.NameWithNamespace
253 if project.Description != "" {
254 description, err = utils.RenderMarkdownWithoutIndentations(project.Description, opts.glamourStyle)
255 if err != nil {
256 description = project.Description
257 }
258 } else {
259 description = "\n(No description provided)\n\n"
260 }
262 if readme != nil {
263 readmeContent, err = utils.RenderMarkdown(readme.Content, opts.glamourStyle)
264 if err != nil {
265 readmeContent = readme.Content
266 }
267 }
269 c := opts.io.Color()
270 // Header
271 opts.io.LogInfof("%s", c.Bold(fullName))
272 opts.io.LogInfof("%s", c.Gray(description))
274 // Readme
275 if readme != nil {
276 opts.io.LogInfof("%s", readmeContent)
277 } else {
278 opts.io.LogInfo(c.Gray("(This repository does not have a README file.)"))
279 }
281 opts.io.LogInfo()
282 opts.io.LogInfof(c.Gray("View this project on GitLab: %s\n"), project.WebURL)
285func printProjectContentRaw(opts *options, project *gitlab.Project, readme *gitlab.File) {
286 fullName := project.NameWithNamespace
287 description := project.Description
289 opts.io.LogInfof("name:\t%s\n", fullName)
290 opts.io.LogInfof("description:\t%s\n", description)
292 if readme != nil {
293 opts.io.LogInfo("---")
294 opts.io.LogInfof("%s", readme.Content)
295 opts.io.LogInfo()
296 }
299func printProjectContentJSON(opts *options, project *gitlab.Project) error {
300 return opts.io.PrintJSON(project)
Diagnostics8 git calls · 222 ms
CallStatusSizeTime0222 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 · hit3 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=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
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=2
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 · hit2 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=32926
git.response.cache=HIT
git.response.duration_ms=2
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 · 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=1857
git.response.cache=HIT
git.response.duration_ms=2
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:0200614 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=614
git.response.cache=HIT
git.response.duration_ms=2
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=eb8250f8e8340ff2fafc22c5aba90db34fd906a9
Open pack map
fetchtree:0200144 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=144
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=tree:0
git.fetch.wants=07856548f31627c156093092d9ba11933f27466d
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=144
git.pkt.payload.max=117
git.sideband.band1.bytes=117
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=117
git.pack.trailer=34e6e16d08a698193239463a1692183c2563a257
Open pack map
fetch2002.7 KiB210 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=210
git.response.bytes=2733
git.response.cache=MISS
git.response.duration_ms=210
git.fetch.wants=84dd99c114ad0004def3884b3fb6a32f3f3d5631
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=2733
git.pkt.payload.max=2706
git.sideband.band1.bytes=2706
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
a5ea5670f8c17089
Request
1b53ce26…
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