Browse Source

api: support listing repository tags (#6656)

Co-authored-by: zhouzhibo <zhouzhibo>
Co-authored-by: Joe Chen <jc@unknwon.io>
Devops 3 years ago
parent
commit
d60d9cf985

+ 52 - 0
internal/db/repo_tag.go

@@ -0,0 +1,52 @@
+// Copyright 2021 The Gogs Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package db
+
+import (
+	"fmt"
+
+	"github.com/gogs/git-module"
+)
+
+type Tag struct {
+	RepoPath string
+	Name     string
+
+	IsProtected bool
+	Commit      *git.Commit
+}
+
+func (ta *Tag) GetCommit() (*git.Commit, error) {
+	gitRepo, err := git.Open(ta.RepoPath)
+	if err != nil {
+		return nil, fmt.Errorf("open repository: %v", err)
+	}
+	return gitRepo.TagCommit(ta.Name)
+}
+
+func GetTagsByPath(path string) ([]*Tag, error) {
+	gitRepo, err := git.Open(path)
+	if err != nil {
+		return nil, fmt.Errorf("open repository: %v", err)
+	}
+
+	names, err := gitRepo.Tags()
+	if err != nil {
+		return nil, fmt.Errorf("list tags")
+	}
+
+	tags := make([]*Tag, len(names))
+	for i := range names {
+		tags[i] = &Tag{
+			RepoPath: path,
+			Name:     names[i],
+		}
+	}
+	return tags, nil
+}
+
+func (repo *Repository) GetTags() ([]*Tag, error) {
+	return GetTagsByPath(repo.RepoPath())
+}

+ 1 - 0
internal/route/api/v1/api.go

@@ -280,6 +280,7 @@ func RegisterRoutes(m *macaron.Macaron) {
 					m.Get("/:sha", repo.GetRepoGitTree)
 				})
 				m.Get("/forks", repo.ListForks)
+				m.Get("/tags", repo.ListTags)
 				m.Group("/branches", func() {
 					m.Get("", repo.ListBranches)
 					m.Get("/*", repo.GetBranch)

+ 12 - 0
internal/route/api/v1/convert/convert.go

@@ -30,6 +30,18 @@ func ToBranch(b *db.Branch, c *git.Commit) *api.Branch {
 	}
 }
 
+type Tag struct {
+	Name   string             `json:"name"`
+	Commit *api.PayloadCommit `json:"commit"`
+}
+
+func ToTag(b *db.Tag, c *git.Commit) *Tag {
+	return &Tag{
+		Name:   b.Name,
+		Commit: ToCommit(c),
+	}
+}
+
 func ToCommit(c *git.Commit) *api.PayloadCommit {
 	authorUsername := ""
 	author, err := db.GetUserByEmail(c.Author.Email)

+ 30 - 0
internal/route/api/v1/repo/tag.go

@@ -0,0 +1,30 @@
+// Copyright 2021 The Gogs Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package repo
+
+import (
+	"gogs.io/gogs/internal/context"
+	"gogs.io/gogs/internal/route/api/v1/convert"
+)
+
+func ListTags(c *context.APIContext) {
+	tags, err := c.Repo.Repository.GetTags()
+	if err != nil {
+		c.Error(err, "get tags")
+		return
+	}
+
+	apiTags := make([]*convert.Tag, len(tags))
+	for i := range tags {
+		commit, err := tags[i].GetCommit()
+		if err != nil {
+			c.Error(err, "get commit")
+			return
+		}
+		apiTags[i] = convert.ToTag(tags[i], commit)
+	}
+
+	c.JSONSuccess(&apiTags)
+}