repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/api.go
internal/route/api/v1/api.go
// Copyright 2015 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 v1 import ( "net/http" "strings" "github.com/go-macaron/binding" "gopkg.in/macaron.v1" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/route/api/v1/admin" "gogs.io/gogs/internal/route/api/v1/misc" "gogs.io/gogs/internal/route/api/v1/org" "gogs.io/gogs/internal/route/api/v1/repo" "gogs.io/gogs/internal/route/api/v1/user" ) // repoAssignment extracts information from URL parameters to retrieve the repository, // and makes sure the context user has at least the read access to the repository. func repoAssignment() macaron.Handler { return func(c *context.APIContext) { username := c.Params(":username") reponame := c.Params(":reponame") var err error var owner *database.User // Check if the context user is the repository owner. if c.IsLogged && c.User.LowerName == strings.ToLower(username) { owner = c.User } else { owner, err = database.Handle.Users().GetByUsername(c.Req.Context(), username) if err != nil { c.NotFoundOrError(err, "get user by name") return } } c.Repo.Owner = owner repo, err := database.Handle.Repositories().GetByName(c.Req.Context(), owner.ID, reponame) if err != nil { c.NotFoundOrError(err, "get repository by name") return } else if err = repo.GetOwner(); err != nil { c.Error(err, "get owner") return } if c.IsTokenAuth && c.User.IsAdmin { c.Repo.AccessMode = database.AccessModeOwner } else { c.Repo.AccessMode = database.Handle.Permissions().AccessMode(c.Req.Context(), c.UserID(), repo.ID, database.AccessModeOptions{ OwnerID: repo.OwnerID, Private: repo.IsPrivate, }, ) } if !c.Repo.HasAccess() { c.NotFound() return } c.Repo.Repository = repo } } // orgAssignment extracts information from URL parameters to retrieve the organization or team. func orgAssignment(args ...bool) macaron.Handler { var ( assignOrg bool assignTeam bool ) if len(args) > 0 { assignOrg = args[0] } if len(args) > 1 { assignTeam = args[1] } return func(c *context.APIContext) { c.Org = new(context.APIOrganization) var err error if assignOrg { c.Org.Organization, err = database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":orgname")) if err != nil { c.NotFoundOrError(err, "get organization by name") return } } if assignTeam { c.Org.Team, err = database.GetTeamByID(c.ParamsInt64(":teamid")) if err != nil { c.NotFoundOrError(err, "get team by ID") return } } } } // reqToken makes sure the context user is authorized via access token. func reqToken() macaron.Handler { return func(c *context.Context) { if !c.IsTokenAuth { c.Status(http.StatusUnauthorized) return } } } // reqBasicAuth makes sure the context user is authorized via HTTP Basic Auth. func reqBasicAuth() macaron.Handler { return func(c *context.Context) { if !c.IsBasicAuth { c.Status(http.StatusUnauthorized) return } } } // reqAdmin makes sure the context user is a site admin. func reqAdmin() macaron.Handler { return func(c *context.Context) { if !c.IsLogged || !c.User.IsAdmin { c.Status(http.StatusForbidden) return } } } // reqRepoWriter makes sure the context user has at least write access to the repository. func reqRepoWriter() macaron.Handler { return func(c *context.Context) { if !c.Repo.IsWriter() { c.Status(http.StatusForbidden) return } } } // reqRepoWriter makes sure the context user has at least admin access to the repository. func reqRepoAdmin() macaron.Handler { return func(c *context.Context) { if !c.Repo.IsAdmin() { c.Status(http.StatusForbidden) return } } } func mustEnableIssues(c *context.APIContext) { if !c.Repo.Repository.EnableIssues || c.Repo.Repository.EnableExternalTracker { c.NotFound() return } } // RegisterRoutes registers all route in API v1 to the web application. // FIXME: custom form error response func RegisterRoutes(m *macaron.Macaron) { bind := binding.Bind m.Group("/v1", func() { // Handle preflight OPTIONS request m.Options("/*", func() {}) // Miscellaneous m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown) m.Post("/markdown/raw", misc.MarkdownRaw) // Users m.Group("/users", func() { m.Get("/search", user.Search) m.Group("/:username", func() { m.Get("", user.GetInfo) m.Group("/tokens", func() { accessTokensHandler := user.NewAccessTokensHandler(user.NewAccessTokensStore()) m.Combo(""). Get(accessTokensHandler.List()). Post(bind(api.CreateAccessTokenOption{}), accessTokensHandler.Create()) }, reqBasicAuth()) }) }) m.Group("/users", func() { m.Group("/:username", func() { m.Get("/keys", user.ListPublicKeys) m.Get("/followers", user.ListFollowers) m.Group("/following", func() { m.Get("", user.ListFollowing) m.Get("/:target", user.CheckFollowing) }) }) }, reqToken()) m.Group("/user", func() { m.Get("", user.GetAuthenticatedUser) m.Combo("/emails"). Get(user.ListEmails). Post(bind(api.CreateEmailOption{}), user.AddEmail). Delete(bind(api.CreateEmailOption{}), user.DeleteEmail) m.Get("/followers", user.ListMyFollowers) m.Group("/following", func() { m.Get("", user.ListMyFollowing) m.Combo("/:username"). Get(user.CheckMyFollowing). Put(user.Follow). Delete(user.Unfollow) }) m.Group("/keys", func() { m.Combo(""). Get(user.ListMyPublicKeys). Post(bind(api.CreateKeyOption{}), user.CreatePublicKey) m.Combo("/:id"). Get(user.GetPublicKey). Delete(user.DeletePublicKey) }) m.Get("/issues", repo.ListUserIssues) }, reqToken()) // Repositories m.Get("/users/:username/repos", reqToken(), repo.ListUserRepositories) m.Get("/orgs/:org/repos", reqToken(), repo.ListOrgRepositories) m.Combo("/user/repos", reqToken()). Get(repo.ListMyRepos). Post(bind(api.CreateRepoOption{}), repo.Create) m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo) m.Group("/repos", func() { m.Get("/search", repo.Search) m.Get("/:username/:reponame", repoAssignment(), repo.Get) m.Get("/:username/:reponame/releases", repoAssignment(), repo.Releases) }) m.Group("/repos", func() { m.Post("/migrate", bind(form.MigrateRepo{}), repo.Migrate) m.Delete("/:username/:reponame", repoAssignment(), repo.Delete) m.Group("/:username/:reponame", func() { m.Group("/hooks", func() { m.Combo(""). Get(repo.ListHooks). Post(bind(api.CreateHookOption{}), repo.CreateHook) m.Combo("/:id"). Patch(bind(api.EditHookOption{}), repo.EditHook). Delete(repo.DeleteHook) }, reqRepoAdmin()) m.Group("/collaborators", func() { m.Get("", repo.ListCollaborators) m.Combo("/:collaborator"). Get(repo.IsCollaborator). Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator). Delete(repo.DeleteCollaborator) }, reqRepoAdmin()) m.Get("/raw/*", context.RepoRef(), repo.GetRawFile) m.Group("/contents", func() { m.Get("", repo.GetContents) m.Combo("/*"). Get(repo.GetContents). Put(bind(repo.PutContentsRequest{}), repo.PutContents) }) m.Get("/archive/*", repo.GetArchive) m.Group("/git", func() { m.Group("/trees", func() { m.Get("/:sha", repo.GetRepoGitTree) }) m.Group("/blobs", func() { m.Get("/:sha", repo.RepoGitBlob) }) }) m.Get("/forks", repo.ListForks) m.Get("/tags", repo.ListTags) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", repo.GetBranch) }) m.Group("/commits", func() { m.Get("/:sha", repo.GetSingleCommit) m.Get("", repo.GetAllCommits) m.Get("/*", repo.GetReferenceSHA) }) m.Group("/keys", func() { m.Combo(""). Get(repo.ListDeployKeys). Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey) m.Combo("/:id"). Get(repo.GetDeployKey). Delete(repo.DeleteDeploykey) }, reqRepoAdmin()) m.Group("/issues", func() { m.Combo(""). Get(repo.ListIssues). Post(bind(api.CreateIssueOption{}), repo.CreateIssue) m.Group("/comments", func() { m.Get("", repo.ListRepoIssueComments) m.Patch("/:id", bind(api.EditIssueCommentOption{}), repo.EditIssueComment) }) m.Group("/:index", func() { m.Combo(""). Get(repo.GetIssue). Patch(bind(api.EditIssueOption{}), repo.EditIssue) m.Group("/comments", func() { m.Combo(""). Get(repo.ListIssueComments). Post(bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) m.Combo("/:id"). Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment). Delete(repo.DeleteIssueComment) }) m.Get("/labels", repo.ListIssueLabels) m.Group("/labels", func() { m.Combo(""). Post(bind(api.IssueLabelsOption{}), repo.AddIssueLabels). Put(bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels). Delete(repo.ClearIssueLabels) m.Delete("/:id", repo.DeleteIssueLabel) }, reqRepoWriter()) }) }, mustEnableIssues) m.Group("/labels", func() { m.Get("", repo.ListLabels) m.Get("/:id", repo.GetLabel) }) m.Group("/labels", func() { m.Post("", bind(api.CreateLabelOption{}), repo.CreateLabel) m.Combo("/:id"). Patch(bind(api.EditLabelOption{}), repo.EditLabel). Delete(repo.DeleteLabel) }, reqRepoWriter()) m.Group("/milestones", func() { m.Get("", repo.ListMilestones) m.Get("/:id", repo.GetMilestone) }) m.Group("/milestones", func() { m.Post("", bind(api.CreateMilestoneOption{}), repo.CreateMilestone) m.Combo("/:id"). Patch(bind(api.EditMilestoneOption{}), repo.EditMilestone). Delete(repo.DeleteMilestone) }, reqRepoWriter()) m.Patch("/issue-tracker", reqRepoWriter(), bind(api.EditIssueTrackerOption{}), repo.IssueTracker) m.Patch("/wiki", reqRepoWriter(), bind(api.EditWikiOption{}), repo.Wiki) m.Post("/mirror-sync", reqRepoWriter(), repo.MirrorSync) m.Get("/editorconfig/:filename", context.RepoRef(), repo.GetEditorconfig) }, repoAssignment()) }, reqToken()) m.Get("/issues", reqToken(), repo.ListUserIssues) // Organizations m.Combo("/user/orgs", reqToken()). Get(org.ListMyOrgs). Post(bind(api.CreateOrgOption{}), org.CreateMyOrg) m.Get("/users/:username/orgs", org.ListUserOrgs) m.Group("/orgs/:orgname", func() { m.Combo(""). Get(org.Get). Patch(bind(api.EditOrgOption{}), org.Edit) m.Get("/teams", org.ListTeams) }, orgAssignment(true)) m.Group("/admin", func() { m.Group("/users", func() { m.Post("", bind(api.CreateUserOption{}), admin.CreateUser) m.Group("/:username", func() { m.Combo(""). Patch(bind(api.EditUserOption{}), admin.EditUser). Delete(admin.DeleteUser) m.Post("/keys", bind(api.CreateKeyOption{}), admin.CreatePublicKey) m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg) m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo) }) }) m.Group("/orgs/:orgname", func() { m.Group("/teams", func() { m.Post("", orgAssignment(true), bind(api.CreateTeamOption{}), admin.CreateTeam) }) }) m.Group("/teams", func() { m.Group("/:teamid", func() { m.Get("/members", admin.ListTeamMembers) m.Combo("/members/:username"). Put(admin.AddTeamMember). Delete(admin.RemoveTeamMember) m.Combo("/repos/:reponame"). Put(admin.AddTeamRepository). Delete(admin.RemoveTeamRepository) }, orgAssignment(false, true)) }) }, reqAdmin()) m.Any("/*", func(c *context.Context) { c.NotFound() }) }, context.APIContexter()) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/misc/markdown.go
internal/route/api/v1/misc/markdown.go
// Copyright 2014 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 misc import ( api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/markup" ) func Markdown(c *context.APIContext, form api.MarkdownOption) { if form.Text == "" { _, _ = c.Write([]byte("")) return } _, _ = c.Write(markup.Markdown([]byte(form.Text), form.Context, nil)) } func MarkdownRaw(c *context.APIContext) { body, err := c.Req.Body().Bytes() if err != nil { c.Error(err, "read body") return } _, _ = c.Write(markup.SanitizeBytes(markup.RawMarkdown(body, ""))) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/user/access_tokens.go
internal/route/api/v1/user/access_tokens.go
// Copyright 2014 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 user import ( gocontext "context" "net/http" api "github.com/gogs/go-gogs-client" "gopkg.in/macaron.v1" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) // AccessTokensHandler is the handler for users access tokens API endpoints. type AccessTokensHandler struct { store AccessTokensStore } // NewAccessTokensHandler returns a new AccessTokensHandler for users access // tokens API endpoints. func NewAccessTokensHandler(s AccessTokensStore) *AccessTokensHandler { return &AccessTokensHandler{ store: s, } } func (h *AccessTokensHandler) List() macaron.Handler { return func(c *context.APIContext) { tokens, err := h.store.ListAccessTokens(c.Req.Context(), c.User.ID) if err != nil { c.Error(err, "list access tokens") return } apiTokens := make([]*api.AccessToken, len(tokens)) for i := range tokens { apiTokens[i] = &api.AccessToken{Name: tokens[i].Name, Sha1: tokens[i].Sha1} } c.JSONSuccess(&apiTokens) } } func (h *AccessTokensHandler) Create() macaron.Handler { return func(c *context.APIContext, form api.CreateAccessTokenOption) { t, err := h.store.CreateAccessToken(c.Req.Context(), c.User.ID, form.Name) if err != nil { if database.IsErrAccessTokenAlreadyExist(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "new access token") } return } c.JSON(http.StatusCreated, &api.AccessToken{Name: t.Name, Sha1: t.Sha1}) } } // AccessTokensStore is the data layer carrier for user access tokens API // endpoints. This interface is meant to abstract away and limit the exposure of // the underlying data layer to the handler through a thin-wrapper. type AccessTokensStore interface { // CreateAccessToken creates a new access token and persist to database. It // returns database.ErrAccessTokenAlreadyExist when an access token with same // name already exists for the user. CreateAccessToken(ctx gocontext.Context, userID int64, name string) (*database.AccessToken, error) // ListAccessTokens returns all access tokens belongs to given user. ListAccessTokens(ctx gocontext.Context, userID int64) ([]*database.AccessToken, error) } type accessTokensStore struct{} // NewAccessTokensStore returns a new AccessTokensStore using the global // database handle. func NewAccessTokensStore() AccessTokensStore { return &accessTokensStore{} } func (*accessTokensStore) CreateAccessToken(ctx gocontext.Context, userID int64, name string) (*database.AccessToken, error) { return database.Handle.AccessTokens().Create(ctx, userID, name) } func (*accessTokensStore) ListAccessTokens(ctx gocontext.Context, userID int64) ([]*database.AccessToken, error) { return database.Handle.AccessTokens().List(ctx, userID) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/user/follower.go
internal/route/api/v1/user/follower.go
// Copyright 2015 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 user import ( api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) func responseAPIUsers(c *context.APIContext, users []*database.User) { apiUsers := make([]*api.User, len(users)) for i := range users { apiUsers[i] = users[i].APIFormat() } c.JSONSuccess(&apiUsers) } func listUserFollowers(c *context.APIContext, u *database.User) { users, err := database.Handle.Users().ListFollowers(c.Req.Context(), u.ID, c.QueryInt("page"), database.ItemsPerPage) if err != nil { c.Error(err, "list followers") return } responseAPIUsers(c, users) } func ListMyFollowers(c *context.APIContext) { listUserFollowers(c, c.User) } func ListFollowers(c *context.APIContext) { u := GetUserByParams(c) if c.Written() { return } listUserFollowers(c, u) } func listUserFollowing(c *context.APIContext, u *database.User) { users, err := database.Handle.Users().ListFollowings(c.Req.Context(), u.ID, c.QueryInt("page"), database.ItemsPerPage) if err != nil { c.Error(err, "list followings") return } responseAPIUsers(c, users) } func ListMyFollowing(c *context.APIContext) { listUserFollowing(c, c.User) } func ListFollowing(c *context.APIContext) { u := GetUserByParams(c) if c.Written() { return } listUserFollowing(c, u) } func checkUserFollowing(c *context.APIContext, u *database.User, followID int64) { if database.Handle.Users().IsFollowing(c.Req.Context(), u.ID, followID) { c.NoContent() } else { c.NotFound() } } func CheckMyFollowing(c *context.APIContext) { target := GetUserByParams(c) if c.Written() { return } checkUserFollowing(c, c.User, target.ID) } func CheckFollowing(c *context.APIContext) { u := GetUserByParams(c) if c.Written() { return } target := GetUserByParamsName(c, ":target") if c.Written() { return } checkUserFollowing(c, u, target.ID) } func Follow(c *context.APIContext) { target := GetUserByParams(c) if c.Written() { return } if err := database.Handle.Users().Follow(c.Req.Context(), c.User.ID, target.ID); err != nil { c.Error(err, "follow user") return } c.NoContent() } func Unfollow(c *context.APIContext) { target := GetUserByParams(c) if c.Written() { return } if err := database.Handle.Users().Unfollow(c.Req.Context(), c.User.ID, target.ID); err != nil { c.Error(err, "unfollow user") return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/user/email.go
internal/route/api/v1/user/email.go
// Copyright 2015 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 user import ( "net/http" api "github.com/gogs/go-gogs-client" "github.com/pkg/errors" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/route/api/v1/convert" ) func ListEmails(c *context.APIContext) { emails, err := database.Handle.Users().ListEmails(c.Req.Context(), c.User.ID) if err != nil { c.Error(err, "get email addresses") return } apiEmails := make([]*api.Email, len(emails)) for i := range emails { apiEmails[i] = convert.ToEmail(emails[i]) } c.JSONSuccess(&apiEmails) } func AddEmail(c *context.APIContext, form api.CreateEmailOption) { if len(form.Emails) == 0 { c.Status(http.StatusUnprocessableEntity) return } apiEmails := make([]*api.Email, 0, len(form.Emails)) for _, email := range form.Emails { err := database.Handle.Users().AddEmail(c.Req.Context(), c.User.ID, email, !conf.Auth.RequireEmailConfirmation) if err != nil { if database.IsErrEmailAlreadyUsed(err) { c.ErrorStatus(http.StatusUnprocessableEntity, errors.Errorf("email address has been used: %s", err.(database.ErrEmailAlreadyUsed).Email())) } else { c.Error(err, "add email addresses") } return } apiEmails = append(apiEmails, &api.Email{ Email: email, Verified: !conf.Auth.RequireEmailConfirmation, }, ) } c.JSON(http.StatusCreated, &apiEmails) } func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) { for _, email := range form.Emails { if email == c.User.Email { c.ErrorStatus(http.StatusBadRequest, errors.Errorf("cannot delete primary email %q", email)) return } err := database.Handle.Users().DeleteEmail(c.Req.Context(), c.User.ID, email) if err != nil { c.Error(err, "delete email addresses") return } } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/user/user.go
internal/route/api/v1/user/user.go
// Copyright 2014 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 user import ( "net/http" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/markup" ) func Search(c *context.APIContext) { pageSize := c.QueryInt("limit") if pageSize <= 0 { pageSize = 10 } users, _, err := database.Handle.Users().SearchByName(c.Req.Context(), c.Query("q"), 1, pageSize, "") if err != nil { c.JSON(http.StatusInternalServerError, map[string]any{ "ok": false, "error": err.Error(), }) return } results := make([]*api.User, len(users)) for i := range users { results[i] = &api.User{ ID: users[i].ID, UserName: users[i].Name, AvatarUrl: users[i].AvatarURL(), FullName: markup.Sanitize(users[i].FullName), } if c.IsLogged { results[i].Email = users[i].Email } } c.JSONSuccess(map[string]any{ "ok": true, "data": results, }) } func GetInfo(c *context.APIContext) { u, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":username")) if err != nil { c.NotFoundOrError(err, "get user by name") return } // Hide user e-mail when API caller isn't signed in. if !c.IsLogged { u.Email = "" } c.JSONSuccess(u.APIFormat()) } func GetAuthenticatedUser(c *context.APIContext) { c.JSONSuccess(c.User.APIFormat()) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/user/key.go
internal/route/api/v1/user/key.go
// Copyright 2015 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 user import ( "net/http" api "github.com/gogs/go-gogs-client" "github.com/pkg/errors" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/route/api/v1/convert" "gogs.io/gogs/internal/route/api/v1/repo" ) func GetUserByParamsName(c *context.APIContext, name string) *database.User { user, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(name)) if err != nil { c.NotFoundOrError(err, "get user by name") return nil } return user } // GetUserByParams returns user whose name is presented in URL parameter. func GetUserByParams(c *context.APIContext) *database.User { return GetUserByParamsName(c, ":username") } func composePublicKeysAPILink() string { return conf.Server.ExternalURL + "api/v1/user/keys/" } func listPublicKeys(c *context.APIContext, uid int64) { keys, err := database.ListPublicKeys(uid) if err != nil { c.Error(err, "list public keys") return } apiLink := composePublicKeysAPILink() apiKeys := make([]*api.PublicKey, len(keys)) for i := range keys { apiKeys[i] = convert.ToPublicKey(apiLink, keys[i]) } c.JSONSuccess(&apiKeys) } func ListMyPublicKeys(c *context.APIContext) { listPublicKeys(c, c.User.ID) } func ListPublicKeys(c *context.APIContext) { user := GetUserByParams(c) if c.Written() { return } listPublicKeys(c, user.ID) } func GetPublicKey(c *context.APIContext) { key, err := database.GetPublicKeyByID(c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get public key by ID") return } apiLink := composePublicKeysAPILink() c.JSONSuccess(convert.ToPublicKey(apiLink, key)) } // CreateUserPublicKey creates new public key to given user by ID. func CreateUserPublicKey(c *context.APIContext, form api.CreateKeyOption, uid int64) { content, err := database.CheckPublicKeyString(form.Key) if err != nil { repo.HandleCheckKeyStringError(c, err) return } key, err := database.AddPublicKey(uid, form.Title, content) if err != nil { repo.HandleAddKeyError(c, err) return } apiLink := composePublicKeysAPILink() c.JSON(http.StatusCreated, convert.ToPublicKey(apiLink, key)) } func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) { CreateUserPublicKey(c, form, c.User.ID) } func DeletePublicKey(c *context.APIContext) { if err := database.DeletePublicKey(c.User, c.ParamsInt64(":id")); err != nil { if database.IsErrKeyAccessDenied(err) { c.ErrorStatus(http.StatusForbidden, errors.New("You do not have access to this key.")) } else { c.Error(err, "delete public key") } return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/admin/org_repo.go
internal/route/api/v1/admin/org_repo.go
// Copyright 2016 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 admin import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) func GetRepositoryByParams(c *context.APIContext) *database.Repository { repo, err := database.GetRepositoryByName(c.Org.Team.OrgID, c.Params(":reponame")) if err != nil { c.NotFoundOrError(err, "get repository by name") return nil } return repo } func AddTeamRepository(c *context.APIContext) { repo := GetRepositoryByParams(c) if c.Written() { return } if err := c.Org.Team.AddRepository(repo); err != nil { c.Error(err, "add repository") return } c.NoContent() } func RemoveTeamRepository(c *context.APIContext) { repo := GetRepositoryByParams(c) if c.Written() { return } if err := c.Org.Team.RemoveRepository(repo.ID); err != nil { c.Error(err, "remove repository") return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/admin/org_team.go
internal/route/api/v1/admin/org_team.go
// Copyright 2016 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 admin import ( "net/http" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/route/api/v1/convert" "gogs.io/gogs/internal/route/api/v1/user" ) func CreateTeam(c *context.APIContext, form api.CreateTeamOption) { team := &database.Team{ OrgID: c.Org.Organization.ID, Name: form.Name, Description: form.Description, Authorize: database.ParseAccessMode(form.Permission), } if err := database.NewTeam(team); err != nil { if database.IsErrTeamAlreadyExist(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "new team") } return } c.JSON(http.StatusCreated, convert.ToTeam(team)) } func AddTeamMember(c *context.APIContext) { u := user.GetUserByParams(c) if c.Written() { return } if err := c.Org.Team.AddMember(u.ID); err != nil { c.Error(err, "add member") return } c.NoContent() } func RemoveTeamMember(c *context.APIContext) { u := user.GetUserByParams(c) if c.Written() { return } if err := c.Org.Team.RemoveMember(u.ID); err != nil { c.Error(err, "remove member") return } c.NoContent() } func ListTeamMembers(c *context.APIContext) { team := c.Org.Team if err := team.GetMembers(); err != nil { c.Error(err, "get team members") return } apiMembers := make([]*api.User, len(team.Members)) for i := range team.Members { apiMembers[i] = team.Members[i].APIFormat() } c.JSONSuccess(apiMembers) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/admin/repo.go
internal/route/api/v1/admin/repo.go
// Copyright 2015 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 admin import ( api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/route/api/v1/repo" "gogs.io/gogs/internal/route/api/v1/user" ) func CreateRepo(c *context.APIContext, form api.CreateRepoOption) { owner := user.GetUserByParams(c) if c.Written() { return } repo.CreateUserRepo(c, owner, form) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/admin/user.go
internal/route/api/v1/admin/user.go
// Copyright 2015 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 admin import ( "net/http" api "github.com/gogs/go-gogs-client" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/email" "gogs.io/gogs/internal/route/api/v1/user" ) func parseLoginSource(c *context.APIContext, sourceID int64) { if sourceID == 0 { return } _, err := database.Handle.LoginSources().GetByID(c.Req.Context(), sourceID) if err != nil { if database.IsErrLoginSourceNotExist(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "get login source by ID") } return } } func CreateUser(c *context.APIContext, form api.CreateUserOption) { parseLoginSource(c, form.SourceID) if c.Written() { return } user, err := database.Handle.Users().Create( c.Req.Context(), form.Username, form.Email, database.CreateUserOptions{ FullName: form.FullName, Password: form.Password, LoginSource: form.SourceID, LoginName: form.LoginName, Activated: true, }, ) if err != nil { if database.IsErrUserAlreadyExist(err) || database.IsErrEmailAlreadyUsed(err) || database.IsErrNameNotAllowed(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "create user") } return } log.Trace("Account %q created by admin %q", user.Name, c.User.Name) // Send email notification. if form.SendNotify && conf.Email.Enabled { email.SendRegisterNotifyMail(c.Context.Context, database.NewMailerUser(user)) } c.JSON(http.StatusCreated, user.APIFormat()) } func EditUser(c *context.APIContext, form api.EditUserOption) { u := user.GetUserByParams(c) if c.Written() { return } parseLoginSource(c, form.SourceID) if c.Written() { return } opts := database.UpdateUserOptions{ LoginSource: &form.SourceID, LoginName: &form.LoginName, FullName: &form.FullName, Website: &form.Website, Location: &form.Location, MaxRepoCreation: form.MaxRepoCreation, IsActivated: form.Active, IsAdmin: form.Admin, AllowGitHook: form.AllowGitHook, AllowImportLocal: form.AllowImportLocal, ProhibitLogin: nil, // TODO: Add this option to API } if form.Password != "" { opts.Password = &form.Password } if u.Email != form.Email { opts.Email = &form.Email } err := database.Handle.Users().Update(c.Req.Context(), u.ID, opts) if err != nil { if database.IsErrEmailAlreadyUsed(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "update user") } return } log.Trace("Account updated by admin %q: %s", c.User.Name, u.Name) u, err = database.Handle.Users().GetByID(c.Req.Context(), u.ID) if err != nil { c.Error(err, "get user") return } c.JSONSuccess(u.APIFormat()) } func DeleteUser(c *context.APIContext) { u := user.GetUserByParams(c) if c.Written() { return } if err := database.Handle.Users().DeleteByID(c.Req.Context(), u.ID, false); err != nil { if database.IsErrUserOwnRepos(err) || database.IsErrUserHasOrgs(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "delete user") } return } log.Trace("Account deleted by admin(%s): %s", c.User.Name, u.Name) c.NoContent() } func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) { u := user.GetUserByParams(c) if c.Written() { return } user.CreateUserPublicKey(c, form, u.ID) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/admin/org.go
internal/route/api/v1/admin/org.go
// Copyright 2015 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 admin import ( api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/route/api/v1/org" "gogs.io/gogs/internal/route/api/v1/user" ) func CreateOrg(c *context.APIContext, form api.CreateOrgOption) { org.CreateOrgForUser(c, form, user.GetUserByParams(c)) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/contents.go
internal/route/api/v1/repo/contents.go
// Copyright 2020 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 ( "encoding/base64" "fmt" "net/http" "path" "github.com/gogs/git-module" "github.com/pkg/errors" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/pathutil" "gogs.io/gogs/internal/repoutil" ) type links struct { Git string `json:"git"` Self string `json:"self"` HTML string `json:"html"` } type repoContent struct { Type string `json:"type"` Target string `json:"target,omitempty"` SubmoduleGitURL string `json:"submodule_git_url,omitempty"` Encoding string `json:"encoding,omitempty"` Size int64 `json:"size"` Name string `json:"name"` Path string `json:"path"` Content string `json:"content,omitempty"` Sha string `json:"sha"` URL string `json:"url"` GitURL string `json:"git_url"` HTMLURL string `json:"html_url"` DownloadURL string `json:"download_url"` Links links `json:"_links"` } func toRepoContent(c *context.APIContext, ref, subpath string, commit *git.Commit, entry *git.TreeEntry) (*repoContent, error) { repoURL := fmt.Sprintf("%s/repos/%s/%s", c.BaseURL, c.Params(":username"), c.Params(":reponame")) selfURL := fmt.Sprintf("%s/contents/%s", repoURL, subpath) htmlURL := fmt.Sprintf("%s/src/%s/%s", repoutil.HTMLURL(c.Repo.Owner.Name, c.Repo.Repository.Name), ref, entry.Name()) downloadURL := fmt.Sprintf("%s/raw/%s/%s", repoutil.HTMLURL(c.Repo.Owner.Name, c.Repo.Repository.Name), ref, entry.Name()) content := &repoContent{ Size: entry.Size(), Name: entry.Name(), Path: subpath, Sha: entry.ID().String(), URL: selfURL, HTMLURL: htmlURL, DownloadURL: downloadURL, Links: links{ Self: selfURL, HTML: htmlURL, }, } switch { case entry.IsBlob(), entry.IsExec(): content.Type = "file" p, err := entry.Blob().Bytes() if err != nil { return nil, errors.Wrap(err, "get blob content") } content.Encoding = "base64" content.Content = base64.StdEncoding.EncodeToString(p) content.GitURL = fmt.Sprintf("%s/git/blobs/%s", repoURL, entry.ID().String()) case entry.IsTree(): content.Type = "dir" content.GitURL = fmt.Sprintf("%s/git/trees/%s", repoURL, entry.ID().String()) case entry.IsSymlink(): content.Type = "symlink" p, err := entry.Blob().Bytes() if err != nil { return nil, errors.Wrap(err, "get blob content") } content.Target = string(p) case entry.IsCommit(): content.Type = "submodule" mod, err := commit.Submodule(subpath) if err != nil { return nil, errors.Wrap(err, "get submodule") } content.SubmoduleGitURL = mod.URL default: panic("unreachable") } content.Links.Git = content.GitURL return content, nil } func GetContents(c *context.APIContext) { repoPath := repoutil.RepositoryPath(c.Params(":username"), c.Params(":reponame")) gitRepo, err := git.Open(repoPath) if err != nil { c.Error(err, "open repository") return } ref := c.Query("ref") if ref == "" { ref = c.Repo.Repository.DefaultBranch } commit, err := gitRepo.CatFileCommit(ref) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get commit") return } // 🚨 SECURITY: Prevent path traversal. treePath := pathutil.Clean(c.Params("*")) entry, err := commit.TreeEntry(treePath) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get tree entry") return } if !entry.IsTree() { content, err := toRepoContent(c, ref, treePath, commit, entry) if err != nil { c.Errorf(err, "convert %q to repoContent", treePath) return } c.JSONSuccess(content) return } // The entry is a directory dir, err := gitRepo.LsTree(entry.ID().String()) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get tree") return } entries, err := dir.Entries() if err != nil { c.NotFoundOrError(gitutil.NewError(err), "list entries") return } if len(entries) == 0 { c.JSONSuccess([]string{}) return } contents := make([]*repoContent, 0, len(entries)) for _, entry := range entries { subpath := path.Join(treePath, entry.Name()) content, err := toRepoContent(c, ref, subpath, commit, entry) if err != nil { c.Errorf(err, "convert %q to repoContent", subpath) return } contents = append(contents, content) } c.JSONSuccess(contents) } // PutContentsRequest is the API message for creating or updating a file. type PutContentsRequest struct { Message string `json:"message" binding:"Required"` Content string `json:"content" binding:"Required"` Branch string `json:"branch"` } // PUT /repos/:username/:reponame/contents/* func PutContents(c *context.APIContext, r PutContentsRequest) { content, err := base64.StdEncoding.DecodeString(r.Content) if err != nil { c.Error(err, "decoding base64") return } if r.Branch == "" { r.Branch = c.Repo.Repository.DefaultBranch } // 🚨 SECURITY: Prevent path traversal. treePath := pathutil.Clean(c.Params("*")) err = c.Repo.Repository.UpdateRepoFile( c.User, database.UpdateRepoFileOptions{ OldBranch: c.Repo.Repository.DefaultBranch, NewBranch: r.Branch, OldTreeName: treePath, NewTreeName: treePath, Message: r.Message, Content: string(content), }, ) if err != nil { c.Error(err, "updating repository file") return } repoPath := repoutil.RepositoryPath(c.Params(":username"), c.Params(":reponame")) gitRepo, err := git.Open(repoPath) if err != nil { c.Error(err, "open repository") return } commit, err := gitRepo.CatFileCommit(r.Branch) if err != nil { c.Error(err, "get file commit") return } entry, err := commit.TreeEntry(treePath) if err != nil { c.Error(err, "get tree entry") return } apiContent, err := toRepoContent(c, r.Branch, treePath, commit, entry) if err != nil { c.Error(err, "convert to *repoContent") return } apiCommit, err := gitCommitToAPICommit(commit, c) if err != nil { c.Error(err, "convert to *api.Commit") return } c.JSON( http.StatusCreated, map[string]any{ "content": apiContent, "commit": apiCommit, }, ) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/hook.go
internal/route/api/v1/repo/hook.go
// Copyright 2014 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 ( "net/http" jsoniter "github.com/json-iterator/go" "github.com/pkg/errors" "github.com/unknwon/com" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/route/api/v1/convert" ) // https://github.com/gogs/go-gogs-client/wiki/Repositories#list-hooks func ListHooks(c *context.APIContext) { hooks, err := database.GetWebhooksByRepoID(c.Repo.Repository.ID) if err != nil { c.Errorf(err, "get webhooks by repository ID") return } apiHooks := make([]*api.Hook, len(hooks)) for i := range hooks { apiHooks[i] = convert.ToHook(c.Repo.RepoLink, hooks[i]) } c.JSONSuccess(&apiHooks) } // https://github.com/gogs/go-gogs-client/wiki/Repositories#create-a-hook func CreateHook(c *context.APIContext, form api.CreateHookOption) { if !database.IsValidHookTaskType(form.Type) { c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Invalid hook type.")) return } for _, name := range []string{"url", "content_type"} { if _, ok := form.Config[name]; !ok { c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Missing config option: "+name)) return } } if !database.IsValidHookContentType(form.Config["content_type"]) { c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Invalid content type.")) return } if len(form.Events) == 0 { form.Events = []string{"push"} } w := &database.Webhook{ RepoID: c.Repo.Repository.ID, URL: form.Config["url"], ContentType: database.ToHookContentType(form.Config["content_type"]), Secret: form.Config["secret"], HookEvent: &database.HookEvent{ ChooseEvents: true, HookEvents: database.HookEvents{ Create: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeCreate)), Delete: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeDelete)), Fork: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeFork)), Push: com.IsSliceContainsStr(form.Events, string(database.HookEventTypePush)), Issues: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeIssues)), IssueComment: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeIssueComment)), PullRequest: com.IsSliceContainsStr(form.Events, string(database.HookEventTypePullRequest)), Release: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeRelease)), }, }, IsActive: form.Active, HookTaskType: database.ToHookTaskType(form.Type), } if w.HookTaskType == database.SLACK { channel, ok := form.Config["channel"] if !ok { c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Missing config option: channel")) return } meta, err := jsoniter.Marshal(&database.SlackMeta{ Channel: channel, Username: form.Config["username"], IconURL: form.Config["icon_url"], Color: form.Config["color"], }) if err != nil { c.Errorf(err, "marshal JSON") return } w.Meta = string(meta) } if err := w.UpdateEvent(); err != nil { c.Errorf(err, "update event") return } else if err := database.CreateWebhook(w); err != nil { c.Errorf(err, "create webhook") return } c.JSON(http.StatusCreated, convert.ToHook(c.Repo.RepoLink, w)) } // https://github.com/gogs/go-gogs-client/wiki/Repositories#edit-a-hook func EditHook(c *context.APIContext, form api.EditHookOption) { w, err := database.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get webhook of repository by ID") return } if form.Config != nil { if url, ok := form.Config["url"]; ok { w.URL = url } if ct, ok := form.Config["content_type"]; ok { if !database.IsValidHookContentType(ct) { c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Invalid content type.")) return } w.ContentType = database.ToHookContentType(ct) } if w.HookTaskType == database.SLACK { if channel, ok := form.Config["channel"]; ok { meta, err := jsoniter.Marshal(&database.SlackMeta{ Channel: channel, Username: form.Config["username"], IconURL: form.Config["icon_url"], Color: form.Config["color"], }) if err != nil { c.Errorf(err, "marshal JSON") return } w.Meta = string(meta) } } } // Update events if len(form.Events) == 0 { form.Events = []string{"push"} } w.PushOnly = false w.SendEverything = false w.ChooseEvents = true w.Create = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeCreate)) w.Delete = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeDelete)) w.Fork = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeFork)) w.Push = com.IsSliceContainsStr(form.Events, string(database.HookEventTypePush)) w.Issues = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeIssues)) w.IssueComment = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeIssueComment)) w.PullRequest = com.IsSliceContainsStr(form.Events, string(database.HookEventTypePullRequest)) w.Release = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeRelease)) if err = w.UpdateEvent(); err != nil { c.Errorf(err, "update event") return } if form.Active != nil { w.IsActive = *form.Active } if err := database.UpdateWebhook(w); err != nil { c.Errorf(err, "update webhook") return } c.JSONSuccess(convert.ToHook(c.Repo.RepoLink, w)) } func DeleteHook(c *context.APIContext) { if err := database.DeleteWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil { c.Errorf(err, "delete webhook of repository by ID") return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/tree.go
internal/route/api/v1/repo/tree.go
// Copyright 2020 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 ( "fmt" "github.com/gogs/git-module" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/gitutil" ) func GetRepoGitTree(c *context.APIContext) { gitRepo, err := git.Open(c.Repo.Repository.RepoPath()) if err != nil { c.Error(err, "open repository") return } sha := c.Params(":sha") tree, err := gitRepo.LsTree(sha) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get tree") return } entries, err := tree.Entries() if err != nil { c.Error(err, "list entries") return } type repoGitTreeEntry struct { Path string `json:"path"` Mode string `json:"mode"` Type string `json:"type"` Size int64 `json:"size"` Sha string `json:"sha"` URL string `json:"url"` } type repoGitTree struct { Sha string `json:"sha"` URL string `json:"url"` Tree []*repoGitTreeEntry `json:"tree"` } treesURL := fmt.Sprintf("%s/repos/%s/%s/git/trees", c.BaseURL, c.Params(":username"), c.Params(":reponame")) if len(entries) == 0 { c.JSONSuccess(&repoGitTree{ Sha: sha, URL: fmt.Sprintf(treesURL+"/%s", sha), }) return } children := make([]*repoGitTreeEntry, 0, len(entries)) for _, entry := range entries { var mode string switch entry.Type() { case git.ObjectCommit: mode = "160000" case git.ObjectTree: mode = "040000" case git.ObjectBlob: mode = "120000" case git.ObjectTag: mode = "100644" default: panic("unreachable") } children = append(children, &repoGitTreeEntry{ Path: entry.Name(), Mode: mode, Type: string(entry.Type()), Size: entry.Size(), Sha: entry.ID().String(), URL: fmt.Sprintf(treesURL+"/%s", entry.ID().String()), }) } c.JSONSuccess(&repoGitTree{ Sha: c.Params(":sha"), URL: fmt.Sprintf(treesURL+"/%s", sha), Tree: children, }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/milestone.go
internal/route/api/v1/repo/milestone.go
// Copyright 2016 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 ( "net/http" "time" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) func ListMilestones(c *context.APIContext) { milestones, err := database.GetMilestonesByRepoID(c.Repo.Repository.ID) if err != nil { c.Error(err, "get milestones by repository ID") return } apiMilestones := make([]*api.Milestone, len(milestones)) for i := range milestones { apiMilestones[i] = milestones[i].APIFormat() } c.JSONSuccess(&apiMilestones) } func GetMilestone(c *context.APIContext) { milestone, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get milestone by repository ID") return } c.JSONSuccess(milestone.APIFormat()) } func CreateMilestone(c *context.APIContext, form api.CreateMilestoneOption) { if form.Deadline == nil { defaultDeadline, _ := time.ParseInLocation("2006-01-02", "9999-12-31", time.Local) form.Deadline = &defaultDeadline } milestone := &database.Milestone{ RepoID: c.Repo.Repository.ID, Name: form.Title, Content: form.Description, Deadline: *form.Deadline, } if err := database.NewMilestone(milestone); err != nil { c.Error(err, "new milestone") return } c.JSON(http.StatusCreated, milestone.APIFormat()) } func EditMilestone(c *context.APIContext, form api.EditMilestoneOption) { milestone, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get milestone by repository ID") return } if len(form.Title) > 0 { milestone.Name = form.Title } if form.Description != nil { milestone.Content = *form.Description } if form.Deadline != nil && !form.Deadline.IsZero() { milestone.Deadline = *form.Deadline } if form.State != nil { if err = milestone.ChangeStatus(api.STATE_CLOSED == api.StateType(*form.State)); err != nil { c.Error(err, "change status") return } } else if err = database.UpdateMilestone(milestone); err != nil { c.Error(err, "update milestone") return } c.JSONSuccess(milestone.APIFormat()) } func DeleteMilestone(c *context.APIContext) { if err := database.DeleteMilestoneOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil { c.Error(err, "delete milestone of repository by ID") return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/file.go
internal/route/api/v1/repo/file.go
// Copyright 2014 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 ( "github.com/gogs/git-module" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/route/repo" ) func GetRawFile(c *context.APIContext) { if !c.Repo.HasAccess() { c.NotFound() return } if c.Repo.Repository.IsBare { c.NotFound() return } blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get blob") return } if err = repo.ServeBlob(c.Context, blob); err != nil { c.Error(err, "serve blob") } } func GetArchive(c *context.APIContext) { repoPath := database.RepoPath(c.Params(":username"), c.Params(":reponame")) gitRepo, err := git.Open(repoPath) if err != nil { c.Error(err, "open repository") return } c.Repo.GitRepo = gitRepo repo.Download(c.Context) } func GetEditorconfig(c *context.APIContext) { ec, err := c.Repo.Editorconfig() if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get .editorconfig") return } fileName := c.Params("filename") def, err := ec.GetDefinitionForFilename(fileName) if err != nil { c.Error(err, "get definition for filename") return } if def == nil { c.NotFound() return } c.JSONSuccess(def) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/issue_comment.go
internal/route/api/v1/repo/issue_comment.go
// Copyright 2015 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 ( "net/http" "time" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) func ListIssueComments(c *context.APIContext) { var since time.Time if len(c.Query("since")) > 0 { var err error since, err = time.Parse(time.RFC3339, c.Query("since")) if err != nil { c.ErrorStatus(http.StatusUnprocessableEntity, err) return } } // comments,err:=db.GetCommentsByIssueIDSince(, since) issue, err := database.GetRawIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.Error(err, "get raw issue by index") return } comments, err := database.GetCommentsByIssueIDSince(issue.ID, since.Unix()) if err != nil { c.Error(err, "get comments by issue ID") return } apiComments := make([]*api.Comment, len(comments)) for i := range comments { apiComments[i] = comments[i].APIFormat() } c.JSONSuccess(&apiComments) } func ListRepoIssueComments(c *context.APIContext) { var since time.Time if len(c.Query("since")) > 0 { var err error since, err = time.Parse(time.RFC3339, c.Query("since")) if err != nil { c.ErrorStatus(http.StatusUnprocessableEntity, err) return } } comments, err := database.GetCommentsByRepoIDSince(c.Repo.Repository.ID, since.Unix()) if err != nil { c.Error(err, "get comments by repository ID") return } apiComments := make([]*api.Comment, len(comments)) for i := range comments { apiComments[i] = comments[i].APIFormat() } c.JSONSuccess(&apiComments) } func CreateIssueComment(c *context.APIContext, form api.CreateIssueCommentOption) { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.Error(err, "get issue by index") return } comment, err := database.CreateIssueComment(c.User, c.Repo.Repository, issue, form.Body, nil) if err != nil { c.Error(err, "create issue comment") return } c.JSON(http.StatusCreated, comment.APIFormat()) } func EditIssueComment(c *context.APIContext, form api.EditIssueCommentOption) { comment, err := database.GetCommentByID(c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get comment by ID") return } if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() { c.Status(http.StatusForbidden) return } else if comment.Type != database.CommentTypeComment { c.NoContent() return } oldContent := comment.Content comment.Content = form.Body if err := database.UpdateComment(c.User, comment, oldContent); err != nil { c.Error(err, "update comment") return } c.JSONSuccess(comment.APIFormat()) } func DeleteIssueComment(c *context.APIContext) { comment, err := database.GetCommentByID(c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get comment by ID") return } if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() { c.Status(http.StatusForbidden) return } else if comment.Type != database.CommentTypeComment { c.NoContent() return } if err = database.DeleteCommentByID(c.User, comment.ID); err != nil { c.Error(err, "delete comment by ID") return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/issue.go
internal/route/api/v1/repo/issue.go
// Copyright 2016 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 ( "fmt" "net/http" "strings" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) func listIssues(c *context.APIContext, opts *database.IssuesOptions) { issues, err := database.Issues(opts) if err != nil { c.Error(err, "list issues") return } count, err := database.IssuesCount(opts) if err != nil { c.Error(err, "count issues") return } // FIXME: use IssueList to improve performance. apiIssues := make([]*api.Issue, len(issues)) for i := range issues { if err = issues[i].LoadAttributes(); err != nil { c.Error(err, "load attributes") return } apiIssues[i] = issues[i].APIFormat() } c.SetLinkHeader(int(count), conf.UI.IssuePagingNum) c.JSONSuccess(&apiIssues) } func ListUserIssues(c *context.APIContext) { opts := database.IssuesOptions{ AssigneeID: c.User.ID, Page: c.QueryInt("page"), IsClosed: api.StateType(c.Query("state")) == api.STATE_CLOSED, } listIssues(c, &opts) } func ListIssues(c *context.APIContext) { opts := database.IssuesOptions{ RepoID: c.Repo.Repository.ID, Page: c.QueryInt("page"), IsClosed: api.StateType(c.Query("state")) == api.STATE_CLOSED, } listIssues(c, &opts) } func GetIssue(c *context.APIContext) { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return } c.JSONSuccess(issue.APIFormat()) } func CreateIssue(c *context.APIContext, form api.CreateIssueOption) { issue := &database.Issue{ RepoID: c.Repo.Repository.ID, Title: form.Title, PosterID: c.User.ID, Poster: c.User, Content: form.Body, } if c.Repo.IsWriter() { if len(form.Assignee) > 0 { assignee, err := database.Handle.Users().GetByUsername(c.Req.Context(), form.Assignee) if err != nil { if database.IsErrUserNotExist(err) { c.ErrorStatus(http.StatusUnprocessableEntity, fmt.Errorf("assignee does not exist: [name: %s]", form.Assignee)) } else { c.Error(err, "get user by name") } return } issue.AssigneeID = assignee.ID } issue.MilestoneID = form.Milestone } else { form.Labels = nil } if err := database.NewIssue(c.Repo.Repository, issue, form.Labels, nil); err != nil { c.Error(err, "new issue") return } if form.Closed { if err := issue.ChangeStatus(c.User, c.Repo.Repository, true); err != nil { c.Error(err, "change status to closed") return } } // Refetch from database to assign some automatic values var err error issue, err = database.GetIssueByID(issue.ID) if err != nil { c.Error(err, "get issue by ID") return } c.JSON(http.StatusCreated, issue.APIFormat()) } func EditIssue(c *context.APIContext, form api.EditIssueOption) { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return } if !issue.IsPoster(c.User.ID) && !c.Repo.IsWriter() { c.Status(http.StatusForbidden) return } if len(form.Title) > 0 { issue.Title = form.Title } if form.Body != nil { issue.Content = *form.Body } if c.Repo.IsWriter() && form.Assignee != nil && (issue.Assignee == nil || issue.Assignee.LowerName != strings.ToLower(*form.Assignee)) { if *form.Assignee == "" { issue.AssigneeID = 0 } else { assignee, err := database.Handle.Users().GetByUsername(c.Req.Context(), *form.Assignee) if err != nil { if database.IsErrUserNotExist(err) { c.ErrorStatus(http.StatusUnprocessableEntity, fmt.Errorf("assignee does not exist: [name: %s]", *form.Assignee)) } else { c.Error(err, "get user by name") } return } issue.AssigneeID = assignee.ID } if err = database.UpdateIssueUserByAssignee(issue); err != nil { c.Error(err, "update issue user by assignee") return } } if c.Repo.IsWriter() && form.Milestone != nil && issue.MilestoneID != *form.Milestone { oldMilestoneID := issue.MilestoneID issue.MilestoneID = *form.Milestone if err = database.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil { c.Error(err, "change milestone assign") return } } if err = database.UpdateIssue(issue); err != nil { c.Error(err, "update issue") return } if form.State != nil { if err = issue.ChangeStatus(c.User, c.Repo.Repository, api.STATE_CLOSED == api.StateType(*form.State)); err != nil { c.Error(err, "change status") return } } // Refetch from database to assign some automatic values issue, err = database.GetIssueByID(issue.ID) if err != nil { c.Error(err, "get issue by ID") return } c.JSON(http.StatusCreated, issue.APIFormat()) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/collaborators.go
internal/route/api/v1/repo/collaborators.go
// Copyright 2016 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 ( "net/http" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) func ListCollaborators(c *context.APIContext) { collaborators, err := c.Repo.Repository.GetCollaborators() if err != nil { c.Error(err, "get collaborators") return } apiCollaborators := make([]*api.Collaborator, len(collaborators)) for i := range collaborators { apiCollaborators[i] = collaborators[i].APIFormat() } c.JSONSuccess(&apiCollaborators) } func AddCollaborator(c *context.APIContext, form api.AddCollaboratorOption) { collaborator, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":collaborator")) if err != nil { if database.IsErrUserNotExist(err) { c.Status(http.StatusUnprocessableEntity) } else { c.Error(err, "get user by name") } return } if err := c.Repo.Repository.AddCollaborator(collaborator); err != nil { c.Error(err, "add collaborator") return } if form.Permission != nil { if err := c.Repo.Repository.ChangeCollaborationAccessMode(collaborator.ID, database.ParseAccessMode(*form.Permission)); err != nil { c.Error(err, "change collaboration access mode") return } } c.NoContent() } func IsCollaborator(c *context.APIContext) { collaborator, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":collaborator")) if err != nil { if database.IsErrUserNotExist(err) { c.Status(http.StatusUnprocessableEntity) } else { c.Error(err, "get user by name") } return } if !c.Repo.Repository.IsCollaborator(collaborator.ID) { c.NotFound() } else { c.NoContent() } } func DeleteCollaborator(c *context.APIContext) { collaborator, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":collaborator")) if err != nil { if database.IsErrUserNotExist(err) { c.Status(http.StatusUnprocessableEntity) } else { c.Error(err, "get user by name") } return } if err := c.Repo.Repository.DeleteCollaboration(collaborator.ID); err != nil { c.Error(err, "delete collaboration") return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/repo.go
internal/route/api/v1/repo/repo.go
// Copyright 2014 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 ( "net/http" "path" api "github.com/gogs/go-gogs-client" "github.com/pkg/errors" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/route/api/v1/convert" ) func Search(c *context.APIContext) { opts := &database.SearchRepoOptions{ Keyword: path.Base(c.Query("q")), OwnerID: c.QueryInt64("uid"), PageSize: convert.ToCorrectPageSize(c.QueryInt("limit")), Page: c.QueryInt("page"), } // Check visibility. if c.IsLogged && opts.OwnerID > 0 { if c.User.ID == opts.OwnerID { opts.Private = true } else { u, err := database.Handle.Users().GetByID(c.Req.Context(), opts.OwnerID) if err != nil { c.JSON(http.StatusInternalServerError, map[string]any{ "ok": false, "error": err.Error(), }) return } if u.IsOrganization() && u.IsOwnedBy(c.User.ID) { opts.Private = true } // FIXME: how about collaborators? } } repos, count, err := database.SearchRepositoryByName(opts) if err != nil { c.JSON(http.StatusInternalServerError, map[string]any{ "ok": false, "error": err.Error(), }) return } if err = database.RepositoryList(repos).LoadAttributes(); err != nil { c.JSON(http.StatusInternalServerError, map[string]any{ "ok": false, "error": err.Error(), }) return } results := make([]*api.Repository, len(repos)) for i := range repos { results[i] = repos[i].APIFormatLegacy(nil) } c.SetLinkHeader(int(count), opts.PageSize) c.JSONSuccess(map[string]any{ "ok": true, "data": results, }) } func listUserRepositories(c *context.APIContext, username string) { user, err := database.Handle.Users().GetByUsername(c.Req.Context(), username) if err != nil { c.NotFoundOrError(err, "get user by name") return } // Only list public repositories if user requests someone else's repository list, // or an organization isn't a member of. var ownRepos []*database.Repository if user.IsOrganization() { ownRepos, _, err = user.GetUserRepositories(c.User.ID, 1, user.NumRepos) } else { ownRepos, err = database.GetUserRepositories(&database.UserRepoOptions{ UserID: user.ID, Private: c.User.ID == user.ID, Page: 1, PageSize: user.NumRepos, }) } if err != nil { c.Error(err, "get user repositories") return } if err = database.RepositoryList(ownRepos).LoadAttributes(); err != nil { c.Error(err, "load attributes") return } // Early return for querying other user's repositories if c.User.ID != user.ID { repos := make([]*api.Repository, len(ownRepos)) for i := range ownRepos { repos[i] = ownRepos[i].APIFormatLegacy(&api.Permission{Admin: true, Push: true, Pull: true}) } c.JSONSuccess(&repos) return } accessibleRepos, err := database.Handle.Repositories().GetByCollaboratorIDWithAccessMode(c.Req.Context(), user.ID) if err != nil { c.Error(err, "get repositories accesses by collaborator") return } numOwnRepos := len(ownRepos) repos := make([]*api.Repository, 0, numOwnRepos+len(accessibleRepos)) for _, r := range ownRepos { repos = append(repos, r.APIFormatLegacy(&api.Permission{Admin: true, Push: true, Pull: true})) } for repo, access := range accessibleRepos { repos = append(repos, repo.APIFormatLegacy(&api.Permission{ Admin: access >= database.AccessModeAdmin, Push: access >= database.AccessModeWrite, Pull: true, }), ) } c.JSONSuccess(&repos) } func ListMyRepos(c *context.APIContext) { listUserRepositories(c, c.User.Name) } func ListUserRepositories(c *context.APIContext) { listUserRepositories(c, c.Params(":username")) } func ListOrgRepositories(c *context.APIContext) { listUserRepositories(c, c.Params(":org")) } func CreateUserRepo(c *context.APIContext, owner *database.User, opt api.CreateRepoOption) { repo, err := database.CreateRepository(c.User, owner, database.CreateRepoOptionsLegacy{ Name: opt.Name, Description: opt.Description, Gitignores: opt.Gitignores, License: opt.License, Readme: opt.Readme, IsPrivate: opt.Private, AutoInit: opt.AutoInit, }) if err != nil { if database.IsErrRepoAlreadyExist(err) || database.IsErrNameNotAllowed(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { if repo != nil { if err = database.DeleteRepository(c.User.ID, repo.ID); err != nil { log.Error("Failed to delete repository: %v", err) } } c.Error(err, "create repository") } return } c.JSON(201, repo.APIFormatLegacy(&api.Permission{Admin: true, Push: true, Pull: true})) } func Create(c *context.APIContext, opt api.CreateRepoOption) { // Shouldn't reach this condition, but just in case. if c.User.IsOrganization() { c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Not allowed to create repository for organization.")) return } CreateUserRepo(c, c.User, opt) } func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) { org, err := database.GetOrgByName(c.Params(":org")) if err != nil { c.NotFoundOrError(err, "get organization by name") return } if !org.IsOwnedBy(c.User.ID) { c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization.")) return } CreateUserRepo(c, org, opt) } func Migrate(c *context.APIContext, f form.MigrateRepo) { ctxUser := c.User // Not equal means context user is an organization, // or is another user/organization if current user is admin. if f.UID != ctxUser.ID { org, err := database.Handle.Users().GetByID(c.Req.Context(), f.UID) if err != nil { if database.IsErrUserNotExist(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "get user by ID") } return } else if !org.IsOrganization() && !c.User.IsAdmin { c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not an organization.")) return } ctxUser = org } if c.HasError() { c.ErrorStatus(http.StatusUnprocessableEntity, errors.New(c.GetErrMsg())) return } if ctxUser.IsOrganization() && !c.User.IsAdmin { // Check ownership of organization. if !ctxUser.IsOwnedBy(c.User.ID) { c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization.")) return } } remoteAddr, err := f.ParseRemoteAddr(c.User) if err != nil { if database.IsErrInvalidCloneAddr(err) { addrErr := err.(database.ErrInvalidCloneAddr) switch { case addrErr.IsURLError: c.ErrorStatus(http.StatusUnprocessableEntity, err) case addrErr.IsPermissionDenied: c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("You are not allowed to import local repositories.")) case addrErr.IsInvalidPath: c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Invalid local path, it does not exist or not a directory.")) case addrErr.IsBlockedLocalAddress: c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Clone address resolved to a local network address that is implicitly blocked.")) default: c.Error(err, "unexpected error") } } else { c.Error(err, "parse remote address") } return } repo, err := database.MigrateRepository(c.User, ctxUser, database.MigrateRepoOptions{ Name: f.RepoName, Description: f.Description, IsPrivate: f.Private || conf.Repository.ForcePrivate, IsMirror: f.Mirror, RemoteAddr: remoteAddr, }) if err != nil { if repo != nil { if errDelete := database.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil { log.Error("DeleteRepository: %v", errDelete) } } if database.IsErrReachLimitOfRepo(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(errors.New(database.HandleMirrorCredentials(err.Error(), true)), "migrate repository") } return } log.Trace("Repository migrated: %s/%s", ctxUser.Name, f.RepoName) c.JSON(201, repo.APIFormatLegacy(&api.Permission{Admin: true, Push: true, Pull: true})) } // FIXME: inject in the handler chain func parseOwnerAndRepo(c *context.APIContext) (*database.User, *database.Repository) { owner, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":username")) if err != nil { if database.IsErrUserNotExist(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "get user by name") } return nil, nil } repo, err := database.GetRepositoryByName(owner.ID, c.Params(":reponame")) if err != nil { c.NotFoundOrError(err, "get repository by name") return nil, nil } return owner, repo } func Get(c *context.APIContext) { _, repo := parseOwnerAndRepo(c) if c.Written() { return } c.JSONSuccess(repo.APIFormatLegacy(&api.Permission{ Admin: c.Repo.IsAdmin(), Push: c.Repo.IsWriter(), Pull: true, })) } func Delete(c *context.APIContext) { owner, repo := parseOwnerAndRepo(c) if c.Written() { return } if owner.IsOrganization() && !owner.IsOwnedBy(c.User.ID) { c.ErrorStatus(http.StatusForbidden, errors.New("Given user is not owner of organization.")) return } if err := database.DeleteRepository(owner.ID, repo.ID); err != nil { c.Error(err, "delete repository") return } log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name) c.NoContent() } func ListForks(c *context.APIContext) { forks, err := c.Repo.Repository.GetForks() if err != nil { c.Error(err, "get forks") return } apiForks := make([]*api.Repository, len(forks)) for i := range forks { if err := forks[i].GetOwner(); err != nil { c.Error(err, "get owner") return } accessMode := database.Handle.Permissions().AccessMode( c.Req.Context(), c.User.ID, forks[i].ID, database.AccessModeOptions{ OwnerID: forks[i].OwnerID, Private: forks[i].IsPrivate, }, ) apiForks[i] = forks[i].APIFormatLegacy( &api.Permission{ Admin: accessMode >= database.AccessModeAdmin, Push: accessMode >= database.AccessModeWrite, Pull: true, }, ) } c.JSONSuccess(&apiForks) } func IssueTracker(c *context.APIContext, form api.EditIssueTrackerOption) { _, repo := parseOwnerAndRepo(c) if c.Written() { return } if form.EnableIssues != nil { repo.EnableIssues = *form.EnableIssues } if form.EnableExternalTracker != nil { repo.EnableExternalTracker = *form.EnableExternalTracker } if form.ExternalTrackerURL != nil { repo.ExternalTrackerURL = *form.ExternalTrackerURL } if form.TrackerURLFormat != nil { repo.ExternalTrackerFormat = *form.TrackerURLFormat } if form.TrackerIssueStyle != nil { repo.ExternalTrackerStyle = *form.TrackerIssueStyle } if err := database.UpdateRepository(repo, false); err != nil { c.Error(err, "update repository") return } c.NoContent() } func Wiki(c *context.APIContext, form api.EditWikiOption) { _, repo := parseOwnerAndRepo(c) if c.Written() { return } if form.AllowPublicWiki != nil { repo.AllowPublicWiki = *form.AllowPublicWiki } if form.EnableExternalWiki != nil { repo.EnableExternalWiki = *form.EnableExternalWiki } if form.EnableWiki != nil { repo.EnableWiki = *form.EnableWiki } if form.ExternalWikiURL != nil { repo.ExternalWikiURL = *form.ExternalWikiURL } if err := database.UpdateRepository(repo, false); err != nil { c.Error(err, "update repository") return } c.NoContent() } func MirrorSync(c *context.APIContext) { _, repo := parseOwnerAndRepo(c) if c.Written() { return } else if !repo.IsMirror { c.NotFound() return } go database.MirrorQueue.Add(repo.ID) c.Status(http.StatusAccepted) } func Releases(c *context.APIContext) { _, repo := parseOwnerAndRepo(c) releases, err := database.GetReleasesByRepoID(repo.ID) if err != nil { c.Error(err, "get releases by repository ID") return } apiReleases := make([]*api.Release, 0, len(releases)) for _, r := range releases { publisher, err := database.Handle.Users().GetByID(c.Req.Context(), r.PublisherID) if err != nil { c.Error(err, "get release publisher") return } r.Publisher = publisher } for _, r := range releases { apiReleases = append(apiReleases, r.APIFormat()) } c.JSONSuccess(&apiReleases) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/tag.go
internal/route/api/v1/repo/tag.go
// 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) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/branch.go
internal/route/api/v1/repo/branch.go
// Copyright 2016 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 ( api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/route/api/v1/convert" ) // https://github.com/gogs/go-gogs-client/wiki/Repositories#get-branch func GetBranch(c *context.APIContext) { branch, err := c.Repo.Repository.GetBranch(c.Params("*")) if err != nil { c.NotFoundOrError(err, "get branch") return } commit, err := branch.GetCommit() if err != nil { c.Error(err, "get commit") return } c.JSONSuccess(convert.ToBranch(branch, commit)) } // https://github.com/gogs/go-gogs-client/wiki/Repositories#list-branches func ListBranches(c *context.APIContext) { branches, err := c.Repo.Repository.GetBranches() if err != nil { c.Error(err, "get branches") return } apiBranches := make([]*api.Branch, len(branches)) for i := range branches { commit, err := branches[i].GetCommit() if err != nil { c.Error(err, "get commit") return } apiBranches[i] = convert.ToBranch(branches[i], commit) } c.JSONSuccess(&apiBranches) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/issue_label.go
internal/route/api/v1/repo/issue_label.go
// Copyright 2016 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 ( "net/http" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) func ListIssueLabels(c *context.APIContext) { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return } apiLabels := make([]*api.Label, len(issue.Labels)) for i := range issue.Labels { apiLabels[i] = issue.Labels[i].APIFormat() } c.JSONSuccess(&apiLabels) } func AddIssueLabels(c *context.APIContext, form api.IssueLabelsOption) { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return } labels, err := database.GetLabelsInRepoByIDs(c.Repo.Repository.ID, form.Labels) if err != nil { c.Error(err, "get labels in repository by IDs") return } if err = issue.AddLabels(c.User, labels); err != nil { c.Error(err, "add labels") return } labels, err = database.GetLabelsByIssueID(issue.ID) if err != nil { c.Error(err, "get labels by issue ID") return } apiLabels := make([]*api.Label, len(labels)) for i := range labels { apiLabels[i] = issue.Labels[i].APIFormat() } c.JSONSuccess(&apiLabels) } func DeleteIssueLabel(c *context.APIContext) { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return } label, err := database.GetLabelOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { if database.IsErrLabelNotExist(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "get label of repository by ID") } return } if err := database.DeleteIssueLabel(issue, label); err != nil { c.Error(err, "delete issue label") return } c.NoContent() } func ReplaceIssueLabels(c *context.APIContext, form api.IssueLabelsOption) { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return } labels, err := database.GetLabelsInRepoByIDs(c.Repo.Repository.ID, form.Labels) if err != nil { c.Error(err, "get labels in repository by IDs") return } if err := issue.ReplaceLabels(labels); err != nil { c.Error(err, "replace labels") return } labels, err = database.GetLabelsByIssueID(issue.ID) if err != nil { c.Error(err, "get labels by issue ID") return } apiLabels := make([]*api.Label, len(labels)) for i := range labels { apiLabels[i] = issue.Labels[i].APIFormat() } c.JSONSuccess(&apiLabels) } func ClearIssueLabels(c *context.APIContext) { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return } if err := issue.ClearLabels(c.User); err != nil { c.Error(err, "clear labels") return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/commits.go
internal/route/api/v1/repo/commits.go
// Copyright 2018 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 ( "net/http" "strings" "time" "github.com/gogs/git-module" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/gitutil" ) // GetAllCommits returns a slice of commits starting from HEAD. func GetAllCommits(c *context.APIContext) { // Get pagesize, set default if it is not specified. pageSize := c.QueryInt("pageSize") if pageSize == 0 { pageSize = 30 } gitRepo, err := git.Open(c.Repo.Repository.RepoPath()) if err != nil { c.Error(err, "open repository") return } // The response object returned as JSON result := make([]*api.Commit, 0, pageSize) commits, err := gitRepo.Log("HEAD", git.LogOptions{MaxCount: pageSize}) if err != nil { c.Error(err, "git log") } for _, commit := range commits { apiCommit, err := gitCommitToAPICommit(commit, c) if err != nil { c.Error(err, "convert git commit to api commit") return } result = append(result, apiCommit) } c.JSONSuccess(result) } // GetSingleCommit will return a single Commit object based on the specified SHA. func GetSingleCommit(c *context.APIContext) { if strings.Contains(c.Req.Header.Get("Accept"), api.MediaApplicationSHA) { c.SetParams("*", c.Params(":sha")) GetReferenceSHA(c) return } gitRepo, err := git.Open(c.Repo.Repository.RepoPath()) if err != nil { c.Error(err, "open repository") return } commit, err := gitRepo.CatFileCommit(c.Params(":sha")) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get commit") return } apiCommit, err := gitCommitToAPICommit(commit, c) if err != nil { c.Error(err, "convert git commit to api commit") } c.JSONSuccess(apiCommit) } func GetReferenceSHA(c *context.APIContext) { gitRepo, err := git.Open(c.Repo.Repository.RepoPath()) if err != nil { c.Error(err, "open repository") return } ref := c.Params("*") refType := 0 // 0-unknown, 1-branch, 2-tag if strings.HasPrefix(ref, git.RefsHeads) { ref = strings.TrimPrefix(ref, git.RefsHeads) refType = 1 } else if strings.HasPrefix(ref, git.RefsTags) { ref = strings.TrimPrefix(ref, git.RefsTags) refType = 2 } else { if gitRepo.HasBranch(ref) { refType = 1 } else if gitRepo.HasTag(ref) { refType = 2 } else { c.NotFound() return } } var sha string switch refType { case 1: sha, err = gitRepo.BranchCommitID(ref) case 2: sha, err = gitRepo.TagCommitID(ref) } if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get reference commit ID") return } c.PlainText(http.StatusOK, sha) } // gitCommitToApiCommit is a helper function to convert git commit object to API commit. func gitCommitToAPICommit(commit *git.Commit, c *context.APIContext) (*api.Commit, error) { // Retrieve author and committer information var apiAuthor, apiCommitter *api.User author, err := database.Handle.Users().GetByEmail(c.Req.Context(), commit.Author.Email) if err != nil && !database.IsErrUserNotExist(err) { return nil, err } else if err == nil { apiAuthor = author.APIFormat() } // Save one query if the author is also the committer if commit.Committer.Email == commit.Author.Email { apiCommitter = apiAuthor } else { committer, err := database.Handle.Users().GetByEmail(c.Req.Context(), commit.Committer.Email) if err != nil && !database.IsErrUserNotExist(err) { return nil, err } else if err == nil { apiCommitter = committer.APIFormat() } } // Retrieve parent(s) of the commit apiParents := make([]*api.CommitMeta, commit.ParentsCount()) for i := 0; i < commit.ParentsCount(); i++ { sha, _ := commit.ParentID(i) apiParents[i] = &api.CommitMeta{ URL: c.BaseURL + "/repos/" + c.Repo.Repository.FullName() + "/commits/" + sha.String(), SHA: sha.String(), } } return &api.Commit{ CommitMeta: &api.CommitMeta{ URL: conf.Server.ExternalURL + c.Link[1:], SHA: commit.ID.String(), }, HTMLURL: c.Repo.Repository.HTMLURL() + "/commits/" + commit.ID.String(), RepoCommit: &api.RepoCommit{ URL: conf.Server.ExternalURL + c.Link[1:], Author: &api.CommitUser{ Name: commit.Author.Name, Email: commit.Author.Email, Date: commit.Author.When.Format(time.RFC3339), }, Committer: &api.CommitUser{ Name: commit.Committer.Name, Email: commit.Committer.Email, Date: commit.Committer.When.Format(time.RFC3339), }, Message: commit.Summary(), Tree: &api.CommitMeta{ URL: c.BaseURL + "/repos/" + c.Repo.Repository.FullName() + "/tree/" + commit.ID.String(), SHA: commit.ID.String(), }, }, Author: apiAuthor, Committer: apiCommitter, Parents: apiParents, }, nil }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/key.go
internal/route/api/v1/repo/key.go
// Copyright 2015 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 ( "net/http" api "github.com/gogs/go-gogs-client" "github.com/pkg/errors" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/route/api/v1/convert" ) func composeDeployKeysAPILink(repoPath string) string { return conf.Server.ExternalURL + "api/v1/repos/" + repoPath + "/keys/" } // https://github.com/gogs/go-gogs-client/wiki/Repositories-Deploy-Keys#list-deploy-keys func ListDeployKeys(c *context.APIContext) { keys, err := database.ListDeployKeys(c.Repo.Repository.ID) if err != nil { c.Error(err, "list deploy keys") return } apiLink := composeDeployKeysAPILink(c.Repo.Owner.Name + "/" + c.Repo.Repository.Name) apiKeys := make([]*api.DeployKey, len(keys)) for i := range keys { if err = keys[i].GetContent(); err != nil { c.Error(err, "get content") return } apiKeys[i] = convert.ToDeployKey(apiLink, keys[i]) } c.JSONSuccess(&apiKeys) } // https://github.com/gogs/go-gogs-client/wiki/Repositories-Deploy-Keys#get-a-deploy-key func GetDeployKey(c *context.APIContext) { key, err := database.GetDeployKeyByID(c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get deploy key by ID") return } if err = key.GetContent(); err != nil { c.Error(err, "get content") return } apiLink := composeDeployKeysAPILink(c.Repo.Owner.Name + "/" + c.Repo.Repository.Name) c.JSONSuccess(convert.ToDeployKey(apiLink, key)) } func HandleCheckKeyStringError(c *context.APIContext, err error) { if database.IsErrKeyUnableVerify(err) { c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Unable to verify key content")) } else { c.ErrorStatus(http.StatusUnprocessableEntity, errors.Wrap(err, "Invalid key content: %v")) } } func HandleAddKeyError(c *context.APIContext, err error) { switch { case database.IsErrKeyAlreadyExist(err): c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Key content has been used as non-deploy key")) case database.IsErrKeyNameAlreadyUsed(err): c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("Key title has been used")) default: c.Error(err, "add key") } } // https://github.com/gogs/go-gogs-client/wiki/Repositories-Deploy-Keys#add-a-new-deploy-key func CreateDeployKey(c *context.APIContext, form api.CreateKeyOption) { content, err := database.CheckPublicKeyString(form.Key) if err != nil { HandleCheckKeyStringError(c, err) return } key, err := database.AddDeployKey(c.Repo.Repository.ID, form.Title, content) if err != nil { HandleAddKeyError(c, err) return } key.Content = content apiLink := composeDeployKeysAPILink(c.Repo.Owner.Name + "/" + c.Repo.Repository.Name) c.JSON(http.StatusCreated, convert.ToDeployKey(apiLink, key)) } // https://github.com/gogs/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key func DeleteDeploykey(c *context.APIContext) { if err := database.DeleteDeployKey(c.User, c.ParamsInt64(":id")); err != nil { if database.IsErrKeyAccessDenied(err) { c.ErrorStatus(http.StatusForbidden, errors.New("You do not have access to this key")) } else { c.Error(err, "delete deploy key") } return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/blob.go
internal/route/api/v1/repo/blob.go
package repo import ( "encoding/base64" "fmt" "github.com/gogs/git-module" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/repoutil" ) func RepoGitBlob(c *context.APIContext) { gitRepo, err := git.Open(repoutil.RepositoryPath(c.Params(":username"), c.Params(":reponame"))) if err != nil { c.Error(err, "open repository") return } sha := c.Params(":sha") blob, err := gitRepo.CatFileBlob(sha) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get blob") return } type repoGitBlob struct { Content string `json:"content"` Encoding string `json:"encoding"` URL string `json:"url"` SHA string `json:"sha"` Size int64 `json:"size"` } content, err := blob.Blob().Bytes() if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get blob content") return } c.JSONSuccess(&repoGitBlob{ Content: base64.StdEncoding.EncodeToString(content), Encoding: "base64", URL: fmt.Sprintf("%s/repos/%s/%s/git/blobs/%s", c.BaseURL, c.Params(":username"), c.Params(":reponame"), sha), SHA: sha, Size: blob.Size(), }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/repo/label.go
internal/route/api/v1/repo/label.go
// Copyright 2016 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 ( "net/http" api "github.com/gogs/go-gogs-client" "github.com/unknwon/com" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) func ListLabels(c *context.APIContext) { labels, err := database.GetLabelsByRepoID(c.Repo.Repository.ID) if err != nil { c.Error(err, "get labels by repository ID") return } apiLabels := make([]*api.Label, len(labels)) for i := range labels { apiLabels[i] = labels[i].APIFormat() } c.JSONSuccess(&apiLabels) } func GetLabel(c *context.APIContext) { var label *database.Label var err error idStr := c.Params(":id") if id := com.StrTo(idStr).MustInt64(); id > 0 { label, err = database.GetLabelOfRepoByID(c.Repo.Repository.ID, id) } else { label, err = database.GetLabelOfRepoByName(c.Repo.Repository.ID, idStr) } if err != nil { c.NotFoundOrError(err, "get label") return } c.JSONSuccess(label.APIFormat()) } func CreateLabel(c *context.APIContext, form api.CreateLabelOption) { label := &database.Label{ Name: form.Name, Color: form.Color, RepoID: c.Repo.Repository.ID, } if err := database.NewLabels(label); err != nil { c.Error(err, "new labels") return } c.JSON(http.StatusCreated, label.APIFormat()) } func EditLabel(c *context.APIContext, form api.EditLabelOption) { label, err := database.GetLabelOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get label of repository by ID") return } if form.Name != nil { label.Name = *form.Name } if form.Color != nil { label.Color = *form.Color } if err := database.UpdateLabel(label); err != nil { c.Error(err, "update label") return } c.JSONSuccess(label.APIFormat()) } func DeleteLabel(c *context.APIContext) { if err := database.DeleteLabel(c.Repo.Repository.ID, c.ParamsInt64(":id")); err != nil { c.Error(err, "delete label") return } c.NoContent() }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/org/team.go
internal/route/api/v1/org/team.go
// Copyright 2016 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 org import ( api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/route/api/v1/convert" ) func ListTeams(c *context.APIContext) { org := c.Org.Organization if err := org.GetTeams(); err != nil { c.Error(err, "get teams") return } apiTeams := make([]*api.Team, len(org.Teams)) for i := range org.Teams { apiTeams[i] = convert.ToTeam(org.Teams[i]) } c.JSONSuccess(apiTeams) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/org/org.go
internal/route/api/v1/org/org.go
// Copyright 2015 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 org import ( "net/http" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/route/api/v1/convert" "gogs.io/gogs/internal/route/api/v1/user" ) func CreateOrgForUser(c *context.APIContext, apiForm api.CreateOrgOption, user *database.User) { if c.Written() { return } org := &database.User{ Name: apiForm.UserName, FullName: apiForm.FullName, Description: apiForm.Description, Website: apiForm.Website, Location: apiForm.Location, IsActive: true, Type: database.UserTypeOrganization, } if err := database.CreateOrganization(org, user); err != nil { if database.IsErrUserAlreadyExist(err) || database.IsErrNameNotAllowed(err) { c.ErrorStatus(http.StatusUnprocessableEntity, err) } else { c.Error(err, "create organization") } return } c.JSON(201, convert.ToOrganization(org)) } func listUserOrgs(c *context.APIContext, u *database.User, all bool) { orgs, err := database.Handle.Organizations().List( c.Req.Context(), database.ListOrgsOptions{ MemberID: u.ID, IncludePrivateMembers: all, }, ) if err != nil { c.Error(err, "list organizations") return } apiOrgs := make([]*api.Organization, len(orgs)) for i := range orgs { apiOrgs[i] = convert.ToOrganization(orgs[i]) } c.JSONSuccess(&apiOrgs) } func ListMyOrgs(c *context.APIContext) { listUserOrgs(c, c.User, true) } func CreateMyOrg(c *context.APIContext, apiForm api.CreateOrgOption) { CreateOrgForUser(c, apiForm, c.User) } func ListUserOrgs(c *context.APIContext) { u := user.GetUserByParams(c) if c.Written() { return } listUserOrgs(c, u, false) } func Get(c *context.APIContext) { c.JSONSuccess(convert.ToOrganization(c.Org.Organization)) } func Edit(c *context.APIContext, form api.EditOrgOption) { org := c.Org.Organization if !org.IsOwnedBy(c.User.ID) { c.Status(http.StatusForbidden) return } err := database.Handle.Users().Update( c.Req.Context(), c.Org.Organization.ID, database.UpdateUserOptions{ FullName: &form.FullName, Website: &form.Website, Location: &form.Location, Description: &form.Description, }, ) if err != nil { c.Error(err, "update organization") return } org, err = database.GetOrgByName(org.Name) if err != nil { c.Error(err, "get organization") return } c.JSONSuccess(convert.ToOrganization(org)) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/convert/utils.go
internal/route/api/v1/convert/utils.go
// Copyright 2016 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 convert import ( "gogs.io/gogs/internal/conf" ) // ToCorrectPageSize makes sure page size is in allowed range. func ToCorrectPageSize(size int) int { if size <= 0 { size = 10 } else if size > conf.API.MaxResponseItems { size = conf.API.MaxResponseItems } return size }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/api/v1/convert/convert.go
internal/route/api/v1/convert/convert.go
// Copyright 2015 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 convert import ( "context" "fmt" "github.com/unknwon/com" "github.com/gogs/git-module" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/database" ) func ToEmail(email *database.EmailAddress) *api.Email { return &api.Email{ Email: email.Email, Verified: email.IsActivated, Primary: email.IsPrimary, } } func ToBranch(b *database.Branch, c *git.Commit) *api.Branch { return &api.Branch{ Name: b.Name, Commit: ToCommit(c), } } type Tag struct { Name string `json:"name"` Commit *api.PayloadCommit `json:"commit"` } func ToTag(b *database.Tag, c *git.Commit) *Tag { return &Tag{ Name: b.Name, Commit: ToCommit(c), } } func ToCommit(c *git.Commit) *api.PayloadCommit { authorUsername := "" author, err := database.Handle.Users().GetByEmail(context.TODO(), c.Author.Email) if err == nil { authorUsername = author.Name } committerUsername := "" committer, err := database.Handle.Users().GetByEmail(context.TODO(), c.Committer.Email) if err == nil { committerUsername = committer.Name } return &api.PayloadCommit{ ID: c.ID.String(), Message: c.Message, URL: "Not implemented", Author: &api.PayloadUser{ Name: c.Author.Name, Email: c.Author.Email, UserName: authorUsername, }, Committer: &api.PayloadUser{ Name: c.Committer.Name, Email: c.Committer.Email, UserName: committerUsername, }, Timestamp: c.Author.When, } } func ToPublicKey(apiLink string, key *database.PublicKey) *api.PublicKey { return &api.PublicKey{ ID: key.ID, Key: key.Content, URL: apiLink + com.ToStr(key.ID), Title: key.Name, Created: key.Created, } } func ToHook(repoLink string, w *database.Webhook) *api.Hook { config := map[string]string{ "url": w.URL, "content_type": w.ContentType.Name(), } if w.HookTaskType == database.SLACK { s := w.SlackMeta() config["channel"] = s.Channel config["username"] = s.Username config["icon_url"] = s.IconURL config["color"] = s.Color } return &api.Hook{ ID: w.ID, Type: w.HookTaskType.Name(), URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID), Active: w.IsActive, Config: config, Events: w.EventsArray(), Updated: w.Updated, Created: w.Created, } } func ToDeployKey(apiLink string, key *database.DeployKey) *api.DeployKey { return &api.DeployKey{ ID: key.ID, Key: key.Content, URL: apiLink + com.ToStr(key.ID), Title: key.Name, Created: key.Created, ReadOnly: true, // All deploy keys are read-only. } } func ToOrganization(org *database.User) *api.Organization { return &api.Organization{ ID: org.ID, AvatarUrl: org.AvatarURL(), UserName: org.Name, FullName: org.FullName, Description: org.Description, Website: org.Website, Location: org.Location, } } func ToTeam(team *database.Team) *api.Team { return &api.Team{ ID: team.ID, Name: team.Name, Description: team.Description, Permission: team.Authorize.String(), } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/view.go
internal/route/repo/view.go
// Copyright 2014 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 ( "bytes" "fmt" gotemplate "html/template" "path" "strings" "time" "github.com/gogs/git-module" "github.com/unknwon/paginater" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/template" "gogs.io/gogs/internal/template/highlight" "gogs.io/gogs/internal/tool" ) const ( BARE = "repo/bare" HOME = "repo/home" WATCHERS = "repo/watchers" FORKS = "repo/forks" ) func renderDirectory(c *context.Context, treeLink string) { tree, err := c.Repo.Commit.Subtree(c.Repo.TreePath) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get subtree") return } entries, err := tree.Entries() if err != nil { c.Error(err, "list entries") return } entries.Sort() c.Data["Files"], err = entries.CommitsInfo(c.Repo.Commit, git.CommitsInfoOptions{ Path: c.Repo.TreePath, MaxConcurrency: conf.Repository.CommitsFetchConcurrency, Timeout: 5 * time.Minute, }) if err != nil { c.Error(err, "get commits info") return } var readmeFile *git.Blob for _, entry := range entries { if entry.IsTree() || !markup.IsReadmeFile(entry.Name()) { continue } // TODO(unknwon): collect all possible README files and show with priority. readmeFile = entry.Blob() break } if readmeFile != nil { c.Data["RawFileLink"] = "" c.Data["ReadmeInList"] = true c.Data["ReadmeExist"] = true p, err := readmeFile.Bytes() if err != nil { c.Error(err, "read file") return } isTextFile := tool.IsTextFile(p) c.Data["IsTextFile"] = isTextFile c.Data["FileName"] = readmeFile.Name() if isTextFile { switch markup.Detect(readmeFile.Name()) { case markup.TypeMarkdown: c.Data["IsMarkdown"] = true p = markup.Markdown(p, treeLink, c.Repo.Repository.ComposeMetas()) case markup.TypeOrgMode: c.Data["IsMarkdown"] = true p = markup.OrgMode(p, treeLink, c.Repo.Repository.ComposeMetas()) case markup.TypeIPythonNotebook: c.Data["IsIPythonNotebook"] = true c.Data["RawFileLink"] = c.Repo.RepoLink + "/raw/" + path.Join(c.Repo.BranchName, c.Repo.TreePath, readmeFile.Name()) default: p = bytes.ReplaceAll(p, []byte("\n"), []byte(`<br>`)) } c.Data["FileContent"] = string(p) } } // Show latest commit info of repository in table header, // or of directory if not in root directory. latestCommit := c.Repo.Commit if len(c.Repo.TreePath) > 0 { latestCommit, err = c.Repo.Commit.CommitByPath(git.CommitByRevisionOptions{Path: c.Repo.TreePath}) if err != nil { c.Error(err, "get commit by path") return } } c.Data["LatestCommit"] = latestCommit c.Data["LatestCommitUser"] = tryGetUserByEmail(c.Req.Context(), latestCommit.Author.Email) if c.Repo.CanEnableEditor() { c.Data["CanAddFile"] = true c.Data["CanUploadFile"] = conf.Repository.Upload.Enabled } } func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink string) { c.Data["IsViewFile"] = true blob := entry.Blob() p, err := blob.Bytes() if err != nil { c.Error(err, "read blob") return } c.Data["FileSize"] = blob.Size() c.Data["FileName"] = blob.Name() c.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name()) c.Data["RawFileLink"] = rawLink + "/" + c.Repo.TreePath isTextFile := tool.IsTextFile(p) c.Data["IsTextFile"] = isTextFile // Assume file is not editable first. if !isTextFile { c.Data["EditFileTooltip"] = c.Tr("repo.editor.cannot_edit_non_text_files") } canEnableEditor := c.Repo.CanEnableEditor() switch { case isTextFile: if blob.Size() >= conf.UI.MaxDisplayFileSize { c.Data["IsFileTooLarge"] = true break } c.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name()) switch markup.Detect(blob.Name()) { case markup.TypeMarkdown: c.Data["IsMarkdown"] = true c.Data["FileContent"] = string(markup.Markdown(p, path.Dir(treeLink), c.Repo.Repository.ComposeMetas())) case markup.TypeOrgMode: c.Data["IsMarkdown"] = true c.Data["FileContent"] = string(markup.OrgMode(p, path.Dir(treeLink), c.Repo.Repository.ComposeMetas())) case markup.TypeIPythonNotebook: c.Data["IsIPythonNotebook"] = true default: // Building code view blocks with line number on server side. var fileContent string if content, err := template.ToUTF8WithErr(p); err != nil { log.Error("ToUTF8WithErr: %s", err) fileContent = string(p) } else { fileContent = content } var output bytes.Buffer lines := strings.Split(fileContent, "\n") // Remove blank line at the end of file if len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } for index, line := range lines { output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(strings.TrimRight(line, "\r"))) + "\n") } c.Data["FileContent"] = gotemplate.HTML(output.String()) output.Reset() for i := 0; i < len(lines); i++ { output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1)) } c.Data["LineNums"] = gotemplate.HTML(output.String()) } if canEnableEditor { c.Data["CanEditFile"] = true c.Data["EditFileTooltip"] = c.Tr("repo.editor.edit_this_file") } else if !c.Repo.IsViewBranch { c.Data["EditFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch") } else if !c.Repo.IsWriter() { c.Data["EditFileTooltip"] = c.Tr("repo.editor.fork_before_edit") } case tool.IsPDFFile(p): c.Data["IsPDFFile"] = true case tool.IsVideoFile(p): c.Data["IsVideoFile"] = true case tool.IsImageFile(p): c.Data["IsImageFile"] = true } if canEnableEditor { c.Data["CanDeleteFile"] = true c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.delete_this_file") } else if !c.Repo.IsViewBranch { c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch") } else if !c.Repo.IsWriter() { c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_have_write_access") } } func setEditorconfigIfExists(c *context.Context) { ec, err := c.Repo.Editorconfig() if err != nil && !gitutil.IsErrRevisionNotExist(err) { log.Warn("setEditorconfigIfExists.Editorconfig [repo_id: %d]: %v", c.Repo.Repository.ID, err) return } c.Data["Editorconfig"] = ec } func Home(c *context.Context) { c.Data["PageIsViewFiles"] = true if c.Repo.Repository.IsBare { c.Success(BARE) return } title := c.Repo.Repository.Owner.Name + "/" + c.Repo.Repository.Name if len(c.Repo.Repository.Description) > 0 { title += ": " + c.Repo.Repository.Description } c.Data["Title"] = title if c.Repo.BranchName != c.Repo.Repository.DefaultBranch { c.Data["Title"] = title + " @ " + c.Repo.BranchName } c.Data["RequireHighlightJS"] = true branchLink := c.Repo.RepoLink + "/src/" + c.Repo.BranchName treeLink := branchLink rawLink := c.Repo.RepoLink + "/raw/" + c.Repo.BranchName isRootDir := false if len(c.Repo.TreePath) > 0 { treeLink += "/" + c.Repo.TreePath } else { isRootDir = true // Only show Git stats panel when view root directory var err error c.Repo.CommitsCount, err = c.Repo.Commit.CommitsCount() if err != nil { c.Error(err, "count commits") return } c.Data["CommitsCount"] = c.Repo.CommitsCount } c.Data["PageIsRepoHome"] = isRootDir // Get current entry user currently looking at. entry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get tree entry") return } if entry.IsTree() { renderDirectory(c, treeLink) } else { renderFile(c, entry, treeLink, rawLink) } if c.Written() { return } setEditorconfigIfExists(c) if c.Written() { return } var treeNames []string paths := make([]string, 0, 5) if len(c.Repo.TreePath) > 0 { treeNames = strings.Split(c.Repo.TreePath, "/") for i := range treeNames { paths = append(paths, strings.Join(treeNames[:i+1], "/")) } c.Data["HasParentPath"] = true if len(paths)-2 >= 0 { c.Data["ParentPath"] = "/" + paths[len(paths)-2] } } c.Data["Paths"] = paths c.Data["TreeLink"] = treeLink c.Data["TreeNames"] = treeNames c.Data["BranchLink"] = branchLink c.Success(HOME) } func RenderUserCards(c *context.Context, total int, getter func(page int) ([]*database.User, error), tpl string) { page := c.QueryInt("page") if page <= 0 { page = 1 } pager := paginater.New(total, database.ItemsPerPage, page, 5) c.Data["Page"] = pager items, err := getter(pager.Current()) if err != nil { c.Error(err, "getter") return } c.Data["Cards"] = items c.Success(tpl) } func Watchers(c *context.Context) { c.Data["Title"] = c.Tr("repo.watchers") c.Data["CardsTitle"] = c.Tr("repo.watchers") c.Data["PageIsWatchers"] = true RenderUserCards(c, c.Repo.Repository.NumWatches, c.Repo.Repository.GetWatchers, WATCHERS) } func Stars(c *context.Context) { c.Data["Title"] = c.Tr("repo.stargazers") c.Data["CardsTitle"] = c.Tr("repo.stargazers") c.Data["PageIsStargazers"] = true RenderUserCards(c, c.Repo.Repository.NumStars, c.Repo.Repository.GetStargazers, WATCHERS) } func Forks(c *context.Context) { c.Data["Title"] = c.Tr("repos.forks") forks, err := c.Repo.Repository.GetForks() if err != nil { c.Error(err, "get forks") return } for _, fork := range forks { if err = fork.GetOwner(); err != nil { c.Error(err, "get owner") return } } c.Data["Forks"] = forks c.Success(FORKS) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/commit.go
internal/route/repo/commit.go
// Copyright 2014 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 ( gocontext "context" "path" "time" "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/tool" ) const ( COMMITS = "repo/commits" DIFF = "repo/diff/page" ) func RefCommits(c *context.Context) { c.Data["PageIsViewFiles"] = true switch c.Repo.TreePath { case "": Commits(c) case "search": SearchCommits(c) default: FileHistory(c) } } // TODO(unknwon) func RenderIssueLinks(oldCommits []*git.Commit, _ string) []*git.Commit { return oldCommits } func renderCommits(c *context.Context, filename string) { c.Data["Title"] = c.Tr("repo.commits.commit_history") + " · " + c.Repo.Repository.FullName() c.Data["PageIsCommits"] = true c.Data["FileName"] = filename page := c.QueryInt("page") if page < 1 { page = 1 } pageSize := c.QueryInt("pageSize") if pageSize < 1 { pageSize = conf.UI.User.CommitsPagingNum } commits, err := c.Repo.Commit.CommitsByPage(page, pageSize, git.CommitsByPageOptions{Path: filename}) if err != nil { c.Error(err, "paging commits") return } commits = RenderIssueLinks(commits, c.Repo.RepoLink) c.Data["Commits"] = matchUsersWithCommitEmails(c.Req.Context(), commits) if page > 1 { c.Data["HasPrevious"] = true c.Data["PreviousPage"] = page - 1 } if len(commits) == pageSize { c.Data["HasNext"] = true c.Data["NextPage"] = page + 1 } c.Data["PageSize"] = pageSize c.Data["Username"] = c.Repo.Owner.Name c.Data["Reponame"] = c.Repo.Repository.Name c.Success(COMMITS) } func Commits(c *context.Context) { renderCommits(c, "") } func SearchCommits(c *context.Context) { c.Data["PageIsCommits"] = true keyword := c.Query("q") if keyword == "" { c.Redirect(c.Repo.RepoLink + "/commits/" + c.Repo.BranchName) return } commits, err := c.Repo.Commit.SearchCommits(keyword) if err != nil { c.Error(err, "search commits") return } commits = RenderIssueLinks(commits, c.Repo.RepoLink) c.Data["Commits"] = matchUsersWithCommitEmails(c.Req.Context(), commits) c.Data["Keyword"] = keyword c.Data["Username"] = c.Repo.Owner.Name c.Data["Reponame"] = c.Repo.Repository.Name c.Data["Branch"] = c.Repo.BranchName c.Success(COMMITS) } func FileHistory(c *context.Context) { renderCommits(c, c.Repo.TreePath) } // tryGetUserByEmail returns a non-nil value if the email is corresponding to an // existing user. func tryGetUserByEmail(ctx gocontext.Context, email string) *database.User { user, _ := database.Handle.Users().GetByEmail(ctx, email) return user } func Diff(c *context.Context) { c.PageIs("Diff") c.RequireHighlightJS() userName := c.Repo.Owner.Name repoName := c.Repo.Repository.Name commitID := c.Params(":sha") commit, err := c.Repo.GitRepo.CatFileCommit(commitID) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get commit by ID") return } diff, err := gitutil.RepoDiff(c.Repo.GitRepo, commitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, git.DiffOptions{Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second}, ) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get diff") return } parents := make([]string, commit.ParentsCount()) for i := 0; i < commit.ParentsCount(); i++ { sha, err := commit.ParentID(i) if err != nil { c.NotFound() return } parents[i] = sha.String() } setEditorconfigIfExists(c) if c.Written() { return } c.RawTitle(commit.Summary() + " · " + tool.ShortSHA1(commitID)) c.Data["CommitID"] = commitID c.Data["IsSplitStyle"] = c.Query("style") == "split" c.Data["Username"] = userName c.Data["Reponame"] = repoName c.Data["IsImageFile"] = commit.IsImageFile c.Data["IsImageFileByIndex"] = commit.IsImageFileByIndex c.Data["Commit"] = commit c.Data["Author"] = tryGetUserByEmail(c.Req.Context(), commit.Author.Email) c.Data["Diff"] = diff c.Data["Parents"] = parents c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "src", commitID) c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "raw", commitID) if commit.ParentsCount() > 0 { c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "src", parents[0]) c.Data["BeforeRawPath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "raw", parents[0]) } c.Success(DIFF) } func RawDiff(c *context.Context) { if err := c.Repo.GitRepo.RawDiff( c.Params(":sha"), git.RawDiffFormat(c.Params(":ext")), c.Resp, ); err != nil { c.NotFoundOrError(gitutil.NewError(err), "get raw diff") return } } type userCommit struct { User *database.User *git.Commit } // matchUsersWithCommitEmails matches existing users using commit author emails. func matchUsersWithCommitEmails(ctx gocontext.Context, oldCommits []*git.Commit) []*userCommit { emailToUsers := make(map[string]*database.User) newCommits := make([]*userCommit, len(oldCommits)) usersStore := database.Handle.Users() for i := range oldCommits { var u *database.User if v, ok := emailToUsers[oldCommits[i].Author.Email]; !ok { u, _ = usersStore.GetByEmail(ctx, oldCommits[i].Author.Email) emailToUsers[oldCommits[i].Author.Email] = u } else { u = v } newCommits[i] = &userCommit{ User: u, Commit: oldCommits[i], } } return newCommits } func CompareDiff(c *context.Context) { c.Data["IsDiffCompare"] = true userName := c.Repo.Owner.Name repoName := c.Repo.Repository.Name beforeCommitID := c.Params(":before") afterCommitID := c.Params(":after") commit, err := c.Repo.GitRepo.CatFileCommit(afterCommitID) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get head commit") return } diff, err := gitutil.RepoDiff(c.Repo.GitRepo, afterCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, git.DiffOptions{Base: beforeCommitID, Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second}, ) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get diff") return } commits, err := commit.CommitsAfter(beforeCommitID) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get commits after") return } c.Data["IsSplitStyle"] = c.Query("style") == "split" c.Data["CommitRepoLink"] = c.Repo.RepoLink c.Data["Commits"] = matchUsersWithCommitEmails(c.Req.Context(), commits) c.Data["CommitsCount"] = len(commits) c.Data["BeforeCommitID"] = beforeCommitID c.Data["AfterCommitID"] = afterCommitID c.Data["Username"] = userName c.Data["Reponame"] = repoName c.Data["IsImageFile"] = commit.IsImageFile c.Data["IsImageFileByIndex"] = commit.IsImageFileByIndex c.Data["Title"] = "Comparing " + tool.ShortSHA1(beforeCommitID) + "..." + tool.ShortSHA1(afterCommitID) + " · " + userName + "/" + repoName c.Data["Commit"] = commit c.Data["Diff"] = diff c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "src", afterCommitID) c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "raw", afterCommitID) c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "src", beforeCommitID) c.Data["BeforeRawPath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "raw", beforeCommitID) c.Success(DIFF) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/editor.go
internal/route/repo/editor.go
// Copyright 2016 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 ( "fmt" "net/http" "path" "strings" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database/errors" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/pathutil" "gogs.io/gogs/internal/template" "gogs.io/gogs/internal/tool" ) const ( tmplEditorEdit = "repo/editor/edit" tmplEditorDiffPreview = "repo/editor/diff_preview" tmplEditorDelete = "repo/editor/delete" tmplEditorUpload = "repo/editor/upload" ) // getParentTreeFields returns list of parent tree names and corresponding tree paths // based on given tree path. func getParentTreeFields(treePath string) (treeNames, treePaths []string) { if treePath == "" { return treeNames, treePaths } treeNames = strings.Split(treePath, "/") treePaths = make([]string, len(treeNames)) for i := range treeNames { treePaths[i] = strings.Join(treeNames[:i+1], "/") } return treeNames, treePaths } func editFile(c *context.Context, isNewFile bool) { c.PageIs("Edit") c.RequireHighlightJS() c.RequireSimpleMDE() c.Data["IsNewFile"] = isNewFile treeNames, treePaths := getParentTreeFields(c.Repo.TreePath) if !isNewFile { entry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get tree entry") return } // No way to edit a directory online. if entry.IsTree() { c.NotFound() return } blob := entry.Blob() p, err := blob.Bytes() if err != nil { c.Error(err, "get blob data") return } c.Data["FileSize"] = blob.Size() c.Data["FileName"] = blob.Name() // Only text file are editable online. if !tool.IsTextFile(p) { c.NotFound() return } if content, err := template.ToUTF8WithErr(p); err != nil { if err != nil { log.Error("Failed to convert encoding to UTF-8: %v", err) } c.Data["FileContent"] = string(p) } else { c.Data["FileContent"] = content } } else { treeNames = append(treeNames, "") // Append empty string to allow user name the new file. } c.Data["ParentTreePath"] = path.Dir(c.Repo.TreePath) c.Data["TreeNames"] = treeNames c.Data["TreePaths"] = treePaths c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName c.Data["commit_summary"] = "" c.Data["commit_message"] = "" c.Data["commit_choice"] = "direct" c.Data["new_branch_name"] = "" c.Data["last_commit"] = c.Repo.Commit.ID c.Data["MarkdownFileExts"] = strings.Join(conf.Markdown.FileExtensions, ",") c.Data["LineWrapExtensions"] = strings.Join(conf.Repository.Editor.LineWrapExtensions, ",") c.Data["PreviewableFileModes"] = strings.Join(conf.Repository.Editor.PreviewableFileModes, ",") c.Data["EditorconfigURLPrefix"] = fmt.Sprintf("%s/api/v1/repos/%s/editorconfig/", conf.Server.Subpath, c.Repo.Repository.FullName()) c.Success(tmplEditorEdit) } func EditFile(c *context.Context) { editFile(c, false) } func NewFile(c *context.Context) { editFile(c, true) } func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { c.PageIs("Edit") c.RequireHighlightJS() c.RequireSimpleMDE() c.Data["IsNewFile"] = isNewFile oldBranchName := c.Repo.BranchName branchName := oldBranchName oldTreePath := c.Repo.TreePath lastCommit := f.LastCommit f.LastCommit = c.Repo.Commit.ID.String() if f.IsNewBrnach() { branchName = f.NewBranchName } // 🚨 SECURITY: Prevent path traversal. f.TreePath = pathutil.Clean(f.TreePath) treeNames, treePaths := getParentTreeFields(f.TreePath) c.Data["ParentTreePath"] = path.Dir(c.Repo.TreePath) c.Data["TreePath"] = f.TreePath c.Data["TreeNames"] = treeNames c.Data["TreePaths"] = treePaths c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + branchName c.Data["FileContent"] = f.Content c.Data["commit_summary"] = f.CommitSummary c.Data["commit_message"] = f.CommitMessage c.Data["commit_choice"] = f.CommitChoice c.Data["new_branch_name"] = branchName c.Data["last_commit"] = f.LastCommit c.Data["MarkdownFileExts"] = strings.Join(conf.Markdown.FileExtensions, ",") c.Data["LineWrapExtensions"] = strings.Join(conf.Repository.Editor.LineWrapExtensions, ",") c.Data["PreviewableFileModes"] = strings.Join(conf.Repository.Editor.PreviewableFileModes, ",") if c.HasError() { c.Success(tmplEditorEdit) return } if f.TreePath == "" { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.filename_cannot_be_empty"), tmplEditorEdit, &f) return } if oldBranchName != branchName { if _, err := c.Repo.Repository.GetBranch(branchName); err == nil { c.FormErr("NewBranchName") c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), tmplEditorEdit, &f) return } } var newTreePath string for index, part := range treeNames { newTreePath = path.Join(newTreePath, part) entry, err := c.Repo.Commit.TreeEntry(newTreePath) if err != nil { if gitutil.IsErrRevisionNotExist(err) { // Means there is no item with that name, so we're good break } c.Error(err, "get tree entry") return } if index != len(treeNames)-1 { if !entry.IsTree() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), tmplEditorEdit, &f) return } } else { // 🚨 SECURITY: Do not allow editing if the target file is a symlink. if entry.IsSymlink() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.file_is_a_symlink", part), tmplEditorEdit, &f) return } else if entry.IsTree() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.filename_is_a_directory", part), tmplEditorEdit, &f) return } } } if !isNewFile { entry, err := c.Repo.Commit.TreeEntry(oldTreePath) if err != nil { if gitutil.IsErrRevisionNotExist(err) { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), tmplEditorEdit, &f) } else { c.Error(err, "get tree entry") } return } // 🚨 SECURITY: Do not allow editing if the old file is a symlink. if entry.IsSymlink() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.file_is_a_symlink", oldTreePath), tmplEditorEdit, &f) return } if lastCommit != c.Repo.CommitID { files, err := c.Repo.Commit.FilesChangedAfter(lastCommit) if err != nil { c.Error(err, "get changed files") return } for _, file := range files { if file == f.TreePath { c.RenderWithErr(c.Tr("repo.editor.file_changed_while_editing", c.Repo.RepoLink+"/compare/"+lastCommit+"..."+c.Repo.CommitID), tmplEditorEdit, &f) return } } } } if oldTreePath != f.TreePath { // We have a new filename (rename or completely new file) so we need to make sure it doesn't already exist, can't clobber. entry, err := c.Repo.Commit.TreeEntry(f.TreePath) if err != nil { if !gitutil.IsErrRevisionNotExist(err) { c.Error(err, "get tree entry") return } } if entry != nil { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.file_already_exists", f.TreePath), tmplEditorEdit, &f) return } } message := strings.TrimSpace(f.CommitSummary) if message == "" { if isNewFile { message = c.Tr("repo.editor.add", f.TreePath) } else { message = c.Tr("repo.editor.update", f.TreePath) } } f.CommitMessage = strings.TrimSpace(f.CommitMessage) if len(f.CommitMessage) > 0 { message += "\n\n" + f.CommitMessage } if err := c.Repo.Repository.UpdateRepoFile(c.User, database.UpdateRepoFileOptions{ OldBranch: oldBranchName, NewBranch: branchName, OldTreeName: oldTreePath, NewTreeName: f.TreePath, Message: message, Content: strings.ReplaceAll(f.Content, "\r", ""), IsNewFile: isNewFile, }); err != nil { log.Error("Failed to update repo file: %v", err) c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.fail_to_update_file", f.TreePath, errors.ErrInternalServerError), tmplEditorEdit, &f) return } if f.IsNewBrnach() && c.Repo.PullRequest.Allowed { c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) } else { c.Redirect(c.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath) } } func EditFilePost(c *context.Context, f form.EditRepoFile) { editFilePost(c, f, false) } func NewFilePost(c *context.Context, f form.EditRepoFile) { editFilePost(c, f, true) } func DiffPreviewPost(c *context.Context, f form.EditPreviewDiff) { // 🚨 SECURITY: Prevent path traversal. treePath := pathutil.Clean(c.Repo.TreePath) entry, err := c.Repo.Commit.TreeEntry(treePath) if err != nil { c.Error(err, "get tree entry") return } else if entry.IsTree() { c.Status(http.StatusUnprocessableEntity) return } diff, err := c.Repo.Repository.GetDiffPreview(c.Repo.BranchName, treePath, f.Content) if err != nil { c.Error(err, "get diff preview") return } if diff.NumFiles() == 0 { c.PlainText(http.StatusOK, c.Tr("repo.editor.no_changes_to_show")) return } c.Data["File"] = diff.Files[0] c.Success(tmplEditorDiffPreview) } func DeleteFile(c *context.Context) { c.PageIs("Delete") c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName c.Data["TreePath"] = c.Repo.TreePath c.Data["commit_summary"] = "" c.Data["commit_message"] = "" c.Data["commit_choice"] = "direct" c.Data["new_branch_name"] = "" c.Success(tmplEditorDelete) } func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) { c.PageIs("Delete") c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName // 🚨 SECURITY: Prevent path traversal. c.Repo.TreePath = pathutil.Clean(c.Repo.TreePath) c.Data["TreePath"] = c.Repo.TreePath oldBranchName := c.Repo.BranchName branchName := oldBranchName if f.IsNewBrnach() { branchName = f.NewBranchName } c.Data["commit_summary"] = f.CommitSummary c.Data["commit_message"] = f.CommitMessage c.Data["commit_choice"] = f.CommitChoice c.Data["new_branch_name"] = branchName if c.HasError() { c.Success(tmplEditorDelete) return } if oldBranchName != branchName { if _, err := c.Repo.Repository.GetBranch(branchName); err == nil { c.FormErr("NewBranchName") c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), tmplEditorDelete, &f) return } } message := strings.TrimSpace(f.CommitSummary) if message == "" { message = c.Tr("repo.editor.delete", c.Repo.TreePath) } f.CommitMessage = strings.TrimSpace(f.CommitMessage) if len(f.CommitMessage) > 0 { message += "\n\n" + f.CommitMessage } if err := c.Repo.Repository.DeleteRepoFile(c.User, database.DeleteRepoFileOptions{ LastCommitID: c.Repo.CommitID, OldBranch: oldBranchName, NewBranch: branchName, TreePath: c.Repo.TreePath, Message: message, }); err != nil { log.Error("Failed to delete repo file: %v", err) c.RenderWithErr(c.Tr("repo.editor.fail_to_delete_file", c.Repo.TreePath, errors.ErrInternalServerError), tmplEditorDelete, &f) return } if f.IsNewBrnach() && c.Repo.PullRequest.Allowed { c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) } else { c.Flash.Success(c.Tr("repo.editor.file_delete_success", c.Repo.TreePath)) c.Redirect(c.Repo.RepoLink + "/src/" + branchName) } } func renderUploadSettings(c *context.Context) { c.RequireDropzone() c.Data["UploadAllowedTypes"] = strings.Join(conf.Repository.Upload.AllowedTypes, ",") c.Data["UploadMaxSize"] = conf.Repository.Upload.FileMaxSize c.Data["UploadMaxFiles"] = conf.Repository.Upload.MaxFiles } func UploadFile(c *context.Context) { c.PageIs("Upload") renderUploadSettings(c) treeNames, treePaths := getParentTreeFields(c.Repo.TreePath) if len(treeNames) == 0 { // We must at least have one element for user to input. treeNames = []string{""} } c.Data["TreeNames"] = treeNames c.Data["TreePaths"] = treePaths c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName c.Data["commit_summary"] = "" c.Data["commit_message"] = "" c.Data["commit_choice"] = "direct" c.Data["new_branch_name"] = "" c.Success(tmplEditorUpload) } func UploadFilePost(c *context.Context, f form.UploadRepoFile) { c.PageIs("Upload") renderUploadSettings(c) oldBranchName := c.Repo.BranchName branchName := oldBranchName if f.IsNewBrnach() { branchName = f.NewBranchName } // 🚨 SECURITY: Prevent path traversal. f.TreePath = pathutil.Clean(f.TreePath) treeNames, treePaths := getParentTreeFields(f.TreePath) if len(treeNames) == 0 { // We must at least have one element for user to input. treeNames = []string{""} } c.Data["TreePath"] = f.TreePath c.Data["TreeNames"] = treeNames c.Data["TreePaths"] = treePaths c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + branchName c.Data["commit_summary"] = f.CommitSummary c.Data["commit_message"] = f.CommitMessage c.Data["commit_choice"] = f.CommitChoice c.Data["new_branch_name"] = branchName if c.HasError() { c.Success(tmplEditorUpload) return } if oldBranchName != branchName { if _, err := c.Repo.Repository.GetBranch(branchName); err == nil { c.FormErr("NewBranchName") c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), tmplEditorUpload, &f) return } } var newTreePath string for _, part := range treeNames { newTreePath = path.Join(newTreePath, part) entry, err := c.Repo.Commit.TreeEntry(newTreePath) if err != nil { if gitutil.IsErrRevisionNotExist(err) { // Means there is no item with that name, so we're good break } c.Error(err, "get tree entry") return } // User can only upload files to a directory. if !entry.IsTree() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), tmplEditorUpload, &f) return } } message := strings.TrimSpace(f.CommitSummary) if message == "" { message = c.Tr("repo.editor.upload_files_to_dir", f.TreePath) } f.CommitMessage = strings.TrimSpace(f.CommitMessage) if len(f.CommitMessage) > 0 { message += "\n\n" + f.CommitMessage } if err := c.Repo.Repository.UploadRepoFiles(c.User, database.UploadRepoFileOptions{ LastCommitID: c.Repo.CommitID, OldBranch: oldBranchName, NewBranch: branchName, TreePath: f.TreePath, Message: message, Files: f.Files, }); err != nil { log.Error("Failed to upload files: %v", err) c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, errors.ErrInternalServerError), tmplEditorUpload, &f) return } if f.IsNewBrnach() && c.Repo.PullRequest.Allowed { c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName)) } else { c.Redirect(c.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath) } } func UploadFileToServer(c *context.Context) { file, header, err := c.Req.FormFile("file") if err != nil { c.Error(err, "get file") return } defer file.Close() buf := make([]byte, 1024) n, _ := file.Read(buf) if n > 0 { buf = buf[:n] } fileType := http.DetectContentType(buf) if len(conf.Repository.Upload.AllowedTypes) > 0 { allowed := false for _, t := range conf.Repository.Upload.AllowedTypes { t := strings.Trim(t, " ") if t == "*/*" || t == fileType { allowed = true break } } if !allowed { c.PlainText(http.StatusBadRequest, ErrFileTypeForbidden.Error()) return } } upload, err := database.NewUpload(header.Filename, buf, file) if err != nil { c.Error(err, "new upload") return } log.Trace("New file uploaded by user[%d]: %s", c.UserID(), upload.UUID) c.JSONSuccess(map[string]string{ "uuid": upload.UUID, }) } func RemoveUploadFileFromServer(c *context.Context, f form.RemoveUploadFile) { if f.File == "" { c.Status(http.StatusNoContent) return } if err := database.DeleteUploadByUUID(f.File); err != nil { c.Error(err, "delete upload by UUID") return } log.Trace("Upload file removed: %s", f.File) c.Status(http.StatusNoContent) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/webhook.go
internal/route/repo/webhook.go
// Copyright 2015 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 ( "fmt" "net/http" "net/url" "strings" "time" "github.com/gogs/git-module" api "github.com/gogs/go-gogs-client" jsoniter "github.com/json-iterator/go" "gopkg.in/macaron.v1" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database/errors" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/netutil" ) const ( tmplRepoSettingsWebhooks = "repo/settings/webhook/base" tmplRepoSettingsWebhookNew = "repo/settings/webhook/new" tmplOrgSettingsWebhooks = "org/settings/webhooks" tmplOrgSettingsWebhookNew = "org/settings/webhook_new" ) func InjectOrgRepoContext() macaron.Handler { return func(c *context.Context) { orCtx, err := getOrgRepoContext(c) if err != nil { c.Error(err, "get organization or repository context") return } c.Map(orCtx) } } type orgRepoContext struct { OrgID int64 RepoID int64 Link string TmplList string TmplNew string } // getOrgRepoContext determines whether this is a repo context or organization context. func getOrgRepoContext(c *context.Context) (*orgRepoContext, error) { if len(c.Repo.RepoLink) > 0 { c.PageIs("RepositoryContext") return &orgRepoContext{ RepoID: c.Repo.Repository.ID, Link: c.Repo.RepoLink, TmplList: tmplRepoSettingsWebhooks, TmplNew: tmplRepoSettingsWebhookNew, }, nil } if len(c.Org.OrgLink) > 0 { c.PageIs("OrganizationContext") return &orgRepoContext{ OrgID: c.Org.Organization.ID, Link: c.Org.OrgLink, TmplList: tmplOrgSettingsWebhooks, TmplNew: tmplOrgSettingsWebhookNew, }, nil } return nil, errors.New("unable to determine context") } func Webhooks(c *context.Context, orCtx *orgRepoContext) { c.Title("repo.settings.hooks") c.PageIs("SettingsHooks") c.Data["Types"] = conf.Webhook.Types var err error var ws []*database.Webhook if orCtx.RepoID > 0 { c.Data["Description"] = c.Tr("repo.settings.hooks_desc", "https://gogs.io/docs/features/webhook.html") ws, err = database.GetWebhooksByRepoID(orCtx.RepoID) } else { c.Data["Description"] = c.Tr("org.settings.hooks_desc") ws, err = database.GetWebhooksByOrgID(orCtx.OrgID) } if err != nil { c.Error(err, "get webhooks") return } c.Data["Webhooks"] = ws c.Success(orCtx.TmplList) } func WebhooksNew(c *context.Context, orCtx *orgRepoContext) { c.Title("repo.settings.add_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksNew") allowed := false hookType := strings.ToLower(c.Params(":type")) for _, typ := range conf.Webhook.Types { if hookType == typ { allowed = true c.Data["HookType"] = typ break } } if !allowed { c.NotFound() return } c.Success(orCtx.TmplNew) } func validateWebhook(l macaron.Locale, w *database.Webhook) (field, msg string, ok bool) { // 🚨 SECURITY: Local addresses must not be allowed by non-admins to prevent SSRF, // see https://github.com/gogs/gogs/issues/5366 for details. payloadURL, err := url.Parse(w.URL) if err != nil { return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_parse_payload_url", err), false } if netutil.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) { return "PayloadURL", l.Tr("repo.settings.webhook.url_resolved_to_blocked_local_address"), false } return "", "", true } func validateAndCreateWebhook(c *context.Context, orCtx *orgRepoContext, w *database.Webhook) { c.Data["Webhook"] = w if c.HasError() { c.Success(orCtx.TmplNew) return } field, msg, ok := validateWebhook(c.Locale, w) if !ok { c.FormErr(field) c.RenderWithErr(msg, orCtx.TmplNew, nil) return } if err := w.UpdateEvent(); err != nil { c.Error(err, "update event") return } else if err := database.CreateWebhook(w); err != nil { c.Error(err, "create webhook") return } c.Flash.Success(c.Tr("repo.settings.add_hook_success")) c.Redirect(orCtx.Link + "/settings/hooks") } func toHookEvent(f form.Webhook) *database.HookEvent { return &database.HookEvent{ PushOnly: f.PushOnly(), SendEverything: f.SendEverything(), ChooseEvents: f.ChooseEvents(), HookEvents: database.HookEvents{ Create: f.Create, Delete: f.Delete, Fork: f.Fork, Push: f.Push, Issues: f.Issues, IssueComment: f.IssueComment, PullRequest: f.PullRequest, Release: f.Release, }, } } func WebhooksNewPost(c *context.Context, orCtx *orgRepoContext, f form.NewWebhook) { c.Title("repo.settings.add_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksNew") c.Data["HookType"] = "gogs" contentType := database.JSON if database.HookContentType(f.ContentType) == database.FORM { contentType = database.FORM } w := &database.Webhook{ RepoID: orCtx.RepoID, OrgID: orCtx.OrgID, URL: f.PayloadURL, ContentType: contentType, Secret: f.Secret, HookEvent: toHookEvent(f.Webhook), IsActive: f.Active, HookTaskType: database.GOGS, } validateAndCreateWebhook(c, orCtx, w) } func WebhooksSlackNewPost(c *context.Context, orCtx *orgRepoContext, f form.NewSlackHook) { c.Title("repo.settings.add_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksNew") c.Data["HookType"] = "slack" meta := &database.SlackMeta{ Channel: f.Channel, Username: f.Username, IconURL: f.IconURL, Color: f.Color, } c.Data["SlackMeta"] = meta p, err := jsoniter.Marshal(meta) if err != nil { c.Error(err, "marshal JSON") return } w := &database.Webhook{ RepoID: orCtx.RepoID, URL: f.PayloadURL, ContentType: database.JSON, HookEvent: toHookEvent(f.Webhook), IsActive: f.Active, HookTaskType: database.SLACK, Meta: string(p), OrgID: orCtx.OrgID, } validateAndCreateWebhook(c, orCtx, w) } func WebhooksDiscordNewPost(c *context.Context, orCtx *orgRepoContext, f form.NewDiscordHook) { c.Title("repo.settings.add_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksNew") c.Data["HookType"] = "discord" meta := &database.SlackMeta{ Username: f.Username, IconURL: f.IconURL, Color: f.Color, } c.Data["SlackMeta"] = meta p, err := jsoniter.Marshal(meta) if err != nil { c.Error(err, "marshal JSON") return } w := &database.Webhook{ RepoID: orCtx.RepoID, URL: f.PayloadURL, ContentType: database.JSON, HookEvent: toHookEvent(f.Webhook), IsActive: f.Active, HookTaskType: database.DISCORD, Meta: string(p), OrgID: orCtx.OrgID, } validateAndCreateWebhook(c, orCtx, w) } func WebhooksDingtalkNewPost(c *context.Context, orCtx *orgRepoContext, f form.NewDingtalkHook) { c.Title("repo.settings.add_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksNew") c.Data["HookType"] = "dingtalk" w := &database.Webhook{ RepoID: orCtx.RepoID, URL: f.PayloadURL, ContentType: database.JSON, HookEvent: toHookEvent(f.Webhook), IsActive: f.Active, HookTaskType: database.DINGTALK, OrgID: orCtx.OrgID, } validateAndCreateWebhook(c, orCtx, w) } func loadWebhook(c *context.Context, orCtx *orgRepoContext) *database.Webhook { c.RequireHighlightJS() var err error var w *database.Webhook if orCtx.RepoID > 0 { w, err = database.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) } else { w, err = database.GetWebhookByOrgID(c.Org.Organization.ID, c.ParamsInt64(":id")) } if err != nil { c.NotFoundOrError(err, "get webhook") return nil } c.Data["Webhook"] = w switch w.HookTaskType { case database.SLACK: c.Data["SlackMeta"] = w.SlackMeta() c.Data["HookType"] = "slack" case database.DISCORD: c.Data["SlackMeta"] = w.SlackMeta() c.Data["HookType"] = "discord" case database.DINGTALK: c.Data["HookType"] = "dingtalk" default: c.Data["HookType"] = "gogs" } c.Data["FormURL"] = fmt.Sprintf("%s/settings/hooks/%s/%d", orCtx.Link, c.Data["HookType"], w.ID) c.Data["DeleteURL"] = fmt.Sprintf("%s/settings/hooks/delete", orCtx.Link) c.Data["History"], err = w.History(1) if err != nil { c.Error(err, "get history") return nil } return w } func WebhooksEdit(c *context.Context, orCtx *orgRepoContext) { c.Title("repo.settings.update_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksEdit") loadWebhook(c, orCtx) if c.Written() { return } c.Success(orCtx.TmplNew) } func validateAndUpdateWebhook(c *context.Context, orCtx *orgRepoContext, w *database.Webhook) { c.Data["Webhook"] = w if c.HasError() { c.Success(orCtx.TmplNew) return } field, msg, ok := validateWebhook(c.Locale, w) if !ok { c.FormErr(field) c.RenderWithErr(msg, orCtx.TmplNew, nil) return } if err := w.UpdateEvent(); err != nil { c.Error(err, "update event") return } else if err := database.UpdateWebhook(w); err != nil { c.Error(err, "update webhook") return } c.Flash.Success(c.Tr("repo.settings.update_hook_success")) c.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) } func WebhooksEditPost(c *context.Context, orCtx *orgRepoContext, f form.NewWebhook) { c.Title("repo.settings.update_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksEdit") w := loadWebhook(c, orCtx) if c.Written() { return } contentType := database.JSON if database.HookContentType(f.ContentType) == database.FORM { contentType = database.FORM } w.URL = f.PayloadURL w.ContentType = contentType w.Secret = f.Secret w.HookEvent = toHookEvent(f.Webhook) w.IsActive = f.Active validateAndUpdateWebhook(c, orCtx, w) } func WebhooksSlackEditPost(c *context.Context, orCtx *orgRepoContext, f form.NewSlackHook) { c.Title("repo.settings.update_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksEdit") w := loadWebhook(c, orCtx) if c.Written() { return } meta, err := jsoniter.Marshal(&database.SlackMeta{ Channel: f.Channel, Username: f.Username, IconURL: f.IconURL, Color: f.Color, }) if err != nil { c.Error(err, "marshal JSON") return } w.URL = f.PayloadURL w.Meta = string(meta) w.HookEvent = toHookEvent(f.Webhook) w.IsActive = f.Active validateAndUpdateWebhook(c, orCtx, w) } func WebhooksDiscordEditPost(c *context.Context, orCtx *orgRepoContext, f form.NewDiscordHook) { c.Title("repo.settings.update_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksEdit") w := loadWebhook(c, orCtx) if c.Written() { return } meta, err := jsoniter.Marshal(&database.SlackMeta{ Username: f.Username, IconURL: f.IconURL, Color: f.Color, }) if err != nil { c.Error(err, "marshal JSON") return } w.URL = f.PayloadURL w.Meta = string(meta) w.HookEvent = toHookEvent(f.Webhook) w.IsActive = f.Active validateAndUpdateWebhook(c, orCtx, w) } func WebhooksDingtalkEditPost(c *context.Context, orCtx *orgRepoContext, f form.NewDingtalkHook) { c.Title("repo.settings.update_webhook") c.PageIs("SettingsHooks") c.PageIs("SettingsHooksEdit") w := loadWebhook(c, orCtx) if c.Written() { return } w.URL = f.PayloadURL w.HookEvent = toHookEvent(f.Webhook) w.IsActive = f.Active validateAndUpdateWebhook(c, orCtx, w) } func TestWebhook(c *context.Context) { var ( commitID string commitMessage string author *git.Signature committer *git.Signature authorUsername string committerUsername string nameStatus *git.NameStatus ) // Grab latest commit or fake one if it's empty repository. if c.Repo.Commit == nil { commitID = git.EmptyID commitMessage = "This is a fake commit" ghost := database.NewGhostUser() author = &git.Signature{ Name: ghost.DisplayName(), Email: ghost.Email, When: time.Now(), } committer = author authorUsername = ghost.Name committerUsername = ghost.Name nameStatus = &git.NameStatus{} } else { commitID = c.Repo.Commit.ID.String() commitMessage = c.Repo.Commit.Message author = c.Repo.Commit.Author committer = c.Repo.Commit.Committer // Try to match email with a real user. author, err := database.Handle.Users().GetByEmail(c.Req.Context(), c.Repo.Commit.Author.Email) if err == nil { authorUsername = author.Name } else if !database.IsErrUserNotExist(err) { c.Error(err, "get user by email") return } user, err := database.Handle.Users().GetByEmail(c.Req.Context(), c.Repo.Commit.Committer.Email) if err == nil { committerUsername = user.Name } else if !database.IsErrUserNotExist(err) { c.Error(err, "get user by email") return } nameStatus, err = c.Repo.Commit.ShowNameStatus() if err != nil { c.Error(err, "get changed files") return } } apiUser := c.User.APIFormat() p := &api.PushPayload{ Ref: git.RefsHeads + c.Repo.Repository.DefaultBranch, Before: commitID, After: commitID, Commits: []*api.PayloadCommit{ { ID: commitID, Message: commitMessage, URL: c.Repo.Repository.HTMLURL() + "/commit/" + commitID, Author: &api.PayloadUser{ Name: author.Name, Email: author.Email, UserName: authorUsername, }, Committer: &api.PayloadUser{ Name: committer.Name, Email: committer.Email, UserName: committerUsername, }, Added: nameStatus.Added, Removed: nameStatus.Removed, Modified: nameStatus.Modified, }, }, Repo: c.Repo.Repository.APIFormatLegacy(nil), Pusher: apiUser, Sender: apiUser, } if err := database.TestWebhook(c.Repo.Repository, database.HookEventTypePush, p, c.ParamsInt64("id")); err != nil { c.Error(err, "test webhook") return } c.Flash.Info(c.Tr("repo.settings.webhook.test_delivery_success")) c.Status(http.StatusOK) } func RedeliveryWebhook(c *context.Context) { webhook, err := database.GetWebhookOfRepoByID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get webhook") return } hookTask, err := database.GetHookTaskOfWebhookByUUID(webhook.ID, c.Query("uuid")) if err != nil { c.NotFoundOrError(err, "get hook task by UUID") return } hookTask.IsDelivered = false if err = database.UpdateHookTask(hookTask); err != nil { c.Error(err, "update hook task") return } go database.HookQueue.Add(c.Repo.Repository.ID) c.Flash.Info(c.Tr("repo.settings.webhook.redelivery_success", hookTask.UUID)) c.Status(http.StatusOK) } func DeleteWebhook(c *context.Context, orCtx *orgRepoContext) { var err error if orCtx.RepoID > 0 { err = database.DeleteWebhookOfRepoByID(orCtx.RepoID, c.QueryInt64("id")) } else { err = database.DeleteWebhookOfOrgByID(orCtx.OrgID, c.QueryInt64("id")) } if err != nil { c.Error(err, "delete webhook") return } c.Flash.Success(c.Tr("repo.settings.webhook_deletion_success")) c.JSONSuccess(map[string]any{ "redirect": orCtx.Link + "/settings/hooks", }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/setting.go
internal/route/repo/setting.go
// Copyright 2014 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 ( "fmt" "io" "strings" "time" "github.com/gogs/git-module" "github.com/unknwon/com" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database/errors" "gogs.io/gogs/internal/email" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/osutil" "gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/userutil" ) const ( tmplRepoSettingsOptions = "repo/settings/options" tmplRepoSettingsAvatar = "repo/settings/avatar" tmplRepoSettingsCollaboration = "repo/settings/collaboration" tmplRepoSettingsBranches = "repo/settings/branches" tmplRepoSettingsProtectedBranch = "repo/settings/protected_branch" tmplRepoSettingsGithooks = "repo/settings/githooks" tmplRepoSettingsGithookEdit = "repo/settings/githook_edit" tmplRepoSettingsDeployKeys = "repo/settings/deploy_keys" ) func Settings(c *context.Context) { c.Title("repo.settings") c.PageIs("SettingsOptions") c.RequireAutosize() c.Success(tmplRepoSettingsOptions) } func SettingsPost(c *context.Context, f form.RepoSetting) { c.Title("repo.settings") c.PageIs("SettingsOptions") c.RequireAutosize() repo := c.Repo.Repository switch c.Query("action") { case "update": if c.HasError() { c.Success(tmplRepoSettingsOptions) return } isNameChanged := false oldRepoName := repo.Name newRepoName := f.RepoName // Check if repository name has been changed. if repo.LowerName != strings.ToLower(newRepoName) { isNameChanged = true if err := database.ChangeRepositoryName(c.Repo.Owner, repo.Name, newRepoName); err != nil { c.FormErr("RepoName") switch { case database.IsErrRepoAlreadyExist(err): c.RenderWithErr(c.Tr("form.repo_name_been_taken"), tmplRepoSettingsOptions, &f) case database.IsErrNameNotAllowed(err): c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplRepoSettingsOptions, &f) default: c.Error(err, "change repository name") } return } log.Trace("Repository name changed: %s/%s -> %s", c.Repo.Owner.Name, repo.Name, newRepoName) } // In case it's just a case change. repo.Name = newRepoName repo.LowerName = strings.ToLower(newRepoName) repo.Description = f.Description repo.Website = f.Website // Visibility of forked repository is forced sync with base repository. if repo.IsFork { f.Private = repo.BaseRepo.IsPrivate f.Unlisted = repo.BaseRepo.IsUnlisted } visibilityChanged := repo.IsPrivate != f.Private || repo.IsUnlisted != f.Unlisted repo.IsPrivate = f.Private repo.IsUnlisted = f.Unlisted if err := database.UpdateRepository(repo, visibilityChanged); err != nil { c.Error(err, "update repository") return } log.Trace("Repository basic settings updated: %s/%s", c.Repo.Owner.Name, repo.Name) if isNameChanged { if err := database.Handle.Actions().RenameRepo(c.Req.Context(), c.User, repo.MustOwner(), oldRepoName, repo); err != nil { log.Error("create rename repository action: %v", err) } } c.Flash.Success(c.Tr("repo.settings.update_settings_success")) c.Redirect(repo.Link() + "/settings") case "mirror": if !repo.IsMirror { c.NotFound() return } if f.Interval > 0 { c.Repo.Mirror.EnablePrune = f.EnablePrune c.Repo.Mirror.Interval = f.Interval c.Repo.Mirror.NextSync = time.Now().Add(time.Duration(f.Interval) * time.Hour) if err := database.UpdateMirror(c.Repo.Mirror); err != nil { c.Error(err, "update mirror") return } } if err := c.Repo.Mirror.SaveAddress(f.MirrorAddress); err != nil { c.Error(err, "save address") return } c.Flash.Success(c.Tr("repo.settings.update_settings_success")) c.Redirect(repo.Link() + "/settings") case "mirror-sync": if !repo.IsMirror { c.NotFound() return } go database.MirrorQueue.Add(repo.ID) c.Flash.Info(c.Tr("repo.settings.mirror_sync_in_progress")) c.Redirect(repo.Link() + "/settings") case "advanced": repo.EnableWiki = f.EnableWiki repo.AllowPublicWiki = f.AllowPublicWiki repo.EnableExternalWiki = f.EnableExternalWiki repo.ExternalWikiURL = f.ExternalWikiURL repo.EnableIssues = f.EnableIssues repo.AllowPublicIssues = f.AllowPublicIssues repo.EnableExternalTracker = f.EnableExternalTracker repo.ExternalTrackerURL = f.ExternalTrackerURL repo.ExternalTrackerFormat = f.TrackerURLFormat repo.ExternalTrackerStyle = f.TrackerIssueStyle repo.EnablePulls = f.EnablePulls repo.PullsIgnoreWhitespace = f.PullsIgnoreWhitespace repo.PullsAllowRebase = f.PullsAllowRebase if !repo.EnableWiki || repo.EnableExternalWiki { repo.AllowPublicWiki = false } if !repo.EnableIssues || repo.EnableExternalTracker { repo.AllowPublicIssues = false } if err := database.UpdateRepository(repo, false); err != nil { c.Error(err, "update repository") return } log.Trace("Repository advanced settings updated: %s/%s", c.Repo.Owner.Name, repo.Name) c.Flash.Success(c.Tr("repo.settings.update_settings_success")) c.Redirect(c.Repo.RepoLink + "/settings") case "convert": if !c.Repo.IsOwner() { c.NotFound() return } if repo.Name != f.RepoName { c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), tmplRepoSettingsOptions, nil) return } if c.Repo.Owner.IsOrganization() { if !c.Repo.Owner.IsOwnedBy(c.User.ID) { c.NotFound() return } } if !repo.IsMirror { c.NotFound() return } repo.IsMirror = false if _, err := database.CleanUpMigrateInfo(repo); err != nil { c.Error(err, "clean up migrate info") return } else if err = database.DeleteMirrorByRepoID(c.Repo.Repository.ID); err != nil { c.Error(err, "delete mirror by repository ID") return } log.Trace("Repository converted from mirror to regular: %s/%s", c.Repo.Owner.Name, repo.Name) c.Flash.Success(c.Tr("repo.settings.convert_succeed")) c.Redirect(conf.Server.Subpath + "/" + c.Repo.Owner.Name + "/" + repo.Name) case "transfer": if !c.Repo.IsOwner() { c.NotFound() return } if repo.Name != f.RepoName { c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), tmplRepoSettingsOptions, nil) return } if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin { if !c.Repo.Owner.IsOwnedBy(c.User.ID) { c.NotFound() return } } newOwner := c.Query("new_owner_name") if !database.Handle.Users().IsUsernameUsed(c.Req.Context(), newOwner, c.Repo.Owner.ID) { c.RenderWithErr(c.Tr("form.enterred_invalid_owner_name"), tmplRepoSettingsOptions, nil) return } if err := database.TransferOwnership(c.User, newOwner, repo); err != nil { if database.IsErrRepoAlreadyExist(err) { c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), tmplRepoSettingsOptions, nil) } else { c.Error(err, "transfer ownership") } return } log.Trace("Repository transferred: %s/%s -> %s", c.Repo.Owner.Name, repo.Name, newOwner) c.Flash.Success(c.Tr("repo.settings.transfer_succeed")) c.Redirect(conf.Server.Subpath + "/" + newOwner + "/" + repo.Name) case "delete": if !c.Repo.IsOwner() { c.NotFound() return } if repo.Name != f.RepoName { c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), tmplRepoSettingsOptions, nil) return } if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin { if !c.Repo.Owner.IsOwnedBy(c.User.ID) { c.NotFound() return } } if err := database.DeleteRepository(c.Repo.Owner.ID, repo.ID); err != nil { c.Error(err, "delete repository") return } log.Trace("Repository deleted: %s/%s", c.Repo.Owner.Name, repo.Name) c.Flash.Success(c.Tr("repo.settings.deletion_success")) c.Redirect(userutil.DashboardURLPath(c.Repo.Owner.Name, c.Repo.Owner.IsOrganization())) case "delete-wiki": if !c.Repo.IsOwner() { c.NotFound() return } if repo.Name != f.RepoName { c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), tmplRepoSettingsOptions, nil) return } if c.Repo.Owner.IsOrganization() && !c.User.IsAdmin { if !c.Repo.Owner.IsOwnedBy(c.User.ID) { c.NotFound() return } } repo.DeleteWiki() log.Trace("Repository wiki deleted: %s/%s", c.Repo.Owner.Name, repo.Name) repo.EnableWiki = false if err := database.UpdateRepository(repo, false); err != nil { c.Error(err, "update repository") return } c.Flash.Success(c.Tr("repo.settings.wiki_deletion_success")) c.Redirect(c.Repo.RepoLink + "/settings") default: c.NotFound() } } func SettingsAvatar(c *context.Context) { c.Title("settings.avatar") c.PageIs("SettingsAvatar") c.Success(tmplRepoSettingsAvatar) } func SettingsAvatarPost(c *context.Context, f form.Avatar) { f.Source = form.AvatarLocal if err := UpdateAvatarSetting(c, f, c.Repo.Repository); err != nil { c.Flash.Error(err.Error()) } else { c.Flash.Success(c.Tr("settings.update_avatar_success")) } c.RedirectSubpath(c.Repo.RepoLink + "/settings") } func SettingsDeleteAvatar(c *context.Context) { if err := c.Repo.Repository.DeleteAvatar(); err != nil { c.Flash.Error(fmt.Sprintf("Failed to delete avatar: %v", err)) } c.RedirectSubpath(c.Repo.RepoLink + "/settings") } // FIXME: limit upload size func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxRepo *database.Repository) error { ctxRepo.UseCustomAvatar = true if f.Avatar != nil { r, err := f.Avatar.Open() if err != nil { return fmt.Errorf("open avatar reader: %v", err) } defer r.Close() data, err := io.ReadAll(r) if err != nil { return fmt.Errorf("read avatar content: %v", err) } if !tool.IsImageFile(data) { return errors.New(c.Tr("settings.uploaded_avatar_not_a_image")) } if err = ctxRepo.UploadAvatar(data); err != nil { return fmt.Errorf("upload avatar: %v", err) } } else { // No avatar is uploaded and reset setting back. if !com.IsFile(ctxRepo.CustomAvatarPath()) { ctxRepo.UseCustomAvatar = false } } if err := database.UpdateRepository(ctxRepo, false); err != nil { return fmt.Errorf("update repository: %v", err) } return nil } func SettingsCollaboration(c *context.Context) { c.Data["Title"] = c.Tr("repo.settings") c.Data["PageIsSettingsCollaboration"] = true users, err := c.Repo.Repository.GetCollaborators() if err != nil { c.Error(err, "get collaborators") return } c.Data["Collaborators"] = users c.Success(tmplRepoSettingsCollaboration) } func SettingsCollaborationPost(c *context.Context) { name := strings.ToLower(c.Query("collaborator")) if name == "" || c.Repo.Owner.LowerName == name { c.Redirect(conf.Server.Subpath + c.Req.URL.Path) return } u, err := database.Handle.Users().GetByUsername(c.Req.Context(), name) if err != nil { if database.IsErrUserNotExist(err) { c.Flash.Error(c.Tr("form.user_not_exist")) c.Redirect(conf.Server.Subpath + c.Req.URL.Path) } else { c.Error(err, "get user by name") } return } // Organization is not allowed to be added as a collaborator if u.IsOrganization() { c.Flash.Error(c.Tr("repo.settings.org_not_allowed_to_be_collaborator")) c.Redirect(conf.Server.Subpath + c.Req.URL.Path) return } if err = c.Repo.Repository.AddCollaborator(u); err != nil { c.Error(err, "add collaborator") return } if conf.User.EnableEmailNotification { email.SendCollaboratorMail(database.NewMailerUser(u), database.NewMailerUser(c.User), database.NewMailerRepo(c.Repo.Repository)) } c.Flash.Success(c.Tr("repo.settings.add_collaborator_success")) c.Redirect(conf.Server.Subpath + c.Req.URL.Path) } func ChangeCollaborationAccessMode(c *context.Context) { if err := c.Repo.Repository.ChangeCollaborationAccessMode( c.QueryInt64("uid"), database.AccessMode(c.QueryInt("mode"))); err != nil { log.Error("ChangeCollaborationAccessMode: %v", err) return } c.Status(204) } func DeleteCollaboration(c *context.Context) { if err := c.Repo.Repository.DeleteCollaboration(c.QueryInt64("id")); err != nil { c.Flash.Error("DeleteCollaboration: " + err.Error()) } else { c.Flash.Success(c.Tr("repo.settings.remove_collaborator_success")) } c.JSONSuccess(map[string]any{ "redirect": c.Repo.RepoLink + "/settings/collaboration", }) } func SettingsBranches(c *context.Context) { c.Data["Title"] = c.Tr("repo.settings.branches") c.Data["PageIsSettingsBranches"] = true if c.Repo.Repository.IsBare { c.Flash.Info(c.Tr("repo.settings.branches_bare"), true) c.Success(tmplRepoSettingsBranches) return } protectBranches, err := database.GetProtectBranchesByRepoID(c.Repo.Repository.ID) if err != nil { c.Error(err, "get protect branch by repository ID") return } // Filter out deleted branches branches := make([]string, 0, len(protectBranches)) for i := range protectBranches { if c.Repo.GitRepo.HasBranch(protectBranches[i].Name) { branches = append(branches, protectBranches[i].Name) } } c.Data["ProtectBranches"] = branches c.Success(tmplRepoSettingsBranches) } func UpdateDefaultBranch(c *context.Context) { branch := c.Query("branch") if c.Repo.GitRepo.HasBranch(branch) && c.Repo.Repository.DefaultBranch != branch { c.Repo.Repository.DefaultBranch = branch if _, err := c.Repo.GitRepo.SymbolicRef(git.SymbolicRefOptions{ Ref: git.RefsHeads + branch, }); err != nil { c.Flash.Warning(c.Tr("repo.settings.update_default_branch_unsupported")) c.Redirect(c.Repo.RepoLink + "/settings/branches") return } } if err := database.UpdateRepository(c.Repo.Repository, false); err != nil { c.Error(err, "update repository") return } c.Flash.Success(c.Tr("repo.settings.update_default_branch_success")) c.Redirect(c.Repo.RepoLink + "/settings/branches") } func SettingsProtectedBranch(c *context.Context) { branch := c.Params("*") if !c.Repo.GitRepo.HasBranch(branch) { c.NotFound() return } c.Data["Title"] = c.Tr("repo.settings.protected_branches") + " - " + branch c.Data["PageIsSettingsBranches"] = true protectBranch, err := database.GetProtectBranchOfRepoByName(c.Repo.Repository.ID, branch) if err != nil { if !database.IsErrBranchNotExist(err) { c.Error(err, "get protect branch of repository by name") return } // No options found, create defaults. protectBranch = &database.ProtectBranch{ Name: branch, } } if c.Repo.Owner.IsOrganization() { users, err := c.Repo.Repository.GetWriters() if err != nil { c.Error(err, "get writers") return } c.Data["Users"] = users c.Data["whitelist_users"] = protectBranch.WhitelistUserIDs teams, err := c.Repo.Owner.TeamsHaveAccessToRepo(c.Repo.Repository.ID, database.AccessModeWrite) if err != nil { c.Error(err, "get teams have access to the repository") return } c.Data["Teams"] = teams c.Data["whitelist_teams"] = protectBranch.WhitelistTeamIDs } c.Data["Branch"] = protectBranch c.Success(tmplRepoSettingsProtectedBranch) } func SettingsProtectedBranchPost(c *context.Context, f form.ProtectBranch) { branch := c.Params("*") if !c.Repo.GitRepo.HasBranch(branch) { c.NotFound() return } protectBranch, err := database.GetProtectBranchOfRepoByName(c.Repo.Repository.ID, branch) if err != nil { if !database.IsErrBranchNotExist(err) { c.Error(err, "get protect branch of repository by name") return } // No options found, create defaults. protectBranch = &database.ProtectBranch{ RepoID: c.Repo.Repository.ID, Name: branch, } } protectBranch.Protected = f.Protected protectBranch.RequirePullRequest = f.RequirePullRequest protectBranch.EnableWhitelist = f.EnableWhitelist if c.Repo.Owner.IsOrganization() { err = database.UpdateOrgProtectBranch(c.Repo.Repository, protectBranch, f.WhitelistUsers, f.WhitelistTeams) } else { err = database.UpdateProtectBranch(protectBranch) } if err != nil { c.Error(err, "update protect branch") return } c.Flash.Success(c.Tr("repo.settings.update_protect_branch_success")) c.Redirect(fmt.Sprintf("%s/settings/branches/%s", c.Repo.RepoLink, branch)) } func SettingsGitHooks(c *context.Context) { c.Data["Title"] = c.Tr("repo.settings.githooks") c.Data["PageIsSettingsGitHooks"] = true hooks, err := c.Repo.GitRepo.Hooks("custom_hooks") if err != nil { c.Error(err, "get hooks") return } c.Data["Hooks"] = hooks c.Success(tmplRepoSettingsGithooks) } func SettingsGitHooksEdit(c *context.Context) { c.Data["Title"] = c.Tr("repo.settings.githooks") c.Data["PageIsSettingsGitHooks"] = true c.Data["RequireSimpleMDE"] = true name := c.Params(":name") hook, err := c.Repo.GitRepo.Hook("custom_hooks", git.HookName(name)) if err != nil { c.NotFoundOrError(osutil.NewError(err), "get hook") return } c.Data["Hook"] = hook c.Success(tmplRepoSettingsGithookEdit) } func SettingsGitHooksEditPost(c *context.Context) { name := c.Params(":name") hook, err := c.Repo.GitRepo.Hook("custom_hooks", git.HookName(name)) if err != nil { c.NotFoundOrError(osutil.NewError(err), "get hook") return } if err = hook.Update(c.Query("content")); err != nil { c.Error(err, "update hook") return } c.Redirect(c.Data["Link"].(string)) } func SettingsDeployKeys(c *context.Context) { c.Data["Title"] = c.Tr("repo.settings.deploy_keys") c.Data["PageIsSettingsKeys"] = true keys, err := database.ListDeployKeys(c.Repo.Repository.ID) if err != nil { c.Error(err, "list deploy keys") return } c.Data["Deploykeys"] = keys c.Success(tmplRepoSettingsDeployKeys) } func SettingsDeployKeysPost(c *context.Context, f form.AddSSHKey) { c.Data["Title"] = c.Tr("repo.settings.deploy_keys") c.Data["PageIsSettingsKeys"] = true keys, err := database.ListDeployKeys(c.Repo.Repository.ID) if err != nil { c.Error(err, "list deploy keys") return } c.Data["Deploykeys"] = keys if c.HasError() { c.Success(tmplRepoSettingsDeployKeys) return } content, err := database.CheckPublicKeyString(f.Content) if err != nil { if database.IsErrKeyUnableVerify(err) { c.Flash.Info(c.Tr("form.unable_verify_ssh_key")) } else { c.Data["HasError"] = true c.Data["Err_Content"] = true c.Flash.Error(c.Tr("form.invalid_ssh_key", err.Error())) c.Redirect(c.Repo.RepoLink + "/settings/keys") return } } key, err := database.AddDeployKey(c.Repo.Repository.ID, f.Title, content) if err != nil { c.Data["HasError"] = true switch { case database.IsErrKeyAlreadyExist(err): c.Data["Err_Content"] = true c.RenderWithErr(c.Tr("repo.settings.key_been_used"), tmplRepoSettingsDeployKeys, &f) case database.IsErrKeyNameAlreadyUsed(err): c.Data["Err_Title"] = true c.RenderWithErr(c.Tr("repo.settings.key_name_used"), tmplRepoSettingsDeployKeys, &f) default: c.Error(err, "add deploy key") } return } log.Trace("Deploy key added: %d", c.Repo.Repository.ID) c.Flash.Success(c.Tr("repo.settings.add_key_success", key.Name)) c.Redirect(c.Repo.RepoLink + "/settings/keys") } func DeleteDeployKey(c *context.Context) { if err := database.DeleteDeployKey(c.User, c.QueryInt64("id")); err != nil { c.Flash.Error("DeleteDeployKey: " + err.Error()) } else { c.Flash.Success(c.Tr("repo.settings.deploy_key_deletion_success")) } c.JSONSuccess(map[string]any{ "redirect": c.Repo.RepoLink + "/settings/keys", }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/release.go
internal/route/repo/release.go
// Copyright 2014 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 ( "fmt" "strings" "github.com/gogs/git-module" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/markup" ) const ( tmplRepoReleaseList = "repo/release/list" tmplRepoReleaseNew = "repo/release/new" ) // calReleaseNumCommitsBehind calculates given release has how many commits behind release target. func calReleaseNumCommitsBehind(repoCtx *context.Repository, release *database.Release, countCache map[string]int64) error { // Get count if not exists if _, ok := countCache[release.Target]; !ok { if repoCtx.GitRepo.HasBranch(release.Target) { commit, err := repoCtx.GitRepo.BranchCommit(release.Target) if err != nil { return fmt.Errorf("get branch commit: %v", err) } countCache[release.Target], err = commit.CommitsCount() if err != nil { return fmt.Errorf("count commits: %v", err) } } else { // Use NumCommits of the newest release on that target countCache[release.Target] = release.NumCommits } } release.NumCommitsBehind = countCache[release.Target] - release.NumCommits return nil } func Releases(c *context.Context) { c.Data["Title"] = c.Tr("repo.release.releases") c.Data["PageIsViewFiles"] = true c.Data["PageIsReleaseList"] = true tagsPage, err := gitutil.Module.ListTagsAfter(c.Repo.GitRepo.Path(), c.Query("after"), 10) if err != nil { c.Error(err, "get tags") return } releases, err := database.GetPublishedReleasesByRepoID(c.Repo.Repository.ID, tagsPage.Tags...) if err != nil { c.Error(err, "get published releases by repository ID") return } // Temporary cache commits count of used branches to speed up. countCache := make(map[string]int64) results := make([]*database.Release, len(tagsPage.Tags)) for i, rawTag := range tagsPage.Tags { for j, r := range releases { if r == nil || r.TagName != rawTag { continue } releases[j] = nil // Mark as used. if err = r.LoadAttributes(); err != nil { c.Error(err, "load attributes") return } if err := calReleaseNumCommitsBehind(c.Repo, r, countCache); err != nil { c.Error(err, "calculate number of commits after release") return } r.Note = string(markup.Markdown(r.Note, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) results[i] = r break } // No published release matches this tag if results[i] == nil { commit, err := c.Repo.GitRepo.TagCommit(rawTag) if err != nil { c.Error(err, "get tag commit") return } results[i] = &database.Release{ Title: rawTag, TagName: rawTag, Sha1: commit.ID.String(), } results[i].NumCommits, err = commit.CommitsCount() if err != nil { c.Error(err, "count commits") return } results[i].NumCommitsBehind = c.Repo.CommitsCount - results[i].NumCommits } } database.SortReleases(results) // Only show drafts if user is viewing the latest page var drafts []*database.Release if tagsPage.HasLatest { drafts, err = database.GetDraftReleasesByRepoID(c.Repo.Repository.ID) if err != nil { c.Error(err, "get draft releases by repository ID") return } for _, r := range drafts { if err = r.LoadAttributes(); err != nil { c.Error(err, "load attributes") return } if err := calReleaseNumCommitsBehind(c.Repo, r, countCache); err != nil { c.Error(err, "calculate number of commits after release") return } r.Note = string(markup.Markdown(r.Note, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) } if len(drafts) > 0 { results = append(drafts, results...) } } c.Data["Releases"] = results c.Data["HasPrevious"] = !tagsPage.HasLatest c.Data["ReachEnd"] = !tagsPage.HasNext c.Data["PreviousAfter"] = tagsPage.PreviousAfter if len(results) > 0 { c.Data["NextAfter"] = results[len(results)-1].TagName } c.Success(tmplRepoReleaseList) } func renderReleaseAttachmentSettings(c *context.Context) { c.Data["RequireDropzone"] = true c.Data["IsAttachmentEnabled"] = conf.Release.Attachment.Enabled c.Data["AttachmentAllowedTypes"] = strings.Join(conf.Release.Attachment.AllowedTypes, ",") c.Data["AttachmentMaxSize"] = conf.Release.Attachment.MaxSize c.Data["AttachmentMaxFiles"] = conf.Release.Attachment.MaxFiles } func NewRelease(c *context.Context) { c.Data["Title"] = c.Tr("repo.release.new_release") c.Data["PageIsReleaseList"] = true c.Data["tag_target"] = c.Repo.Repository.DefaultBranch renderReleaseAttachmentSettings(c) c.Success(tmplRepoReleaseNew) } func NewReleasePost(c *context.Context, f form.NewRelease) { c.Data["Title"] = c.Tr("repo.release.new_release") c.Data["PageIsReleaseList"] = true renderReleaseAttachmentSettings(c) if c.HasError() { c.Success(tmplRepoReleaseNew) return } if !c.Repo.GitRepo.HasBranch(f.Target) { c.RenderWithErr(c.Tr("form.target_branch_not_exist"), tmplRepoReleaseNew, &f) return } // Use current time if tag not yet exist, otherwise get time from Git var tagCreatedUnix int64 tag, err := c.Repo.GitRepo.Tag(git.RefsTags + f.TagName) if err == nil { commit, err := tag.Commit() if err == nil { tagCreatedUnix = commit.Author.When.Unix() } } commit, err := c.Repo.GitRepo.BranchCommit(f.Target) if err != nil { c.Error(err, "get branch commit") return } commitsCount, err := commit.CommitsCount() if err != nil { c.Error(err, "count commits") return } var attachments []string if conf.Release.Attachment.Enabled { attachments = f.Files } rel := &database.Release{ RepoID: c.Repo.Repository.ID, PublisherID: c.User.ID, Title: f.Title, TagName: f.TagName, Target: f.Target, Sha1: commit.ID.String(), NumCommits: commitsCount, Note: f.Content, IsDraft: len(f.Draft) > 0, IsPrerelease: f.Prerelease, CreatedUnix: tagCreatedUnix, } if err = database.NewRelease(c.Repo.GitRepo, rel, attachments); err != nil { c.Data["Err_TagName"] = true switch { case database.IsErrReleaseAlreadyExist(err): c.RenderWithErr(c.Tr("repo.release.tag_name_already_exist"), tmplRepoReleaseNew, &f) case database.IsErrInvalidTagName(err): c.RenderWithErr(c.Tr("repo.release.tag_name_invalid"), tmplRepoReleaseNew, &f) default: c.Error(err, "new release") } return } log.Trace("Release created: %s/%s:%s", c.User.LowerName, c.Repo.Repository.Name, f.TagName) c.Redirect(c.Repo.RepoLink + "/releases") } func EditRelease(c *context.Context) { c.Data["Title"] = c.Tr("repo.release.edit_release") c.Data["PageIsReleaseList"] = true c.Data["PageIsEditRelease"] = true renderReleaseAttachmentSettings(c) tagName := c.Params("*") rel, err := database.GetRelease(c.Repo.Repository.ID, tagName) if err != nil { c.NotFoundOrError(err, "get release") return } c.Data["ID"] = rel.ID c.Data["tag_name"] = rel.TagName c.Data["tag_target"] = rel.Target c.Data["title"] = rel.Title c.Data["content"] = rel.Note c.Data["attachments"] = rel.Attachments c.Data["prerelease"] = rel.IsPrerelease c.Data["IsDraft"] = rel.IsDraft c.Success(tmplRepoReleaseNew) } func EditReleasePost(c *context.Context, f form.EditRelease) { c.Data["Title"] = c.Tr("repo.release.edit_release") c.Data["PageIsReleaseList"] = true c.Data["PageIsEditRelease"] = true renderReleaseAttachmentSettings(c) tagName := c.Params("*") rel, err := database.GetRelease(c.Repo.Repository.ID, tagName) if err != nil { c.NotFoundOrError(err, "get release") return } c.Data["tag_name"] = rel.TagName c.Data["tag_target"] = rel.Target c.Data["title"] = rel.Title c.Data["content"] = rel.Note c.Data["attachments"] = rel.Attachments c.Data["prerelease"] = rel.IsPrerelease c.Data["IsDraft"] = rel.IsDraft if c.HasError() { c.Success(tmplRepoReleaseNew) return } var attachments []string if conf.Release.Attachment.Enabled { attachments = f.Files } isPublish := rel.IsDraft && f.Draft == "" rel.Title = f.Title rel.Note = f.Content rel.IsDraft = len(f.Draft) > 0 rel.IsPrerelease = f.Prerelease if err = database.UpdateRelease(c.User, c.Repo.GitRepo, rel, isPublish, attachments); err != nil { c.Error(err, "update release") return } c.Redirect(c.Repo.RepoLink + "/releases") } func UploadReleaseAttachment(c *context.Context) { if !conf.Release.Attachment.Enabled { c.NotFound() return } uploadAttachment(c, conf.Release.Attachment.AllowedTypes) } func DeleteRelease(c *context.Context) { if err := database.DeleteReleaseOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil { c.Flash.Error("DeleteReleaseByID: " + err.Error()) } else { c.Flash.Success(c.Tr("repo.release.deletion_success")) } c.JSONSuccess(map[string]any{ "redirect": c.Repo.RepoLink + "/releases", }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/issue.go
internal/route/repo/issue.go
// Copyright 2014 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 ( "fmt" "net/http" "net/url" "strings" "time" "github.com/unknwon/com" "github.com/unknwon/paginater" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database/errors" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/tool" ) const ( tmplRepoIssueList = "repo/issue/list" tmplRepoIssueNew = "repo/issue/new" tmplRepoIssueView = "repo/issue/view" tmplRepoIssueLabels = "repo/issue/labels" tmplRepoIssueMilestones = "repo/issue/milestones" tmplRepoIssueMilestoneNew = "repo/issue/milestone_new" tmplRepoIssueMilestoneEdit = "repo/issue/milestone_edit" IssueTemplateKey = "IssueTemplate" ) var ( ErrFileTypeForbidden = errors.New("File type is not allowed") ErrTooManyFiles = errors.New("Maximum number of files to upload exceeded") IssueTemplateCandidates = []string{ "ISSUE_TEMPLATE.md", ".gogs/ISSUE_TEMPLATE.md", ".github/ISSUE_TEMPLATE.md", } ) func MustEnableIssues(c *context.Context) { if !c.Repo.Repository.EnableIssues { c.NotFound() return } if c.Repo.Repository.EnableExternalTracker { c.Redirect(c.Repo.Repository.ExternalTrackerURL) return } } func MustAllowPulls(c *context.Context) { if !c.Repo.Repository.AllowsPulls() { c.NotFound() return } // User can send pull request if owns a forked repository. if c.IsLogged && database.Handle.Repositories().HasForkedBy(c.Req.Context(), c.Repo.Repository.ID, c.User.ID) { c.Repo.PullRequest.Allowed = true c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName } } func RetrieveLabels(c *context.Context) { labels, err := database.GetLabelsByRepoID(c.Repo.Repository.ID) if err != nil { c.Error(err, "get labels by repository ID") return } for _, l := range labels { l.CalOpenIssues() } c.Data["Labels"] = labels c.Data["NumLabels"] = len(labels) } func issues(c *context.Context, isPullList bool) { if isPullList { MustAllowPulls(c) if c.Written() { return } c.Data["Title"] = c.Tr("repo.pulls") c.Data["PageIsPullList"] = true } else { MustEnableIssues(c) if c.Written() { return } c.Data["Title"] = c.Tr("repo.issues") c.Data["PageIsIssueList"] = true } viewType := c.Query("type") sortType := c.Query("sort") types := []string{"assigned", "created_by", "mentioned"} if !com.IsSliceContainsStr(types, viewType) { viewType = "all" } // Must sign in to see issues about you. if viewType != "all" && !c.IsLogged { c.SetCookie("redirect_to", "/"+url.QueryEscape(conf.Server.Subpath+c.Req.RequestURI), 0, conf.Server.Subpath) c.Redirect(conf.Server.Subpath + "/user/login") return } var ( assigneeID = c.QueryInt64("assignee") posterID int64 ) filterMode := database.FilterModeYourRepos switch viewType { case "assigned": filterMode = database.FilterModeAssign assigneeID = c.User.ID case "created_by": filterMode = database.FilterModeCreate posterID = c.User.ID case "mentioned": filterMode = database.FilterModeMention } var uid int64 = -1 if c.IsLogged { uid = c.User.ID } repo := c.Repo.Repository selectLabels := c.Query("labels") milestoneID := c.QueryInt64("milestone") isShowClosed := c.Query("state") == "closed" issueStats := database.GetIssueStats(&database.IssueStatsOptions{ RepoID: repo.ID, UserID: uid, Labels: selectLabels, MilestoneID: milestoneID, AssigneeID: assigneeID, FilterMode: filterMode, IsPull: isPullList, }) page := c.QueryInt("page") if page <= 1 { page = 1 } var total int if !isShowClosed { total = int(issueStats.OpenCount) } else { total = int(issueStats.ClosedCount) } pager := paginater.New(total, conf.UI.IssuePagingNum, page, 5) c.Data["Page"] = pager issues, err := database.Issues(&database.IssuesOptions{ UserID: uid, AssigneeID: assigneeID, RepoID: repo.ID, PosterID: posterID, MilestoneID: milestoneID, Page: pager.Current(), IsClosed: isShowClosed, IsMention: filterMode == database.FilterModeMention, IsPull: isPullList, Labels: selectLabels, SortType: sortType, }) if err != nil { c.Error(err, "list issues") return } // Get issue-user relations. pairs, err := database.GetIssueUsers(repo.ID, posterID, isShowClosed) if err != nil { c.Error(err, "get issue-user relations") return } // Get posters. for i := range issues { if !c.IsLogged { issues[i].IsRead = true continue } // Check read status. idx := database.PairsContains(pairs, issues[i].ID, c.User.ID) if idx > -1 { issues[i].IsRead = pairs[idx].IsRead } else { issues[i].IsRead = true } } c.Data["Issues"] = issues // Get milestones. c.Data["Milestones"], err = database.GetMilestonesByRepoID(repo.ID) if err != nil { c.Error(err, "get milestone by repository ID") return } // Get assignees. c.Data["Assignees"], err = repo.GetAssignees() if err != nil { c.Error(err, "get assignees") return } if viewType == "assigned" { assigneeID = 0 // Reset ID to prevent unexpected selection of assignee. } c.Data["IssueStats"] = issueStats c.Data["SelectLabels"] = com.StrTo(selectLabels).MustInt64() c.Data["ViewType"] = viewType c.Data["SortType"] = sortType c.Data["MilestoneID"] = milestoneID c.Data["AssigneeID"] = assigneeID c.Data["IsShowClosed"] = isShowClosed if isShowClosed { c.Data["State"] = "closed" } else { c.Data["State"] = "open" } c.Success(tmplRepoIssueList) } func Issues(c *context.Context) { issues(c, false) } func Pulls(c *context.Context) { issues(c, true) } func renderAttachmentSettings(c *context.Context) { c.Data["RequireDropzone"] = true c.Data["IsAttachmentEnabled"] = conf.Attachment.Enabled c.Data["AttachmentAllowedTypes"] = conf.Attachment.AllowedTypes c.Data["AttachmentMaxSize"] = conf.Attachment.MaxSize c.Data["AttachmentMaxFiles"] = conf.Attachment.MaxFiles } func RetrieveRepoMilestonesAndAssignees(c *context.Context, repo *database.Repository) { var err error c.Data["OpenMilestones"], err = database.GetMilestones(repo.ID, -1, false) if err != nil { c.Error(err, "get open milestones") return } c.Data["ClosedMilestones"], err = database.GetMilestones(repo.ID, -1, true) if err != nil { c.Error(err, "get closed milestones") return } c.Data["Assignees"], err = repo.GetAssignees() if err != nil { c.Error(err, "get assignees") return } } func RetrieveRepoMetas(c *context.Context, repo *database.Repository) []*database.Label { if !c.Repo.IsWriter() { return nil } labels, err := database.GetLabelsByRepoID(repo.ID) if err != nil { c.Error(err, "get labels by repository ID") return nil } c.Data["Labels"] = labels RetrieveRepoMilestonesAndAssignees(c, repo) if c.Written() { return nil } return labels } func getFileContentFromDefaultBranch(c *context.Context, filename string) (string, bool) { if c.Repo.Commit == nil { var err error c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(c.Repo.Repository.DefaultBranch) if err != nil { return "", false } } entry, err := c.Repo.Commit.TreeEntry(filename) if err != nil { return "", false } p, err := entry.Blob().Bytes() if err != nil { return "", false } return string(p), true } func setTemplateIfExists(c *context.Context, ctxDataKey string, possibleFiles []string) { for _, filename := range possibleFiles { content, found := getFileContentFromDefaultBranch(c, filename) if found { c.Data[ctxDataKey] = content return } } } func NewIssue(c *context.Context) { c.Data["Title"] = c.Tr("repo.issues.new") c.Data["PageIsIssueList"] = true c.Data["RequireHighlightJS"] = true c.Data["RequireSimpleMDE"] = true c.Data["title"] = c.Query("title") c.Data["content"] = c.Query("content") setTemplateIfExists(c, IssueTemplateKey, IssueTemplateCandidates) renderAttachmentSettings(c) RetrieveRepoMetas(c, c.Repo.Repository) if c.Written() { return } c.Success(tmplRepoIssueNew) } func ValidateRepoMetas(c *context.Context, f form.NewIssue) ([]int64, int64, int64) { var ( repo = c.Repo.Repository err error ) labels := RetrieveRepoMetas(c, c.Repo.Repository) if c.Written() { return nil, 0, 0 } if !c.Repo.IsWriter() { return nil, 0, 0 } // Check labels. labelIDs := tool.StringsToInt64s(strings.Split(f.LabelIDs, ",")) labelIDMark := tool.Int64sToMap(labelIDs) hasSelected := false for i := range labels { if labelIDMark[labels[i].ID] { labels[i].IsChecked = true hasSelected = true } } c.Data["HasSelectedLabel"] = hasSelected c.Data["label_ids"] = f.LabelIDs c.Data["Labels"] = labels // Check milestone. milestoneID := f.MilestoneID if milestoneID > 0 { c.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID) if err != nil { c.Error(err, "get milestone by ID") return nil, 0, 0 } c.Data["milestone_id"] = milestoneID } // Check assignee. assigneeID := f.AssigneeID if assigneeID > 0 { c.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID) if err != nil { c.Error(err, "get assignee by ID") return nil, 0, 0 } c.Data["assignee_id"] = assigneeID } return labelIDs, milestoneID, assigneeID } func NewIssuePost(c *context.Context, f form.NewIssue) { c.Data["Title"] = c.Tr("repo.issues.new") c.Data["PageIsIssueList"] = true c.Data["RequireHighlightJS"] = true c.Data["RequireSimpleMDE"] = true renderAttachmentSettings(c) labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f) if c.Written() { return } if c.HasError() { c.Success(tmplRepoIssueNew) return } var attachments []string if conf.Attachment.Enabled { attachments = f.Files } issue := &database.Issue{ RepoID: c.Repo.Repository.ID, Title: f.Title, PosterID: c.User.ID, Poster: c.User, MilestoneID: milestoneID, AssigneeID: assigneeID, Content: f.Content, } if err := database.NewIssue(c.Repo.Repository, issue, labelIDs, attachments); err != nil { c.Error(err, "new issue") return } log.Trace("Issue created: %d/%d", c.Repo.Repository.ID, issue.ID) c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("issues/%d", issue.Index))) } func uploadAttachment(c *context.Context, allowedTypes []string) { file, header, err := c.Req.FormFile("file") if err != nil { c.Error(err, "get file") return } defer file.Close() buf := make([]byte, 1024) n, _ := file.Read(buf) if n > 0 { buf = buf[:n] } fileType := http.DetectContentType(buf) allowed := false for _, t := range allowedTypes { t := strings.Trim(t, " ") if t == "*/*" || t == fileType { allowed = true break } } if !allowed { c.PlainText(http.StatusBadRequest, ErrFileTypeForbidden.Error()) return } attach, err := database.NewAttachment(header.Filename, buf, file) if err != nil { c.Error(err, "new attachment") return } log.Trace("New attachment uploaded: %s", attach.UUID) c.JSONSuccess(map[string]string{ "uuid": attach.UUID, }) } func UploadIssueAttachment(c *context.Context) { if !conf.Attachment.Enabled { c.NotFound() return } uploadAttachment(c, conf.Attachment.AllowedTypes) } func viewIssue(c *context.Context, isPullList bool) { c.Data["RequireHighlightJS"] = true c.Data["RequireDropzone"] = true renderAttachmentSettings(c) index := c.ParamsInt64(":index") if index <= 0 { c.NotFound() return } issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, index) if err != nil { c.NotFoundOrError(err, "get issue by index") return } c.Data["Title"] = issue.Title // Make sure type and URL matches. if !isPullList && issue.IsPull { c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("pulls/%d", issue.Index))) return } else if isPullList && !issue.IsPull { c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("issues/%d", issue.Index))) return } if issue.IsPull { MustAllowPulls(c) if c.Written() { return } c.Data["PageIsPullList"] = true c.Data["PageIsPullConversation"] = true } else { MustEnableIssues(c) if c.Written() { return } c.Data["PageIsIssueList"] = true } issue.RenderedContent = string(markup.Markdown(issue.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) repo := c.Repo.Repository // Get more information if it's a pull request. if issue.IsPull { if issue.PullRequest.HasMerged { c.Data["DisableStatusChange"] = issue.PullRequest.HasMerged PrepareMergedViewPullInfo(c, issue) } else { PrepareViewPullInfo(c, issue) } if c.Written() { return } } // Metas. // Check labels. labelIDMark := make(map[int64]bool) for i := range issue.Labels { labelIDMark[issue.Labels[i].ID] = true } labels, err := database.GetLabelsByRepoID(repo.ID) if err != nil { c.Error(err, "get labels by repository ID") return } hasSelected := false for i := range labels { if labelIDMark[labels[i].ID] { labels[i].IsChecked = true hasSelected = true } } c.Data["HasSelectedLabel"] = hasSelected c.Data["Labels"] = labels // Check milestone and assignee. if c.Repo.IsWriter() { RetrieveRepoMilestonesAndAssignees(c, repo) if c.Written() { return } } if c.IsLogged { // Update issue-user. if err = issue.ReadBy(c.User.ID); err != nil { c.Error(err, "mark read by") return } } var ( tag database.CommentTag ok bool marked = make(map[int64]database.CommentTag) comment *database.Comment participants = make([]*database.User, 1, 10) ) // Render comments and fetch participants. participants[0] = issue.Poster for _, comment = range issue.Comments { if comment.Type == database.CommentTypeComment { comment.RenderedContent = string(markup.Markdown(comment.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) // Check tag. tag, ok = marked[comment.PosterID] if ok { comment.ShowTag = tag continue } if repo.IsOwnedBy(comment.PosterID) || (repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(comment.PosterID)) { comment.ShowTag = database.CommentTagOwner } else if database.Handle.Permissions().Authorize( c.Req.Context(), comment.PosterID, repo.ID, database.AccessModeWrite, database.AccessModeOptions{ OwnerID: repo.OwnerID, Private: repo.IsPrivate, }, ) { comment.ShowTag = database.CommentTagWriter } else if comment.PosterID == issue.PosterID { comment.ShowTag = database.CommentTagPoster } marked[comment.PosterID] = comment.ShowTag isAdded := false for j := range participants { if comment.Poster == participants[j] { isAdded = true break } } if !isAdded && !issue.IsPoster(comment.Poster.ID) { participants = append(participants, comment.Poster) } } } if issue.IsPull && issue.PullRequest.HasMerged { pull := issue.PullRequest branchProtected := false protectBranch, err := database.GetProtectBranchOfRepoByName(pull.BaseRepoID, pull.HeadBranch) if err != nil { if !database.IsErrBranchNotExist(err) { c.Error(err, "get protect branch of repository by name") return } } else { branchProtected = protectBranch.Protected } c.Data["IsPullBranchDeletable"] = pull.BaseRepoID == pull.HeadRepoID && c.Repo.IsWriter() && c.Repo.GitRepo.HasBranch(pull.HeadBranch) && !branchProtected c.Data["DeleteBranchLink"] = c.Repo.MakeURL(url.URL{ Path: "branches/delete/" + pull.HeadBranch, RawQuery: fmt.Sprintf("commit=%s&redirect_to=%s", pull.MergedCommitID, c.Data["Link"]), }) } c.Data["Participants"] = participants c.Data["NumParticipants"] = len(participants) c.Data["Issue"] = issue c.Data["IsIssueOwner"] = c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID)) c.Data["SignInLink"] = conf.Server.Subpath + "/user/login?redirect_to=" + c.Data["Link"].(string) c.Success(tmplRepoIssueView) } func ViewIssue(c *context.Context) { viewIssue(c, false) } func ViewPull(c *context.Context) { viewIssue(c, true) } func getActionIssue(c *context.Context) *database.Issue { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return nil } // Prevent guests accessing pull requests if !c.Repo.HasAccess() && issue.IsPull { c.NotFound() return nil } return issue } func UpdateIssueTitle(c *context.Context) { issue := getActionIssue(c) if c.Written() { return } if !c.IsLogged || (!issue.IsPoster(c.User.ID) && !c.Repo.IsWriter()) { c.Status(http.StatusForbidden) return } title := c.QueryTrim("title") if title == "" { c.Status(http.StatusNoContent) return } if err := issue.ChangeTitle(c.User, title); err != nil { c.Error(err, "change title") return } c.JSONSuccess(map[string]any{ "title": issue.Title, }) } func UpdateIssueContent(c *context.Context) { issue := getActionIssue(c) if c.Written() { return } if !c.IsLogged || (c.User.ID != issue.PosterID && !c.Repo.IsWriter()) { c.Status(http.StatusForbidden) return } content := c.Query("content") if err := issue.ChangeContent(c.User, content); err != nil { c.Error(err, "change content") return } c.JSONSuccess(map[string]string{ "content": string(markup.Markdown(issue.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())), }) } func UpdateIssueLabel(c *context.Context) { issue := getActionIssue(c) if c.Written() { return } if c.Query("action") == "clear" { if err := issue.ClearLabels(c.User); err != nil { c.Error(err, "clear labels") return } } else { isAttach := c.Query("action") == "attach" label, err := database.GetLabelOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")) if err != nil { c.NotFoundOrError(err, "get label by ID") return } if isAttach && !issue.HasLabel(label.ID) { if err = issue.AddLabel(c.User, label); err != nil { c.Error(err, "add label") return } } else if !isAttach && issue.HasLabel(label.ID) { if err = issue.RemoveLabel(c.User, label); err != nil { c.Error(err, "remove label") return } } } c.JSONSuccess(map[string]any{ "ok": true, }) } func UpdateIssueMilestone(c *context.Context) { issue := getActionIssue(c) if c.Written() { return } oldMilestoneID := issue.MilestoneID milestoneID := c.QueryInt64("id") if oldMilestoneID == milestoneID { c.JSONSuccess(map[string]any{ "ok": true, }) return } // Not check for invalid milestone id and give responsibility to owners. issue.MilestoneID = milestoneID if err := database.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil { c.Error(err, "change milestone assign") return } c.JSONSuccess(map[string]any{ "ok": true, }) } func UpdateIssueAssignee(c *context.Context) { issue := getActionIssue(c) if c.Written() { return } assigneeID := c.QueryInt64("id") if issue.AssigneeID == assigneeID { c.JSONSuccess(map[string]any{ "ok": true, }) return } if err := issue.ChangeAssignee(c.User, assigneeID); err != nil { c.Error(err, "change assignee") return } c.JSONSuccess(map[string]any{ "ok": true, }) } func NewComment(c *context.Context, f form.CreateComment) { issue := getActionIssue(c) if c.Written() { return } var attachments []string if conf.Attachment.Enabled { attachments = f.Files } if c.HasError() { c.Flash.Error(c.Data["ErrorMsg"].(string)) c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("issues/%d", issue.Index))) return } var err error var comment *database.Comment defer func() { // Check if issue admin/poster changes the status of issue. if (c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID))) && (f.Status == "reopen" || f.Status == "close") && !(issue.IsPull && issue.PullRequest.HasMerged) { // Duplication and conflict check should apply to reopen pull request. var pr *database.PullRequest if f.Status == "reopen" && issue.IsPull { pull := issue.PullRequest pr, err = database.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch) if err != nil { if !database.IsErrPullRequestNotExist(err) { c.Error(err, "get unmerged pull request") return } } // Regenerate patch and test conflict. if pr == nil { if err = issue.PullRequest.UpdatePatch(); err != nil { c.Error(err, "update patch") return } issue.PullRequest.AddToTaskQueue() } } if pr != nil { c.Flash.Info(c.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index)) } else { if err = issue.ChangeStatus(c.User, c.Repo.Repository, f.Status == "close"); err != nil { log.Error("ChangeStatus: %v", err) } else { log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed) } } } // Redirect to comment hashtag if there is any actual content. typeName := "issues" if issue.IsPull { typeName = "pulls" } location := url.URL{ Path: fmt.Sprintf("%s/%d", typeName, issue.Index), } if comment != nil { location.Fragment = comment.HashTag() } c.RawRedirect(c.Repo.MakeURL(location)) }() // Fix #321: Allow empty comments, as long as we have attachments. if f.Content == "" && len(attachments) == 0 { return } comment, err = database.CreateIssueComment(c.User, c.Repo.Repository, issue, f.Content, attachments) if err != nil { c.Error(err, "create issue comment") return } log.Trace("Comment created: %d/%d/%d", c.Repo.Repository.ID, issue.ID, comment.ID) } func UpdateCommentContent(c *context.Context) { comment, err := database.GetCommentByID(c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get comment by ID") return } if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() { c.NotFound() return } else if comment.Type != database.CommentTypeComment { c.Status(http.StatusNoContent) return } oldContent := comment.Content comment.Content = c.Query("content") if comment.Content == "" { c.JSONSuccess(map[string]any{ "content": "", }) return } if err = database.UpdateComment(c.User, comment, oldContent); err != nil { c.Error(err, "update comment") return } c.JSONSuccess(map[string]string{ "content": string(markup.Markdown(comment.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())), }) } func DeleteComment(c *context.Context) { comment, err := database.GetCommentByID(c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get comment by ID") return } if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() { c.NotFound() return } else if comment.Type != database.CommentTypeComment { c.Status(http.StatusNoContent) return } if err = database.DeleteCommentByID(c.User, comment.ID); err != nil { c.Error(err, "delete comment by ID") return } c.Status(http.StatusOK) } func Labels(c *context.Context) { c.Data["Title"] = c.Tr("repo.labels") c.Data["PageIsIssueList"] = true c.Data["PageIsLabels"] = true c.Data["RequireMinicolors"] = true c.Data["LabelTemplates"] = database.LabelTemplates c.Success(tmplRepoIssueLabels) } func InitializeLabels(c *context.Context, f form.InitializeLabels) { if c.HasError() { c.RawRedirect(c.Repo.MakeURL("labels")) return } list, err := database.GetLabelTemplateFile(f.TemplateName) if err != nil { c.Flash.Error(c.Tr("repo.issues.label_templates.fail_to_load_file", f.TemplateName, err)) c.RawRedirect(c.Repo.MakeURL("labels")) return } labels := make([]*database.Label, len(list)) for i := 0; i < len(list); i++ { labels[i] = &database.Label{ RepoID: c.Repo.Repository.ID, Name: list[i][0], Color: list[i][1], } } if err := database.NewLabels(labels...); err != nil { c.Error(err, "new labels") return } c.RawRedirect(c.Repo.MakeURL("labels")) } func NewLabel(c *context.Context, f form.CreateLabel) { c.Data["Title"] = c.Tr("repo.labels") c.Data["PageIsLabels"] = true if c.HasError() { c.Flash.Error(c.Data["ErrorMsg"].(string)) c.RawRedirect(c.Repo.MakeURL("labels")) return } l := &database.Label{ RepoID: c.Repo.Repository.ID, Name: f.Title, Color: f.Color, } if err := database.NewLabels(l); err != nil { c.Error(err, "new labels") return } c.RawRedirect(c.Repo.MakeURL("labels")) } func UpdateLabel(c *context.Context, f form.CreateLabel) { l, err := database.GetLabelByID(f.ID) if err != nil { c.NotFoundOrError(err, "get label by ID") return } l.Name = f.Title l.Color = f.Color if err := database.UpdateLabel(l); err != nil { c.Error(err, "update label") return } c.RawRedirect(c.Repo.MakeURL("labels")) } func DeleteLabel(c *context.Context) { if err := database.DeleteLabel(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil { c.Flash.Error("DeleteLabel: " + err.Error()) } else { c.Flash.Success(c.Tr("repo.issues.label_deletion_success")) } c.JSONSuccess(map[string]any{ "redirect": c.Repo.MakeURL("labels"), }) } func Milestones(c *context.Context) { c.Data["Title"] = c.Tr("repo.milestones") c.Data["PageIsIssueList"] = true c.Data["PageIsMilestones"] = true isShowClosed := c.Query("state") == "closed" openCount, closedCount := database.MilestoneStats(c.Repo.Repository.ID) c.Data["OpenCount"] = openCount c.Data["ClosedCount"] = closedCount page := c.QueryInt("page") if page <= 1 { page = 1 } var total int if !isShowClosed { total = int(openCount) } else { total = int(closedCount) } c.Data["Page"] = paginater.New(total, conf.UI.IssuePagingNum, page, 5) miles, err := database.GetMilestones(c.Repo.Repository.ID, page, isShowClosed) if err != nil { c.Error(err, "get milestones") return } for _, m := range miles { m.NumOpenIssues = int(m.CountIssues(false, false)) m.NumClosedIssues = int(m.CountIssues(true, false)) if m.NumOpenIssues+m.NumClosedIssues > 0 { m.Completeness = m.NumClosedIssues * 100 / (m.NumOpenIssues + m.NumClosedIssues) } m.RenderedContent = string(markup.Markdown(m.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) } c.Data["Milestones"] = miles if isShowClosed { c.Data["State"] = "closed" } else { c.Data["State"] = "open" } c.Data["IsShowClosed"] = isShowClosed c.Success(tmplRepoIssueMilestones) } func NewMilestone(c *context.Context) { c.Data["Title"] = c.Tr("repo.milestones.new") c.Data["PageIsIssueList"] = true c.Data["PageIsMilestones"] = true c.Data["RequireDatetimepicker"] = true c.Data["DateLang"] = conf.I18n.DateLang(c.Language()) c.Success(tmplRepoIssueMilestoneNew) } func NewMilestonePost(c *context.Context, f form.CreateMilestone) { c.Data["Title"] = c.Tr("repo.milestones.new") c.Data["PageIsIssueList"] = true c.Data["PageIsMilestones"] = true c.Data["RequireDatetimepicker"] = true c.Data["DateLang"] = conf.I18n.DateLang(c.Language()) if c.HasError() { c.Success(tmplRepoIssueMilestoneNew) return } if f.Deadline == "" { f.Deadline = "9999-12-31" } deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local) if err != nil { c.Data["Err_Deadline"] = true c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), tmplRepoIssueMilestoneNew, &f) return } if err = database.NewMilestone(&database.Milestone{ RepoID: c.Repo.Repository.ID, Name: f.Title, Content: f.Content, Deadline: deadline, }); err != nil { c.Error(err, "new milestone") return } c.Flash.Success(c.Tr("repo.milestones.create_success", f.Title)) c.RawRedirect(c.Repo.MakeURL("milestones")) } func EditMilestone(c *context.Context) { c.Data["Title"] = c.Tr("repo.milestones.edit") c.Data["PageIsMilestones"] = true c.Data["PageIsEditMilestone"] = true c.Data["RequireDatetimepicker"] = true c.Data["DateLang"] = conf.I18n.DateLang(c.Language()) m, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get milestone by repository ID") return } c.Data["title"] = m.Name c.Data["content"] = m.Content if len(m.DeadlineString) > 0 { c.Data["deadline"] = m.DeadlineString } c.Success(tmplRepoIssueMilestoneNew) } func EditMilestonePost(c *context.Context, f form.CreateMilestone) { c.Data["Title"] = c.Tr("repo.milestones.edit") c.Data["PageIsMilestones"] = true c.Data["PageIsEditMilestone"] = true c.Data["RequireDatetimepicker"] = true c.Data["DateLang"] = conf.I18n.DateLang(c.Language()) if c.HasError() { c.Success(tmplRepoIssueMilestoneNew) return } if f.Deadline == "" { f.Deadline = "9999-12-31" } deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local) if err != nil { c.Data["Err_Deadline"] = true c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), tmplRepoIssueMilestoneNew, &f) return } m, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get milestone by repository ID") return } m.Name = f.Title m.Content = f.Content m.Deadline = deadline if err = database.UpdateMilestone(m); err != nil { c.Error(err, "update milestone") return } c.Flash.Success(c.Tr("repo.milestones.edit_success", m.Name)) c.RawRedirect(c.Repo.MakeURL("milestones")) } func ChangeMilestonStatus(c *context.Context) { m, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) if err != nil { c.NotFoundOrError(err, "get milestone by repository ID") return } location := url.URL{ Path: "milestones", } switch c.Params(":action") { case "open": if m.IsClosed { if err = database.ChangeMilestoneStatus(m, false); err != nil { c.Error(err, "change milestone status to open") return } } location.RawQuery = "state=open" case "close": if !m.IsClosed { m.ClosedDate = time.Now() if err = database.ChangeMilestoneStatus(m, true); err != nil { c.Error(err, "change milestone status to closed") return } } location.RawQuery = "state=closed" } c.RawRedirect(c.Repo.MakeURL(location)) } func DeleteMilestone(c *context.Context) { if err := database.DeleteMilestoneOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil { c.Flash.Error("DeleteMilestoneByRepoID: " + err.Error()) } else { c.Flash.Success(c.Tr("repo.milestones.deletion_success")) } c.JSONSuccess(map[string]any{ "redirect": c.Repo.MakeURL("milestones"), }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/wiki.go
internal/route/repo/wiki.go
// Copyright 2015 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 ( "strings" "time" "github.com/gogs/git-module" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/markup" ) const ( tmplRepoWikiStart = "repo/wiki/start" tmplRepoWikiView = "repo/wiki/view" tmplRepoWikiNew = "repo/wiki/new" tmplRepoWikiPages = "repo/wiki/pages" ) func MustEnableWiki(c *context.Context) { if !c.Repo.Repository.EnableWiki { c.NotFound() return } if c.Repo.Repository.EnableExternalWiki { c.Redirect(c.Repo.Repository.ExternalWikiURL) return } } type PageMeta struct { Name string URL string Updated time.Time } func renderWikiPage(c *context.Context, isViewPage bool) (*git.Repository, string) { wikiRepo, err := git.Open(c.Repo.Repository.WikiPath()) if err != nil { c.Error(err, "open repository") return nil, "" } commit, err := wikiRepo.BranchCommit("master") if err != nil { c.Error(err, "get branch commit") return nil, "" } // Get page list. if isViewPage { entries, err := commit.Entries() if err != nil { c.Error(err, "list entries") return nil, "" } pages := make([]PageMeta, 0, len(entries)) for i := range entries { if entries[i].Type() == git.ObjectBlob && strings.HasSuffix(entries[i].Name(), ".md") { name := strings.TrimSuffix(entries[i].Name(), ".md") pages = append(pages, PageMeta{ Name: name, URL: database.ToWikiPageURL(name), }) } } c.Data["Pages"] = pages } pageURL := c.Params(":page") if pageURL == "" { pageURL = "Home" } c.Data["PageURL"] = pageURL pageName := database.ToWikiPageName(pageURL) c.Data["old_title"] = pageName c.Data["Title"] = pageName c.Data["title"] = pageName c.Data["RequireHighlightJS"] = true blob, err := commit.Blob(pageName + ".md") if err != nil { if gitutil.IsErrRevisionNotExist(err) { c.Redirect(c.Repo.RepoLink + "/wiki/_pages") } else { c.Error(err, "get blob") } return nil, "" } p, err := blob.Bytes() if err != nil { c.Error(err, "read blob") return nil, "" } if isViewPage { c.Data["content"] = string(markup.Markdown(p, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) } else { c.Data["content"] = string(p) } return wikiRepo, pageName } func Wiki(c *context.Context) { c.Data["PageIsWiki"] = true if !c.Repo.Repository.HasWiki() { c.Data["Title"] = c.Tr("repo.wiki") c.Success(tmplRepoWikiStart) return } wikiRepo, pageName := renderWikiPage(c, true) if c.Written() { return } // Get last change information. commits, err := wikiRepo.Log(git.RefsHeads+"master", git.LogOptions{Path: pageName + ".md"}) if err != nil { c.Error(err, "get commits by path") return } c.Data["Author"] = commits[0].Author c.Success(tmplRepoWikiView) } func WikiPages(c *context.Context) { c.Data["Title"] = c.Tr("repo.wiki.pages") c.Data["PageIsWiki"] = true if !c.Repo.Repository.HasWiki() { c.Redirect(c.Repo.RepoLink + "/wiki") return } wikiRepo, err := git.Open(c.Repo.Repository.WikiPath()) if err != nil { c.Error(err, "open repository") return } commit, err := wikiRepo.BranchCommit("master") if err != nil { c.Error(err, "get branch commit") return } entries, err := commit.Entries() if err != nil { c.Error(err, "list entries") return } pages := make([]PageMeta, 0, len(entries)) for i := range entries { if entries[i].Type() == git.ObjectBlob && strings.HasSuffix(entries[i].Name(), ".md") { commits, err := wikiRepo.Log(git.RefsHeads+"master", git.LogOptions{Path: entries[i].Name()}) if err != nil { c.Error(err, "get commits by path") return } name := strings.TrimSuffix(entries[i].Name(), ".md") pages = append(pages, PageMeta{ Name: name, URL: database.ToWikiPageURL(name), Updated: commits[0].Author.When, }) } } c.Data["Pages"] = pages c.Success(tmplRepoWikiPages) } func NewWiki(c *context.Context) { c.Data["Title"] = c.Tr("repo.wiki.new_page") c.Data["PageIsWiki"] = true c.Data["RequireSimpleMDE"] = true if !c.Repo.Repository.HasWiki() { c.Data["title"] = "Home" } c.Success(tmplRepoWikiNew) } func NewWikiPost(c *context.Context, f form.NewWiki) { c.Data["Title"] = c.Tr("repo.wiki.new_page") c.Data["PageIsWiki"] = true c.Data["RequireSimpleMDE"] = true if c.HasError() { c.Success(tmplRepoWikiNew) return } if err := c.Repo.Repository.AddWikiPage(c.User, f.Title, f.Content, f.Message); err != nil { if database.IsErrWikiAlreadyExist(err) { c.Data["Err_Title"] = true c.RenderWithErr(c.Tr("repo.wiki.page_already_exists"), tmplRepoWikiNew, &f) } else { c.Error(err, "add wiki page") } return } c.Redirect(c.Repo.RepoLink + "/wiki/" + database.ToWikiPageURL(database.ToWikiPageName(f.Title))) } func EditWiki(c *context.Context) { c.Data["PageIsWiki"] = true c.Data["PageIsWikiEdit"] = true c.Data["RequireSimpleMDE"] = true if !c.Repo.Repository.HasWiki() { c.Redirect(c.Repo.RepoLink + "/wiki") return } renderWikiPage(c, false) if c.Written() { return } c.Success(tmplRepoWikiNew) } func EditWikiPost(c *context.Context, f form.NewWiki) { c.Data["Title"] = c.Tr("repo.wiki.new_page") c.Data["PageIsWiki"] = true c.Data["RequireSimpleMDE"] = true if c.HasError() { c.Success(tmplRepoWikiNew) return } if err := c.Repo.Repository.EditWikiPage(c.User, f.OldTitle, f.Title, f.Content, f.Message); err != nil { c.Error(err, "edit wiki page") return } c.Redirect(c.Repo.RepoLink + "/wiki/" + database.ToWikiPageURL(database.ToWikiPageName(f.Title))) } func DeleteWikiPagePost(c *context.Context) { pageURL := c.Params(":page") if pageURL == "" { pageURL = "Home" } pageName := database.ToWikiPageName(pageURL) if err := c.Repo.Repository.DeleteWikiPage(c.User, pageName); err != nil { c.Error(err, "delete wiki page") return } c.JSONSuccess(map[string]any{ "redirect": c.Repo.RepoLink + "/wiki/", }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/repo.go
internal/route/repo/repo.go
// Copyright 2014 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 ( "net/http" "os" "path" "path/filepath" "strings" "github.com/unknwon/com" log "unknwon.dev/clog/v2" "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/tool" ) const ( CREATE = "repo/create" MIGRATE = "repo/migrate" ) func MustBeNotBare(c *context.Context) { if c.Repo.Repository.IsBare { c.NotFound() } } func checkContextUser(c *context.Context, uid int64) *database.User { orgs, err := database.GetOwnedOrgsByUserIDDesc(c.User.ID, "updated_unix") if err != nil { c.Error(err, "get owned organization by user ID") return nil } c.Data["Orgs"] = orgs // Not equal means current user is an organization. if uid == c.User.ID || uid == 0 { return c.User } org, err := database.Handle.Users().GetByID(c.Req.Context(), uid) if database.IsErrUserNotExist(err) { return c.User } if err != nil { c.Error(err, "get user by ID") return nil } // Check ownership of organization. if !org.IsOrganization() || !(c.User.IsAdmin || org.IsOwnedBy(c.User.ID)) { c.Status(http.StatusForbidden) return nil } return org } func Create(c *context.Context) { c.Title("new_repo") c.RequireAutosize() // Give default value for template to render. c.Data["Gitignores"] = database.Gitignores c.Data["Licenses"] = database.Licenses c.Data["Readmes"] = database.Readmes c.Data["readme"] = "Default" c.Data["private"] = c.User.LastRepoVisibility c.Data["IsForcedPrivate"] = conf.Repository.ForcePrivate ctxUser := checkContextUser(c, c.QueryInt64("org")) if c.Written() { return } c.Data["ContextUser"] = ctxUser c.Success(CREATE) } func handleCreateError(c *context.Context, err error, name, tpl string, form any) { switch { case database.IsErrReachLimitOfRepo(err): c.RenderWithErr(c.Tr("repo.form.reach_limit_of_creation", err.(database.ErrReachLimitOfRepo).Limit), tpl, form) case database.IsErrRepoAlreadyExist(err): c.Data["Err_RepoName"] = true c.RenderWithErr(c.Tr("form.repo_name_been_taken"), tpl, form) case database.IsErrNameNotAllowed(err): c.Data["Err_RepoName"] = true c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tpl, form) default: c.Error(err, name) } } func CreatePost(c *context.Context, f form.CreateRepo) { c.Data["Title"] = c.Tr("new_repo") c.Data["Gitignores"] = database.Gitignores c.Data["Licenses"] = database.Licenses c.Data["Readmes"] = database.Readmes ctxUser := checkContextUser(c, f.UserID) if c.Written() { return } c.Data["ContextUser"] = ctxUser if c.HasError() { c.Success(CREATE) return } repo, err := database.CreateRepository(c.User, ctxUser, database.CreateRepoOptionsLegacy{ Name: f.RepoName, Description: f.Description, Gitignores: f.Gitignores, License: f.License, Readme: f.Readme, IsPrivate: f.Private || conf.Repository.ForcePrivate, IsUnlisted: f.Unlisted, AutoInit: f.AutoInit, }) if err == nil { log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) c.Redirect(conf.Server.Subpath + "/" + ctxUser.Name + "/" + repo.Name) return } if repo != nil { if errDelete := database.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil { log.Error("DeleteRepository: %v", errDelete) } } handleCreateError(c, err, "CreatePost", CREATE, &f) } func Migrate(c *context.Context) { c.Data["Title"] = c.Tr("new_migrate") c.Data["private"] = c.User.LastRepoVisibility c.Data["IsForcedPrivate"] = conf.Repository.ForcePrivate c.Data["mirror"] = c.Query("mirror") == "1" ctxUser := checkContextUser(c, c.QueryInt64("org")) if c.Written() { return } c.Data["ContextUser"] = ctxUser c.Success(MIGRATE) } func MigratePost(c *context.Context, f form.MigrateRepo) { c.Data["Title"] = c.Tr("new_migrate") ctxUser := checkContextUser(c, f.UID) if c.Written() { return } c.Data["ContextUser"] = ctxUser if c.HasError() { c.Success(MIGRATE) return } remoteAddr, err := f.ParseRemoteAddr(c.User) if err != nil { if database.IsErrInvalidCloneAddr(err) { c.Data["Err_CloneAddr"] = true addrErr := err.(database.ErrInvalidCloneAddr) switch { case addrErr.IsURLError: c.RenderWithErr(c.Tr("repo.migrate.clone_address")+c.Tr("form.url_error"), MIGRATE, &f) case addrErr.IsPermissionDenied: c.RenderWithErr(c.Tr("repo.migrate.permission_denied"), MIGRATE, &f) case addrErr.IsInvalidPath: c.RenderWithErr(c.Tr("repo.migrate.invalid_local_path"), MIGRATE, &f) case addrErr.IsBlockedLocalAddress: c.RenderWithErr(c.Tr("repo.migrate.clone_address_resolved_to_blocked_local_address"), MIGRATE, &f) default: c.Error(err, "unexpected error") } } else { c.Error(err, "parse remote address") } return } repo, err := database.MigrateRepository(c.User, ctxUser, database.MigrateRepoOptions{ Name: f.RepoName, Description: f.Description, IsPrivate: f.Private || conf.Repository.ForcePrivate, IsUnlisted: f.Unlisted, IsMirror: f.Mirror, RemoteAddr: remoteAddr, }) if err == nil { log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, f.RepoName) c.Redirect(conf.Server.Subpath + "/" + ctxUser.Name + "/" + f.RepoName) return } if repo != nil { if errDelete := database.DeleteRepository(ctxUser.ID, repo.ID); errDelete != nil { log.Error("DeleteRepository: %v", errDelete) } } if strings.Contains(err.Error(), "Authentication failed") || strings.Contains(err.Error(), "could not read Username") { c.Data["Err_Auth"] = true c.RenderWithErr(c.Tr("form.auth_failed", database.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f) return } else if strings.Contains(err.Error(), "fatal:") { c.Data["Err_CloneAddr"] = true c.RenderWithErr(c.Tr("repo.migrate.failed", database.HandleMirrorCredentials(err.Error(), true)), MIGRATE, &f) return } handleCreateError(c, err, "MigratePost", MIGRATE, &f) } func Action(c *context.Context) { var err error switch c.Params(":action") { case "watch": err = database.WatchRepo(c.User.ID, c.Repo.Repository.ID, true) case "unwatch": if userID := c.QueryInt64("user_id"); userID != 0 { if c.User.IsAdmin { err = database.WatchRepo(userID, c.Repo.Repository.ID, false) } } else { err = database.WatchRepo(c.User.ID, c.Repo.Repository.ID, false) } case "star": err = database.StarRepo(c.User.ID, c.Repo.Repository.ID, true) case "unstar": err = database.StarRepo(c.User.ID, c.Repo.Repository.ID, false) case "desc": // FIXME: this is not used if !c.Repo.IsOwner() { c.NotFound() return } c.Repo.Repository.Description = c.Query("desc") c.Repo.Repository.Website = c.Query("site") err = database.UpdateRepository(c.Repo.Repository, false) } if err != nil { c.Errorf(err, "action %q", c.Params(":action")) return } redirectTo := c.Query("redirect_to") if !tool.IsSameSiteURLPath(redirectTo) { redirectTo = c.Repo.RepoLink } c.Redirect(redirectTo) } func Download(c *context.Context) { var ( uri = c.Params("*") refName string ext string archivePath string archiveFormat git.ArchiveFormat ) switch { case strings.HasSuffix(uri, ".zip"): ext = ".zip" archivePath = filepath.Join(c.Repo.GitRepo.Path(), "archives", "zip") archiveFormat = git.ArchiveZip case strings.HasSuffix(uri, ".tar.gz"): ext = ".tar.gz" archivePath = filepath.Join(c.Repo.GitRepo.Path(), "archives", "targz") archiveFormat = git.ArchiveTarGz default: log.Trace("Unknown format: %s", uri) c.NotFound() return } refName = strings.TrimSuffix(uri, ext) if !com.IsDir(archivePath) { if err := os.MkdirAll(archivePath, os.ModePerm); err != nil { c.Error(err, "create archive directory") return } } // Get corresponding commit. var ( commit *git.Commit err error ) gitRepo := c.Repo.GitRepo if gitRepo.HasBranch(refName) { commit, err = gitRepo.BranchCommit(refName) if err != nil { c.Error(err, "get branch commit") return } } else if gitRepo.HasTag(refName) { commit, err = gitRepo.TagCommit(refName) if err != nil { c.Error(err, "get tag commit") return } } else if len(refName) >= 7 && len(refName) <= 40 { commit, err = gitRepo.CatFileCommit(refName) if err != nil { c.NotFound() return } } else { c.NotFound() return } archivePath = path.Join(archivePath, tool.ShortSHA1(commit.ID.String())+ext) if !com.IsFile(archivePath) { if err := commit.CreateArchive(archiveFormat, archivePath); err != nil { c.Error(err, "creates archive") return } } c.ServeFile(archivePath, c.Repo.Repository.Name+"-"+refName+ext) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/store.go
internal/route/repo/store.go
package repo import ( "context" "gogs.io/gogs/internal/database" ) // Store is the data layer carrier for context middleware. This interface is // meant to abstract away and limit the exposure of the underlying data layer to // the handler through a thin-wrapper. type Store interface { // GetAccessTokenBySHA1 returns the access token with given SHA1. It returns // database.ErrAccessTokenNotExist when not found. GetAccessTokenBySHA1(ctx context.Context, sha1 string) (*database.AccessToken, error) // TouchAccessTokenByID updates the updated time of the given access token to // the current time. TouchAccessTokenByID(ctx context.Context, id int64) error // GetRepositoryByName returns the repository with given owner and name. It // returns database.ErrRepoNotExist when not found. GetRepositoryByName(ctx context.Context, ownerID int64, name string) (*database.Repository, error) // IsTwoFactorEnabled returns true if the user has enabled 2FA. IsTwoFactorEnabled(ctx context.Context, userID int64) bool // GetUserByID returns the user with given ID. It returns // database.ErrUserNotExist when not found. GetUserByID(ctx context.Context, id int64) (*database.User, error) // GetUserByUsername returns the user with given username. It returns // database.ErrUserNotExist when not found. GetUserByUsername(ctx context.Context, username string) (*database.User, error) // CreateUser creates a new user and persists to database. It returns // database.ErrNameNotAllowed if the given name or pattern of the name is not // allowed as a username, or database.ErrUserAlreadyExist when a user with same // name already exists, or database.ErrEmailAlreadyUsed if the email has been // verified by another user. CreateUser(ctx context.Context, username, email string, opts database.CreateUserOptions) (*database.User, error) // AuthenticateUser validates username and password via given login source ID. // It returns database.ErrUserNotExist when the user was not found. // // When the "loginSourceID" is negative, it aborts the process and returns // database.ErrUserNotExist if the user was not found in the database. // // When the "loginSourceID" is non-negative, it returns // database.ErrLoginSourceMismatch if the user has different login source ID // than the "loginSourceID". // // When the "loginSourceID" is positive, it tries to authenticate via given // login source and creates a new user when not yet exists in the database. AuthenticateUser(ctx context.Context, login, password string, loginSourceID int64) (*database.User, error) } type store struct{} // NewStore returns a new Store using the global database handle. func NewStore() Store { return &store{} } func (*store) GetAccessTokenBySHA1(ctx context.Context, sha1 string) (*database.AccessToken, error) { return database.Handle.AccessTokens().GetBySHA1(ctx, sha1) } func (*store) TouchAccessTokenByID(ctx context.Context, id int64) error { return database.Handle.AccessTokens().Touch(ctx, id) } func (*store) GetRepositoryByName(ctx context.Context, ownerID int64, name string) (*database.Repository, error) { return database.Handle.Repositories().GetByName(ctx, ownerID, name) } func (*store) IsTwoFactorEnabled(ctx context.Context, userID int64) bool { return database.Handle.TwoFactors().IsEnabled(ctx, userID) } func (*store) GetUserByID(ctx context.Context, id int64) (*database.User, error) { return database.Handle.Users().GetByID(ctx, id) } func (*store) GetUserByUsername(ctx context.Context, username string) (*database.User, error) { return database.Handle.Users().GetByUsername(ctx, username) } func (*store) CreateUser(ctx context.Context, username, email string, opts database.CreateUserOptions) (*database.User, error) { return database.Handle.Users().Create(ctx, username, email, opts) } func (*store) AuthenticateUser(ctx context.Context, login, password string, loginSourceID int64) (*database.User, error) { return database.Handle.Users().Authenticate(ctx, login, password, loginSourceID) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/http.go
internal/route/repo/http.go
// Copyright 2017 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 ( "bytes" "compress/gzip" "fmt" "net/http" "os" "os/exec" "path" "path/filepath" "strconv" "strings" "time" "gopkg.in/macaron.v1" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/lazyregexp" "gogs.io/gogs/internal/pathutil" "gogs.io/gogs/internal/tool" ) type HTTPContext struct { *macaron.Context OwnerName string OwnerSalt string RepoID int64 RepoName string AuthUser *database.User } // askCredentials responses HTTP header and status which informs client to provide credentials. func askCredentials(c *macaron.Context, status int, text string) { c.Header().Set("WWW-Authenticate", "Basic realm=\".\"") c.Error(status, text) } func HTTPContexter(store Store) macaron.Handler { return func(c *macaron.Context) { if len(conf.HTTP.AccessControlAllowOrigin) > 0 { // Set CORS headers for browser-based git clients c.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin) c.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, User-Agent") // Handle preflight OPTIONS request if c.Req.Method == "OPTIONS" { c.Status(http.StatusOK) return } } ownerName := c.Params(":username") repoName := strings.TrimSuffix(c.Params(":reponame"), ".git") repoName = strings.TrimSuffix(repoName, ".wiki") isPull := c.Query("service") == "git-upload-pack" || strings.HasSuffix(c.Req.URL.Path, "git-upload-pack") || c.Req.Method == "GET" owner, err := store.GetUserByUsername(c.Req.Context(), ownerName) if err != nil { if database.IsErrUserNotExist(err) { c.Status(http.StatusNotFound) } else { c.Status(http.StatusInternalServerError) log.Error("Failed to get user [name: %s]: %v", ownerName, err) } return } repo, err := store.GetRepositoryByName(c.Req.Context(), owner.ID, repoName) if err != nil { if database.IsErrRepoNotExist(err) { c.Status(http.StatusNotFound) } else { c.Status(http.StatusInternalServerError) log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, repoName, err) } return } // Authentication is not required for pulling from public repositories. if isPull && !repo.IsPrivate && !conf.Auth.RequireSigninView { c.Map(&HTTPContext{ Context: c, }) return } // In case user requested a wrong URL and not intended to access Git objects. action := c.Params("*") if !strings.Contains(action, "git-") && !strings.Contains(action, "info/") && !strings.Contains(action, "HEAD") && !strings.Contains(action, "objects/") { c.Error(http.StatusBadRequest, fmt.Sprintf("Unrecognized action %q", action)) return } // Handle HTTP Basic Authentication authHead := c.Req.Header.Get("Authorization") if authHead == "" { askCredentials(c, http.StatusUnauthorized, "") return } auths := strings.Fields(authHead) if len(auths) != 2 || auths[0] != "Basic" { askCredentials(c, http.StatusUnauthorized, "") return } authUsername, authPassword, err := tool.BasicAuthDecode(auths[1]) if err != nil { askCredentials(c, http.StatusUnauthorized, "") return } authUser, err := store.AuthenticateUser(c.Req.Context(), authUsername, authPassword, -1) if err != nil && !auth.IsErrBadCredentials(err) { c.Status(http.StatusInternalServerError) log.Error("Failed to authenticate user [name: %s]: %v", authUsername, err) return } // If username and password combination failed, try again using either username // or password as the token. if authUser == nil { authUser, err = context.AuthenticateByToken(store, c.Req.Context(), authUsername) if err != nil && !database.IsErrAccessTokenNotExist(err) { c.Status(http.StatusInternalServerError) log.Error("Failed to authenticate by access token via username: %v", err) return } else if database.IsErrAccessTokenNotExist(err) { // Try again using the password field as the token. authUser, err = context.AuthenticateByToken(store, c.Req.Context(), authPassword) if err != nil { if database.IsErrAccessTokenNotExist(err) { askCredentials(c, http.StatusUnauthorized, "") } else { c.Status(http.StatusInternalServerError) log.Error("Failed to authenticate by access token via password: %v", err) } return } } } else if store.IsTwoFactorEnabled(c.Req.Context(), authUser.ID) { askCredentials(c, http.StatusUnauthorized, `User with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password Please create and use personal access token on user settings page`) return } log.Trace("[Git] Authenticated user: %s", authUser.Name) mode := database.AccessModeWrite if isPull { mode = database.AccessModeRead } if !database.Handle.Permissions().Authorize(c.Req.Context(), authUser.ID, repo.ID, mode, database.AccessModeOptions{ OwnerID: repo.OwnerID, Private: repo.IsPrivate, }, ) { askCredentials(c, http.StatusForbidden, "User permission denied") return } if !isPull && repo.IsMirror { c.Error(http.StatusForbidden, "Mirror repository is read-only") return } c.Map(&HTTPContext{ Context: c, OwnerName: ownerName, OwnerSalt: owner.Salt, RepoID: repo.ID, RepoName: repoName, AuthUser: authUser, }) } } type serviceHandler struct { w http.ResponseWriter r *http.Request dir string file string authUser *database.User ownerName string ownerSalt string repoID int64 repoName string } func (h *serviceHandler) setHeaderNoCache() { h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT") h.w.Header().Set("Pragma", "no-cache") h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate") } func (h *serviceHandler) setHeaderCacheForever() { now := time.Now().Unix() expires := now + 31536000 h.w.Header().Set("Date", fmt.Sprintf("%d", now)) h.w.Header().Set("Expires", fmt.Sprintf("%d", expires)) h.w.Header().Set("Cache-Control", "public, max-age=31536000") } func (h *serviceHandler) sendFile(contentType string) { reqFile := path.Join(h.dir, h.file) fi, err := os.Stat(reqFile) if os.IsNotExist(err) { h.w.WriteHeader(http.StatusNotFound) return } h.w.Header().Set("Content-Type", contentType) h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size())) h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat)) http.ServeFile(h.w, h.r, reqFile) } func serviceRPC(h serviceHandler, service string) { defer h.r.Body.Close() if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) { h.w.WriteHeader(http.StatusUnauthorized) return } h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service)) var ( reqBody = h.r.Body err error ) // Handle GZIP if h.r.Header.Get("Content-Encoding") == "gzip" { reqBody, err = gzip.NewReader(reqBody) if err != nil { log.Error("HTTP.Get: fail to create gzip reader: %v", err) h.w.WriteHeader(http.StatusInternalServerError) return } } var stderr bytes.Buffer cmd := exec.Command("git", service, "--stateless-rpc", h.dir) if service == "receive-pack" { cmd.Env = append(os.Environ(), database.ComposeHookEnvs(database.ComposeHookEnvsOptions{ AuthUser: h.authUser, OwnerName: h.ownerName, OwnerSalt: h.ownerSalt, RepoID: h.repoID, RepoName: h.repoName, RepoPath: h.dir, })...) } cmd.Dir = h.dir cmd.Stdout = h.w cmd.Stderr = &stderr cmd.Stdin = reqBody if err = cmd.Run(); err != nil { log.Error("HTTP.serviceRPC: fail to serve RPC '%s': %v - %s", service, err, stderr.String()) h.w.WriteHeader(http.StatusInternalServerError) return } } func serviceUploadPack(h serviceHandler) { serviceRPC(h, "upload-pack") } func serviceReceivePack(h serviceHandler) { serviceRPC(h, "receive-pack") } func getServiceType(r *http.Request) string { serviceType := r.FormValue("service") if !strings.HasPrefix(serviceType, "git-") { return "" } return strings.TrimPrefix(serviceType, "git-") } // FIXME: use process module func gitCommand(dir string, args ...string) []byte { cmd := exec.Command("git", args...) cmd.Dir = dir out, err := cmd.Output() if err != nil { log.Error("Git: %v - %s", err, out) } return out } func updateServerInfo(dir string) []byte { return gitCommand(dir, "update-server-info") } func packetWrite(str string) []byte { s := strconv.FormatInt(int64(len(str)+4), 16) if len(s)%4 != 0 { s = strings.Repeat("0", 4-len(s)%4) + s } return []byte(s + str) } func getInfoRefs(h serviceHandler) { h.setHeaderNoCache() service := getServiceType(h.r) if service != "upload-pack" && service != "receive-pack" { updateServerInfo(h.dir) h.sendFile("text/plain; charset=utf-8") return } refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".") h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service)) h.w.WriteHeader(http.StatusOK) _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n")) _, _ = h.w.Write([]byte("0000")) _, _ = h.w.Write(refs) } func getTextFile(h serviceHandler) { h.setHeaderNoCache() h.sendFile("text/plain") } func getInfoPacks(h serviceHandler) { h.setHeaderCacheForever() h.sendFile("text/plain; charset=utf-8") } func getLooseObject(h serviceHandler) { h.setHeaderCacheForever() h.sendFile("application/x-git-loose-object") } func getPackFile(h serviceHandler) { h.setHeaderCacheForever() h.sendFile("application/x-git-packed-objects") } func getIdxFile(h serviceHandler) { h.setHeaderCacheForever() h.sendFile("application/x-git-packed-objects-toc") } var routes = []struct { re *lazyregexp.Regexp method string handler func(serviceHandler) }{ {lazyregexp.New("(.*?)/git-upload-pack$"), "POST", serviceUploadPack}, {lazyregexp.New("(.*?)/git-receive-pack$"), "POST", serviceReceivePack}, {lazyregexp.New("(.*?)/info/refs$"), "GET", getInfoRefs}, {lazyregexp.New("(.*?)/HEAD$"), "GET", getTextFile}, {lazyregexp.New("(.*?)/objects/info/alternates$"), "GET", getTextFile}, {lazyregexp.New("(.*?)/objects/info/http-alternates$"), "GET", getTextFile}, {lazyregexp.New("(.*?)/objects/info/packs$"), "GET", getInfoPacks}, {lazyregexp.New("(.*?)/objects/info/[^/]*$"), "GET", getTextFile}, {lazyregexp.New("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject}, {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile}, {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile}, } func getGitRepoPath(dir string) (string, error) { if !strings.HasSuffix(dir, ".git") { dir += ".git" } filename := filepath.Join(conf.Repository.Root, dir) if _, err := os.Stat(filename); os.IsNotExist(err) { return "", err } return filename, nil } func HTTP(c *HTTPContext) { for _, route := range routes { reqPath := strings.ToLower(c.Req.URL.Path) m := route.re.FindStringSubmatch(reqPath) if m == nil { continue } // We perform check here because route matched in cmd/web.go is wider than needed, // but we only want to output this message only if user is really trying to access // Git HTTP endpoints. if conf.Repository.DisableHTTPGit { c.Error(http.StatusForbidden, "Interacting with repositories by HTTP protocol is disabled") return } if route.method != c.Req.Method { c.Error(http.StatusNotFound) return } // 🚨 SECURITY: Prevent path traversal. cleaned := pathutil.Clean(m[1]) if m[1] != "/"+cleaned { c.Error(http.StatusBadRequest, "Request path contains suspicious characters") return } file := strings.TrimPrefix(reqPath, cleaned) dir, err := getGitRepoPath(cleaned) if err != nil { log.Warn("HTTP.getGitRepoPath: %v", err) c.Error(http.StatusNotFound) return } route.handler(serviceHandler{ w: c.Resp, r: c.Req.Request, dir: dir, file: file, authUser: c.AuthUser, ownerName: c.OwnerName, ownerSalt: c.OwnerSalt, repoID: c.RepoID, repoName: c.RepoName, }) return } c.Error(http.StatusNotFound) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/branch.go
internal/route/repo/branch.go
// Copyright 2014 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 ( "time" log "unknwon.dev/clog/v2" "github.com/gogs/git-module" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/tool" ) const ( tmplRepoBranchesOverview = "repo/branches/overview" tmplRepoBranchesAll = "repo/branches/all" ) type Branch struct { Name string Commit *git.Commit IsProtected bool } func loadBranches(c *context.Context) []*Branch { rawBranches, err := c.Repo.Repository.GetBranches() if err != nil { c.Error(err, "get branches") return nil } protectBranches, err := database.GetProtectBranchesByRepoID(c.Repo.Repository.ID) if err != nil { c.Error(err, "get protect branches by repository ID") return nil } branches := make([]*Branch, len(rawBranches)) for i := range rawBranches { commit, err := rawBranches[i].GetCommit() if err != nil { c.Error(err, "get commit") return nil } branches[i] = &Branch{ Name: rawBranches[i].Name, Commit: commit, } for j := range protectBranches { if branches[i].Name == protectBranches[j].Name { branches[i].IsProtected = true break } } } c.Data["AllowPullRequest"] = c.Repo.Repository.AllowsPulls() return branches } func Branches(c *context.Context) { c.Data["Title"] = c.Tr("repo.git_branches") c.Data["PageIsBranchesOverview"] = true branches := loadBranches(c) if c.Written() { return } now := time.Now() activeBranches := make([]*Branch, 0, 3) staleBranches := make([]*Branch, 0, 3) for i := range branches { switch { case branches[i].Name == c.Repo.BranchName: c.Data["DefaultBranch"] = branches[i] case branches[i].Commit.Committer.When.Add(30 * 24 * time.Hour).After(now): // 30 days activeBranches = append(activeBranches, branches[i]) case branches[i].Commit.Committer.When.Add(3 * 30 * 24 * time.Hour).Before(now): // 90 days staleBranches = append(staleBranches, branches[i]) } } c.Data["ActiveBranches"] = activeBranches c.Data["StaleBranches"] = staleBranches c.Success(tmplRepoBranchesOverview) } func AllBranches(c *context.Context) { c.Data["Title"] = c.Tr("repo.git_branches") c.Data["PageIsBranchesAll"] = true branches := loadBranches(c) if c.Written() { return } c.Data["Branches"] = branches c.Success(tmplRepoBranchesAll) } func DeleteBranchPost(c *context.Context) { branchName := c.Params("*") commitID := c.Query("commit") defer func() { redirectTo := c.Query("redirect_to") if !tool.IsSameSiteURLPath(redirectTo) { redirectTo = c.Repo.RepoLink } c.Redirect(redirectTo) }() if !c.Repo.GitRepo.HasBranch(branchName) { return } if len(commitID) > 0 { branchCommitID, err := c.Repo.GitRepo.BranchCommitID(branchName) if err != nil { log.Error("Failed to get commit ID of branch %q: %v", branchName, err) return } if branchCommitID != commitID { c.Flash.Error(c.Tr("repo.pulls.delete_branch_has_new_commits")) return } } if err := c.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{ Force: true, }); err != nil { log.Error("Failed to delete branch %q: %v", branchName, err) return } if err := database.PrepareWebhooks(c.Repo.Repository, database.HookEventTypeDelete, &api.DeletePayload{ Ref: branchName, RefType: "branch", PusherType: api.PUSHER_TYPE_USER, Repo: c.Repo.Repository.APIFormatLegacy(nil), Sender: c.User.APIFormat(), }); err != nil { log.Error("Failed to prepare webhooks for %q: %v", database.HookEventTypeDelete, err) return } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/pull.go
internal/route/repo/pull.go
// Copyright 2014 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 ( "net/http" "path" "strings" "time" "github.com/unknwon/com" log "unknwon.dev/clog/v2" "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/gitutil" ) const ( tmplRepoPullsFork = "repo/pulls/fork" tmplRepoPullsCompare = "repo/pulls/compare" tmplRepoPullsCommits = "repo/pulls/commits" tmplRepoPullsFiles = "repo/pulls/files" PullRequestTemplateKey = "PullRequestTemplate" PullRequestTitleTemplateKey = "PullRequestTitleTemplate" ) var ( PullRequestTemplateCandidates = []string{ "PULL_REQUEST.md", ".gogs/PULL_REQUEST.md", ".github/PULL_REQUEST.md", } PullRequestTitleTemplateCandidates = []string{ "PULL_REQUEST_TITLE.md", ".gogs/PULL_REQUEST_TITLE.md", ".github/PULL_REQUEST_TITLE.md", } ) func parseBaseRepository(c *context.Context) *database.Repository { baseRepo, err := database.GetRepositoryByID(c.ParamsInt64(":repoid")) if err != nil { c.NotFoundOrError(err, "get repository by ID") return nil } if !baseRepo.CanBeForked() || !baseRepo.HasAccess(c.User.ID) { c.NotFound() return nil } c.Data["repo_name"] = baseRepo.Name c.Data["description"] = baseRepo.Description c.Data["IsPrivate"] = baseRepo.IsPrivate c.Data["IsUnlisted"] = baseRepo.IsUnlisted if err = baseRepo.GetOwner(); err != nil { c.Error(err, "get owner") return nil } c.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name orgs, err := database.Handle.Organizations().List( c.Req.Context(), database.ListOrgsOptions{ MemberID: c.User.ID, IncludePrivateMembers: true, }, ) if err != nil { c.Error(err, "list organizations") return nil } c.Data["Orgs"] = orgs return baseRepo } func Fork(c *context.Context) { c.Data["Title"] = c.Tr("new_fork") parseBaseRepository(c) if c.Written() { return } c.Data["ContextUser"] = c.User c.Success(tmplRepoPullsFork) } func ForkPost(c *context.Context, f form.CreateRepo) { c.Data["Title"] = c.Tr("new_fork") baseRepo := parseBaseRepository(c) if c.Written() { return } ctxUser := checkContextUser(c, f.UserID) if c.Written() { return } c.Data["ContextUser"] = ctxUser if c.HasError() { c.Success(tmplRepoPullsFork) return } repo, has, err := database.HasForkedRepo(ctxUser.ID, baseRepo.ID) if err != nil { c.Error(err, "check forked repository") return } else if has { c.Redirect(repo.Link()) return } // Check ownership of organization. if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(c.User.ID) { c.Status(http.StatusForbidden) return } // Cannot fork to same owner if ctxUser.ID == baseRepo.OwnerID { c.RenderWithErr(c.Tr("repo.settings.cannot_fork_to_same_owner"), tmplRepoPullsFork, &f) return } repo, err = database.ForkRepository(c.User, ctxUser, baseRepo, f.RepoName, f.Description) if err != nil { c.Data["Err_RepoName"] = true switch { case database.IsErrReachLimitOfRepo(err): c.RenderWithErr(c.Tr("repo.form.reach_limit_of_creation", err.(database.ErrReachLimitOfRepo).Limit), tmplRepoPullsFork, &f) case database.IsErrRepoAlreadyExist(err): c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), tmplRepoPullsFork, &f) case database.IsErrNameNotAllowed(err): c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplRepoPullsFork, &f) default: c.Error(err, "fork repository") } return } log.Trace("Repository forked from '%s' -> '%s'", baseRepo.FullName(), repo.FullName()) c.Redirect(repo.Link()) } func checkPullInfo(c *context.Context) *database.Issue { issue, err := database.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index")) if err != nil { c.NotFoundOrError(err, "get issue by index") return nil } c.Data["Title"] = issue.Title c.Data["Issue"] = issue if !issue.IsPull { c.NotFound() return nil } if c.IsLogged { // Update issue-user. if err = issue.ReadBy(c.User.ID); err != nil { c.Error(err, "mark read by") return nil } } return issue } func PrepareMergedViewPullInfo(c *context.Context, issue *database.Issue) { pull := issue.PullRequest c.Data["HasMerged"] = true c.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch var err error c.Data["NumCommits"], err = c.Repo.GitRepo.RevListCount([]string{pull.MergeBase + "..." + pull.MergedCommitID}) if err != nil { c.Error(err, "count commits") return } names, err := c.Repo.GitRepo.DiffNameOnly(pull.MergeBase, pull.MergedCommitID, git.DiffNameOnlyOptions{NeedsMergeBase: true}) c.Data["NumFiles"] = len(names) if err != nil { c.Error(err, "get changed files") return } } func PrepareViewPullInfo(c *context.Context, issue *database.Issue) *gitutil.PullRequestMeta { repo := c.Repo.Repository pull := issue.PullRequest c.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch var ( headGitRepo *git.Repository err error ) if pull.HeadRepo != nil { headGitRepo, err = git.Open(pull.HeadRepo.RepoPath()) if err != nil { c.Error(err, "open repository") return nil } } if pull.HeadRepo == nil || !headGitRepo.HasBranch(pull.HeadBranch) { c.Data["IsPullReuqestBroken"] = true c.Data["HeadTarget"] = "deleted" c.Data["NumCommits"] = 0 c.Data["NumFiles"] = 0 return nil } baseRepoPath := database.RepoPath(repo.Owner.Name, repo.Name) prMeta, err := gitutil.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, pull.HeadBranch, pull.BaseBranch) if err != nil { if strings.Contains(err.Error(), "fatal: Not a valid object name") { c.Data["IsPullReuqestBroken"] = true c.Data["BaseTarget"] = "deleted" c.Data["NumCommits"] = 0 c.Data["NumFiles"] = 0 return nil } c.Error(err, "get pull request meta") return nil } c.Data["NumCommits"] = len(prMeta.Commits) c.Data["NumFiles"] = prMeta.NumFiles return prMeta } func ViewPullCommits(c *context.Context) { c.Data["PageIsPullList"] = true c.Data["PageIsPullCommits"] = true issue := checkPullInfo(c) if c.Written() { return } pull := issue.PullRequest if pull.HeadRepo != nil { c.Data["Username"] = pull.HeadUserName c.Data["Reponame"] = pull.HeadRepo.Name } var commits []*git.Commit if pull.HasMerged { PrepareMergedViewPullInfo(c, issue) if c.Written() { return } startCommit, err := c.Repo.GitRepo.CatFileCommit(pull.MergeBase) if err != nil { c.Error(err, "get commit of merge base") return } endCommit, err := c.Repo.GitRepo.CatFileCommit(pull.MergedCommitID) if err != nil { c.Error(err, "get merged commit") return } commits, err = c.Repo.GitRepo.RevList([]string{startCommit.ID.String() + "..." + endCommit.ID.String()}) if err != nil { c.Error(err, "list commits") return } } else { prInfo := PrepareViewPullInfo(c, issue) if c.Written() { return } else if prInfo == nil { c.NotFound() return } commits = prInfo.Commits } c.Data["Commits"] = matchUsersWithCommitEmails(c.Req.Context(), commits) c.Data["CommitsCount"] = len(commits) c.Success(tmplRepoPullsCommits) } func ViewPullFiles(c *context.Context) { c.Data["PageIsPullList"] = true c.Data["PageIsPullFiles"] = true issue := checkPullInfo(c) if c.Written() { return } pull := issue.PullRequest var ( diffGitRepo *git.Repository startCommitID string endCommitID string gitRepo *git.Repository ) if pull.HasMerged { PrepareMergedViewPullInfo(c, issue) if c.Written() { return } diffGitRepo = c.Repo.GitRepo startCommitID = pull.MergeBase endCommitID = pull.MergedCommitID gitRepo = c.Repo.GitRepo } else { prInfo := PrepareViewPullInfo(c, issue) if c.Written() { return } else if prInfo == nil { c.NotFound() return } headRepoPath := database.RepoPath(pull.HeadUserName, pull.HeadRepo.Name) headGitRepo, err := git.Open(headRepoPath) if err != nil { c.Error(err, "open repository") return } headCommitID, err := headGitRepo.BranchCommitID(pull.HeadBranch) if err != nil { c.Error(err, "get head branch commit ID") return } diffGitRepo = headGitRepo startCommitID = prInfo.MergeBase endCommitID = headCommitID gitRepo = headGitRepo } diff, err := gitutil.RepoDiff(diffGitRepo, endCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, git.DiffOptions{Base: startCommitID, Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second}, ) if err != nil { c.Error(err, "get diff") return } c.Data["Diff"] = diff c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 commit, err := gitRepo.CatFileCommit(endCommitID) if err != nil { c.Error(err, "get commit") return } setEditorconfigIfExists(c) if c.Written() { return } c.Data["IsSplitStyle"] = c.Query("style") == "split" c.Data["IsImageFile"] = commit.IsImageFile c.Data["IsImageFileByIndex"] = commit.IsImageFileByIndex // It is possible head repo has been deleted for merged pull requests if pull.HeadRepo != nil { c.Data["Username"] = pull.HeadUserName c.Data["Reponame"] = pull.HeadRepo.Name headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name) c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", endCommitID) c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", endCommitID) c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", startCommitID) c.Data["BeforeRawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", startCommitID) } c.Data["RequireHighlightJS"] = true c.Success(tmplRepoPullsFiles) } func MergePullRequest(c *context.Context) { issue := checkPullInfo(c) if c.Written() { return } if issue.IsClosed { c.NotFound() return } pr, err := database.GetPullRequestByIssueID(issue.ID) if err != nil { c.NotFoundOrError(err, "get pull request by issue ID") return } if !pr.CanAutoMerge() || pr.HasMerged { c.NotFound() return } pr.Issue = issue pr.Issue.Repo = c.Repo.Repository if err = pr.Merge(c.User, c.Repo.GitRepo, database.MergeStyle(c.Query("merge_style")), c.Query("commit_description")); err != nil { c.Error(err, "merge") return } log.Trace("Pull request merged: %d", pr.ID) c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) } func ParseCompareInfo(c *context.Context) (*database.User, *database.Repository, *git.Repository, *gitutil.PullRequestMeta, string, string) { baseRepo := c.Repo.Repository // Get compared branches information // format: <base branch>...[<head repo>:]<head branch> // base<-head: master...head:feature // same repo: master...feature infos := strings.Split(c.Params("*"), "...") if len(infos) != 2 { log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos) c.NotFound() return nil, nil, nil, nil, "", "" } baseBranch := infos[0] c.Data["BaseBranch"] = baseBranch var ( headUser *database.User headBranch string isSameRepo bool err error ) // If there is no head repository, it means pull request between same repository. headInfos := strings.Split(infos[1], ":") if len(headInfos) == 1 { isSameRepo = true headUser = c.Repo.Owner headBranch = headInfos[0] } else if len(headInfos) == 2 { headUser, err = database.Handle.Users().GetByUsername(c.Req.Context(), headInfos[0]) if err != nil { c.NotFoundOrError(err, "get user by name") return nil, nil, nil, nil, "", "" } headBranch = headInfos[1] isSameRepo = headUser.ID == baseRepo.OwnerID } else { c.NotFound() return nil, nil, nil, nil, "", "" } c.Data["HeadUser"] = headUser c.Data["HeadBranch"] = headBranch c.Repo.PullRequest.SameRepo = isSameRepo // Check if base branch is valid. if !c.Repo.GitRepo.HasBranch(baseBranch) { c.NotFound() return nil, nil, nil, nil, "", "" } var ( headRepo *database.Repository headGitRepo *git.Repository ) // In case user included redundant head user name for comparison in same repository, // no need to check the fork relation. if !isSameRepo { var has bool headRepo, has, err = database.HasForkedRepo(headUser.ID, baseRepo.ID) if err != nil { c.Error(err, "get forked repository") return nil, nil, nil, nil, "", "" } else if !has { log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have fork or in same repository", baseRepo.ID) c.NotFound() return nil, nil, nil, nil, "", "" } headGitRepo, err = git.Open(database.RepoPath(headUser.Name, headRepo.Name)) if err != nil { c.Error(err, "open repository") return nil, nil, nil, nil, "", "" } } else { headRepo = c.Repo.Repository headGitRepo = c.Repo.GitRepo } if !database.Handle.Permissions().Authorize( c.Req.Context(), c.User.ID, headRepo.ID, database.AccessModeWrite, database.AccessModeOptions{ OwnerID: headRepo.OwnerID, Private: headRepo.IsPrivate, }, ) && !c.User.IsAdmin { log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have write access or site admin", baseRepo.ID) c.NotFound() return nil, nil, nil, nil, "", "" } // Check if head branch is valid. if !headGitRepo.HasBranch(headBranch) { c.NotFound() return nil, nil, nil, nil, "", "" } headBranches, err := headGitRepo.Branches() if err != nil { c.Error(err, "get branches") return nil, nil, nil, nil, "", "" } c.Data["HeadBranches"] = headBranches baseRepoPath := database.RepoPath(baseRepo.Owner.Name, baseRepo.Name) meta, err := gitutil.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, headBranch, baseBranch) if err != nil { if gitutil.IsErrNoMergeBase(err) { c.Data["IsNoMergeBase"] = true c.Success(tmplRepoPullsCompare) } else { c.Error(err, "get pull request meta") } return nil, nil, nil, nil, "", "" } c.Data["BeforeCommitID"] = meta.MergeBase return headUser, headRepo, headGitRepo, meta, baseBranch, headBranch } func PrepareCompareDiff( c *context.Context, headUser *database.User, headRepo *database.Repository, headGitRepo *git.Repository, meta *gitutil.PullRequestMeta, headBranch string, ) bool { var ( repo = c.Repo.Repository err error ) // Get diff information. c.Data["CommitRepoLink"] = headRepo.Link() headCommitID, err := headGitRepo.BranchCommitID(headBranch) if err != nil { c.Error(err, "get head branch commit ID") return false } c.Data["AfterCommitID"] = headCommitID if headCommitID == meta.MergeBase { c.Data["IsNothingToCompare"] = true return true } diff, err := gitutil.RepoDiff(headGitRepo, headCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, git.DiffOptions{Base: meta.MergeBase, Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second}, ) if err != nil { c.Error(err, "get repository diff") return false } c.Data["Diff"] = diff c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 headCommit, err := headGitRepo.CatFileCommit(headCommitID) if err != nil { c.Error(err, "get head commit") return false } c.Data["Commits"] = matchUsersWithCommitEmails(c.Req.Context(), meta.Commits) c.Data["CommitCount"] = len(meta.Commits) c.Data["Username"] = headUser.Name c.Data["Reponame"] = headRepo.Name c.Data["IsImageFile"] = headCommit.IsImageFile c.Data["IsImageFileByIndex"] = headCommit.IsImageFileByIndex headTarget := path.Join(headUser.Name, repo.Name) c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", headCommitID) c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", headCommitID) c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", meta.MergeBase) c.Data["BeforeRawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", meta.MergeBase) return false } func CompareAndPullRequest(c *context.Context) { c.Data["Title"] = c.Tr("repo.pulls.compare_changes") c.Data["PageIsComparePull"] = true c.Data["IsDiffCompare"] = true c.Data["RequireHighlightJS"] = true setTemplateIfExists(c, PullRequestTemplateKey, PullRequestTemplateCandidates) renderAttachmentSettings(c) headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c) if c.Written() { return } pr, err := database.GetUnmergedPullRequest(headRepo.ID, c.Repo.Repository.ID, headBranch, baseBranch) if err != nil { if !database.IsErrPullRequestNotExist(err) { c.Error(err, "get unmerged pull request") return } } else { c.Data["HasPullRequest"] = true c.Data["PullRequest"] = pr c.Success(tmplRepoPullsCompare) return } nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, headBranch) if c.Written() { return } if !nothingToCompare { // Setup information for new form. RetrieveRepoMetas(c, c.Repo.Repository) if c.Written() { return } } setEditorconfigIfExists(c) if c.Written() { return } c.Data["IsSplitStyle"] = c.Query("style") == "split" setTemplateIfExists(c, PullRequestTitleTemplateKey, PullRequestTitleTemplateCandidates) if c.Data[PullRequestTitleTemplateKey] != nil { customTitle := c.Data[PullRequestTitleTemplateKey].(string) r := strings.NewReplacer("{{headBranch}}", headBranch, "{{baseBranch}}", baseBranch) c.Data["title"] = r.Replace(customTitle) } c.Success(tmplRepoPullsCompare) } func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) { c.Data["Title"] = c.Tr("repo.pulls.compare_changes") c.Data["PageIsComparePull"] = true c.Data["IsDiffCompare"] = true c.Data["RequireHighlightJS"] = true renderAttachmentSettings(c) var ( repo = c.Repo.Repository attachments []string ) headUser, headRepo, headGitRepo, meta, baseBranch, headBranch := ParseCompareInfo(c) if c.Written() { return } labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f) if c.Written() { return } if conf.Attachment.Enabled { attachments = f.Files } if c.HasError() { form.Assign(f, c.Data) // This stage is already stop creating new pull request, so it does not matter if it has // something to compare or not. PrepareCompareDiff(c, headUser, headRepo, headGitRepo, meta, headBranch) if c.Written() { return } c.Success(tmplRepoPullsCompare) return } patch, err := headGitRepo.DiffBinary(meta.MergeBase, headBranch) if err != nil { c.Error(err, "get patch") return } pullIssue := &database.Issue{ RepoID: repo.ID, Index: repo.NextIssueIndex(), Title: f.Title, PosterID: c.User.ID, Poster: c.User, MilestoneID: milestoneID, AssigneeID: assigneeID, IsPull: true, Content: f.Content, } pullRequest := &database.PullRequest{ HeadRepoID: headRepo.ID, BaseRepoID: repo.ID, HeadUserName: headUser.Name, HeadBranch: headBranch, BaseBranch: baseBranch, HeadRepo: headRepo, BaseRepo: repo, MergeBase: meta.MergeBase, Type: database.PullRequestTypeGogs, } // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt // instead of 500. if err := database.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil { c.Error(err, "new pull request") return } else if err := pullRequest.PushToBaseRepo(); err != nil { c.Error(err, "push to base repository") return } log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID) c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index)) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/tasks.go
internal/route/repo/tasks.go
// Copyright 2020 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 ( "net/http" "gopkg.in/macaron.v1" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/cryptoutil" "gogs.io/gogs/internal/database" ) func TriggerTask(c *macaron.Context) { branch := c.Query("branch") pusherID := c.QueryInt64("pusher") secret := c.Query("secret") if branch == "" || pusherID <= 0 || secret == "" { c.Error(http.StatusBadRequest, "Incomplete branch, pusher or secret") return } username := c.Params(":username") reponame := c.Params(":reponame") owner, err := database.Handle.Users().GetByUsername(c.Req.Context(), username) if err != nil { if database.IsErrUserNotExist(err) { c.Error(http.StatusBadRequest, "Owner does not exist") } else { c.Status(http.StatusInternalServerError) log.Error("Failed to get user [name: %s]: %v", username, err) } return } // 🚨 SECURITY: No need to check existence of the repository if the client // can't even get the valid secret. Mostly likely not a legitimate request. if secret != cryptoutil.MD5(owner.Salt) { c.Error(http.StatusBadRequest, "Invalid secret") return } repo, err := database.Handle.Repositories().GetByName(c.Req.Context(), owner.ID, reponame) if err != nil { if database.IsErrRepoNotExist(err) { c.Error(http.StatusBadRequest, "Repository does not exist") } else { c.Status(http.StatusInternalServerError) log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, reponame, err) } return } pusher, err := database.Handle.Users().GetByID(c.Req.Context(), pusherID) if err != nil { if database.IsErrUserNotExist(err) { c.Error(http.StatusBadRequest, "Pusher does not exist") } else { c.Status(http.StatusInternalServerError) log.Error("Failed to get user [id: %d]: %v", pusherID, err) } return } log.Trace("TriggerTask: %s/%s@%s by %q", owner.Name, repo.Name, branch, pusher.Name) go database.HookQueue.Add(repo.ID) go database.AddTestPullRequestTask(pusher, repo.ID, branch, true) c.Status(http.StatusAccepted) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/download.go
internal/route/repo/download.go
// Copyright 2014 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 ( "fmt" "net/http" "path" "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/tool" ) func serveData(c *context.Context, name string, data []byte) error { commit, err := c.Repo.Commit.CommitByPath(git.CommitByRevisionOptions{Path: c.Repo.TreePath}) if err != nil { return fmt.Errorf("get commit by path %q: %v", c.Repo.TreePath, err) } c.Resp.Header().Set("Last-Modified", commit.Committer.When.Format(http.TimeFormat)) if !tool.IsTextFile(data) { if !tool.IsImageFile(data) { c.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"") c.Resp.Header().Set("Content-Transfer-Encoding", "binary") } } else if !conf.Repository.EnableRawFileRenderMode || !c.QueryBool("render") { c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8") } if _, err := c.Resp.Write(data); err != nil { return fmt.Errorf("write buffer to response: %v", err) } return nil } func ServeBlob(c *context.Context, blob *git.Blob) error { p, err := blob.Bytes() if err != nil { return err } return serveData(c, path.Base(c.Repo.TreePath), p) } func SingleDownload(c *context.Context) { blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { c.NotFoundOrError(gitutil.NewError(err), "get blob") return } if err = ServeBlob(c, blob); err != nil { c.Error(err, "serve blob") return } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/repo/webhook_test.go
internal/route/repo/webhook_test.go
// Copyright 2020 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 ( "testing" "github.com/stretchr/testify/assert" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/mocks" ) func Test_validateWebhook(t *testing.T) { l := &mocks.Locale{ MockLang: "en", MockTr: func(s string, _ ...any) string { return s }, } tests := []struct { name string actor *database.User webhook *database.Webhook expField string expMsg string expOK bool }{ { name: "admin bypass local address check", webhook: &database.Webhook{URL: "https://www.google.com"}, expOK: true, }, { name: "local address not allowed", webhook: &database.Webhook{URL: "http://localhost:3306"}, expField: "PayloadURL", expMsg: "repo.settings.webhook.url_resolved_to_blocked_local_address", expOK: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { field, msg, ok := validateWebhook(l, test.webhook) assert.Equal(t, test.expOK, ok) assert.Equal(t, test.expMsg, msg) assert.Equal(t, test.expField, field) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/org/members.go
internal/route/org/members.go
// Copyright 2014 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 org import ( "github.com/unknwon/com" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" ) const ( tmplOrgMembers = "org/member/members" templOrgMemberInvite = "org/member/invite" ) func Members(c *context.Context) { org := c.Org.Organization c.Data["Title"] = org.FullName c.Data["PageIsOrgMembers"] = true if err := org.GetMembers(0); err != nil { c.Error(err, "get members") return } c.Data["Members"] = org.Members c.Success(tmplOrgMembers) } func MembersAction(c *context.Context) { uid := com.StrTo(c.Query("uid")).MustInt64() if uid == 0 { c.Redirect(c.Org.OrgLink + "/members") return } org := c.Org.Organization var err error switch c.Params(":action") { case "private": if c.User.ID != uid && !c.Org.IsOwner { c.NotFound() return } err = database.ChangeOrgUserStatus(org.ID, uid, false) case "public": if c.User.ID != uid && !c.Org.IsOwner { c.NotFound() return } err = database.ChangeOrgUserStatus(org.ID, uid, true) case "remove": if !c.Org.IsOwner { c.NotFound() return } err = org.RemoveMember(uid) if database.IsErrLastOrgOwner(err) { c.Flash.Error(c.Tr("form.last_org_owner")) c.Redirect(c.Org.OrgLink + "/members") return } case "leave": err = org.RemoveMember(c.User.ID) if database.IsErrLastOrgOwner(err) { c.Flash.Error(c.Tr("form.last_org_owner")) c.Redirect(c.Org.OrgLink + "/members") return } } if err != nil { log.Error("Action(%s): %v", c.Params(":action"), err) c.JSONSuccess(map[string]any{ "ok": false, "err": err.Error(), }) return } if c.Params(":action") != "leave" { c.Redirect(c.Org.OrgLink + "/members") } else { c.Redirect(conf.Server.Subpath + "/") } } func Invitation(c *context.Context) { org := c.Org.Organization c.Data["Title"] = org.FullName c.Data["PageIsOrgMembers"] = true if c.Req.Method == "POST" { uname := c.Query("uname") u, err := database.Handle.Users().GetByUsername(c.Req.Context(), uname) if err != nil { if database.IsErrUserNotExist(err) { c.Flash.Error(c.Tr("form.user_not_exist")) c.Redirect(c.Org.OrgLink + "/invitations/new") } else { c.Error(err, "get user by name") } return } if err = org.AddMember(u.ID); err != nil { c.Error(err, "add member") return } log.Trace("New member added(%s): %s", org.Name, u.Name) c.Redirect(c.Org.OrgLink + "/members") return } c.Success(templOrgMemberInvite) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/org/teams.go
internal/route/org/teams.go
// Copyright 2014 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 org import ( "net/http" "path" "github.com/unknwon/com" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" ) const ( tmplOrgTeams = "org/team/teams" tmplOrgTeamNew = "org/team/new" tmplOrgTeamMembers = "org/team/members" tmplOrgTeamRepositories = "org/team/repositories" ) func Teams(c *context.Context) { org := c.Org.Organization c.Data["Title"] = org.FullName c.Data["PageIsOrgTeams"] = true for _, t := range org.Teams { if err := t.GetMembers(); err != nil { c.Error(err, "get members") return } } c.Data["Teams"] = org.Teams c.Success(tmplOrgTeams) } func TeamsAction(c *context.Context) { uid := com.StrTo(c.Query("uid")).MustInt64() if uid == 0 { c.Redirect(c.Org.OrgLink + "/teams") return } page := c.Query("page") var err error switch c.Params(":action") { case "join": if !c.Org.IsOwner { c.NotFound() return } err = c.Org.Team.AddMember(c.User.ID) case "leave": err = c.Org.Team.RemoveMember(c.User.ID) case "remove": if !c.Org.IsOwner { c.NotFound() return } err = c.Org.Team.RemoveMember(uid) page = "team" case "add": if !c.Org.IsOwner { c.NotFound() return } uname := c.Query("uname") var u *database.User u, err = database.Handle.Users().GetByUsername(c.Req.Context(), uname) if err != nil { if database.IsErrUserNotExist(err) { c.Flash.Error(c.Tr("form.user_not_exist")) c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName) } else { c.Error(err, "get user by name") } return } err = c.Org.Team.AddMember(u.ID) page = "team" } if err != nil { if database.IsErrLastOrgOwner(err) { c.Flash.Error(c.Tr("form.last_org_owner")) } else { log.Error("Action(%s): %v", c.Params(":action"), err) c.JSONSuccess(map[string]any{ "ok": false, "err": err.Error(), }) return } } switch page { case "team": c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName) default: c.Redirect(c.Org.OrgLink + "/teams") } } func TeamsRepoAction(c *context.Context) { if !c.Org.IsOwner { c.NotFound() return } var err error switch c.Params(":action") { case "add": repoName := path.Base(c.Query("repo_name")) var repo *database.Repository repo, err = database.GetRepositoryByName(c.Org.Organization.ID, repoName) if err != nil { if database.IsErrRepoNotExist(err) { c.Flash.Error(c.Tr("org.teams.add_nonexistent_repo")) c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName + "/repositories") return } c.Error(err, "get repository by name") return } err = c.Org.Team.AddRepository(repo) case "remove": err = c.Org.Team.RemoveRepository(com.StrTo(c.Query("repoid")).MustInt64()) } if err != nil { c.Errorf(err, "action %q", c.Params(":action")) return } c.Redirect(c.Org.OrgLink + "/teams/" + c.Org.Team.LowerName + "/repositories") } func NewTeam(c *context.Context) { c.Data["Title"] = c.Org.Organization.FullName c.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeamsNew"] = true c.Data["Team"] = &database.Team{} c.Success(tmplOrgTeamNew) } func NewTeamPost(c *context.Context, f form.CreateTeam) { c.Data["Title"] = c.Org.Organization.FullName c.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeamsNew"] = true t := &database.Team{ OrgID: c.Org.Organization.ID, Name: f.TeamName, Description: f.Description, Authorize: database.ParseAccessMode(f.Permission), } c.Data["Team"] = t if c.HasError() { c.Success(tmplOrgTeamNew) return } if err := database.NewTeam(t); err != nil { c.Data["Err_TeamName"] = true switch { case database.IsErrTeamAlreadyExist(err): c.RenderWithErr(c.Tr("form.team_name_been_taken"), tmplOrgTeamNew, &f) case database.IsErrNameNotAllowed(err): c.RenderWithErr(c.Tr("org.form.team_name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplOrgTeamNew, &f) default: c.Error(err, "new team") } return } log.Trace("Team created: %s/%s", c.Org.Organization.Name, t.Name) c.Redirect(c.Org.OrgLink + "/teams/" + t.LowerName) } func TeamMembers(c *context.Context) { c.Data["Title"] = c.Org.Team.Name c.Data["PageIsOrgTeams"] = true if err := c.Org.Team.GetMembers(); err != nil { c.Error(err, "get members") return } c.Success(tmplOrgTeamMembers) } func TeamRepositories(c *context.Context) { c.Data["Title"] = c.Org.Team.Name c.Data["PageIsOrgTeams"] = true if err := c.Org.Team.GetRepositories(); err != nil { c.Error(err, "get repositories") return } c.Success(tmplOrgTeamRepositories) } func EditTeam(c *context.Context) { c.Data["Title"] = c.Org.Organization.FullName c.Data["PageIsOrgTeams"] = true c.Data["team_name"] = c.Org.Team.Name c.Data["desc"] = c.Org.Team.Description c.Success(tmplOrgTeamNew) } func EditTeamPost(c *context.Context, f form.CreateTeam) { t := c.Org.Team c.Data["Title"] = c.Org.Organization.FullName c.Data["PageIsOrgTeams"] = true c.Data["Team"] = t if c.HasError() { c.Success(tmplOrgTeamNew) return } isAuthChanged := false if !t.IsOwnerTeam() { // Validate permission level. var auth database.AccessMode switch f.Permission { case "read": auth = database.AccessModeRead case "write": auth = database.AccessModeWrite case "admin": auth = database.AccessModeAdmin default: c.Status(http.StatusUnauthorized) return } t.Name = f.TeamName if t.Authorize != auth { isAuthChanged = true t.Authorize = auth } } t.Description = f.Description if err := database.UpdateTeam(t, isAuthChanged); err != nil { c.Data["Err_TeamName"] = true switch { case database.IsErrTeamAlreadyExist(err): c.RenderWithErr(c.Tr("form.team_name_been_taken"), tmplOrgTeamNew, &f) default: c.Error(err, "update team") } return } c.Redirect(c.Org.OrgLink + "/teams/" + t.LowerName) } func DeleteTeam(c *context.Context) { if err := database.DeleteTeam(c.Org.Team); err != nil { c.Flash.Error("DeleteTeam: " + err.Error()) } else { c.Flash.Success(c.Tr("org.teams.delete_team_success")) } c.JSONSuccess(map[string]any{ "redirect": c.Org.OrgLink + "/teams", }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/org/setting.go
internal/route/org/setting.go
// Copyright 2014 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 org import ( log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/route/user" ) const ( tmplOrgSettingsOptions = "org/settings/options" tmplOrgSettingsDelete = "org/settings/delete" ) func Settings(c *context.Context) { c.Title("org.settings") c.Data["PageIsSettingsOptions"] = true c.Success(tmplOrgSettingsOptions) } func SettingsPost(c *context.Context, f form.UpdateOrgSetting) { c.Title("org.settings") c.Data["PageIsSettingsOptions"] = true if c.HasError() { c.Success(tmplOrgSettingsOptions) return } org := c.Org.Organization // Check if the organization username (including cases) had been changed if org.Name != f.Name { err := database.Handle.Users().ChangeUsername(c.Req.Context(), c.Org.Organization.ID, f.Name) if err != nil { c.Data["OrgName"] = true var msg string switch { case database.IsErrUserAlreadyExist(err): msg = c.Tr("form.username_been_taken") case database.IsErrNameNotAllowed(err): msg = c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()) default: c.Error(err, "change organization name") return } c.RenderWithErr(msg, tmplOrgSettingsOptions, &f) return } // reset c.org.OrgLink with new name c.Org.OrgLink = conf.Server.Subpath + "/org/" + f.Name log.Trace("Organization name changed: %s -> %s", org.Name, f.Name) } opts := database.UpdateUserOptions{ FullName: &f.FullName, Website: &f.Website, Location: &f.Location, Description: &f.Description, } if c.User.IsAdmin { opts.MaxRepoCreation = &f.MaxRepoCreation } err := database.Handle.Users().Update(c.Req.Context(), c.Org.Organization.ID, opts) if err != nil { c.Error(err, "update organization") return } c.Flash.Success(c.Tr("org.settings.update_setting_success")) c.Redirect(c.Org.OrgLink + "/settings") } func SettingsAvatar(c *context.Context, f form.Avatar) { f.Source = form.AvatarLocal if err := user.UpdateAvatarSetting(c, f, c.Org.Organization); err != nil { c.Flash.Error(err.Error()) } else { c.Flash.Success(c.Tr("org.settings.update_avatar_success")) } c.Redirect(c.Org.OrgLink + "/settings") } func SettingsDeleteAvatar(c *context.Context) { if err := database.Handle.Users().DeleteCustomAvatar(c.Req.Context(), c.Org.Organization.ID); err != nil { c.Flash.Error(err.Error()) } c.Redirect(c.Org.OrgLink + "/settings") } func SettingsDelete(c *context.Context) { c.Title("org.settings") c.PageIs("SettingsDelete") org := c.Org.Organization if c.Req.Method == "POST" { if _, err := database.Handle.Users().Authenticate(c.Req.Context(), c.User.Name, c.Query("password"), c.User.LoginSource); err != nil { if auth.IsErrBadCredentials(err) { c.RenderWithErr(c.Tr("form.enterred_invalid_password"), tmplOrgSettingsDelete, nil) } else { c.Error(err, "authenticate user") } return } if err := database.DeleteOrganization(org); err != nil { if database.IsErrUserOwnRepos(err) { c.Flash.Error(c.Tr("form.org_still_own_repo")) c.Redirect(c.Org.OrgLink + "/settings/delete") } else { c.Error(err, "delete organization") } } else { log.Trace("Organization deleted: %s", org.Name) c.Redirect(conf.Server.Subpath + "/") } return } c.Success(tmplOrgSettingsDelete) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/org/org.go
internal/route/org/org.go
// Copyright 2014 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 org import ( log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" ) const ( CREATE = "org/create" ) func Create(c *context.Context) { c.Title("new_org") c.Success(CREATE) } func CreatePost(c *context.Context, f form.CreateOrg) { c.Title("new_org") if c.HasError() { c.Success(CREATE) return } org := &database.User{ Name: f.OrgName, IsActive: true, Type: database.UserTypeOrganization, } if err := database.CreateOrganization(org, c.User); err != nil { c.Data["Err_OrgName"] = true switch { case database.IsErrUserAlreadyExist(err): c.RenderWithErr(c.Tr("form.org_name_been_taken"), CREATE, &f) case database.IsErrNameNotAllowed(err): c.RenderWithErr(c.Tr("org.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), CREATE, &f) default: c.Error(err, "create organization") } return } log.Trace("Organization created: %s", org.Name) c.RedirectSubpath("/org/" + f.OrgName + "/dashboard") }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/batch_test.go
internal/route/lfs/batch_test.go
// Copyright 2020 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 lfs import ( "bytes" "encoding/json" "io" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/macaron.v1" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" ) func TestServeBatch(t *testing.T) { conf.SetMockServer(t, conf.ServerOpts{ ExternalURL: "https://gogs.example.com/", }) tests := []struct { name string body string mockStore func() *MockStore expStatusCode int expBody string }{ { name: "unrecognized operation", body: `{"operation": "update"}`, expStatusCode: http.StatusBadRequest, expBody: `{"message": "Operation not recognized"}` + "\n", }, { name: "upload: contains invalid oid", body: `{ "operation": "upload", "objects": [ {"oid": "bad_oid", "size": 123}, {"oid": "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", "size": 123} ]}`, expStatusCode: http.StatusOK, expBody: `{ "transfer": "basic", "objects": [ {"oid": "bad_oid", "size":123, "actions": {"error": {"code": 422, "message": "Object has invalid oid"}}}, { "oid": "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", "size": 123, "actions": { "upload": { "href": "https://gogs.example.com/owner/repo.git/info/lfs/objects/basic/ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", "header": {"Content-Type": "application/octet-stream"} }, "verify": { "href": "https://gogs.example.com/owner/repo.git/info/lfs/objects/basic/verify" } } } ] }` + "\n", }, { name: "download: contains non-existent oid and mismatched size", body: `{ "operation": "download", "objects": [ {"oid": "bad_oid", "size": 123}, {"oid": "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", "size": 123}, {"oid": "5cac0a318669fadfee734fb340a5f5b70b428ac57a9f4b109cb6e150b2ba7e57", "size": 456} ]}`, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectsByOIDsFunc.SetDefaultReturn( []*database.LFSObject{ { OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", Size: 1234, }, { OID: "5cac0a318669fadfee734fb340a5f5b70b428ac57a9f4b109cb6e150b2ba7e57", Size: 456, }, }, nil, ) return mockStore }, expStatusCode: http.StatusOK, expBody: `{ "transfer": "basic", "objects": [ {"oid": "bad_oid", "size": 123, "actions": {"error": {"code": 404, "message": "Object does not exist"}}}, { "oid": "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", "size": 123, "actions": {"error": {"code": 422, "message": "Object size mismatch"}} }, { "oid": "5cac0a318669fadfee734fb340a5f5b70b428ac57a9f4b109cb6e150b2ba7e57", "size": 456, "actions": { "download": { "href": "https://gogs.example.com/owner/repo.git/info/lfs/objects/basic/5cac0a318669fadfee734fb340a5f5b70b428ac57a9f4b109cb6e150b2ba7e57" } } } ] }` + "\n", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { mockStore := NewMockStore() if test.mockStore != nil { mockStore = test.mockStore() } m := macaron.New() m.Use(func(c *macaron.Context) { c.Map(&database.User{Name: "owner"}) c.Map(&database.Repository{Name: "repo"}) }) m.Post("/", serveBatch(mockStore)) r, err := http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(test.body)) require.NoError(t, err) rr := httptest.NewRecorder() m.ServeHTTP(rr, r) resp := rr.Result() assert.Equal(t, test.expStatusCode, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) var expBody bytes.Buffer err = json.Indent(&expBody, []byte(test.expBody), "", " ") require.NoError(t, err) var gotBody bytes.Buffer err = json.Indent(&gotBody, body, "", " ") require.NoError(t, err) assert.Equal(t, expBody.String(), gotBody.String()) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/basic.go
internal/route/lfs/basic.go
// Copyright 2020 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 lfs import ( "encoding/json" "io" "net/http" "strconv" "gopkg.in/macaron.v1" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/lfsutil" "gogs.io/gogs/internal/strutil" ) const transferBasic = "basic" const ( basicOperationUpload = "upload" basicOperationDownload = "download" ) type basicHandler struct { store Store // The default storage backend for uploading new objects. defaultStorage lfsutil.Storage // The list of available storage backends to access objects. storagers map[lfsutil.Storage]lfsutil.Storager } // DefaultStorager returns the default storage backend. func (h *basicHandler) DefaultStorager() lfsutil.Storager { return h.storagers[h.defaultStorage] } // Storager returns the given storage backend. func (h *basicHandler) Storager(storage lfsutil.Storage) lfsutil.Storager { return h.storagers[storage] } // GET /{owner}/{repo}.git/info/lfs/object/basic/{oid} func (h *basicHandler) serveDownload(c *macaron.Context, repo *database.Repository, oid lfsutil.OID) { object, err := h.store.GetLFSObjectByOID(c.Req.Context(), repo.ID, oid) if err != nil { if database.IsErrLFSObjectNotExist(err) { responseJSON(c.Resp, http.StatusNotFound, responseError{ Message: "Object does not exist", }) } else { internalServerError(c.Resp) log.Error("Failed to get object [repo_id: %d, oid: %s]: %v", repo.ID, oid, err) } return } s := h.Storager(object.Storage) if s == nil { internalServerError(c.Resp) log.Error("Failed to locate the object [repo_id: %d, oid: %s]: storage %q not found", object.RepoID, object.OID, object.Storage) return } c.Header().Set("Content-Type", "application/octet-stream") c.Header().Set("Content-Length", strconv.FormatInt(object.Size, 10)) c.Status(http.StatusOK) err = s.Download(object.OID, c.Resp) if err != nil { log.Error("Failed to download object [oid: %s]: %v", object.OID, err) return } } // PUT /{owner}/{repo}.git/info/lfs/object/basic/{oid} func (h *basicHandler) serveUpload(c *macaron.Context, repo *database.Repository, oid lfsutil.OID) { // NOTE: LFS client will retry upload the same object if there was a partial failure, // therefore we would like to skip ones that already exist. _, err := h.store.GetLFSObjectByOID(c.Req.Context(), repo.ID, oid) if err == nil { // Object exists, drain the request body and we're good. _, _ = io.Copy(io.Discard, c.Req.Request.Body) c.Req.Request.Body.Close() c.Status(http.StatusOK) return } else if !database.IsErrLFSObjectNotExist(err) { internalServerError(c.Resp) log.Error("Failed to get object [repo_id: %d, oid: %s]: %v", repo.ID, oid, err) return } s := h.DefaultStorager() written, err := s.Upload(oid, c.Req.Request.Body) if err != nil { if err == lfsutil.ErrInvalidOID { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: err.Error(), }) } else { internalServerError(c.Resp) log.Error("Failed to upload object [storage: %s, oid: %s]: %v", s.Storage(), oid, err) } return } err = h.store.CreateLFSObject(c.Req.Context(), repo.ID, oid, written, s.Storage()) if err != nil { // NOTE: It is OK to leave the file when the whole operation failed // with a DB error, a retry on client side can safely overwrite the // same file as OID is seen as unique to every file. internalServerError(c.Resp) log.Error("Failed to create object [repo_id: %d, oid: %s]: %v", repo.ID, oid, err) return } c.Status(http.StatusOK) log.Trace("[LFS] Object created %q", oid) } // POST /{owner}/{repo}.git/info/lfs/object/basic/verify func (h *basicHandler) serveVerify(c *macaron.Context, repo *database.Repository) { var request basicVerifyRequest defer func() { _ = c.Req.Request.Body.Close() }() err := json.NewDecoder(c.Req.Request.Body).Decode(&request) if err != nil { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: strutil.ToUpperFirst(err.Error()), }) return } if !lfsutil.ValidOID(request.Oid) { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: "Invalid oid", }) return } object, err := h.store.GetLFSObjectByOID(c.Req.Context(), repo.ID, request.Oid) if err != nil { if database.IsErrLFSObjectNotExist(err) { responseJSON(c.Resp, http.StatusNotFound, responseError{ Message: "Object does not exist", }) } else { internalServerError(c.Resp) log.Error("Failed to get object [repo_id: %d, oid: %s]: %v", repo.ID, request.Oid, err) } return } if object.Size != request.Size { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: "Object size mismatch", }) return } c.Status(http.StatusOK) } type basicVerifyRequest struct { Oid lfsutil.OID `json:"oid"` Size int64 `json:"size"` }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/basic_test.go
internal/route/lfs/basic_test.go
// Copyright 2020 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 lfs import ( "bytes" "io" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/macaron.v1" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/lfsutil" ) var _ lfsutil.Storager = (*mockStorage)(nil) // mockStorage is an in-memory storage for LFS objects. type mockStorage struct { buf *bytes.Buffer } func (*mockStorage) Storage() lfsutil.Storage { return "memory" } func (s *mockStorage) Upload(_ lfsutil.OID, rc io.ReadCloser) (int64, error) { defer func() { _ = rc.Close() }() return io.Copy(s.buf, rc) } func (s *mockStorage) Download(_ lfsutil.OID, w io.Writer) error { _, err := io.Copy(w, s.buf) return err } func TestBasicHandler_serveDownload(t *testing.T) { s := &mockStorage{} basic := &basicHandler{ defaultStorage: s.Storage(), storagers: map[lfsutil.Storage]lfsutil.Storager{ s.Storage(): s, }, } m := macaron.New() m.Use(macaron.Renderer()) m.Use(func(c *macaron.Context) { c.Map(&database.Repository{Name: "repo"}) c.Map(lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")) }) m.Get("/", basic.serveDownload) tests := []struct { name string content string mockStore func() *MockStore expStatusCode int expHeader http.Header expBody string }{ { name: "object does not exist", mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectByOIDFunc.SetDefaultReturn(nil, database.ErrLFSObjectNotExist{}) return mockStore }, expStatusCode: http.StatusNotFound, expHeader: http.Header{ "Content-Type": []string{"application/vnd.git-lfs+json"}, }, expBody: `{"message":"Object does not exist"}` + "\n", }, { name: "storage not found", mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectByOIDFunc.SetDefaultReturn(&database.LFSObject{Storage: "bad_storage"}, nil) return mockStore }, expStatusCode: http.StatusInternalServerError, expHeader: http.Header{ "Content-Type": []string{"application/vnd.git-lfs+json"}, }, expBody: `{"message":"Internal server error"}` + "\n", }, { name: "object exists", content: "Hello world!", mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectByOIDFunc.SetDefaultReturn( &database.LFSObject{ Size: 12, Storage: s.Storage(), }, nil, ) return mockStore }, expStatusCode: http.StatusOK, expHeader: http.Header{ "Content-Type": []string{"application/octet-stream"}, "Content-Length": []string{"12"}, }, expBody: "Hello world!", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { basic.store = test.mockStore() s.buf = bytes.NewBufferString(test.content) r, err := http.NewRequest(http.MethodGet, "/", nil) require.NoError(t, err) rr := httptest.NewRecorder() m.ServeHTTP(rr, r) resp := rr.Result() assert.Equal(t, test.expStatusCode, resp.StatusCode) assert.Equal(t, test.expHeader, resp.Header) body, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, test.expBody, string(body)) }) } } func TestBasicHandler_serveUpload(t *testing.T) { s := &mockStorage{buf: &bytes.Buffer{}} basic := &basicHandler{ defaultStorage: s.Storage(), storagers: map[lfsutil.Storage]lfsutil.Storager{ s.Storage(): s, }, } m := macaron.New() m.Use(macaron.Renderer()) m.Use(func(c *macaron.Context) { c.Map(&database.Repository{Name: "repo"}) c.Map(lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")) }) m.Put("/", basic.serveUpload) tests := []struct { name string mockStore func() *MockStore expStatusCode int expBody string }{ { name: "object already exists", mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectByOIDFunc.SetDefaultReturn(&database.LFSObject{}, nil) return mockStore }, expStatusCode: http.StatusOK, }, { name: "new object", mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectByOIDFunc.SetDefaultReturn(nil, database.ErrLFSObjectNotExist{}) return mockStore }, expStatusCode: http.StatusOK, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { basic.store = test.mockStore() r, err := http.NewRequest("PUT", "/", strings.NewReader("Hello world!")) require.NoError(t, err) rr := httptest.NewRecorder() m.ServeHTTP(rr, r) resp := rr.Result() assert.Equal(t, test.expStatusCode, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, test.expBody, string(body)) }) } } func TestBasicHandler_serveVerify(t *testing.T) { basic := &basicHandler{} m := macaron.New() m.Use(macaron.Renderer()) m.Use(func(c *macaron.Context) { c.Map(&database.Repository{Name: "repo"}) }) m.Post("/", basic.serveVerify) tests := []struct { name string body string mockStore func() *MockStore expStatusCode int expBody string }{ { name: "invalid oid", body: `{"oid": "bad_oid"}`, expStatusCode: http.StatusBadRequest, expBody: `{"message":"Invalid oid"}` + "\n", }, { name: "object does not exist", body: `{"oid":"ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f"}`, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectByOIDFunc.SetDefaultReturn(nil, database.ErrLFSObjectNotExist{}) return mockStore }, expStatusCode: http.StatusNotFound, expBody: `{"message":"Object does not exist"}` + "\n", }, { name: "object size mismatch", body: `{"oid":"ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f"}`, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectByOIDFunc.SetDefaultReturn(&database.LFSObject{Size: 12}, nil) return mockStore }, expStatusCode: http.StatusBadRequest, expBody: `{"message":"Object size mismatch"}` + "\n", }, { name: "object exists", body: `{"oid":"ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", "size":12}`, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetLFSObjectByOIDFunc.SetDefaultReturn(&database.LFSObject{Size: 12}, nil) return mockStore }, expStatusCode: http.StatusOK, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { if test.mockStore != nil { basic.store = test.mockStore() } r, err := http.NewRequest("POST", "/", strings.NewReader(test.body)) require.NoError(t, err) rr := httptest.NewRecorder() m.ServeHTTP(rr, r) resp := rr.Result() assert.Equal(t, test.expStatusCode, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, test.expBody, string(body)) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/route_test.go
internal/route/lfs/route_test.go
// Copyright 2020 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 lfs import ( "context" "fmt" "io" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "gopkg.in/macaron.v1" "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/lfsutil" ) func TestAuthenticate(t *testing.T) { tests := []struct { name string header http.Header mockStore func() *MockStore expStatusCode int expHeader http.Header expBody string }{ { name: "no authorization", expStatusCode: http.StatusUnauthorized, expHeader: http.Header{ "Lfs-Authenticate": []string{`Basic realm="Git LFS"`}, "Content-Type": []string{"application/vnd.git-lfs+json"}, }, expBody: `{"message":"Credentials needed"}` + "\n", }, { name: "user has 2FA enabled", header: http.Header{ "Authorization": []string{"Basic dXNlcm5hbWU6cGFzc3dvcmQ="}, }, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.IsTwoFactorEnabledFunc.SetDefaultReturn(true) mockStore.AuthenticateUserFunc.SetDefaultReturn(&database.User{}, nil) return mockStore }, expStatusCode: http.StatusBadRequest, expHeader: http.Header{}, expBody: "Users with 2FA enabled are not allowed to authenticate via username and password.", }, { name: "both user and access token do not exist", header: http.Header{ "Authorization": []string{"Basic dXNlcm5hbWU="}, }, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetAccessTokenBySHA1Func.SetDefaultReturn(nil, database.ErrAccessTokenNotExist{}) mockStore.AuthenticateUserFunc.SetDefaultReturn(nil, auth.ErrBadCredentials{}) return mockStore }, expStatusCode: http.StatusUnauthorized, expHeader: http.Header{ "Lfs-Authenticate": []string{`Basic realm="Git LFS"`}, "Content-Type": []string{"application/vnd.git-lfs+json"}, }, expBody: `{"message":"Credentials needed"}` + "\n", }, { name: "authenticated by username and password", header: http.Header{ "Authorization": []string{"Basic dXNlcm5hbWU6cGFzc3dvcmQ="}, }, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.IsTwoFactorEnabledFunc.SetDefaultReturn(false) mockStore.AuthenticateUserFunc.SetDefaultReturn(&database.User{ID: 1, Name: "unknwon"}, nil) return mockStore }, expStatusCode: http.StatusOK, expHeader: http.Header{}, expBody: "ID: 1, Name: unknwon", }, { name: "authenticate by access token via username", header: http.Header{ "Authorization": []string{"Basic dXNlcm5hbWU="}, }, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetAccessTokenBySHA1Func.SetDefaultReturn(&database.AccessToken{}, nil) mockStore.AuthenticateUserFunc.SetDefaultReturn(nil, auth.ErrBadCredentials{}) mockStore.GetUserByIDFunc.SetDefaultReturn(&database.User{ID: 1, Name: "unknwon"}, nil) return mockStore }, expStatusCode: http.StatusOK, expHeader: http.Header{}, expBody: "ID: 1, Name: unknwon", }, { name: "authenticate by access token via password", header: http.Header{ "Authorization": []string{"Basic dXNlcm5hbWU6cGFzc3dvcmQ="}, }, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetAccessTokenBySHA1Func.SetDefaultHook(func(_ context.Context, sha1 string) (*database.AccessToken, error) { if sha1 == "password" { return &database.AccessToken{}, nil } return nil, database.ErrAccessTokenNotExist{} }) mockStore.AuthenticateUserFunc.SetDefaultReturn(nil, auth.ErrBadCredentials{}) mockStore.GetUserByIDFunc.SetDefaultReturn(&database.User{ID: 1, Name: "unknwon"}, nil) return mockStore }, expStatusCode: http.StatusOK, expHeader: http.Header{}, expBody: "ID: 1, Name: unknwon", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { if test.mockStore == nil { test.mockStore = NewMockStore } m := macaron.New() m.Use(macaron.Renderer()) m.Get("/", authenticate(test.mockStore()), func(w http.ResponseWriter, user *database.User) { _, _ = fmt.Fprintf(w, "ID: %d, Name: %s", user.ID, user.Name) }) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } r.Header = test.header rr := httptest.NewRecorder() m.ServeHTTP(rr, r) resp := rr.Result() assert.Equal(t, test.expStatusCode, resp.StatusCode) assert.Equal(t, test.expHeader, resp.Header) body, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } assert.Equal(t, test.expBody, string(body)) }) } } func TestAuthorize(t *testing.T) { tests := []struct { name string accessMode database.AccessMode mockStore func() *MockStore expStatusCode int expBody string }{ { name: "user does not exist", accessMode: database.AccessModeNone, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetUserByUsernameFunc.SetDefaultReturn(nil, database.ErrUserNotExist{}) return mockStore }, expStatusCode: http.StatusNotFound, }, { name: "repository does not exist", accessMode: database.AccessModeNone, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.GetRepositoryByNameFunc.SetDefaultReturn(nil, database.ErrRepoNotExist{}) mockStore.GetUserByUsernameFunc.SetDefaultHook(func(ctx context.Context, username string) (*database.User, error) { return &database.User{Name: username}, nil }) return mockStore }, expStatusCode: http.StatusNotFound, }, { name: "actor is not authorized", accessMode: database.AccessModeWrite, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.AuthorizeRepositoryAccessFunc.SetDefaultHook(func(_ context.Context, _ int64, _ int64, desired database.AccessMode, _ database.AccessModeOptions) bool { return desired <= database.AccessModeRead }) mockStore.GetRepositoryByNameFunc.SetDefaultHook(func(ctx context.Context, ownerID int64, name string) (*database.Repository, error) { return &database.Repository{Name: name}, nil }) mockStore.GetUserByUsernameFunc.SetDefaultHook(func(ctx context.Context, username string) (*database.User, error) { return &database.User{Name: username}, nil }) return mockStore }, expStatusCode: http.StatusNotFound, }, { name: "actor is authorized", accessMode: database.AccessModeRead, mockStore: func() *MockStore { mockStore := NewMockStore() mockStore.AuthorizeRepositoryAccessFunc.SetDefaultHook(func(_ context.Context, _ int64, _ int64, desired database.AccessMode, _ database.AccessModeOptions) bool { return desired <= database.AccessModeRead }) mockStore.GetRepositoryByNameFunc.SetDefaultHook(func(ctx context.Context, ownerID int64, name string) (*database.Repository, error) { return &database.Repository{Name: name}, nil }) mockStore.GetUserByUsernameFunc.SetDefaultHook(func(ctx context.Context, username string) (*database.User, error) { return &database.User{Name: username}, nil }) return mockStore }, expStatusCode: http.StatusOK, expBody: "owner.Name: owner, repo.Name: repo", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { mockStore := NewMockStore() if test.mockStore != nil { mockStore = test.mockStore() } m := macaron.New() m.Use(macaron.Renderer()) m.Use(func(c *macaron.Context) { c.Map(&database.User{}) }) m.Get( "/:username/:reponame", authorize(mockStore, test.accessMode), func(w http.ResponseWriter, owner *database.User, repo *database.Repository) { _, _ = fmt.Fprintf(w, "owner.Name: %s, repo.Name: %s", owner.Name, repo.Name) }, ) r, err := http.NewRequest("GET", "/owner/repo", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() m.ServeHTTP(rr, r) resp := rr.Result() assert.Equal(t, test.expStatusCode, resp.StatusCode) body, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } assert.Equal(t, test.expBody, string(body)) }) } } func Test_verifyHeader(t *testing.T) { tests := []struct { name string verifyHeader macaron.Handler header http.Header expStatusCode int }{ { name: "header not found", verifyHeader: verifyHeader("Accept", contentType, http.StatusNotAcceptable), expStatusCode: http.StatusNotAcceptable, }, { name: "header found", verifyHeader: verifyHeader("Accept", "application/vnd.git-lfs+json", http.StatusNotAcceptable), header: http.Header{ "Accept": []string{"application/vnd.git-lfs+json; charset=utf-8"}, }, expStatusCode: http.StatusOK, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { m := macaron.New() m.Use(macaron.Renderer()) m.Get("/", test.verifyHeader) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } r.Header = test.header rr := httptest.NewRecorder() m.ServeHTTP(rr, r) resp := rr.Result() assert.Equal(t, test.expStatusCode, resp.StatusCode) }) } } func Test_verifyOID(t *testing.T) { m := macaron.New() m.Get("/:oid", verifyOID(), func(w http.ResponseWriter, oid lfsutil.OID) { fmt.Fprintf(w, "oid: %s", oid) }) tests := []struct { name string url string expStatusCode int expBody string }{ { name: "bad oid", url: "/bad_oid", expStatusCode: http.StatusBadRequest, expBody: `{"message":"Invalid oid"}` + "\n", }, { name: "good oid", url: "/ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", expStatusCode: http.StatusOK, expBody: "oid: ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { r, err := http.NewRequest("GET", test.url, nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() m.ServeHTTP(rr, r) resp := rr.Result() assert.Equal(t, test.expStatusCode, resp.StatusCode) body, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } assert.Equal(t, test.expBody, string(body)) }) } } func Test_internalServerError(t *testing.T) { rr := httptest.NewRecorder() internalServerError(rr) resp := rr.Result() assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) body, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } assert.Equal(t, `{"message":"Internal server error"}`+"\n", string(body)) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/main_test.go
internal/route/lfs/main_test.go
// Copyright 2020 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 lfs import ( "flag" "fmt" "os" "testing" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/testutil" ) func TestMain(m *testing.M) { flag.Parse() if !testing.Verbose() { // Remove the primary logger and register a noop logger. log.Remove(log.DefaultConsoleName) err := log.New("noop", testutil.InitNoopLogger) if err != nil { fmt.Println(err) os.Exit(1) } } os.Exit(m.Run()) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/mocks_test.go
internal/route/lfs/mocks_test.go
// Code generated by go-mockgen 2.1.1; DO NOT EDIT. // // This file was generated by running `go-mockgen` at the root of this repository. // To add additional mocks to this or another package, add a new entry to the // mockgen.yaml file in the root of this repository. package lfs import ( "context" "sync" database "gogs.io/gogs/internal/database" lfsutil "gogs.io/gogs/internal/lfsutil" ) // MockStore is a mock implementation of the Store interface (from the // package gogs.io/gogs/internal/route/lfs) used for unit testing. type MockStore struct { // AuthenticateUserFunc is an instance of a mock function object // controlling the behavior of the method AuthenticateUser. AuthenticateUserFunc *StoreAuthenticateUserFunc // AuthorizeRepositoryAccessFunc is an instance of a mock function // object controlling the behavior of the method // AuthorizeRepositoryAccess. AuthorizeRepositoryAccessFunc *StoreAuthorizeRepositoryAccessFunc // CreateLFSObjectFunc is an instance of a mock function object // controlling the behavior of the method CreateLFSObject. CreateLFSObjectFunc *StoreCreateLFSObjectFunc // CreateUserFunc is an instance of a mock function object controlling // the behavior of the method CreateUser. CreateUserFunc *StoreCreateUserFunc // GetAccessTokenBySHA1Func is an instance of a mock function object // controlling the behavior of the method GetAccessTokenBySHA1. GetAccessTokenBySHA1Func *StoreGetAccessTokenBySHA1Func // GetLFSObjectByOIDFunc is an instance of a mock function object // controlling the behavior of the method GetLFSObjectByOID. GetLFSObjectByOIDFunc *StoreGetLFSObjectByOIDFunc // GetLFSObjectsByOIDsFunc is an instance of a mock function object // controlling the behavior of the method GetLFSObjectsByOIDs. GetLFSObjectsByOIDsFunc *StoreGetLFSObjectsByOIDsFunc // GetRepositoryByNameFunc is an instance of a mock function object // controlling the behavior of the method GetRepositoryByName. GetRepositoryByNameFunc *StoreGetRepositoryByNameFunc // GetUserByIDFunc is an instance of a mock function object controlling // the behavior of the method GetUserByID. GetUserByIDFunc *StoreGetUserByIDFunc // GetUserByUsernameFunc is an instance of a mock function object // controlling the behavior of the method GetUserByUsername. GetUserByUsernameFunc *StoreGetUserByUsernameFunc // IsTwoFactorEnabledFunc is an instance of a mock function object // controlling the behavior of the method IsTwoFactorEnabled. IsTwoFactorEnabledFunc *StoreIsTwoFactorEnabledFunc // TouchAccessTokenByIDFunc is an instance of a mock function object // controlling the behavior of the method TouchAccessTokenByID. TouchAccessTokenByIDFunc *StoreTouchAccessTokenByIDFunc } // NewMockStore creates a new mock of the Store interface. All methods // return zero values for all results, unless overwritten. func NewMockStore() *MockStore { return &MockStore{ AuthenticateUserFunc: &StoreAuthenticateUserFunc{ defaultHook: func(context.Context, string, string, int64) (r0 *database.User, r1 error) { return }, }, AuthorizeRepositoryAccessFunc: &StoreAuthorizeRepositoryAccessFunc{ defaultHook: func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) (r0 bool) { return }, }, CreateLFSObjectFunc: &StoreCreateLFSObjectFunc{ defaultHook: func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) (r0 error) { return }, }, CreateUserFunc: &StoreCreateUserFunc{ defaultHook: func(context.Context, string, string, database.CreateUserOptions) (r0 *database.User, r1 error) { return }, }, GetAccessTokenBySHA1Func: &StoreGetAccessTokenBySHA1Func{ defaultHook: func(context.Context, string) (r0 *database.AccessToken, r1 error) { return }, }, GetLFSObjectByOIDFunc: &StoreGetLFSObjectByOIDFunc{ defaultHook: func(context.Context, int64, lfsutil.OID) (r0 *database.LFSObject, r1 error) { return }, }, GetLFSObjectsByOIDsFunc: &StoreGetLFSObjectsByOIDsFunc{ defaultHook: func(context.Context, int64, ...lfsutil.OID) (r0 []*database.LFSObject, r1 error) { return }, }, GetRepositoryByNameFunc: &StoreGetRepositoryByNameFunc{ defaultHook: func(context.Context, int64, string) (r0 *database.Repository, r1 error) { return }, }, GetUserByIDFunc: &StoreGetUserByIDFunc{ defaultHook: func(context.Context, int64) (r0 *database.User, r1 error) { return }, }, GetUserByUsernameFunc: &StoreGetUserByUsernameFunc{ defaultHook: func(context.Context, string) (r0 *database.User, r1 error) { return }, }, IsTwoFactorEnabledFunc: &StoreIsTwoFactorEnabledFunc{ defaultHook: func(context.Context, int64) (r0 bool) { return }, }, TouchAccessTokenByIDFunc: &StoreTouchAccessTokenByIDFunc{ defaultHook: func(context.Context, int64) (r0 error) { return }, }, } } // NewStrictMockStore creates a new mock of the Store interface. All methods // panic on invocation, unless overwritten. func NewStrictMockStore() *MockStore { return &MockStore{ AuthenticateUserFunc: &StoreAuthenticateUserFunc{ defaultHook: func(context.Context, string, string, int64) (*database.User, error) { panic("unexpected invocation of MockStore.AuthenticateUser") }, }, AuthorizeRepositoryAccessFunc: &StoreAuthorizeRepositoryAccessFunc{ defaultHook: func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) bool { panic("unexpected invocation of MockStore.AuthorizeRepositoryAccess") }, }, CreateLFSObjectFunc: &StoreCreateLFSObjectFunc{ defaultHook: func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error { panic("unexpected invocation of MockStore.CreateLFSObject") }, }, CreateUserFunc: &StoreCreateUserFunc{ defaultHook: func(context.Context, string, string, database.CreateUserOptions) (*database.User, error) { panic("unexpected invocation of MockStore.CreateUser") }, }, GetAccessTokenBySHA1Func: &StoreGetAccessTokenBySHA1Func{ defaultHook: func(context.Context, string) (*database.AccessToken, error) { panic("unexpected invocation of MockStore.GetAccessTokenBySHA1") }, }, GetLFSObjectByOIDFunc: &StoreGetLFSObjectByOIDFunc{ defaultHook: func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) { panic("unexpected invocation of MockStore.GetLFSObjectByOID") }, }, GetLFSObjectsByOIDsFunc: &StoreGetLFSObjectsByOIDsFunc{ defaultHook: func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error) { panic("unexpected invocation of MockStore.GetLFSObjectsByOIDs") }, }, GetRepositoryByNameFunc: &StoreGetRepositoryByNameFunc{ defaultHook: func(context.Context, int64, string) (*database.Repository, error) { panic("unexpected invocation of MockStore.GetRepositoryByName") }, }, GetUserByIDFunc: &StoreGetUserByIDFunc{ defaultHook: func(context.Context, int64) (*database.User, error) { panic("unexpected invocation of MockStore.GetUserByID") }, }, GetUserByUsernameFunc: &StoreGetUserByUsernameFunc{ defaultHook: func(context.Context, string) (*database.User, error) { panic("unexpected invocation of MockStore.GetUserByUsername") }, }, IsTwoFactorEnabledFunc: &StoreIsTwoFactorEnabledFunc{ defaultHook: func(context.Context, int64) bool { panic("unexpected invocation of MockStore.IsTwoFactorEnabled") }, }, TouchAccessTokenByIDFunc: &StoreTouchAccessTokenByIDFunc{ defaultHook: func(context.Context, int64) error { panic("unexpected invocation of MockStore.TouchAccessTokenByID") }, }, } } // NewMockStoreFrom creates a new mock of the MockStore interface. All // methods delegate to the given implementation, unless overwritten. func NewMockStoreFrom(i Store) *MockStore { return &MockStore{ AuthenticateUserFunc: &StoreAuthenticateUserFunc{ defaultHook: i.AuthenticateUser, }, AuthorizeRepositoryAccessFunc: &StoreAuthorizeRepositoryAccessFunc{ defaultHook: i.AuthorizeRepositoryAccess, }, CreateLFSObjectFunc: &StoreCreateLFSObjectFunc{ defaultHook: i.CreateLFSObject, }, CreateUserFunc: &StoreCreateUserFunc{ defaultHook: i.CreateUser, }, GetAccessTokenBySHA1Func: &StoreGetAccessTokenBySHA1Func{ defaultHook: i.GetAccessTokenBySHA1, }, GetLFSObjectByOIDFunc: &StoreGetLFSObjectByOIDFunc{ defaultHook: i.GetLFSObjectByOID, }, GetLFSObjectsByOIDsFunc: &StoreGetLFSObjectsByOIDsFunc{ defaultHook: i.GetLFSObjectsByOIDs, }, GetRepositoryByNameFunc: &StoreGetRepositoryByNameFunc{ defaultHook: i.GetRepositoryByName, }, GetUserByIDFunc: &StoreGetUserByIDFunc{ defaultHook: i.GetUserByID, }, GetUserByUsernameFunc: &StoreGetUserByUsernameFunc{ defaultHook: i.GetUserByUsername, }, IsTwoFactorEnabledFunc: &StoreIsTwoFactorEnabledFunc{ defaultHook: i.IsTwoFactorEnabled, }, TouchAccessTokenByIDFunc: &StoreTouchAccessTokenByIDFunc{ defaultHook: i.TouchAccessTokenByID, }, } } // StoreAuthenticateUserFunc describes the behavior when the // AuthenticateUser method of the parent MockStore instance is invoked. type StoreAuthenticateUserFunc struct { defaultHook func(context.Context, string, string, int64) (*database.User, error) hooks []func(context.Context, string, string, int64) (*database.User, error) history []StoreAuthenticateUserFuncCall mutex sync.Mutex } // AuthenticateUser delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. func (m *MockStore) AuthenticateUser(v0 context.Context, v1 string, v2 string, v3 int64) (*database.User, error) { r0, r1 := m.AuthenticateUserFunc.nextHook()(v0, v1, v2, v3) m.AuthenticateUserFunc.appendCall(StoreAuthenticateUserFuncCall{v0, v1, v2, v3, r0, r1}) return r0, r1 } // SetDefaultHook sets function that is called when the AuthenticateUser // method of the parent MockStore instance is invoked and the hook queue is // empty. func (f *StoreAuthenticateUserFunc) SetDefaultHook(hook func(context.Context, string, string, int64) (*database.User, error)) { f.defaultHook = hook } // PushHook adds a function to the end of hook queue. Each invocation of the // AuthenticateUser method of the parent MockStore instance invokes the hook // at the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. func (f *StoreAuthenticateUserFunc) PushHook(hook func(context.Context, string, string, int64) (*database.User, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() } // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreAuthenticateUserFunc) SetDefaultReturn(r0 *database.User, r1 error) { f.SetDefaultHook(func(context.Context, string, string, int64) (*database.User, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreAuthenticateUserFunc) PushReturn(r0 *database.User, r1 error) { f.PushHook(func(context.Context, string, string, int64) (*database.User, error) { return r0, r1 }) } func (f *StoreAuthenticateUserFunc) nextHook() func(context.Context, string, string, int64) (*database.User, error) { f.mutex.Lock() defer f.mutex.Unlock() if len(f.hooks) == 0 { return f.defaultHook } hook := f.hooks[0] f.hooks = f.hooks[1:] return hook } func (f *StoreAuthenticateUserFunc) appendCall(r0 StoreAuthenticateUserFuncCall) { f.mutex.Lock() f.history = append(f.history, r0) f.mutex.Unlock() } // History returns a sequence of StoreAuthenticateUserFuncCall objects // describing the invocations of this function. func (f *StoreAuthenticateUserFunc) History() []StoreAuthenticateUserFuncCall { f.mutex.Lock() history := make([]StoreAuthenticateUserFuncCall, len(f.history)) copy(history, f.history) f.mutex.Unlock() return history } // StoreAuthenticateUserFuncCall is an object that describes an invocation // of method AuthenticateUser on an instance of MockStore. type StoreAuthenticateUserFuncCall struct { // Arg0 is the value of the 1st argument passed to this method // invocation. Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. Arg1 string // Arg2 is the value of the 3rd argument passed to this method // invocation. Arg2 string // Arg3 is the value of the 4th argument passed to this method // invocation. Arg3 int64 // Result0 is the value of the 1st result returned from this method // invocation. Result0 *database.User // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error } // Args returns an interface slice containing the arguments of this // invocation. func (c StoreAuthenticateUserFuncCall) Args() []interface{} { return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3} } // Results returns an interface slice containing the results of this // invocation. func (c StoreAuthenticateUserFuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1} } // StoreAuthorizeRepositoryAccessFunc describes the behavior when the // AuthorizeRepositoryAccess method of the parent MockStore instance is // invoked. type StoreAuthorizeRepositoryAccessFunc struct { defaultHook func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) bool hooks []func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) bool history []StoreAuthorizeRepositoryAccessFuncCall mutex sync.Mutex } // AuthorizeRepositoryAccess delegates to the next hook function in the // queue and stores the parameter and result values of this invocation. func (m *MockStore) AuthorizeRepositoryAccess(v0 context.Context, v1 int64, v2 int64, v3 database.AccessMode, v4 database.AccessModeOptions) bool { r0 := m.AuthorizeRepositoryAccessFunc.nextHook()(v0, v1, v2, v3, v4) m.AuthorizeRepositoryAccessFunc.appendCall(StoreAuthorizeRepositoryAccessFuncCall{v0, v1, v2, v3, v4, r0}) return r0 } // SetDefaultHook sets function that is called when the // AuthorizeRepositoryAccess method of the parent MockStore instance is // invoked and the hook queue is empty. func (f *StoreAuthorizeRepositoryAccessFunc) SetDefaultHook(hook func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) bool) { f.defaultHook = hook } // PushHook adds a function to the end of hook queue. Each invocation of the // AuthorizeRepositoryAccess method of the parent MockStore instance invokes // the hook at the front of the queue and discards it. After the queue is // empty, the default hook function is invoked for any future action. func (f *StoreAuthorizeRepositoryAccessFunc) PushHook(hook func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) bool) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() } // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreAuthorizeRepositoryAccessFunc) SetDefaultReturn(r0 bool) { f.SetDefaultHook(func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) bool { return r0 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreAuthorizeRepositoryAccessFunc) PushReturn(r0 bool) { f.PushHook(func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) bool { return r0 }) } func (f *StoreAuthorizeRepositoryAccessFunc) nextHook() func(context.Context, int64, int64, database.AccessMode, database.AccessModeOptions) bool { f.mutex.Lock() defer f.mutex.Unlock() if len(f.hooks) == 0 { return f.defaultHook } hook := f.hooks[0] f.hooks = f.hooks[1:] return hook } func (f *StoreAuthorizeRepositoryAccessFunc) appendCall(r0 StoreAuthorizeRepositoryAccessFuncCall) { f.mutex.Lock() f.history = append(f.history, r0) f.mutex.Unlock() } // History returns a sequence of StoreAuthorizeRepositoryAccessFuncCall // objects describing the invocations of this function. func (f *StoreAuthorizeRepositoryAccessFunc) History() []StoreAuthorizeRepositoryAccessFuncCall { f.mutex.Lock() history := make([]StoreAuthorizeRepositoryAccessFuncCall, len(f.history)) copy(history, f.history) f.mutex.Unlock() return history } // StoreAuthorizeRepositoryAccessFuncCall is an object that describes an // invocation of method AuthorizeRepositoryAccess on an instance of // MockStore. type StoreAuthorizeRepositoryAccessFuncCall struct { // Arg0 is the value of the 1st argument passed to this method // invocation. Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. Arg1 int64 // Arg2 is the value of the 3rd argument passed to this method // invocation. Arg2 int64 // Arg3 is the value of the 4th argument passed to this method // invocation. Arg3 database.AccessMode // Arg4 is the value of the 5th argument passed to this method // invocation. Arg4 database.AccessModeOptions // Result0 is the value of the 1st result returned from this method // invocation. Result0 bool } // Args returns an interface slice containing the arguments of this // invocation. func (c StoreAuthorizeRepositoryAccessFuncCall) Args() []interface{} { return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4} } // Results returns an interface slice containing the results of this // invocation. func (c StoreAuthorizeRepositoryAccessFuncCall) Results() []interface{} { return []interface{}{c.Result0} } // StoreCreateLFSObjectFunc describes the behavior when the CreateLFSObject // method of the parent MockStore instance is invoked. type StoreCreateLFSObjectFunc struct { defaultHook func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error hooks []func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error history []StoreCreateLFSObjectFuncCall mutex sync.Mutex } // CreateLFSObject delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. func (m *MockStore) CreateLFSObject(v0 context.Context, v1 int64, v2 lfsutil.OID, v3 int64, v4 lfsutil.Storage) error { r0 := m.CreateLFSObjectFunc.nextHook()(v0, v1, v2, v3, v4) m.CreateLFSObjectFunc.appendCall(StoreCreateLFSObjectFuncCall{v0, v1, v2, v3, v4, r0}) return r0 } // SetDefaultHook sets function that is called when the CreateLFSObject // method of the parent MockStore instance is invoked and the hook queue is // empty. func (f *StoreCreateLFSObjectFunc) SetDefaultHook(hook func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error) { f.defaultHook = hook } // PushHook adds a function to the end of hook queue. Each invocation of the // CreateLFSObject method of the parent MockStore instance invokes the hook // at the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. func (f *StoreCreateLFSObjectFunc) PushHook(hook func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() } // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreCreateLFSObjectFunc) SetDefaultReturn(r0 error) { f.SetDefaultHook(func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error { return r0 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreCreateLFSObjectFunc) PushReturn(r0 error) { f.PushHook(func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error { return r0 }) } func (f *StoreCreateLFSObjectFunc) nextHook() func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error { f.mutex.Lock() defer f.mutex.Unlock() if len(f.hooks) == 0 { return f.defaultHook } hook := f.hooks[0] f.hooks = f.hooks[1:] return hook } func (f *StoreCreateLFSObjectFunc) appendCall(r0 StoreCreateLFSObjectFuncCall) { f.mutex.Lock() f.history = append(f.history, r0) f.mutex.Unlock() } // History returns a sequence of StoreCreateLFSObjectFuncCall objects // describing the invocations of this function. func (f *StoreCreateLFSObjectFunc) History() []StoreCreateLFSObjectFuncCall { f.mutex.Lock() history := make([]StoreCreateLFSObjectFuncCall, len(f.history)) copy(history, f.history) f.mutex.Unlock() return history } // StoreCreateLFSObjectFuncCall is an object that describes an invocation of // method CreateLFSObject on an instance of MockStore. type StoreCreateLFSObjectFuncCall struct { // Arg0 is the value of the 1st argument passed to this method // invocation. Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. Arg1 int64 // Arg2 is the value of the 3rd argument passed to this method // invocation. Arg2 lfsutil.OID // Arg3 is the value of the 4th argument passed to this method // invocation. Arg3 int64 // Arg4 is the value of the 5th argument passed to this method // invocation. Arg4 lfsutil.Storage // Result0 is the value of the 1st result returned from this method // invocation. Result0 error } // Args returns an interface slice containing the arguments of this // invocation. func (c StoreCreateLFSObjectFuncCall) Args() []interface{} { return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4} } // Results returns an interface slice containing the results of this // invocation. func (c StoreCreateLFSObjectFuncCall) Results() []interface{} { return []interface{}{c.Result0} } // StoreCreateUserFunc describes the behavior when the CreateUser method of // the parent MockStore instance is invoked. type StoreCreateUserFunc struct { defaultHook func(context.Context, string, string, database.CreateUserOptions) (*database.User, error) hooks []func(context.Context, string, string, database.CreateUserOptions) (*database.User, error) history []StoreCreateUserFuncCall mutex sync.Mutex } // CreateUser delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. func (m *MockStore) CreateUser(v0 context.Context, v1 string, v2 string, v3 database.CreateUserOptions) (*database.User, error) { r0, r1 := m.CreateUserFunc.nextHook()(v0, v1, v2, v3) m.CreateUserFunc.appendCall(StoreCreateUserFuncCall{v0, v1, v2, v3, r0, r1}) return r0, r1 } // SetDefaultHook sets function that is called when the CreateUser method of // the parent MockStore instance is invoked and the hook queue is empty. func (f *StoreCreateUserFunc) SetDefaultHook(hook func(context.Context, string, string, database.CreateUserOptions) (*database.User, error)) { f.defaultHook = hook } // PushHook adds a function to the end of hook queue. Each invocation of the // CreateUser method of the parent MockStore instance invokes the hook at // the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. func (f *StoreCreateUserFunc) PushHook(hook func(context.Context, string, string, database.CreateUserOptions) (*database.User, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() } // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreCreateUserFunc) SetDefaultReturn(r0 *database.User, r1 error) { f.SetDefaultHook(func(context.Context, string, string, database.CreateUserOptions) (*database.User, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreCreateUserFunc) PushReturn(r0 *database.User, r1 error) { f.PushHook(func(context.Context, string, string, database.CreateUserOptions) (*database.User, error) { return r0, r1 }) } func (f *StoreCreateUserFunc) nextHook() func(context.Context, string, string, database.CreateUserOptions) (*database.User, error) { f.mutex.Lock() defer f.mutex.Unlock() if len(f.hooks) == 0 { return f.defaultHook } hook := f.hooks[0] f.hooks = f.hooks[1:] return hook } func (f *StoreCreateUserFunc) appendCall(r0 StoreCreateUserFuncCall) { f.mutex.Lock() f.history = append(f.history, r0) f.mutex.Unlock() } // History returns a sequence of StoreCreateUserFuncCall objects describing // the invocations of this function. func (f *StoreCreateUserFunc) History() []StoreCreateUserFuncCall { f.mutex.Lock() history := make([]StoreCreateUserFuncCall, len(f.history)) copy(history, f.history) f.mutex.Unlock() return history } // StoreCreateUserFuncCall is an object that describes an invocation of // method CreateUser on an instance of MockStore. type StoreCreateUserFuncCall struct { // Arg0 is the value of the 1st argument passed to this method // invocation. Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. Arg1 string // Arg2 is the value of the 3rd argument passed to this method // invocation. Arg2 string // Arg3 is the value of the 4th argument passed to this method // invocation. Arg3 database.CreateUserOptions // Result0 is the value of the 1st result returned from this method // invocation. Result0 *database.User // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error } // Args returns an interface slice containing the arguments of this // invocation. func (c StoreCreateUserFuncCall) Args() []interface{} { return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3} } // Results returns an interface slice containing the results of this // invocation. func (c StoreCreateUserFuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1} } // StoreGetAccessTokenBySHA1Func describes the behavior when the // GetAccessTokenBySHA1 method of the parent MockStore instance is invoked. type StoreGetAccessTokenBySHA1Func struct { defaultHook func(context.Context, string) (*database.AccessToken, error) hooks []func(context.Context, string) (*database.AccessToken, error) history []StoreGetAccessTokenBySHA1FuncCall mutex sync.Mutex } // GetAccessTokenBySHA1 delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. func (m *MockStore) GetAccessTokenBySHA1(v0 context.Context, v1 string) (*database.AccessToken, error) { r0, r1 := m.GetAccessTokenBySHA1Func.nextHook()(v0, v1) m.GetAccessTokenBySHA1Func.appendCall(StoreGetAccessTokenBySHA1FuncCall{v0, v1, r0, r1}) return r0, r1 } // SetDefaultHook sets function that is called when the GetAccessTokenBySHA1 // method of the parent MockStore instance is invoked and the hook queue is // empty. func (f *StoreGetAccessTokenBySHA1Func) SetDefaultHook(hook func(context.Context, string) (*database.AccessToken, error)) { f.defaultHook = hook } // PushHook adds a function to the end of hook queue. Each invocation of the // GetAccessTokenBySHA1 method of the parent MockStore instance invokes the // hook at the front of the queue and discards it. After the queue is empty, // the default hook function is invoked for any future action. func (f *StoreGetAccessTokenBySHA1Func) PushHook(hook func(context.Context, string) (*database.AccessToken, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() } // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreGetAccessTokenBySHA1Func) SetDefaultReturn(r0 *database.AccessToken, r1 error) { f.SetDefaultHook(func(context.Context, string) (*database.AccessToken, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreGetAccessTokenBySHA1Func) PushReturn(r0 *database.AccessToken, r1 error) { f.PushHook(func(context.Context, string) (*database.AccessToken, error) { return r0, r1 }) } func (f *StoreGetAccessTokenBySHA1Func) nextHook() func(context.Context, string) (*database.AccessToken, error) { f.mutex.Lock() defer f.mutex.Unlock() if len(f.hooks) == 0 { return f.defaultHook } hook := f.hooks[0] f.hooks = f.hooks[1:] return hook } func (f *StoreGetAccessTokenBySHA1Func) appendCall(r0 StoreGetAccessTokenBySHA1FuncCall) { f.mutex.Lock() f.history = append(f.history, r0) f.mutex.Unlock() } // History returns a sequence of StoreGetAccessTokenBySHA1FuncCall objects // describing the invocations of this function. func (f *StoreGetAccessTokenBySHA1Func) History() []StoreGetAccessTokenBySHA1FuncCall { f.mutex.Lock() history := make([]StoreGetAccessTokenBySHA1FuncCall, len(f.history)) copy(history, f.history) f.mutex.Unlock() return history } // StoreGetAccessTokenBySHA1FuncCall is an object that describes an // invocation of method GetAccessTokenBySHA1 on an instance of MockStore. type StoreGetAccessTokenBySHA1FuncCall struct { // Arg0 is the value of the 1st argument passed to this method // invocation. Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. Arg1 string // Result0 is the value of the 1st result returned from this method // invocation. Result0 *database.AccessToken // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error } // Args returns an interface slice containing the arguments of this // invocation. func (c StoreGetAccessTokenBySHA1FuncCall) Args() []interface{} { return []interface{}{c.Arg0, c.Arg1} } // Results returns an interface slice containing the results of this // invocation. func (c StoreGetAccessTokenBySHA1FuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1} } // StoreGetLFSObjectByOIDFunc describes the behavior when the // GetLFSObjectByOID method of the parent MockStore instance is invoked. type StoreGetLFSObjectByOIDFunc struct { defaultHook func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) hooks []func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) history []StoreGetLFSObjectByOIDFuncCall mutex sync.Mutex } // GetLFSObjectByOID delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. func (m *MockStore) GetLFSObjectByOID(v0 context.Context, v1 int64, v2 lfsutil.OID) (*database.LFSObject, error) { r0, r1 := m.GetLFSObjectByOIDFunc.nextHook()(v0, v1, v2) m.GetLFSObjectByOIDFunc.appendCall(StoreGetLFSObjectByOIDFuncCall{v0, v1, v2, r0, r1}) return r0, r1 } // SetDefaultHook sets function that is called when the GetLFSObjectByOID // method of the parent MockStore instance is invoked and the hook queue is // empty. func (f *StoreGetLFSObjectByOIDFunc) SetDefaultHook(hook func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error)) { f.defaultHook = hook } // PushHook adds a function to the end of hook queue. Each invocation of the // GetLFSObjectByOID method of the parent MockStore instance invokes the // hook at the front of the queue and discards it. After the queue is empty, // the default hook function is invoked for any future action. func (f *StoreGetLFSObjectByOIDFunc) PushHook(hook func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() } // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreGetLFSObjectByOIDFunc) SetDefaultReturn(r0 *database.LFSObject, r1 error) { f.SetDefaultHook(func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreGetLFSObjectByOIDFunc) PushReturn(r0 *database.LFSObject, r1 error) { f.PushHook(func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) { return r0, r1 }) } func (f *StoreGetLFSObjectByOIDFunc) nextHook() func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) { f.mutex.Lock() defer f.mutex.Unlock() if len(f.hooks) == 0 { return f.defaultHook } hook := f.hooks[0] f.hooks = f.hooks[1:] return hook } func (f *StoreGetLFSObjectByOIDFunc) appendCall(r0 StoreGetLFSObjectByOIDFuncCall) { f.mutex.Lock() f.history = append(f.history, r0) f.mutex.Unlock() } // History returns a sequence of StoreGetLFSObjectByOIDFuncCall objects // describing the invocations of this function. func (f *StoreGetLFSObjectByOIDFunc) History() []StoreGetLFSObjectByOIDFuncCall { f.mutex.Lock() history := make([]StoreGetLFSObjectByOIDFuncCall, len(f.history)) copy(history, f.history) f.mutex.Unlock() return history }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
true
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/store.go
internal/route/lfs/store.go
package lfs import ( "context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/lfsutil" ) // Store is the data layer carrier for LFS endpoints. This interface is meant to // abstract away and limit the exposure of the underlying data layer to the // handler through a thin-wrapper. type Store interface { // GetAccessTokenBySHA1 returns the access token with given SHA1. It returns // database.ErrAccessTokenNotExist when not found. GetAccessTokenBySHA1(ctx context.Context, sha1 string) (*database.AccessToken, error) // TouchAccessTokenByID updates the updated time of the given access token to // the current time. TouchAccessTokenByID(ctx context.Context, id int64) error // CreateLFSObject creates an LFS object record in database. CreateLFSObject(ctx context.Context, repoID int64, oid lfsutil.OID, size int64, storage lfsutil.Storage) error // GetLFSObjectByOID returns the LFS object with given OID. It returns // database.ErrLFSObjectNotExist when not found. GetLFSObjectByOID(ctx context.Context, repoID int64, oid lfsutil.OID) (*database.LFSObject, error) // GetLFSObjectsByOIDs returns LFS objects found within "oids". The returned // list could have fewer elements if some oids were not found. GetLFSObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsutil.OID) ([]*database.LFSObject, error) // AuthorizeRepositoryAccess returns true if the user has as good as desired // access mode to the repository. AuthorizeRepositoryAccess(ctx context.Context, userID, repoID int64, desired database.AccessMode, opts database.AccessModeOptions) bool // GetRepositoryByName returns the repository with given owner and name. It // returns database.ErrRepoNotExist when not found. GetRepositoryByName(ctx context.Context, ownerID int64, name string) (*database.Repository, error) // IsTwoFactorEnabled returns true if the user has enabled 2FA. IsTwoFactorEnabled(ctx context.Context, userID int64) bool // GetUserByID returns the user with given ID. It returns // database.ErrUserNotExist when not found. GetUserByID(ctx context.Context, id int64) (*database.User, error) // GetUserByUsername returns the user with given username. It returns // database.ErrUserNotExist when not found. GetUserByUsername(ctx context.Context, username string) (*database.User, error) // CreateUser creates a new user and persists to database. It returns // database.ErrNameNotAllowed if the given name or pattern of the name is not // allowed as a username, or database.ErrUserAlreadyExist when a user with same // name already exists, or database.ErrEmailAlreadyUsed if the email has been // verified by another user. CreateUser(ctx context.Context, username, email string, opts database.CreateUserOptions) (*database.User, error) // AuthenticateUser validates username and password via given login source ID. // It returns database.ErrUserNotExist when the user was not found. // // When the "loginSourceID" is negative, it aborts the process and returns // database.ErrUserNotExist if the user was not found in the database. // // When the "loginSourceID" is non-negative, it returns // database.ErrLoginSourceMismatch if the user has different login source ID // than the "loginSourceID". // // When the "loginSourceID" is positive, it tries to authenticate via given // login source and creates a new user when not yet exists in the database. AuthenticateUser(ctx context.Context, login, password string, loginSourceID int64) (*database.User, error) } type store struct{} // NewStore returns a new Store using the global database handle. func NewStore() Store { return &store{} } func (*store) GetAccessTokenBySHA1(ctx context.Context, sha1 string) (*database.AccessToken, error) { return database.Handle.AccessTokens().GetBySHA1(ctx, sha1) } func (*store) TouchAccessTokenByID(ctx context.Context, id int64) error { return database.Handle.AccessTokens().Touch(ctx, id) } func (*store) CreateLFSObject(ctx context.Context, repoID int64, oid lfsutil.OID, size int64, storage lfsutil.Storage) error { return database.Handle.LFS().CreateObject(ctx, repoID, oid, size, storage) } func (*store) GetLFSObjectByOID(ctx context.Context, repoID int64, oid lfsutil.OID) (*database.LFSObject, error) { return database.Handle.LFS().GetObjectByOID(ctx, repoID, oid) } func (*store) GetLFSObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsutil.OID) ([]*database.LFSObject, error) { return database.Handle.LFS().GetObjectsByOIDs(ctx, repoID, oids...) } func (*store) AuthorizeRepositoryAccess(ctx context.Context, userID, repoID int64, desired database.AccessMode, opts database.AccessModeOptions) bool { return database.Handle.Permissions().Authorize(ctx, userID, repoID, desired, opts) } func (*store) GetRepositoryByName(ctx context.Context, ownerID int64, name string) (*database.Repository, error) { return database.Handle.Repositories().GetByName(ctx, ownerID, name) } func (*store) IsTwoFactorEnabled(ctx context.Context, userID int64) bool { return database.Handle.TwoFactors().IsEnabled(ctx, userID) } func (*store) GetUserByID(ctx context.Context, id int64) (*database.User, error) { return database.Handle.Users().GetByID(ctx, id) } func (*store) GetUserByUsername(ctx context.Context, username string) (*database.User, error) { return database.Handle.Users().GetByUsername(ctx, username) } func (*store) CreateUser(ctx context.Context, username, email string, opts database.CreateUserOptions) (*database.User, error) { return database.Handle.Users().Create(ctx, username, email, opts) } func (*store) AuthenticateUser(ctx context.Context, login, password string, loginSourceID int64) (*database.User, error) { return database.Handle.Users().Authenticate(ctx, login, password, loginSourceID) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/route.go
internal/route/lfs/route.go
// Copyright 2020 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 lfs import ( "net/http" "strings" "gopkg.in/macaron.v1" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/authutil" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/lfsutil" ) // RegisterRoutes registers LFS routes using given router, and inherits all // groups and middleware. func RegisterRoutes(r *macaron.Router) { verifyAccept := verifyHeader("Accept", contentType, http.StatusNotAcceptable) verifyContentTypeJSON := verifyHeader("Content-Type", contentType, http.StatusBadRequest) verifyContentTypeStream := verifyHeader("Content-Type", "application/octet-stream", http.StatusBadRequest) store := NewStore() r.Group("", func() { r.Post("/objects/batch", authorize(store, database.AccessModeRead), verifyAccept, verifyContentTypeJSON, serveBatch(store)) r.Group("/objects/basic", func() { basic := &basicHandler{ store: store, defaultStorage: lfsutil.Storage(conf.LFS.Storage), storagers: map[lfsutil.Storage]lfsutil.Storager{ lfsutil.StorageLocal: &lfsutil.LocalStorage{Root: conf.LFS.ObjectsPath}, }, } r.Combo("/:oid", verifyOID()). Get(authorize(store, database.AccessModeRead), basic.serveDownload). Put(authorize(store, database.AccessModeWrite), verifyContentTypeStream, basic.serveUpload) r.Post("/verify", authorize(store, database.AccessModeWrite), verifyAccept, verifyContentTypeJSON, basic.serveVerify) }) }, authenticate(store)) } // authenticate tries to authenticate user via HTTP Basic Auth. It first tries to authenticate // as plain username and password, then use username as access token if previous step failed. func authenticate(store Store) macaron.Handler { askCredentials := func(w http.ResponseWriter) { w.Header().Set("Lfs-Authenticate", `Basic realm="Git LFS"`) responseJSON(w, http.StatusUnauthorized, responseError{ Message: "Credentials needed", }) } return func(c *macaron.Context) { username, password := authutil.DecodeBasic(c.Req.Header) if username == "" { askCredentials(c.Resp) return } user, err := store.AuthenticateUser(c.Req.Context(), username, password, -1) if err != nil && !auth.IsErrBadCredentials(err) { internalServerError(c.Resp) log.Error("Failed to authenticate user [name: %s]: %v", username, err) return } if err == nil && store.IsTwoFactorEnabled(c.Req.Context(), user.ID) { c.Error(http.StatusBadRequest, "Users with 2FA enabled are not allowed to authenticate via username and password.") return } // If username and password combination failed, try again using either username // or password as the token. if auth.IsErrBadCredentials(err) { user, err = context.AuthenticateByToken(store, c.Req.Context(), username) if err != nil && !database.IsErrAccessTokenNotExist(err) { internalServerError(c.Resp) log.Error("Failed to authenticate by access token via username: %v", err) return } else if database.IsErrAccessTokenNotExist(err) { // Try again using the password field as the token. user, err = context.AuthenticateByToken(store, c.Req.Context(), password) if err != nil { if database.IsErrAccessTokenNotExist(err) { askCredentials(c.Resp) } else { c.Status(http.StatusInternalServerError) log.Error("Failed to authenticate by access token via password: %v", err) } return } } } log.Trace("[LFS] Authenticated user: %s", user.Name) c.Map(user) } } // authorize tries to authorize the user to the context repository with given access mode. func authorize(store Store, mode database.AccessMode) macaron.Handler { return func(c *macaron.Context, actor *database.User) { username := c.Params(":username") reponame := strings.TrimSuffix(c.Params(":reponame"), ".git") owner, err := store.GetUserByUsername(c.Req.Context(), username) if err != nil { if database.IsErrUserNotExist(err) { c.Status(http.StatusNotFound) } else { internalServerError(c.Resp) log.Error("Failed to get user [name: %s]: %v", username, err) } return } repo, err := store.GetRepositoryByName(c.Req.Context(), owner.ID, reponame) if err != nil { if database.IsErrRepoNotExist(err) { c.Status(http.StatusNotFound) } else { internalServerError(c.Resp) log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, reponame, err) } return } if !store.AuthorizeRepositoryAccess(c.Req.Context(), actor.ID, repo.ID, mode, database.AccessModeOptions{ OwnerID: repo.OwnerID, Private: repo.IsPrivate, }, ) { c.Status(http.StatusNotFound) return } log.Trace("[LFS] Authorized user %q to %q", actor.Name, username+"/"+reponame) c.Map(owner) // NOTE: Override actor c.Map(repo) } } // verifyHeader checks if the HTTP header contains given value. // When not, response given "failCode" as status code. func verifyHeader(key, value string, failCode int) macaron.Handler { return func(c *macaron.Context) { vals := c.Req.Header.Values(key) for _, val := range vals { if strings.Contains(val, value) { return } } log.Trace("[LFS] HTTP header %q does not contain value %q", key, value) c.Status(failCode) } } // verifyOID checks if the ":oid" URL parameter is valid. func verifyOID() macaron.Handler { return func(c *macaron.Context) { oid := lfsutil.OID(c.Params(":oid")) if !lfsutil.ValidOID(oid) { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: "Invalid oid", }) return } c.Map(oid) } } func internalServerError(w http.ResponseWriter) { responseJSON(w, http.StatusInternalServerError, responseError{ Message: "Internal server error", }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/lfs/batch.go
internal/route/lfs/batch.go
// Copyright 2020 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 lfs import ( "fmt" "net/http" jsoniter "github.com/json-iterator/go" "gopkg.in/macaron.v1" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/lfsutil" "gogs.io/gogs/internal/strutil" ) // POST /{owner}/{repo}.git/info/lfs/object/batch func serveBatch(store Store) macaron.Handler { return func(c *macaron.Context, owner *database.User, repo *database.Repository) { var request batchRequest defer func() { _ = c.Req.Request.Body.Close() }() err := jsoniter.NewDecoder(c.Req.Request.Body).Decode(&request) if err != nil { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: strutil.ToUpperFirst(err.Error()), }) return } // NOTE: We only support basic transfer as of now. transfer := transferBasic // Example: https://try.gogs.io/gogs/gogs.git/info/lfs/object/basic baseHref := fmt.Sprintf("%s%s/%s.git/info/lfs/objects/basic", conf.Server.ExternalURL, owner.Name, repo.Name) objects := make([]batchObject, 0, len(request.Objects)) switch request.Operation { case basicOperationUpload: for _, obj := range request.Objects { var actions batchActions if lfsutil.ValidOID(obj.Oid) { actions = batchActions{ Upload: &batchAction{ Href: fmt.Sprintf("%s/%s", baseHref, obj.Oid), Header: map[string]string{ // NOTE: git-lfs v2.5.0 sets the Content-Type based on the uploaded file. // This ensures that the client always uses the designated value for the header. "Content-Type": "application/octet-stream", }, }, Verify: &batchAction{ Href: fmt.Sprintf("%s/verify", baseHref), }, } } else { actions = batchActions{ Error: &batchError{ Code: http.StatusUnprocessableEntity, Message: "Object has invalid oid", }, } } objects = append(objects, batchObject{ Oid: obj.Oid, Size: obj.Size, Actions: actions, }) } case basicOperationDownload: oids := make([]lfsutil.OID, 0, len(request.Objects)) for _, obj := range request.Objects { oids = append(oids, obj.Oid) } stored, err := store.GetLFSObjectsByOIDs(c.Req.Context(), repo.ID, oids...) if err != nil { internalServerError(c.Resp) log.Error("Failed to get objects [repo_id: %d, oids: %v]: %v", repo.ID, oids, err) return } storedSet := make(map[lfsutil.OID]*database.LFSObject, len(stored)) for _, obj := range stored { storedSet[obj.OID] = obj } for _, obj := range request.Objects { var actions batchActions if stored := storedSet[obj.Oid]; stored != nil { if stored.Size != obj.Size { actions.Error = &batchError{ Code: http.StatusUnprocessableEntity, Message: "Object size mismatch", } } else { actions.Download = &batchAction{ Href: fmt.Sprintf("%s/%s", baseHref, obj.Oid), } } } else { actions.Error = &batchError{ Code: http.StatusNotFound, Message: "Object does not exist", } } objects = append(objects, batchObject{ Oid: obj.Oid, Size: obj.Size, Actions: actions, }) } default: responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: "Operation not recognized", }) return } responseJSON(c.Resp, http.StatusOK, batchResponse{ Transfer: transfer, Objects: objects, }) } } // batchRequest defines the request payload for the batch endpoint. type batchRequest struct { Operation string `json:"operation"` Objects []struct { Oid lfsutil.OID `json:"oid"` Size int64 `json:"size"` } `json:"objects"` } type batchError struct { Code int `json:"code"` Message string `json:"message"` } type batchAction struct { Href string `json:"href"` Header map[string]string `json:"header,omitempty"` } type batchActions struct { Download *batchAction `json:"download,omitempty"` Upload *batchAction `json:"upload,omitempty"` Verify *batchAction `json:"verify,omitempty"` Error *batchError `json:"error,omitempty"` } type batchObject struct { Oid lfsutil.OID `json:"oid"` Size int64 `json:"size"` Actions batchActions `json:"actions"` } // batchResponse defines the response payload for the batch endpoint. type batchResponse struct { Transfer string `json:"transfer"` Objects []batchObject `json:"objects"` } type responseError struct { Message string `json:"message"` } const contentType = "application/vnd.git-lfs+json" func responseJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", contentType) w.WriteHeader(status) err := jsoniter.NewEncoder(w).Encode(v) if err != nil { log.Error("Failed to encode JSON: %v", err) return } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cryptoutil/aes.go
internal/cryptoutil/aes.go
// Copyright 2020 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 cryptoutil import ( "crypto/aes" "crypto/cipher" "crypto/rand" "errors" ) // AESGCMEncrypt encrypts plaintext with the given key using AES in GCM mode. func AESGCMEncrypt(key, plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonce := make([]byte, gcm.NonceSize()) if _, err := rand.Read(nonce); err != nil { return nil, err } ciphertext := gcm.Seal(nil, nonce, plaintext, nil) return append(nonce, ciphertext...), nil } // AESGCMDecrypt decrypts ciphertext with the given key using AES in GCM mode. func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } size := gcm.NonceSize() if len(ciphertext)-size <= 0 { return nil, errors.New("ciphertext is empty") } nonce := ciphertext[:size] ciphertext = ciphertext[size:] return gcm.Open(nil, nonce, ciphertext, nil) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cryptoutil/aes_test.go
internal/cryptoutil/aes_test.go
// Copyright 2020 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 cryptoutil import ( "crypto/rand" "testing" "github.com/stretchr/testify/assert" ) func TestAESGCM(t *testing.T) { key := make([]byte, 16) // AES-128 _, err := rand.Read(key) if err != nil { t.Fatal(err) } plaintext := []byte("this will be encrypted") encrypted, err := AESGCMEncrypt(key, plaintext) if err != nil { t.Fatal(err) } decrypted, err := AESGCMDecrypt(key, encrypted) if err != nil { t.Fatal(err) } assert.Equal(t, plaintext, decrypted) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cryptoutil/sha.go
internal/cryptoutil/sha.go
// Copyright 2020 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 cryptoutil import ( "crypto/sha1" "crypto/sha256" "encoding/hex" ) // SHA1 encodes string to hexadecimal of SHA1 checksum. func SHA1(str string) string { h := sha1.New() _, _ = h.Write([]byte(str)) return hex.EncodeToString(h.Sum(nil)) } // SHA256 encodes string to hexadecimal of SHA256 checksum. func SHA256(str string) string { h := sha256.New() _, _ = h.Write([]byte(str)) return hex.EncodeToString(h.Sum(nil)) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cryptoutil/md5_test.go
internal/cryptoutil/md5_test.go
// Copyright 2020 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 cryptoutil import ( "testing" "github.com/stretchr/testify/assert" ) func TestMD5(t *testing.T) { tests := []struct { input string output string }{ {input: "", output: "d41d8cd98f00b204e9800998ecf8427e"}, {input: "The quick brown fox jumps over the lazy dog", output: "9e107d9d372bb6826bd81d3542a419d6"}, {input: "The quick brown fox jumps over the lazy dog.", output: "e4d909c290d0fb1ca068ffaddf22cbd0"}, } for _, test := range tests { t.Run(test.input, func(t *testing.T) { assert.Equal(t, test.output, MD5(test.input)) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cryptoutil/sha_test.go
internal/cryptoutil/sha_test.go
// Copyright 2020 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 cryptoutil import ( "testing" "github.com/stretchr/testify/assert" ) func TestSHA1(t *testing.T) { tests := []struct { input string output string }{ {input: "", output: "da39a3ee5e6b4b0d3255bfef95601890afd80709"}, {input: "The quick brown fox jumps over the lazy dog", output: "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"}, {input: "The quick brown fox jumps over the lazy dog.", output: "408d94384216f890ff7a0c3528e8bed1e0b01621"}, } for _, test := range tests { t.Run(test.input, func(t *testing.T) { assert.Equal(t, test.output, SHA1(test.input)) }) } } func TestSHA256(t *testing.T) { tests := []struct { input string output string }{ {input: "", output: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, {input: "The quick brown fox jumps over the lazy dog", output: "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"}, {input: "The quick brown fox jumps over the lazy dog.", output: "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c"}, } for _, test := range tests { t.Run(test.input, func(t *testing.T) { assert.Equal(t, test.output, SHA256(test.input)) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cryptoutil/md5.go
internal/cryptoutil/md5.go
// Copyright 2020 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 cryptoutil import ( "crypto/md5" "encoding/hex" ) // MD5 encodes string to hexadecimal of MD5 checksum. func MD5(str string) string { return hex.EncodeToString(MD5Bytes(str)) } // MD5Bytes encodes string to MD5 checksum. func MD5Bytes(str string) []byte { m := md5.New() _, _ = m.Write([]byte(str)) return m.Sum(nil) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/mocks.go
internal/gitutil/mocks.go
// Copyright 2020 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 gitutil import ( "testing" "github.com/gogs/git-module" ) var _ ModuleStore = (*MockModuleStore)(nil) type MockModuleStore struct { remoteAdd func(repoPath, name, url string, opts ...git.RemoteAddOptions) error diffNameOnly func(repoPath, base, head string, opts ...git.DiffNameOnlyOptions) ([]string, error) log func(repoPath, rev string, opts ...git.LogOptions) ([]*git.Commit, error) mergeBase func(repoPath, base, head string, opts ...git.MergeBaseOptions) (string, error) remoteRemove func(repoPath, name string, opts ...git.RemoteRemoveOptions) error repoTags func(repoPath string, opts ...git.TagsOptions) ([]string, error) pullRequestMeta func(headPath, basePath, headBranch, baseBranch string) (*PullRequestMeta, error) listTagsAfter func(repoPath, after string, limit int) (*TagsPage, error) } func (m *MockModuleStore) RemoteAdd(repoPath, name, url string, opts ...git.RemoteAddOptions) error { return m.remoteAdd(repoPath, name, url, opts...) } func (m *MockModuleStore) DiffNameOnly(repoPath, base, head string, opts ...git.DiffNameOnlyOptions) ([]string, error) { return m.diffNameOnly(repoPath, base, head, opts...) } func (m *MockModuleStore) Log(repoPath, rev string, opts ...git.LogOptions) ([]*git.Commit, error) { return m.log(repoPath, rev, opts...) } func (m *MockModuleStore) MergeBase(repoPath, base, head string, opts ...git.MergeBaseOptions) (string, error) { return m.mergeBase(repoPath, base, head, opts...) } func (m *MockModuleStore) RemoteRemove(repoPath, name string, opts ...git.RemoteRemoveOptions) error { return m.remoteRemove(repoPath, name, opts...) } func (m *MockModuleStore) RepoTags(repoPath string, opts ...git.TagsOptions) ([]string, error) { return m.repoTags(repoPath, opts...) } func (m *MockModuleStore) PullRequestMeta(headPath, basePath, headBranch, baseBranch string) (*PullRequestMeta, error) { return m.pullRequestMeta(headPath, basePath, headBranch, baseBranch) } func (m *MockModuleStore) ListTagsAfter(repoPath, after string, limit int) (*TagsPage, error) { return m.listTagsAfter(repoPath, after, limit) } func SetMockModuleStore(t *testing.T, mock ModuleStore) { before := Module Module = mock t.Cleanup(func() { Module = before }) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/error.go
internal/gitutil/error.go
// Copyright 2020 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 gitutil import ( "github.com/gogs/git-module" "github.com/pkg/errors" "gogs.io/gogs/internal/errutil" ) var _ errutil.NotFound = (*Error)(nil) // Error is a wrapper of a Git error, which handles not found. type Error struct { error } func (e Error) NotFound() bool { return IsErrSubmoduleNotExist(e.error) || IsErrRevisionNotExist(e.error) } // NewError wraps given error. func NewError(err error) error { return Error{error: err} } // IsErrSubmoduleNotExist returns true if the underlying error is // git.ErrSubmoduleNotExist. func IsErrSubmoduleNotExist(err error) bool { return errors.Cause(err) == git.ErrSubmoduleNotExist } // IsErrRevisionNotExist returns true if the underlying error is // git.ErrRevisionNotExist. func IsErrRevisionNotExist(err error) bool { return errors.Cause(err) == git.ErrRevisionNotExist } // IsErrNoMergeBase returns true if the underlying error is git.ErrNoMergeBase. func IsErrNoMergeBase(err error) bool { return errors.Cause(err) == git.ErrNoMergeBase }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/tag_test.go
internal/gitutil/tag_test.go
// Copyright 2020 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 gitutil import ( "testing" "github.com/gogs/git-module" "github.com/stretchr/testify/assert" ) func TestModuler_ListTagsAfter(t *testing.T) { SetMockModuleStore(t, &MockModuleStore{ repoTags: func(string, ...git.TagsOptions) ([]string, error) { return []string{ "v2.3.0", "v2.2.1", "v2.1.0", "v1.3.0", "v1.2.0", "v1.1.0", "v0.8.0", "v0.5.0", "v0.1.0", }, nil }, listTagsAfter: Module.ListTagsAfter, }) tests := []struct { name string after string expTagsPage *TagsPage }{ { name: "first page", expTagsPage: &TagsPage{ Tags: []string{ "v2.3.0", "v2.2.1", "v2.1.0", }, HasLatest: true, HasNext: true, }, }, { name: "second page", after: "v2.1.0", expTagsPage: &TagsPage{ Tags: []string{ "v1.3.0", "v1.2.0", "v1.1.0", }, HasLatest: false, HasNext: true, }, }, { name: "last page", after: "v1.1.0", expTagsPage: &TagsPage{ Tags: []string{ "v0.8.0", "v0.5.0", "v0.1.0", }, HasLatest: false, PreviousAfter: "v2.1.0", HasNext: false, }, }, { name: "arbitrary after", after: "v1.2.0", expTagsPage: &TagsPage{ Tags: []string{ "v1.1.0", "v0.8.0", "v0.5.0", }, HasLatest: false, PreviousAfter: "v2.2.1", HasNext: true, }, }, { name: "after the oldest one", after: "v0.1.0", expTagsPage: &TagsPage{ Tags: []string{}, HasLatest: false, PreviousAfter: "v1.1.0", HasNext: false, }, }, { name: "after does not exist", after: "v2.2.9", expTagsPage: &TagsPage{ Tags: []string{ "v2.3.0", "v2.2.1", "v2.1.0", }, HasLatest: true, HasNext: true, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { tagsPage, err := Module.ListTagsAfter("", test.after, 3) if err != nil { t.Fatal(err) } assert.Equal(t, test.expTagsPage, tagsPage) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/error_test.go
internal/gitutil/error_test.go
// Copyright 2020 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 gitutil import ( "os" "testing" "github.com/gogs/git-module" "github.com/stretchr/testify/assert" "gogs.io/gogs/internal/errutil" ) func TestError_NotFound(t *testing.T) { tests := []struct { err error expVal bool }{ {err: git.ErrSubmoduleNotExist, expVal: true}, {err: git.ErrRevisionNotExist, expVal: true}, {err: git.ErrNoMergeBase, expVal: false}, } for _, test := range tests { t.Run("", func(t *testing.T) { assert.Equal(t, test.expVal, errutil.IsNotFound(NewError(test.err))) }) } } func TestIsErrRevisionNotExist(t *testing.T) { assert.True(t, IsErrRevisionNotExist(git.ErrRevisionNotExist)) assert.False(t, IsErrRevisionNotExist(os.ErrNotExist)) } func TestIsErrNoMergeBase(t *testing.T) { assert.True(t, IsErrNoMergeBase(git.ErrNoMergeBase)) assert.False(t, IsErrNoMergeBase(os.ErrNotExist)) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/pull_request_test.go
internal/gitutil/pull_request_test.go
// Copyright 2020 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 gitutil import ( "fmt" "testing" "github.com/gogs/git-module" "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) func TestModuler_PullRequestMeta(t *testing.T) { headPath := "/head/path" basePath := "/base/path" headBranch := "head_branch" baseBranch := "base_branch" mergeBase := "MERGE-BASE" changedFiles := []string{"a.go", "b.txt"} commits := []*git.Commit{ {ID: git.MustIDFromString("adfd6da3c0a3fb038393144becbf37f14f780087")}, } SetMockModuleStore(t, &MockModuleStore{ remoteAdd: func(repoPath, name, url string, opts ...git.RemoteAddOptions) error { if repoPath != headPath { return fmt.Errorf("repoPath: want %q but got %q", headPath, repoPath) } else if name == "" { return errors.New("empty name") } else if url != basePath { return fmt.Errorf("url: want %q but got %q", basePath, url) } if len(opts) == 0 { return errors.New("no options") } else if !opts[0].Fetch { return fmt.Errorf("opts.Fetch: want %v but got %v", true, opts[0].Fetch) } return nil }, mergeBase: func(repoPath, base, head string, opts ...git.MergeBaseOptions) (string, error) { if repoPath != headPath { return "", fmt.Errorf("repoPath: want %q but got %q", headPath, repoPath) } else if base == "" { return "", errors.New("empty base") } else if head != headBranch { return "", fmt.Errorf("head: want %q but got %q", headBranch, head) } return mergeBase, nil }, log: func(repoPath, rev string, opts ...git.LogOptions) ([]*git.Commit, error) { if repoPath != headPath { return nil, fmt.Errorf("repoPath: want %q but got %q", headPath, repoPath) } expRev := mergeBase + "..." + headBranch if rev != expRev { return nil, fmt.Errorf("rev: want %q but got %q", expRev, rev) } return commits, nil }, diffNameOnly: func(repoPath, base, head string, opts ...git.DiffNameOnlyOptions) ([]string, error) { if repoPath != headPath { return nil, fmt.Errorf("repoPath: want %q but got %q", headPath, repoPath) } else if base == "" { return nil, errors.New("empty base") } else if head != headBranch { return nil, fmt.Errorf("head: want %q but got %q", headBranch, head) } if len(opts) == 0 { return nil, errors.New("no options") } else if !opts[0].NeedsMergeBase { return nil, fmt.Errorf("opts.NeedsMergeBase: want %v but got %v", true, opts[0].NeedsMergeBase) } return changedFiles, nil }, remoteRemove: func(repoPath, name string, opts ...git.RemoteRemoveOptions) error { if repoPath != headPath { return fmt.Errorf("repoPath: want %q but got %q", headPath, repoPath) } else if name == "" { return errors.New("empty name") } return nil }, pullRequestMeta: Module.PullRequestMeta, }) meta, err := Module.PullRequestMeta(headPath, basePath, headBranch, baseBranch) if err != nil { t.Fatal(err) } expMeta := &PullRequestMeta{ MergeBase: mergeBase, Commits: commits, NumFiles: 2, } assert.Equal(t, expMeta, meta) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/pull_request.go
internal/gitutil/pull_request.go
// Copyright 2020 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 gitutil import ( "fmt" "strconv" "time" "github.com/gogs/git-module" "github.com/pkg/errors" log "unknwon.dev/clog/v2" ) // PullRequestMeta contains metadata for a pull request. type PullRequestMeta struct { // The merge base of the pull request. MergeBase string // The commits that are requested to be merged. Commits []*git.Commit // The number of files changed. NumFiles int } func (module) PullRequestMeta(headPath, basePath, headBranch, baseBranch string) (*PullRequestMeta, error) { tmpRemoteBranch := baseBranch // We need to create a temporary remote when the pull request is sent from a forked repository. if headPath != basePath { tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10) err := Module.RemoteAdd(headPath, tmpRemote, basePath, git.RemoteAddOptions{Fetch: true}) if err != nil { return nil, fmt.Errorf("add remote: %v", err) } defer func() { err := Module.RemoteRemove(headPath, tmpRemote) if err != nil { log.Error("Failed to remove remote %q [path: %s]: %v", tmpRemote, headPath, err) return } }() tmpRemoteBranch = "remotes/" + tmpRemote + "/" + baseBranch } mergeBase, err := Module.MergeBase(headPath, tmpRemoteBranch, headBranch) if err != nil { return nil, errors.Wrap(err, "get merge base") } commits, err := Module.Log(headPath, mergeBase+"..."+headBranch) if err != nil { return nil, errors.Wrap(err, "get commits") } // Count number of changed files names, err := Module.DiffNameOnly(headPath, tmpRemoteBranch, headBranch, git.DiffNameOnlyOptions{NeedsMergeBase: true}) if err != nil { return nil, errors.Wrap(err, "get changed files") } return &PullRequestMeta{ MergeBase: mergeBase, Commits: commits, NumFiles: len(names), }, nil }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/tag.go
internal/gitutil/tag.go
// Copyright 2020 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 gitutil import ( "github.com/pkg/errors" ) // TagsPage contains a list of tags and pagination information. type TagsPage struct { // List of tags in the current page. Tags []string // Whether the results include the latest tag. HasLatest bool // When results do not include the latest tag, an indicator of 'after' to go back. PreviousAfter string // Whether there are more tags in the next page. HasNext bool } func (module) ListTagsAfter(repoPath, after string, limit int) (*TagsPage, error) { all, err := Module.RepoTags(repoPath) if err != nil { return nil, errors.Wrap(err, "get tags") } total := len(all) if limit < 0 { limit = 0 } // Returns everything when no filter and no limit if after == "" && limit == 0 { return &TagsPage{ Tags: all, HasLatest: true, }, nil } // No filter but has a limit, returns first X tags if after == "" && limit > 0 { endIdx := limit if limit > total { endIdx = total } return &TagsPage{ Tags: all[:endIdx], HasLatest: true, HasNext: limit < total, }, nil } // Loop over all tags see if we can find the filter previousAfter := "" found := false tags := make([]string, 0, len(all)) for i := range all { if all[i] != after { continue } found = true if limit > 0 && i-limit >= 0 { previousAfter = all[i-limit] } // In case filter is the oldest one if i+1 < total { tags = all[i+1:] } break } if !found { tags = all } // If all tags after match is equal to the limit, it reaches the oldest tag as well. if limit == 0 || len(tags) <= limit { return &TagsPage{ Tags: tags, HasLatest: !found, PreviousAfter: previousAfter, }, nil } return &TagsPage{ Tags: tags[:limit], HasLatest: !found, PreviousAfter: previousAfter, HasNext: true, }, nil }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/diff.go
internal/gitutil/diff.go
// Copyright 2014 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 gitutil import ( "bytes" "fmt" "html" "html/template" "io" "sync" "github.com/sergi/go-diff/diffmatchpatch" "golang.org/x/net/html/charset" "golang.org/x/text/transform" "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/template/highlight" "gogs.io/gogs/internal/tool" ) // DiffSection is a wrapper to git.DiffSection with helper methods. type DiffSection struct { *git.DiffSection initOnce sync.Once dmp *diffmatchpatch.DiffMatchPatch } // ComputedInlineDiffFor computes inline diff for the given line. func (s *DiffSection) ComputedInlineDiffFor(line *git.DiffLine) template.HTML { fallback := template.HTML(html.EscapeString(line.Content)) if conf.Git.DisableDiffHighlight { return fallback } // Find equivalent diff line, ignore when not found. var diff1, diff2 string switch line.Type { case git.DiffLineAdd: compareLine := s.Line(git.DiffLineDelete, line.RightLine) if compareLine == nil { return fallback } diff1 = compareLine.Content diff2 = line.Content case git.DiffLineDelete: compareLine := s.Line(git.DiffLineAdd, line.LeftLine) if compareLine == nil { return fallback } diff1 = line.Content diff2 = compareLine.Content default: return fallback } s.initOnce.Do(func() { s.dmp = diffmatchpatch.New() s.dmp.DiffEditCost = 100 }) diffs := s.dmp.DiffMain(diff1[1:], diff2[1:], true) diffs = s.dmp.DiffCleanupEfficiency(diffs) return diffsToHTML(diffs, line.Type) } func diffsToHTML(diffs []diffmatchpatch.Diff, lineType git.DiffLineType) template.HTML { buf := bytes.NewBuffer(nil) // Reproduce signs which are cutted for inline diff before. switch lineType { case git.DiffLineAdd: buf.WriteByte('+') case git.DiffLineDelete: buf.WriteByte('-') } const ( addedCodePrefix = `<span class="added-code">` removedCodePrefix = `<span class="removed-code">` codeTagSuffix = `</span>` ) for i := range diffs { switch { case diffs[i].Type == diffmatchpatch.DiffInsert && lineType == git.DiffLineAdd: buf.WriteString(addedCodePrefix) buf.WriteString(html.EscapeString(diffs[i].Text)) buf.WriteString(codeTagSuffix) case diffs[i].Type == diffmatchpatch.DiffDelete && lineType == git.DiffLineDelete: buf.WriteString(removedCodePrefix) buf.WriteString(html.EscapeString(diffs[i].Text)) buf.WriteString(codeTagSuffix) case diffs[i].Type == diffmatchpatch.DiffEqual: buf.WriteString(html.EscapeString(diffs[i].Text)) } } return template.HTML(buf.Bytes()) } // DiffFile is a wrapper to git.DiffFile with helper methods. type DiffFile struct { *git.DiffFile Sections []*DiffSection } // HighlightClass returns the detected highlight class for the file. func (diffFile *DiffFile) HighlightClass() string { return highlight.FileNameToHighlightClass(diffFile.Name) } // Diff is a wrapper to git.Diff with helper methods. type Diff struct { *git.Diff Files []*DiffFile } // NewDiff returns a new wrapper of given git.Diff. func NewDiff(oldDiff *git.Diff) *Diff { newDiff := &Diff{ Diff: oldDiff, Files: make([]*DiffFile, oldDiff.NumFiles()), } // FIXME: detect encoding while parsing. var buf bytes.Buffer for i := range oldDiff.Files { buf.Reset() newDiff.Files[i] = &DiffFile{ DiffFile: oldDiff.Files[i], Sections: make([]*DiffSection, oldDiff.Files[i].NumSections()), } for j := range oldDiff.Files[i].Sections { newDiff.Files[i].Sections[j] = &DiffSection{ DiffSection: oldDiff.Files[i].Sections[j], } for k := range newDiff.Files[i].Sections[j].Lines { buf.WriteString(newDiff.Files[i].Sections[j].Lines[k].Content) buf.WriteString("\n") } } charsetLabel, err := tool.DetectEncoding(buf.Bytes()) if charsetLabel != "UTF-8" && err == nil { encoding, _ := charset.Lookup(charsetLabel) if encoding != nil { d := encoding.NewDecoder() for j := range newDiff.Files[i].Sections { for k := range newDiff.Files[i].Sections[j].Lines { if c, _, err := transform.String(d, newDiff.Files[i].Sections[j].Lines[k].Content); err == nil { newDiff.Files[i].Sections[j].Lines[k].Content = c } } } } } } return newDiff } // ParseDiff parses the diff from given io.Reader. func ParseDiff(r io.Reader, maxFiles, maxFileLines, maxLineChars int) (*Diff, error) { done := make(chan git.SteamParseDiffResult) go git.StreamParseDiff(r, done, maxFiles, maxFileLines, maxLineChars) result := <-done if result.Err != nil { return nil, fmt.Errorf("stream parse diff: %v", result.Err) } return NewDiff(result.Diff), nil } // RepoDiff parses the diff on given revisions of given repository. func RepoDiff(repo *git.Repository, rev string, maxFiles, maxFileLines, maxLineChars int, opts ...git.DiffOptions) (*Diff, error) { diff, err := repo.Diff(rev, maxFiles, maxFileLines, maxLineChars, opts...) if err != nil { return nil, fmt.Errorf("get diff: %v", err) } return NewDiff(diff), nil }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/module.go
internal/gitutil/module.go
// Copyright 2020 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 gitutil import ( "github.com/gogs/git-module" ) // ModuleStore is the interface for Git operations. type ModuleStore interface { // RemoteAdd adds a new remote to the repository in given path. RemoteAdd(repoPath, name, url string, opts ...git.RemoteAddOptions) error // DiffNameOnly returns a list of changed files between base and head revisions // of the repository in given path. DiffNameOnly(repoPath, base, head string, opts ...git.DiffNameOnlyOptions) ([]string, error) // Log returns a list of commits in the state of given revision of the // repository in given path. The returned list is in reverse chronological // order. Log(repoPath, rev string, opts ...git.LogOptions) ([]*git.Commit, error) // MergeBase returns merge base between base and head revisions of the // repository in given path. MergeBase(repoPath, base, head string, opts ...git.MergeBaseOptions) (string, error) // RemoteRemove removes a remote from the repository in given path. RemoteRemove(repoPath, name string, opts ...git.RemoteRemoveOptions) error // RepoTags returns a list of tags of the repository in given path. RepoTags(repoPath string, opts ...git.TagsOptions) ([]string, error) // PullRequestMeta gathers pull request metadata based on given head and base // information. PullRequestMeta(headPath, basePath, headBranch, baseBranch string) (*PullRequestMeta, error) // ListTagsAfter returns a list of tags "after" (exclusive) given tag. ListTagsAfter(repoPath, after string, limit int) (*TagsPage, error) } // module holds the real implementation. type module struct{} func (module) RemoteAdd(repoPath, name, url string, opts ...git.RemoteAddOptions) error { return git.RemoteAdd(repoPath, name, url, opts...) } func (module) DiffNameOnly(repoPath, base, head string, opts ...git.DiffNameOnlyOptions) ([]string, error) { return git.DiffNameOnly(repoPath, base, head, opts...) } func (module) Log(repoPath, rev string, opts ...git.LogOptions) ([]*git.Commit, error) { return git.Log(repoPath, rev, opts...) } func (module) MergeBase(repoPath, base, head string, opts ...git.MergeBaseOptions) (string, error) { return git.MergeBase(repoPath, base, head, opts...) } func (module) RemoteRemove(repoPath, name string, opts ...git.RemoteRemoveOptions) error { return git.RemoteRemove(repoPath, name, opts...) } func (module) RepoTags(repoPath string, opts ...git.TagsOptions) ([]string, error) { return git.RepoTags(repoPath, opts...) } // Module is a mockable interface for Git operations. var Module ModuleStore = module{}
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/submodule_test.go
internal/gitutil/submodule_test.go
// Copyright 2020 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 gitutil import ( "testing" "github.com/gogs/git-module" "github.com/stretchr/testify/assert" ) func TestInferSubmoduleURL(t *testing.T) { tests := []struct { name string submodule *git.Submodule expURL string }{ { name: "HTTPS URL", submodule: &git.Submodule{ URL: "https://github.com/gogs/docs-api.git", Commit: "6b08f76a5313fa3d26859515b30aa17a5faa2807", }, expURL: "https://github.com/gogs/docs-api/commit/6b08f76a5313fa3d26859515b30aa17a5faa2807", }, { name: "SSH URL with port", submodule: &git.Submodule{ URL: "ssh://user@github.com:22/gogs/docs-api.git", Commit: "6b08f76a5313fa3d26859515b30aa17a5faa2807", }, expURL: "http://github.com/gogs/docs-api/commit/6b08f76a5313fa3d26859515b30aa17a5faa2807", }, { name: "SSH URL in SCP syntax", submodule: &git.Submodule{ URL: "git@github.com:gogs/docs-api.git", Commit: "6b08f76a5313fa3d26859515b30aa17a5faa2807", }, expURL: "http://github.com/gogs/docs-api/commit/6b08f76a5313fa3d26859515b30aa17a5faa2807", }, { name: "relative path", submodule: &git.Submodule{ URL: "../repo2.git", Commit: "6b08f76a5313fa3d26859515b30aa17a5faa2807", }, expURL: "https://gogs.example.com/user/repo/../repo2/commit/6b08f76a5313fa3d26859515b30aa17a5faa2807", }, { name: "bad URL", submodule: &git.Submodule{ URL: "ftp://example.com", Commit: "6b08f76a5313fa3d26859515b30aa17a5faa2807", }, expURL: "ftp://example.com", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert.Equal(t, test.expURL, InferSubmoduleURL("https://gogs.example.com/user/repo", test.submodule)) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/diff_test.go
internal/gitutil/diff_test.go
// Copyright 2016 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 gitutil import ( "html/template" "testing" dmp "github.com/sergi/go-diff/diffmatchpatch" "github.com/stretchr/testify/assert" "github.com/gogs/git-module" ) func Test_diffsToHTML(t *testing.T) { tests := []struct { diffs []dmp.Diff lineType git.DiffLineType expHTML template.HTML }{ { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffInsert, Text: "bar"}, {Type: dmp.DiffDelete, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineAdd, expHTML: template.HTML(`+foo <span class="added-code">bar</span> biz`), }, { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffDelete, Text: "bar"}, {Type: dmp.DiffInsert, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineDelete, expHTML: template.HTML(`-foo <span class="removed-code">bar</span> biz`), }, } for _, test := range tests { t.Run("", func(t *testing.T) { assert.Equal(t, test.expHTML, diffsToHTML(test.diffs, test.lineType)) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/gitutil/submodule.go
internal/gitutil/submodule.go
// Copyright 2020 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 gitutil import ( "fmt" "net/url" "strings" "github.com/gogs/git-module" "gogs.io/gogs/internal/lazyregexp" ) var scpSyntax = lazyregexp.New(`^([a-zA-Z0-9_]+@)?([a-zA-Z0-9._-]+):(.*)$`) // InferSubmoduleURL returns the inferred external URL of the submodule at best effort. // The `baseURL` should be the URL of the current repository. If the submodule URL looks // like a relative path, it assumes that the submodule is another repository on the same // Gogs instance by appending it to the `baseURL` with the commit. func InferSubmoduleURL(baseURL string, mod *git.Submodule) string { if !strings.HasSuffix(baseURL, "/") { baseURL += "/" } raw := strings.TrimSuffix(mod.URL, "/") raw = strings.TrimSuffix(raw, ".git") if strings.HasPrefix(raw, "../") { return fmt.Sprintf("%s%s/commit/%s", baseURL, raw, mod.Commit) } parsed, err := url.Parse(raw) if err != nil { // Try parse as SCP syntax again match := scpSyntax.FindAllStringSubmatch(raw, -1) if len(match) == 0 { return mod.URL } parsed = &url.URL{ Scheme: "http", Host: match[0][2], Path: match[0][3], } } switch parsed.Scheme { case "http", "https": raw = parsed.String() case "ssh": raw = fmt.Sprintf("http://%s%s", parsed.Hostname(), parsed.Path) default: return raw } return fmt.Sprintf("%s/commit/%s", raw, mod.Commit) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/pathutil/pathutil_test.go
internal/pathutil/pathutil_test.go
// Copyright 2020 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 pathutil import ( "testing" "github.com/stretchr/testify/assert" ) func TestClean(t *testing.T) { tests := []struct { path string wantVal string }{ { path: "../../../readme.txt", wantVal: "readme.txt", }, { path: "a/../../../readme.txt", wantVal: "readme.txt", }, { path: "/../a/b/../c/../readme.txt", wantVal: "a/readme.txt", }, { path: "../../objects/info/..", wantVal: "objects", }, { path: "/a/readme.txt", wantVal: "a/readme.txt", }, { path: "/", wantVal: "", }, { path: "/a/b/c/readme.txt", wantVal: "a/b/c/readme.txt", }, // Windows-specific { path: `..\..\..\readme.txt`, wantVal: "readme.txt", }, { path: `a\..\..\..\readme.txt`, wantVal: "readme.txt", }, { path: `\..\a\b\..\c\..\readme.txt`, wantVal: "a/readme.txt", }, { path: `\a\readme.txt`, wantVal: "a/readme.txt", }, { path: `..\..\..\../README.md`, wantVal: "README.md", }, { path: `\`, wantVal: "", }, { path: `\a\b\c\readme.txt`, wantVal: `a/b/c/readme.txt`, }, } for _, test := range tests { t.Run(test.path, func(t *testing.T) { assert.Equal(t, test.wantVal, Clean(test.path)) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/pathutil/pathutil.go
internal/pathutil/pathutil.go
// Copyright 2020 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 pathutil import ( "path" "strings" ) // Clean cleans up given path and returns a relative path that goes straight // down to prevent path traversal. // // 🚨 SECURITY: This function MUST be used for any user input that is used as // file system path to prevent path traversal. func Clean(p string) string { p = strings.ReplaceAll(p, `\`, "/") return strings.Trim(path.Clean("/"+p), "/") }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/dbutil/dsn.go
internal/dbutil/dsn.go
// Copyright 2020 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 dbutil import ( "fmt" "strings" "github.com/pkg/errors" "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/driver/sqlserver" "gorm.io/gorm" "gogs.io/gogs/internal/conf" ) // ParsePostgreSQLHostPort parses given input in various forms defined in // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING // and returns proper host and port number. func ParsePostgreSQLHostPort(info string) (host, port string) { host, port = "127.0.0.1", "5432" if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") { idx := strings.LastIndex(info, ":") host = info[:idx] port = info[idx+1:] } else if len(info) > 0 { host = info } return host, port } // ParseMSSQLHostPort parses given input in various forms for MSSQL and returns // proper host and port number. func ParseMSSQLHostPort(info string) (host, port string) { host, port = "127.0.0.1", "1433" if strings.Contains(info, ":") { host = strings.Split(info, ":")[0] port = strings.Split(info, ":")[1] } else if strings.Contains(info, ",") { host = strings.Split(info, ",")[0] port = strings.TrimSpace(strings.Split(info, ",")[1]) } else if len(info) > 0 { host = info } return host, port } // NewDSN takes given database options and returns parsed DSN. func NewDSN(opts conf.DatabaseOpts) (dsn string, err error) { // In case the database name contains "?" with some parameters concate := "?" if strings.Contains(opts.Name, concate) { concate = "&" } switch opts.Type { case "mysql": if opts.Host[0] == '/' { // Looks like a unix socket dsn = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true", opts.User, opts.Password, opts.Host, opts.Name, concate) } else { dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true", opts.User, opts.Password, opts.Host, opts.Name, concate) } case "postgres": host, port := ParsePostgreSQLHostPort(opts.Host) dsn = fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s' sslmode='%s' search_path='%s' application_name='gogs'", opts.User, opts.Password, host, port, opts.Name, opts.SSLMode, opts.Schema) case "mssql": host, port := ParseMSSQLHostPort(opts.Host) dsn = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, opts.Name, opts.User, opts.Password) case "sqlite3", "sqlite": dsn = "file:" + opts.Path + "?cache=shared&mode=rwc" default: return "", errors.Errorf("unrecognized dialect: %s", opts.Type) } return dsn, nil } // OpenDB opens a new database connection encapsulated as gorm.DB using given // database options and GORM config. func OpenDB(opts conf.DatabaseOpts, cfg *gorm.Config) (*gorm.DB, error) { dsn, err := NewDSN(opts) if err != nil { return nil, errors.Wrap(err, "parse DSN") } var dialector gorm.Dialector switch opts.Type { case "mysql": dialector = mysql.Open(dsn) case "postgres": dialector = postgres.Open(dsn) case "mssql": dialector = sqlserver.Open(dsn) case "sqlite3": dialector = sqlite.Open(dsn) case "sqlite": dialector = sqlite.Open(dsn) dialector.(*sqlite.Dialector).DriverName = "sqlite" default: panic("unreachable") } return gorm.Open(dialector, cfg) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/dbutil/dsn_test.go
internal/dbutil/dsn_test.go
// Copyright 2020 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 dbutil import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gogs.io/gogs/internal/conf" ) func TestParsePostgreSQLHostPort(t *testing.T) { tests := []struct { info string expHost string expPort string }{ {info: "127.0.0.1:1234", expHost: "127.0.0.1", expPort: "1234"}, {info: "127.0.0.1", expHost: "127.0.0.1", expPort: "5432"}, {info: "[::1]:1234", expHost: "[::1]", expPort: "1234"}, {info: "[::1]", expHost: "[::1]", expPort: "5432"}, {info: "/tmp/pg.sock:1234", expHost: "/tmp/pg.sock", expPort: "1234"}, {info: "/tmp/pg.sock", expHost: "/tmp/pg.sock", expPort: "5432"}, } for _, test := range tests { t.Run("", func(t *testing.T) { host, port := ParsePostgreSQLHostPort(test.info) assert.Equal(t, test.expHost, host) assert.Equal(t, test.expPort, port) }) } } func TestParseMSSQLHostPort(t *testing.T) { tests := []struct { info string expHost string expPort string }{ {info: "127.0.0.1:1234", expHost: "127.0.0.1", expPort: "1234"}, {info: "127.0.0.1,1234", expHost: "127.0.0.1", expPort: "1234"}, {info: "127.0.0.1", expHost: "127.0.0.1", expPort: "1433"}, } for _, test := range tests { t.Run("", func(t *testing.T) { host, port := ParseMSSQLHostPort(test.info) assert.Equal(t, test.expHost, host) assert.Equal(t, test.expPort, port) }) } } func TestNewDSN(t *testing.T) { t.Run("bad dialect", func(t *testing.T) { _, err := NewDSN(conf.DatabaseOpts{ Type: "bad_dialect", }) assert.Equal(t, "unrecognized dialect: bad_dialect", fmt.Sprintf("%v", err)) }) tests := []struct { name string opts conf.DatabaseOpts wantDSN string }{ { name: "mysql: unix", opts: conf.DatabaseOpts{ Type: "mysql", Host: "/tmp/mysql.sock", Name: "gogs", User: "gogs", Password: "pa$$word", }, wantDSN: "gogs:pa$$word@unix(/tmp/mysql.sock)/gogs?charset=utf8mb4&parseTime=true", }, { name: "mysql: tcp", opts: conf.DatabaseOpts{ Type: "mysql", Host: "localhost:3306", Name: "gogs", User: "gogs", Password: "pa$$word", }, wantDSN: "gogs:pa$$word@tcp(localhost:3306)/gogs?charset=utf8mb4&parseTime=true", }, { name: "postgres: unix", opts: conf.DatabaseOpts{ Type: "postgres", Host: "/tmp/pg.sock", Name: "gogs", Schema: "test", User: "gogs@local", Password: "pa$$word", SSLMode: "disable", }, wantDSN: "user='gogs@local' password='pa$$word' host='/tmp/pg.sock' port='5432' dbname='gogs' sslmode='disable' search_path='test' application_name='gogs'", }, { name: "postgres: tcp", opts: conf.DatabaseOpts{ Type: "postgres", Host: "127.0.0.1", Name: "gogs", Schema: "test", User: "gogs@local", Password: "pa$$word", SSLMode: "disable", }, wantDSN: "user='gogs@local' password='pa$$word' host='127.0.0.1' port='5432' dbname='gogs' sslmode='disable' search_path='test' application_name='gogs'", }, { name: "mssql", opts: conf.DatabaseOpts{ Type: "mssql", Host: "127.0.0.1", Name: "gogs", User: "gogs@local", Password: "pa$$word", }, wantDSN: "server=127.0.0.1; port=1433; database=gogs; user id=gogs@local; password=pa$$word;", }, { name: "sqlite3", opts: conf.DatabaseOpts{ Type: "sqlite3", Path: "/tmp/gogs.db", }, wantDSN: "file:/tmp/gogs.db?cache=shared&mode=rwc", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { dsn, err := NewDSN(test.opts) require.NoError(t, err) assert.Equal(t, test.wantDSN, dsn) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/dbutil/string.go
internal/dbutil/string.go
// Copyright 2022 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 dbutil import ( "fmt" "gogs.io/gogs/internal/conf" ) // Quote adds surrounding double quotes for all given arguments before being // formatted if the current database is UsePostgreSQL. func Quote(format string, args ...string) string { anys := make([]any, len(args)) for i := range args { if conf.UsePostgreSQL { anys[i] = `"` + args[i] + `"` } else { anys[i] = args[i] } } return fmt.Sprintf(format, anys...) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/dbutil/logger.go
internal/dbutil/logger.go
// Copyright 2020 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 dbutil import ( "fmt" "io" ) // Logger is a wrapper of io.Writer for the GORM's logger.Writer. type Logger struct { io.Writer } func (l *Logger) Printf(format string, args ...any) { _, _ = fmt.Fprintf(l.Writer, format, args...) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/dbutil/string_test.go
internal/dbutil/string_test.go
// Copyright 2022 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 dbutil import ( "testing" "github.com/stretchr/testify/assert" "gogs.io/gogs/internal/conf" ) func TestQuote(t *testing.T) { conf.UsePostgreSQL = true got := Quote("SELECT * FROM %s", "user") want := `SELECT * FROM "user"` assert.Equal(t, want, got) conf.UsePostgreSQL = false got = Quote("SELECT * FROM %s", "user") want = `SELECT * FROM user` assert.Equal(t, want, got) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/strutil/strutil.go
internal/strutil/strutil.go
// Copyright 2020 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 strutil import ( "crypto/rand" "math/big" "unicode" ) // ToUpperFirst returns s with only the first Unicode letter mapped to its upper case. func ToUpperFirst(s string) string { for i, v := range s { return string(unicode.ToUpper(v)) + s[i+1:] } return "" } // RandomChars returns a generated string in given number of random characters. func RandomChars(n int) (string, error) { const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" randomInt := func(max *big.Int) (int, error) { r, err := rand.Int(rand.Reader, max) if err != nil { return 0, err } return int(r.Int64()), nil } buffer := make([]byte, n) max := big.NewInt(int64(len(alphanum))) for i := 0; i < n; i++ { index, err := randomInt(max) if err != nil { return "", err } buffer[i] = alphanum[index] } return string(buffer), nil } // Ellipsis returns a truncated string and appends "..." to the end of the // string if the string length is larger than the threshold. Otherwise, the // original string is returned. func Ellipsis(str string, threshold int) string { if len(str) <= threshold || threshold < 0 { return str } return str[:threshold] + "..." } // Truncate returns a truncated string if its length is over the limit. // Otherwise, it returns the original string. func Truncate(str string, limit int) string { if len(str) < limit { return str } return str[:limit] }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/strutil/strutil_test.go
internal/strutil/strutil_test.go
// Copyright 2020 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 strutil import ( "testing" "github.com/stretchr/testify/assert" ) func TestToUpperFirst(t *testing.T) { tests := []struct { name string s string expStr string }{ { name: "empty string", }, { name: "first letter is a digit", s: "123 let's go", expStr: "123 let's go", }, { name: "lower to upper", s: "this is a sentence", expStr: "This is a sentence", }, { name: "already in upper case", s: "Let's go", expStr: "Let's go", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert.Equal(t, test.expStr, ToUpperFirst(test.s)) }) } } func TestRandomChars(t *testing.T) { cache := make(map[string]bool) for i := 0; i < 100; i++ { chars, err := RandomChars(10) if err != nil { t.Fatal(err) } if cache[chars] { t.Fatalf("Duplicated chars %q", chars) } cache[chars] = true } } func TestEllipsis(t *testing.T) { tests := []struct { name string str string threshold int want string }{ { name: "empty string and zero threshold", str: "", threshold: 0, want: "", }, { name: "smaller length than threshold", str: "ab", threshold: 3, want: "ab", }, { name: "same length as threshold", str: "abc", threshold: 3, want: "abc", }, { name: "greater length than threshold", str: "ab", threshold: 1, want: "a...", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got := Ellipsis(test.str, test.threshold) assert.Equal(t, test.want, got) }) } } func TestTruncate(t *testing.T) { tests := []struct { name string str string limit int want string }{ { name: "empty string with zero limit", str: "", limit: 0, want: "", }, { name: "smaller length than limit", str: "ab", limit: 3, want: "ab", }, { name: "same length as limit", str: "abc", limit: 3, want: "abc", }, { name: "greater length than limit", str: "ab", limit: 1, want: "a", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got := Truncate(test.str, test.limit) assert.Equal(t, test.want, got) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/lfsutil/storage.go
internal/lfsutil/storage.go
// Copyright 2020 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 lfsutil import ( "io" "os" "path/filepath" "github.com/pkg/errors" "gogs.io/gogs/internal/osutil" ) var ErrObjectNotExist = errors.New("Object does not exist") // Storager is an storage backend for uploading and downloading LFS objects. type Storager interface { // Storage returns the name of the storage backend. Storage() Storage // Upload reads content from the io.ReadCloser and uploads as given oid. // The reader is closed once upload is finished. ErrInvalidOID is returned // if the given oid is not valid. Upload(oid OID, rc io.ReadCloser) (int64, error) // Download streams content of given oid to the io.Writer. It is caller's // responsibility the close the writer when needed. ErrObjectNotExist is // returned if the given oid does not exist. Download(oid OID, w io.Writer) error } // Storage is the storage type of an LFS object. type Storage string const ( StorageLocal Storage = "local" ) var _ Storager = (*LocalStorage)(nil) // LocalStorage is a LFS storage backend on local file system. type LocalStorage struct { // The root path for storing LFS objects. Root string } func (*LocalStorage) Storage() Storage { return StorageLocal } func (s *LocalStorage) storagePath(oid OID) string { if len(oid) < 2 { return "" } return filepath.Join(s.Root, string(oid[0]), string(oid[1]), string(oid)) } func (s *LocalStorage) Upload(oid OID, rc io.ReadCloser) (int64, error) { if !ValidOID(oid) { return 0, ErrInvalidOID } var err error fpath := s.storagePath(oid) defer func() { rc.Close() if err != nil { _ = os.Remove(fpath) } }() err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm) if err != nil { return 0, errors.Wrap(err, "create directories") } w, err := os.Create(fpath) if err != nil { return 0, errors.Wrap(err, "create file") } defer w.Close() written, err := io.Copy(w, rc) if err != nil { return 0, errors.Wrap(err, "copy file") } return written, nil } func (s *LocalStorage) Download(oid OID, w io.Writer) error { fpath := s.storagePath(oid) if !osutil.IsFile(fpath) { return ErrObjectNotExist } r, err := os.Open(fpath) if err != nil { return errors.Wrap(err, "open file") } defer r.Close() _, err = io.Copy(w, r) if err != nil { return errors.Wrap(err, "copy file") } return nil }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/lfsutil/oid_test.go
internal/lfsutil/oid_test.go
// Copyright 2020 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 lfsutil import ( "testing" "github.com/stretchr/testify/assert" ) func TestValidOID(t *testing.T) { tests := []struct { name string oid OID expVal bool }{ { name: "malformed", oid: OID("7c222fb2927d828af22f592134e8932480637c0d"), }, { name: "not all lower cased", oid: OID("EF797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f"), }, { name: "valid", oid: OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f"), expVal: true, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert.Equal(t, test.expVal, ValidOID(test.oid)) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/lfsutil/oid.go
internal/lfsutil/oid.go
// Copyright 2020 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 lfsutil import ( "github.com/pkg/errors" "gogs.io/gogs/internal/lazyregexp" ) // OID is an LFS object ID. type OID string // An OID is a 64-char lower case hexadecimal, produced by SHA256. // Spec: https://github.com/git-lfs/git-lfs/blob/master/docs/spec.md var oidRe = lazyregexp.New("^[a-f0-9]{64}$") var ErrInvalidOID = errors.New("OID is not valid") // ValidOID returns true if given oid is valid. func ValidOID(oid OID) bool { return oidRe.MatchString(string(oid)) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/lfsutil/storage_test.go
internal/lfsutil/storage_test.go
// Copyright 2020 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 lfsutil import ( "bytes" "io" "os" "path/filepath" "runtime" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestLocalStorage_storagePath(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Skipping testing on Windows") return } s := &LocalStorage{ Root: "/lfs-objects", } tests := []struct { name string oid OID expPath string }{ { name: "empty oid", oid: "", }, { name: "valid oid", oid: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", expPath: "/lfs-objects/e/f/ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert.Equal(t, test.expPath, s.storagePath(test.oid)) }) } } func TestLocalStorage_Upload(t *testing.T) { s := &LocalStorage{ Root: filepath.Join(os.TempDir(), "lfs-objects"), } t.Cleanup(func() { _ = os.RemoveAll(s.Root) }) tests := []struct { name string oid OID content string expWritten int64 expErr error }{ { name: "invalid oid", oid: "bad_oid", expErr: ErrInvalidOID, }, { name: "valid oid", oid: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", content: "Hello world!", expWritten: 12, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { written, err := s.Upload(test.oid, io.NopCloser(strings.NewReader(test.content))) assert.Equal(t, test.expWritten, written) assert.Equal(t, test.expErr, err) }) } } func TestLocalStorage_Download(t *testing.T) { oid := OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") s := &LocalStorage{ Root: filepath.Join(os.TempDir(), "lfs-objects"), } t.Cleanup(func() { _ = os.RemoveAll(s.Root) }) fpath := s.storagePath(oid) err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm) if err != nil { t.Fatal(err) } err = os.WriteFile(fpath, []byte("Hello world!"), os.ModePerm) if err != nil { t.Fatal(err) } tests := []struct { name string oid OID expContent string expErr error }{ { name: "object not exists", oid: "bad_oid", expErr: ErrObjectNotExist, }, { name: "valid oid", oid: oid, expContent: "Hello world!", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { var buf bytes.Buffer err := s.Download(test.oid, &buf) assert.Equal(t, test.expContent, buf.String()) assert.Equal(t, test.expErr, err) }) } }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/template/template.go
internal/template/template.go
// Copyright 2014 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 template import ( "fmt" "html/template" "mime" "path/filepath" "strings" "sync" "time" "github.com/editorconfig/editorconfig-core-go/v2" jsoniter "github.com/json-iterator/go" "github.com/microcosm-cc/bluemonday" "golang.org/x/net/html/charset" "golang.org/x/text/transform" log "unknwon.dev/clog/v2" "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/cryptoutil" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/strutil" "gogs.io/gogs/internal/tool" ) var ( funcMap []template.FuncMap funcMapOnce sync.Once ) // FuncMap returns a list of user-defined template functions. func FuncMap() []template.FuncMap { funcMapOnce.Do(func() { funcMap = []template.FuncMap{map[string]any{ "BuildCommit": func() string { return conf.BuildCommit }, "Year": func() int { return time.Now().Year() }, "UseHTTPS": func() bool { return conf.Server.URL.Scheme == "https" }, "AppName": func() string { return conf.App.BrandName }, "AppSubURL": func() string { return conf.Server.Subpath }, "AppURL": func() string { return conf.Server.ExternalURL }, "AppVer": func() string { return conf.App.Version }, "AppDomain": func() string { return conf.Server.Domain }, "DisableGravatar": func() bool { return conf.Picture.DisableGravatar }, "ShowFooterTemplateLoadTime": func() bool { return conf.Other.ShowFooterTemplateLoadTime }, "LoadTimes": func(startTime time.Time) string { return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms" }, "AvatarLink": tool.AvatarLink, "AppendAvatarSize": tool.AppendAvatarSize, "Safe": Safe, "Sanitize": bluemonday.UGCPolicy().Sanitize, "Str2HTML": Str2HTML, "NewLine2br": NewLine2br, "TimeSince": tool.TimeSince, "RawTimeSince": tool.RawTimeSince, "FileSize": tool.FileSize, "Subtract": tool.Subtract, "Add": func(a, b int) int { return a + b }, "ActionIcon": ActionIcon, "DateFmtLong": func(t time.Time) string { return t.Format(time.RFC1123Z) }, "DateFmtShort": func(t time.Time) string { return t.Format("Jan 02, 2006") }, "SubStr": func(str string, start, length int) string { if str == "" { return "" } end := start + length if length == -1 { end = len(str) } if len(str) < end { return str } return str[start:end] }, "Join": strings.Join, "EllipsisString": strutil.Ellipsis, "DiffFileTypeToStr": DiffFileTypeToStr, "DiffLineTypeToStr": DiffLineTypeToStr, "Sha1": Sha1, "ShortSHA1": tool.ShortSHA1, "ActionContent2Commits": ActionContent2Commits, "EscapePound": EscapePound, "RenderCommitMessage": RenderCommitMessage, "ThemeColorMetaTag": func() string { return conf.UI.ThemeColorMetaTag }, "FilenameIsImage": func(filename string) bool { mimeType := mime.TypeByExtension(filepath.Ext(filename)) return strings.HasPrefix(mimeType, "image/") }, "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string { if ec != nil { def, err := ec.GetDefinitionForFilename(filename) if err == nil && def.TabWidth > 0 { return fmt.Sprintf("tab-size-%d", def.TabWidth) } } return "tab-size-8" }, "InferSubmoduleURL": gitutil.InferSubmoduleURL, }} }) return funcMap } func Safe(raw string) template.HTML { return template.HTML(raw) } func Str2HTML(raw string) template.HTML { return template.HTML(markup.Sanitize(raw)) } // NewLine2br simply replaces "\n" to "<br>". func NewLine2br(raw string) string { return strings.ReplaceAll(raw, "\n", "<br>") } func Sha1(str string) string { return cryptoutil.SHA1(str) } func ToUTF8WithErr(content []byte) (string, error) { charsetLabel, err := tool.DetectEncoding(content) if err != nil { return "", err } else if charsetLabel == "UTF-8" { return string(content), nil } encoding, _ := charset.Lookup(charsetLabel) if encoding == nil { return string(content), fmt.Errorf("unknown encoding: %s", charsetLabel) } // If there is an error, we concatenate the nicely decoded part and the // original left over. This way we won't lose data. result, n, err := transform.String(encoding.NewDecoder(), string(content)) if err != nil { result = result + string(content[n:]) } return result, err } // RenderCommitMessage renders commit message with special links. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string { cleanMsg := template.HTMLEscapeString(msg) fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas)) msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n") numLines := len(msgLines) if numLines == 0 { return "" } else if !full { return msgLines[0] } else if numLines == 1 || (numLines >= 2 && msgLines[1] == "") { // First line is a header, standalone or followed by empty line header := fmt.Sprintf("<h3>%s</h3>", msgLines[0]) if numLines >= 2 { fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n")) } else { fullMessage = header } } else { // Non-standard git message, there is no header line fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>")) } return fullMessage } type Actioner interface { GetOpType() int GetActUserName() string GetRepoUserName() string GetRepoName() string GetRepoPath() string GetRepoLink() string GetBranch() string GetContent() string GetCreate() time.Time GetIssueInfos() []string } // ActionIcon accepts a int that represents action operation type // and returns a icon class name. func ActionIcon(opType int) string { switch opType { case 1, 8: // Create and transfer repository return "repo" case 5: // Commit repository return "git-commit" case 6: // Create issue return "issue-opened" case 7: // New pull request return "git-pull-request" case 9: // Push tag return "tag" case 10: // Comment issue return "comment-discussion" case 11: // Merge pull request return "git-merge" case 12, 14: // Close issue or pull request return "issue-closed" case 13, 15: // Reopen issue or pull request return "issue-reopened" case 16: // Create branch return "git-branch" case 17, 18: // Delete branch or tag return "alert" case 19: // Fork a repository return "repo-forked" case 20, 21, 22: // Mirror sync return "repo-clone" default: return "invalid type" } } func ActionContent2Commits(act Actioner) *database.PushCommits { push := database.NewPushCommits() if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil { log.Error("Unmarshal:\n%s\nERROR: %v", act.GetContent(), err) } return push } // TODO(unknwon): Use url.Escape. func EscapePound(str string) string { return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str) } func DiffFileTypeToStr(typ git.DiffFileType) string { return map[git.DiffFileType]string{ git.DiffFileAdd: "add", git.DiffFileChange: "modify", git.DiffFileDelete: "del", git.DiffFileRename: "rename", }[typ] } func DiffLineTypeToStr(typ git.DiffLineType) string { switch typ { case git.DiffLineAdd: return "add" case git.DiffLineDelete: return "del" case git.DiffLineSection: return "tag" } return "same" }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/template/highlight/highlight.go
internal/template/highlight/highlight.go
// Copyright 2015 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 highlight import ( "path" "strings" "gogs.io/gogs/internal/conf" ) var ( // File name should ignore highlight. ignoreFileNames = map[string]bool{ "license": true, "copying": true, } // File names that are representing highlight classes. highlightFileNames = map[string]bool{ "cmakelists.txt": true, "dockerfile": true, "makefile": true, } // Extensions that are same as highlight classes. highlightExts = map[string]bool{ ".arm": true, ".as": true, ".sh": true, ".cs": true, ".cpp": true, ".c": true, ".css": true, ".cmake": true, ".bat": true, ".dart": true, ".patch": true, ".elixir": true, ".erlang": true, ".go": true, ".html": true, ".xml": true, ".hs": true, ".ini": true, ".json": true, ".java": true, ".js": true, ".less": true, ".lua": true, ".php": true, ".py": true, ".rb": true, ".scss": true, ".sql": true, ".scala": true, ".swift": true, ".ts": true, ".vb": true, ".r": true, ".sas": true, ".tex": true, ".yaml": true, } // Extensions that are not same as highlight classes. highlightMapping = map[string]string{ ".txt": "nohighlight", } ) func NewContext() { keys := conf.File.Section("highlight.mapping").Keys() for i := range keys { highlightMapping[keys[i].Name()] = keys[i].Value() } } // FileNameToHighlightClass returns the best match for highlight class name // based on the rule of highlight.js. func FileNameToHighlightClass(fname string) string { fname = strings.ToLower(fname) if ignoreFileNames[fname] { return "nohighlight" } if highlightFileNames[fname] { return fname } ext := path.Ext(fname) if highlightExts[ext] { return ext[1:] } name, ok := highlightMapping[ext] if ok { return name } return "" }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/organizations.go
internal/database/organizations.go
// Copyright 2022 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 database import ( "context" "github.com/pkg/errors" "gorm.io/gorm" "gogs.io/gogs/internal/dbutil" ) // OrganizationsStore is the storage layer for organizations. type OrganizationsStore struct { db *gorm.DB } func newOrganizationsStoreStore(db *gorm.DB) *OrganizationsStore { return &OrganizationsStore{db: db} } type ListOrgsOptions struct { // Filter by the membership with the given user ID. MemberID int64 // Whether to include private memberships. IncludePrivateMembers bool } // List returns a list of organizations filtered by options. func (s *OrganizationsStore) List(ctx context.Context, opts ListOrgsOptions) ([]*Organization, error) { if opts.MemberID <= 0 { return nil, errors.New("MemberID must be greater than 0") } /* Equivalent SQL for PostgreSQL: SELECT * FROM "org" JOIN org_user ON org_user.org_id = org.id WHERE org_user.uid = @memberID [AND org_user.is_public = @includePrivateMembers] ORDER BY org.id ASC */ tx := s.db.WithContext(ctx). Joins(dbutil.Quote("JOIN org_user ON org_user.org_id = %s.id", "user")). Where("org_user.uid = ?", opts.MemberID). Order(dbutil.Quote("%s.id ASC", "user")) if !opts.IncludePrivateMembers { tx = tx.Where("org_user.is_public = ?", true) } var orgs []*Organization return orgs, tx.Find(&orgs).Error } // SearchByName returns a list of organizations whose username or full name // matches the given keyword case-insensitively. Results are paginated by given // page and page size, and sorted by the given order (e.g. "id DESC"). A total // count of all results is also returned. If the order is not given, it's up to // the database to decide. func (s *OrganizationsStore) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*Organization, int64, error) { return searchUserByName(ctx, s.db, UserTypeOrganization, keyword, page, pageSize, orderBy) } // CountByUser returns the number of organizations the user is a member of. func (s *OrganizationsStore) CountByUser(ctx context.Context, userID int64) (int64, error) { var count int64 return count, s.db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error } type Organization = User func (o *Organization) TableName() string { return "user" }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/webhook_discord.go
internal/database/webhook_discord.go
// Copyright 2017 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 database import ( "fmt" "strconv" "strings" jsoniter "github.com/json-iterator/go" "github.com/pkg/errors" "github.com/gogs/git-module" api "github.com/gogs/go-gogs-client" "gogs.io/gogs/internal/conf" ) type DiscordEmbedFooterObject struct { Text string `json:"text"` } type DiscordEmbedAuthorObject struct { Name string `json:"name"` URL string `json:"url"` IconURL string `json:"icon_url"` } type DiscordEmbedFieldObject struct { Name string `json:"name"` Value string `json:"value"` } type DiscordEmbedObject struct { Title string `json:"title"` Description string `json:"description"` URL string `json:"url"` Color int `json:"color"` Footer *DiscordEmbedFooterObject `json:"footer"` Author *DiscordEmbedAuthorObject `json:"author"` Fields []*DiscordEmbedFieldObject `json:"fields"` } type DiscordPayload struct { Content string `json:"content"` Username string `json:"username"` AvatarURL string `json:"avatar_url"` Embeds []*DiscordEmbedObject `json:"embeds"` } func (p *DiscordPayload) JSONPayload() ([]byte, error) { data, err := jsoniter.MarshalIndent(p, "", " ") if err != nil { return []byte{}, err } return data, nil } func DiscordTextFormatter(s string) string { return strings.Split(s, "\n")[0] } func DiscordLinkFormatter(url, text string) string { return fmt.Sprintf("[%s](%s)", text, url) } func DiscordSHALinkFormatter(url, text string) string { return fmt.Sprintf("[`%s`](%s)", text, url) } // getDiscordCreatePayload composes Discord payload for create new branch or tag. func getDiscordCreatePayload(p *api.CreatePayload) *DiscordPayload { refName := git.RefShortName(p.Ref) repoLink := DiscordLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) refLink := DiscordLinkFormatter(p.Repo.HTMLURL+"/src/"+refName, refName) content := fmt.Sprintf("Created new %s: %s/%s", p.RefType, repoLink, refLink) return &DiscordPayload{ Embeds: []*DiscordEmbedObject{{ Description: content, URL: conf.Server.ExternalURL + p.Sender.UserName, Author: &DiscordEmbedAuthorObject{ Name: p.Sender.UserName, IconURL: p.Sender.AvatarUrl, }, }}, } } // getDiscordDeletePayload composes Discord payload for delete a branch or tag. func getDiscordDeletePayload(p *api.DeletePayload) *DiscordPayload { refName := git.RefShortName(p.Ref) repoLink := DiscordLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) content := fmt.Sprintf("Deleted %s: %s/%s", p.RefType, repoLink, refName) return &DiscordPayload{ Embeds: []*DiscordEmbedObject{{ Description: content, URL: conf.Server.ExternalURL + p.Sender.UserName, Author: &DiscordEmbedAuthorObject{ Name: p.Sender.UserName, IconURL: p.Sender.AvatarUrl, }, }}, } } // getDiscordForkPayload composes Discord payload for forked by a repository. func getDiscordForkPayload(p *api.ForkPayload) *DiscordPayload { baseLink := DiscordLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) forkLink := DiscordLinkFormatter(p.Forkee.HTMLURL, p.Forkee.FullName) content := fmt.Sprintf("%s is forked to %s", baseLink, forkLink) return &DiscordPayload{ Embeds: []*DiscordEmbedObject{{ Description: content, URL: conf.Server.ExternalURL + p.Sender.UserName, Author: &DiscordEmbedAuthorObject{ Name: p.Sender.UserName, IconURL: p.Sender.AvatarUrl, }, }}, } } func getDiscordPushPayload(p *api.PushPayload, slack *SlackMeta) *DiscordPayload { // n new commits var ( branchName = git.RefShortName(p.Ref) commitDesc string commitString string ) if len(p.Commits) == 1 { commitDesc = "1 new commit" } else { commitDesc = fmt.Sprintf("%d new commits", len(p.Commits)) } if len(p.CompareURL) > 0 { commitString = DiscordLinkFormatter(p.CompareURL, commitDesc) } else { commitString = commitDesc } repoLink := DiscordLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) branchLink := DiscordLinkFormatter(p.Repo.HTMLURL+"/src/"+branchName, branchName) content := fmt.Sprintf("Pushed %s to %s/%s\n", commitString, repoLink, branchLink) // for each commit, generate attachment text for i, commit := range p.Commits { content += fmt.Sprintf("%s %s - %s", DiscordSHALinkFormatter(commit.URL, commit.ID[:7]), DiscordTextFormatter(commit.Message), commit.Author.Name) // add linebreak to each commit but the last if i < len(p.Commits)-1 { content += "\n" } } color, _ := strconv.ParseInt(strings.TrimLeft(slack.Color, "#"), 16, 32) return &DiscordPayload{ Username: slack.Username, AvatarURL: slack.IconURL, Embeds: []*DiscordEmbedObject{{ Description: content, URL: conf.Server.ExternalURL + p.Sender.UserName, Color: int(color), Author: &DiscordEmbedAuthorObject{ Name: p.Sender.UserName, IconURL: p.Sender.AvatarUrl, }, }}, } } func getDiscordIssuesPayload(p *api.IssuesPayload, slack *SlackMeta) *DiscordPayload { title := fmt.Sprintf("#%d %s", p.Index, p.Issue.Title) url := fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Index) content := "" fields := make([]*DiscordEmbedFieldObject, 0, 1) switch p.Action { case api.HOOK_ISSUE_OPENED: title = "New issue: " + title content = p.Issue.Body case api.HOOK_ISSUE_CLOSED: title = "Issue closed: " + title case api.HOOK_ISSUE_REOPENED: title = "Issue re-opened: " + title case api.HOOK_ISSUE_EDITED: title = "Issue edited: " + title content = p.Issue.Body case api.HOOK_ISSUE_ASSIGNED: title = "Issue assigned: " + title fields = []*DiscordEmbedFieldObject{{ Name: "New Assignee", Value: p.Issue.Assignee.UserName, }} case api.HOOK_ISSUE_UNASSIGNED: title = "Issue unassigned: " + title case api.HOOK_ISSUE_LABEL_UPDATED: title = "Issue labels updated: " + title labels := make([]string, len(p.Issue.Labels)) for i := range p.Issue.Labels { labels[i] = p.Issue.Labels[i].Name } if len(labels) == 0 { labels = []string{"<empty>"} } fields = []*DiscordEmbedFieldObject{{ Name: "Labels", Value: strings.Join(labels, ", "), }} case api.HOOK_ISSUE_LABEL_CLEARED: title = "Issue labels cleared: " + title case api.HOOK_ISSUE_SYNCHRONIZED: title = "Issue synchronized: " + title case api.HOOK_ISSUE_MILESTONED: title = "Issue milestoned: " + title fields = []*DiscordEmbedFieldObject{{ Name: "New Milestone", Value: p.Issue.Milestone.Title, }} case api.HOOK_ISSUE_DEMILESTONED: title = "Issue demilestoned: " + title } color, _ := strconv.ParseInt(strings.TrimLeft(slack.Color, "#"), 16, 32) return &DiscordPayload{ Username: slack.Username, AvatarURL: slack.IconURL, Embeds: []*DiscordEmbedObject{{ Title: title, Description: content, URL: url, Color: int(color), Footer: &DiscordEmbedFooterObject{ Text: p.Repository.FullName, }, Author: &DiscordEmbedAuthorObject{ Name: p.Sender.UserName, IconURL: p.Sender.AvatarUrl, }, Fields: fields, }}, } } func getDiscordIssueCommentPayload(p *api.IssueCommentPayload, slack *SlackMeta) *DiscordPayload { title := fmt.Sprintf("#%d %s", p.Issue.Index, p.Issue.Title) url := fmt.Sprintf("%s/issues/%d#%s", p.Repository.HTMLURL, p.Issue.Index, CommentHashTag(p.Comment.ID)) content := "" fields := make([]*DiscordEmbedFieldObject, 0, 1) switch p.Action { case api.HOOK_ISSUE_COMMENT_CREATED: title = "New comment: " + title content = p.Comment.Body case api.HOOK_ISSUE_COMMENT_EDITED: title = "Comment edited: " + title content = p.Comment.Body case api.HOOK_ISSUE_COMMENT_DELETED: title = "Comment deleted: " + title url = fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Issue.Index) content = p.Comment.Body } color, _ := strconv.ParseInt(strings.TrimLeft(slack.Color, "#"), 16, 32) return &DiscordPayload{ Username: slack.Username, AvatarURL: slack.IconURL, Embeds: []*DiscordEmbedObject{{ Title: title, Description: content, URL: url, Color: int(color), Footer: &DiscordEmbedFooterObject{ Text: p.Repository.FullName, }, Author: &DiscordEmbedAuthorObject{ Name: p.Sender.UserName, IconURL: p.Sender.AvatarUrl, }, Fields: fields, }}, } } func getDiscordPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) *DiscordPayload { title := fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title) url := fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index) content := "" fields := make([]*DiscordEmbedFieldObject, 0, 1) switch p.Action { case api.HOOK_ISSUE_OPENED: title = "New pull request: " + title content = p.PullRequest.Body case api.HOOK_ISSUE_CLOSED: if p.PullRequest.HasMerged { title = "Pull request merged: " + title } else { title = "Pull request closed: " + title } case api.HOOK_ISSUE_REOPENED: title = "Pull request re-opened: " + title case api.HOOK_ISSUE_EDITED: title = "Pull request edited: " + title content = p.PullRequest.Body case api.HOOK_ISSUE_ASSIGNED: title = "Pull request assigned: " + title fields = []*DiscordEmbedFieldObject{{ Name: "New Assignee", Value: p.PullRequest.Assignee.UserName, }} case api.HOOK_ISSUE_UNASSIGNED: title = "Pull request unassigned: " + title case api.HOOK_ISSUE_LABEL_UPDATED: title = "Pull request labels updated: " + title labels := make([]string, len(p.PullRequest.Labels)) for i := range p.PullRequest.Labels { labels[i] = p.PullRequest.Labels[i].Name } fields = []*DiscordEmbedFieldObject{{ Name: "Labels", Value: strings.Join(labels, ", "), }} case api.HOOK_ISSUE_LABEL_CLEARED: title = "Pull request labels cleared: " + title case api.HOOK_ISSUE_SYNCHRONIZED: title = "Pull request synchronized: " + title case api.HOOK_ISSUE_MILESTONED: title = "Pull request milestoned: " + title fields = []*DiscordEmbedFieldObject{{ Name: "New Milestone", Value: p.PullRequest.Milestone.Title, }} case api.HOOK_ISSUE_DEMILESTONED: title = "Pull request demilestoned: " + title } color, _ := strconv.ParseInt(strings.TrimLeft(slack.Color, "#"), 16, 32) return &DiscordPayload{ Username: slack.Username, AvatarURL: slack.IconURL, Embeds: []*DiscordEmbedObject{{ Title: title, Description: content, URL: url, Color: int(color), Footer: &DiscordEmbedFooterObject{ Text: p.Repository.FullName, }, Author: &DiscordEmbedAuthorObject{ Name: p.Sender.UserName, IconURL: p.Sender.AvatarUrl, }, Fields: fields, }}, } } func getDiscordReleasePayload(p *api.ReleasePayload) *DiscordPayload { repoLink := DiscordLinkFormatter(p.Repository.HTMLURL, p.Repository.Name) refLink := DiscordLinkFormatter(p.Repository.HTMLURL+"/src/"+p.Release.TagName, p.Release.TagName) content := fmt.Sprintf("Published new release %s of %s", refLink, repoLink) return &DiscordPayload{ Embeds: []*DiscordEmbedObject{{ Description: content, URL: conf.Server.ExternalURL + p.Sender.UserName, Author: &DiscordEmbedAuthorObject{ Name: p.Sender.UserName, IconURL: p.Sender.AvatarUrl, }, }}, } } func GetDiscordPayload(p api.Payloader, event HookEventType, meta string) (payload *DiscordPayload, err error) { slack := &SlackMeta{} if err := jsoniter.Unmarshal([]byte(meta), &slack); err != nil { return nil, fmt.Errorf("jsoniter.Unmarshal: %v", err) } switch event { case HookEventTypeCreate: payload = getDiscordCreatePayload(p.(*api.CreatePayload)) case HookEventTypeDelete: payload = getDiscordDeletePayload(p.(*api.DeletePayload)) case HookEventTypeFork: payload = getDiscordForkPayload(p.(*api.ForkPayload)) case HookEventTypePush: payload = getDiscordPushPayload(p.(*api.PushPayload), slack) case HookEventTypeIssues: payload = getDiscordIssuesPayload(p.(*api.IssuesPayload), slack) case HookEventTypeIssueComment: payload = getDiscordIssueCommentPayload(p.(*api.IssueCommentPayload), slack) case HookEventTypePullRequest: payload = getDiscordPullRequestPayload(p.(*api.PullRequestPayload), slack) case HookEventTypeRelease: payload = getDiscordReleasePayload(p.(*api.ReleasePayload)) default: return nil, errors.Errorf("unexpected event %q", event) } payload.Username = slack.Username payload.AvatarURL = slack.IconURL if len(payload.Embeds) > 0 { color, _ := strconv.ParseInt(strings.TrimLeft(slack.Color, "#"), 16, 32) payload.Embeds[0].Color = int(color) } return payload, nil }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/repo_editor.go
internal/database/repo_editor.go
// Copyright 2016 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 database import ( "fmt" "io" "mime/multipart" "os" "os/exec" "path" "path/filepath" "strings" "time" "github.com/pkg/errors" gouuid "github.com/satori/go.uuid" "github.com/unknwon/com" "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/cryptoutil" dberrors "gogs.io/gogs/internal/database/errors" "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/osutil" "gogs.io/gogs/internal/pathutil" "gogs.io/gogs/internal/process" "gogs.io/gogs/internal/tool" ) const ( EnvAuthUserID = "GOGS_AUTH_USER_ID" EnvAuthUserName = "GOGS_AUTH_USER_NAME" EnvAuthUserEmail = "GOGS_AUTH_USER_EMAIL" EnvRepoOwnerName = "GOGS_REPO_OWNER_NAME" EnvRepoOwnerSaltMd5 = "GOGS_REPO_OWNER_SALT_MD5" EnvRepoID = "GOGS_REPO_ID" EnvRepoName = "GOGS_REPO_NAME" EnvRepoCustomHooksPath = "GOGS_REPO_CUSTOM_HOOKS_PATH" ) type ComposeHookEnvsOptions struct { AuthUser *User OwnerName string OwnerSalt string RepoID int64 RepoName string RepoPath string } func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string { envs := []string{ "SSH_ORIGINAL_COMMAND=1", EnvAuthUserID + "=" + com.ToStr(opts.AuthUser.ID), EnvAuthUserName + "=" + opts.AuthUser.Name, EnvAuthUserEmail + "=" + opts.AuthUser.Email, EnvRepoOwnerName + "=" + opts.OwnerName, EnvRepoOwnerSaltMd5 + "=" + cryptoutil.MD5(opts.OwnerSalt), EnvRepoID + "=" + com.ToStr(opts.RepoID), EnvRepoName + "=" + opts.RepoName, EnvRepoCustomHooksPath + "=" + filepath.Join(opts.RepoPath, "custom_hooks"), } return envs } // ___________ .___.__ __ ___________.__.__ // \_ _____/ __| _/|__|/ |_ \_ _____/|__| | ____ // | __)_ / __ | | \ __\ | __) | | | _/ __ \ // | \/ /_/ | | || | | \ | | |_\ ___/ // /_______ /\____ | |__||__| \___ / |__|____/\___ > // \/ \/ \/ \/ // discardLocalRepoBranchChanges discards local commits/changes of // given branch to make sure it is even to remote branch. func discardLocalRepoBranchChanges(localPath, branch string) error { if !com.IsExist(localPath) { return nil } // No need to check if nothing in the repository. if !git.RepoHasBranch(localPath, branch) { return nil } rev := "origin/" + branch if err := git.Reset(localPath, rev, git.ResetOptions{Hard: true}); err != nil { return fmt.Errorf("reset [revision: %s]: %v", rev, err) } return nil } func (r *Repository) DiscardLocalRepoBranchChanges(branch string) error { return discardLocalRepoBranchChanges(r.LocalCopyPath(), branch) } // CheckoutNewBranch checks out to a new branch from the a branch name. func (r *Repository) CheckoutNewBranch(oldBranch, newBranch string) error { if err := git.Checkout(r.LocalCopyPath(), newBranch, git.CheckoutOptions{ BaseBranch: oldBranch, Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second, }); err != nil { return fmt.Errorf("checkout [base: %s, new: %s]: %v", oldBranch, newBranch, err) } return nil } type UpdateRepoFileOptions struct { OldBranch string NewBranch string OldTreeName string NewTreeName string Message string Content string IsNewFile bool } // UpdateRepoFile adds or updates a file in repository. func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) { // 🚨 SECURITY: Prevent uploading files into the ".git" directory. if isRepositoryGitPath(opts.NewTreeName) { return errors.Errorf("bad tree path %q", opts.NewTreeName) } repoWorkingPool.CheckIn(com.ToStr(r.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID)) if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err) } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil { return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) } repoPath := r.RepoPath() localPath := r.LocalCopyPath() if opts.OldBranch != opts.NewBranch { // Directly return error if new branch already exists in the server if git.RepoHasBranch(repoPath, opts.NewBranch) { return dberrors.BranchAlreadyExists{Name: opts.NewBranch} } // Otherwise, delete branch from local copy in case out of sync if git.RepoHasBranch(localPath, opts.NewBranch) { if err = git.DeleteBranch(localPath, opts.NewBranch, git.DeleteBranchOptions{ Force: true, }); err != nil { return fmt.Errorf("delete branch %q: %v", opts.NewBranch, err) } } if err := r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil { return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err) } } oldFilePath := path.Join(localPath, opts.OldTreeName) filePath := path.Join(localPath, opts.NewTreeName) if err = os.MkdirAll(path.Dir(filePath), os.ModePerm); err != nil { return err } // If it's meant to be a new file, make sure it doesn't exist. if opts.IsNewFile { // 🚨 SECURITY: Prevent updating files in surprising place, check if the file is // a symlink. if osutil.IsSymlink(filePath) { return fmt.Errorf("cannot update symbolic link: %s", opts.NewTreeName) } if osutil.IsExist(filePath) { return ErrRepoFileAlreadyExist{filePath} } } // Ignore move step if it's a new file under a directory. // Otherwise, move the file when name changed. if osutil.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName { // 🚨 SECURITY: Prevent updating files in surprising place, check if the file is // a symlink. if osutil.IsSymlink(oldFilePath) { return fmt.Errorf("cannot move symbolic link: %s", opts.OldTreeName) } if err = git.Move(localPath, opts.OldTreeName, opts.NewTreeName); err != nil { return fmt.Errorf("git mv %q %q: %v", opts.OldTreeName, opts.NewTreeName, err) } } if err = os.WriteFile(filePath, []byte(opts.Content), 0600); err != nil { return fmt.Errorf("write file: %v", err) } if err = git.Add(localPath, git.AddOptions{All: true}); err != nil { return fmt.Errorf("git add --all: %v", err) } err = git.CreateCommit( localPath, &git.Signature{ Name: doer.DisplayName(), Email: doer.Email, When: time.Now(), }, opts.Message, ) if err != nil { return fmt.Errorf("commit changes on %q: %v", localPath, err) } err = git.Push(localPath, "origin", opts.NewBranch, git.PushOptions{ CommandOptions: git.CommandOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ AuthUser: doer, OwnerName: r.MustOwner().Name, OwnerSalt: r.MustOwner().Salt, RepoID: r.ID, RepoName: r.Name, RepoPath: r.RepoPath(), }), }, }, ) if err != nil { return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err) } return nil } // GetDiffPreview produces and returns diff result of a file which is not yet committed. func (r *Repository) GetDiffPreview(branch, treePath, content string) (diff *gitutil.Diff, err error) { // 🚨 SECURITY: Prevent uploading files into the ".git" directory. if isRepositoryGitPath(treePath) { return nil, errors.Errorf("bad tree path %q", treePath) } repoWorkingPool.CheckIn(com.ToStr(r.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID)) if err = r.DiscardLocalRepoBranchChanges(branch); err != nil { return nil, fmt.Errorf("discard local r branch[%s] changes: %v", branch, err) } else if err = r.UpdateLocalCopyBranch(branch); err != nil { return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err) } localPath := r.LocalCopyPath() filePath := path.Join(localPath, treePath) // 🚨 SECURITY: Prevent updating files in surprising place, check if the target is // a symlink. if osutil.IsSymlink(filePath) { return nil, fmt.Errorf("cannot get diff preview for symbolic link: %s", treePath) } if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { return nil, err } else if err = os.WriteFile(filePath, []byte(content), 0600); err != nil { return nil, fmt.Errorf("write file: %v", err) } // 🚨 SECURITY: Prevent including unintended options in the path to the Git command. cmd := exec.Command("git", "diff", "--end-of-options", treePath) cmd.Dir = localPath cmd.Stderr = os.Stderr stdout, err := cmd.StdoutPipe() if err != nil { return nil, fmt.Errorf("get stdout pipe: %v", err) } if err = cmd.Start(); err != nil { return nil, fmt.Errorf("start: %v", err) } pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", r.RepoPath()), cmd) defer process.Remove(pid) diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars) if err != nil { return nil, fmt.Errorf("parse diff: %v", err) } if err = cmd.Wait(); err != nil { return nil, fmt.Errorf("wait: %v", err) } return diff, nil } // ________ .__ __ ___________.__.__ // \______ \ ____ | | _____/ |_ ____ \_ _____/|__| | ____ // | | \_/ __ \| | _/ __ \ __\/ __ \ | __) | | | _/ __ \ // | ` \ ___/| |_\ ___/| | \ ___/ | \ | | |_\ ___/ // /_______ /\___ >____/\___ >__| \___ > \___ / |__|____/\___ > // \/ \/ \/ \/ \/ \/ // type DeleteRepoFileOptions struct { LastCommitID string OldBranch string NewBranch string TreePath string Message string } func (r *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) { // 🚨 SECURITY: Prevent uploading files into the ".git" directory. if isRepositoryGitPath(opts.TreePath) { return errors.Errorf("bad tree path %q", opts.TreePath) } repoWorkingPool.CheckIn(com.ToStr(r.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID)) if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err) } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil { return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) } if opts.OldBranch != opts.NewBranch { if err := r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil { return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err) } } localPath := r.LocalCopyPath() filePath := path.Join(localPath, opts.TreePath) // 🚨 SECURITY: Prevent updating files in surprising place, check if the file is // a symlink. if osutil.IsSymlink(filePath) { return fmt.Errorf("cannot delete symbolic link: %s", opts.TreePath) } if err = os.Remove(filePath); err != nil { return fmt.Errorf("remove file %q: %v", opts.TreePath, err) } if err = git.Add(localPath, git.AddOptions{All: true}); err != nil { return fmt.Errorf("git add --all: %v", err) } err = git.CreateCommit( localPath, &git.Signature{ Name: doer.DisplayName(), Email: doer.Email, When: time.Now(), }, opts.Message, ) if err != nil { return fmt.Errorf("commit changes to %q: %v", localPath, err) } err = git.Push(localPath, "origin", opts.NewBranch, git.PushOptions{ CommandOptions: git.CommandOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ AuthUser: doer, OwnerName: r.MustOwner().Name, OwnerSalt: r.MustOwner().Salt, RepoID: r.ID, RepoName: r.Name, RepoPath: r.RepoPath(), }), }, }, ) if err != nil { return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err) } return nil } // ____ ___ .__ .___ ___________.___.__ // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______ // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/ // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \ // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ > // |__| \/ \/ \/ \/ \/ // // Upload represent a uploaded file to a repo to be deleted when moved type Upload struct { ID int64 UUID string `xorm:"uuid UNIQUE"` Name string } // UploadLocalPath returns where uploads is stored in local file system based on given UUID. func UploadLocalPath(uuid string) string { return path.Join(conf.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid) } // LocalPath returns where uploads are temporarily stored in local file system. func (upload *Upload) LocalPath() string { return UploadLocalPath(upload.UUID) } // NewUpload creates a new upload object. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) { if tool.IsMaliciousPath(name) { return nil, fmt.Errorf("malicious path detected: %s", name) } upload := &Upload{ UUID: gouuid.NewV4().String(), Name: name, } localPath := upload.LocalPath() if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil { return nil, fmt.Errorf("mkdir all: %v", err) } fw, err := os.Create(localPath) if err != nil { return nil, fmt.Errorf("create: %v", err) } defer func() { _ = fw.Close() }() if _, err = fw.Write(buf); err != nil { return nil, fmt.Errorf("write: %v", err) } else if _, err = io.Copy(fw, file); err != nil { return nil, fmt.Errorf("copy: %v", err) } if _, err := x.Insert(upload); err != nil { return nil, err } return upload, nil } func GetUploadByUUID(uuid string) (*Upload, error) { upload := &Upload{UUID: uuid} has, err := x.Get(upload) if err != nil { return nil, err } else if !has { return nil, ErrUploadNotExist{0, uuid} } return upload, nil } func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) { if len(uuids) == 0 { return []*Upload{}, nil } // Silently drop invalid uuids. uploads := make([]*Upload, 0, len(uuids)) return uploads, x.In("uuid", uuids).Find(&uploads) } func DeleteUploads(uploads ...*Upload) (err error) { if len(uploads) == 0 { return nil } sess := x.NewSession() defer sess.Close() if err = sess.Begin(); err != nil { return err } ids := make([]int64, len(uploads)) for i := 0; i < len(uploads); i++ { ids[i] = uploads[i].ID } if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil { return fmt.Errorf("delete uploads: %v", err) } for _, upload := range uploads { localPath := upload.LocalPath() if !osutil.IsFile(localPath) { continue } if err := os.Remove(localPath); err != nil { return fmt.Errorf("remove upload: %v", err) } } return sess.Commit() } func DeleteUpload(u *Upload) error { return DeleteUploads(u) } func DeleteUploadByUUID(uuid string) error { upload, err := GetUploadByUUID(uuid) if err != nil { if IsErrUploadNotExist(err) { return nil } return fmt.Errorf("get upload by UUID[%s]: %v", uuid, err) } if err := DeleteUpload(upload); err != nil { return fmt.Errorf("delete upload: %v", err) } return nil } type UploadRepoFileOptions struct { LastCommitID string OldBranch string NewBranch string TreePath string Message string Files []string // In UUID format } // isRepositoryGitPath returns true if given path is or resides inside ".git" // path of the repository. // // TODO(unknwon): Move to repoutil during refactoring for this file. func isRepositoryGitPath(path string) bool { path = strings.ToLower(path) return strings.HasSuffix(path, ".git") || strings.Contains(path, ".git/") || strings.Contains(path, `.git\`) || // Windows treats ".git." the same as ".git" strings.HasSuffix(path, ".git.") || strings.Contains(path, ".git./") || strings.Contains(path, `.git.\`) } func (r *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) error { if len(opts.Files) == 0 { return nil } // 🚨 SECURITY: Prevent uploading files into the ".git" directory. if isRepositoryGitPath(opts.TreePath) { return errors.Errorf("bad tree path %q", opts.TreePath) } uploads, err := GetUploadsByUUIDs(opts.Files) if err != nil { return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err) } repoWorkingPool.CheckIn(com.ToStr(r.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID)) if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err) } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil { return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) } if opts.OldBranch != opts.NewBranch { if err = r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil { return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err) } } localPath := r.LocalCopyPath() dirPath := path.Join(localPath, opts.TreePath) if err = os.MkdirAll(dirPath, os.ModePerm); err != nil { return err } // Copy uploaded files into repository for _, upload := range uploads { tmpPath := upload.LocalPath() if !osutil.IsFile(tmpPath) { continue } // 🚨 SECURITY: Prevent path traversal. upload.Name = pathutil.Clean(upload.Name) // 🚨 SECURITY: Prevent uploading files into the ".git" directory. if isRepositoryGitPath(upload.Name) { continue } targetPath := path.Join(dirPath, upload.Name) // 🚨 SECURITY: Prevent updating files in surprising place, check if the target // is a symlink. if osutil.IsSymlink(targetPath) { return fmt.Errorf("cannot overwrite symbolic link: %s", upload.Name) } if err = com.Copy(tmpPath, targetPath); err != nil { return fmt.Errorf("copy: %v", err) } } if err = git.Add(localPath, git.AddOptions{All: true}); err != nil { return fmt.Errorf("git add --all: %v", err) } err = git.CreateCommit( localPath, &git.Signature{ Name: doer.DisplayName(), Email: doer.Email, When: time.Now(), }, opts.Message, ) if err != nil { return fmt.Errorf("commit changes on %q: %v", localPath, err) } err = git.Push(localPath, "origin", opts.NewBranch, git.PushOptions{ CommandOptions: git.CommandOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ AuthUser: doer, OwnerName: r.MustOwner().Name, OwnerSalt: r.MustOwner().Salt, RepoID: r.ID, RepoName: r.Name, RepoPath: r.RepoPath(), }), }, }, ) if err != nil { return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err) } return DeleteUploads(uploads...) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/actions.go
internal/database/actions.go
// Copyright 2020 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 database import ( "context" "fmt" "path" "strconv" "strings" "time" "unicode" "github.com/gogs/git-module" api "github.com/gogs/go-gogs-client" jsoniter "github.com/json-iterator/go" "github.com/pkg/errors" "gorm.io/gorm" log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/lazyregexp" "gogs.io/gogs/internal/repoutil" "gogs.io/gogs/internal/strutil" "gogs.io/gogs/internal/testutil" "gogs.io/gogs/internal/tool" ) // ActionsStore is the storage layer for actions. type ActionsStore struct { db *gorm.DB } func newActionsStore(db *gorm.DB) *ActionsStore { return &ActionsStore{db: db} } func (s *ActionsStore) listByOrganization(ctx context.Context, orgID, actorID, afterID int64) *gorm.DB { /* Equivalent SQL for PostgreSQL: SELECT * FROM "action" WHERE user_id = @userID AND (@skipAfter OR id < @afterID) AND repo_id IN ( SELECT repository.id FROM "repository" JOIN team_repo ON repository.id = team_repo.repo_id WHERE team_repo.team_id IN ( SELECT team_id FROM "team_user" WHERE team_user.org_id = @orgID AND uid = @actorID) OR (repository.is_private = FALSE AND repository.is_unlisted = FALSE) ) ORDER BY id DESC LIMIT @limit */ return s.db.WithContext(ctx). Where("user_id = ?", orgID). Where(s.db. // Not apply when afterID is not given Where("?", afterID <= 0). Or("id < ?", afterID), ). Where("repo_id IN (?)", s.db. Select("repository.id"). Table("repository"). Joins("JOIN team_repo ON repository.id = team_repo.repo_id"). Where("team_repo.team_id IN (?)", s.db. Select("team_id"). Table("team_user"). Where("team_user.org_id = ? AND uid = ?", orgID, actorID), ). Or("repository.is_private = ? AND repository.is_unlisted = ?", false, false), ). Limit(conf.UI.User.NewsFeedPagingNum). Order("id DESC") } // ListByOrganization returns actions of the organization viewable by the actor. // Results are paginated if `afterID` is given. func (s *ActionsStore) ListByOrganization(ctx context.Context, orgID, actorID, afterID int64) ([]*Action, error) { actions := make([]*Action, 0, conf.UI.User.NewsFeedPagingNum) return actions, s.listByOrganization(ctx, orgID, actorID, afterID).Find(&actions).Error } func (s *ActionsStore) listByUser(ctx context.Context, userID, actorID, afterID int64, isProfile bool) *gorm.DB { /* Equivalent SQL for PostgreSQL: SELECT * FROM "action" WHERE user_id = @userID AND (@skipAfter OR id < @afterID) AND (@includePrivate OR (is_private = FALSE AND act_user_id = @actorID)) ORDER BY id DESC LIMIT @limit */ return s.db.WithContext(ctx). Where("user_id = ?", userID). Where(s.db. // Not apply when afterID is not given Where("?", afterID <= 0). Or("id < ?", afterID), ). Where(s.db. // Not apply when in not profile page or the user is viewing own profile Where("?", !isProfile || actorID == userID). Or("is_private = ? AND act_user_id = ?", false, userID), ). Limit(conf.UI.User.NewsFeedPagingNum). Order("id DESC") } // ListByUser returns actions of the user viewable by the actor. Results are // paginated if `afterID` is given. The `isProfile` indicates whether repository // permissions should be considered. func (s *ActionsStore) ListByUser(ctx context.Context, userID, actorID, afterID int64, isProfile bool) ([]*Action, error) { actions := make([]*Action, 0, conf.UI.User.NewsFeedPagingNum) return actions, s.listByUser(ctx, userID, actorID, afterID, isProfile).Find(&actions).Error } // notifyWatchers creates rows in action table for watchers who are able to see the action. func (s *ActionsStore) notifyWatchers(ctx context.Context, act *Action) error { watches, err := newReposStore(s.db).ListWatches(ctx, act.RepoID) if err != nil { return errors.Wrap(err, "list watches") } // Clone returns a deep copy of the action with UserID assigned clone := func(userID int64) *Action { tmp := *act tmp.UserID = userID return &tmp } // Plus one for the actor actions := make([]*Action, 0, len(watches)+1) actions = append(actions, clone(act.ActUserID)) for _, watch := range watches { if act.ActUserID == watch.UserID { continue } actions = append(actions, clone(watch.UserID)) } return s.db.Create(actions).Error } // NewRepo creates an action for creating a new repository. The action type // could be ActionCreateRepo or ActionForkRepo based on whether the repository // is a fork. func (s *ActionsStore) NewRepo(ctx context.Context, doer, owner *User, repo *Repository) error { opType := ActionCreateRepo if repo.IsFork { opType = ActionForkRepo } return s.notifyWatchers(ctx, &Action{ ActUserID: doer.ID, ActUserName: doer.Name, OpType: opType, RepoID: repo.ID, RepoUserName: owner.Name, RepoName: repo.Name, IsPrivate: repo.IsPrivate || repo.IsUnlisted, }, ) } // RenameRepo creates an action for renaming a repository. func (s *ActionsStore) RenameRepo(ctx context.Context, doer, owner *User, oldRepoName string, repo *Repository) error { return s.notifyWatchers(ctx, &Action{ ActUserID: doer.ID, ActUserName: doer.Name, OpType: ActionRenameRepo, RepoID: repo.ID, RepoUserName: owner.Name, RepoName: repo.Name, IsPrivate: repo.IsPrivate || repo.IsUnlisted, Content: oldRepoName, }, ) } func (s *ActionsStore) mirrorSyncAction(ctx context.Context, opType ActionType, owner *User, repo *Repository, refName string, content []byte) error { return s.notifyWatchers(ctx, &Action{ ActUserID: owner.ID, ActUserName: owner.Name, OpType: opType, Content: string(content), RepoID: repo.ID, RepoUserName: owner.Name, RepoName: repo.Name, RefName: refName, IsPrivate: repo.IsPrivate || repo.IsUnlisted, }, ) } type MirrorSyncPushOptions struct { Owner *User Repo *Repository RefName string OldCommitID string NewCommitID string Commits *PushCommits } // MirrorSyncPush creates an action for mirror synchronization of pushed // commits. func (s *ActionsStore) MirrorSyncPush(ctx context.Context, opts MirrorSyncPushOptions) error { if conf.UI.FeedMaxCommitNum > 0 && len(opts.Commits.Commits) > conf.UI.FeedMaxCommitNum { opts.Commits.Commits = opts.Commits.Commits[:conf.UI.FeedMaxCommitNum] } apiCommits, err := opts.Commits.APIFormat(ctx, newUsersStore(s.db), repoutil.RepositoryPath(opts.Owner.Name, opts.Repo.Name), repoutil.HTMLURL(opts.Owner.Name, opts.Repo.Name), ) if err != nil { return errors.Wrap(err, "convert commits to API format") } opts.Commits.CompareURL = repoutil.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID) apiPusher := opts.Owner.APIFormat() err = PrepareWebhooks( opts.Repo, HookEventTypePush, &api.PushPayload{ Ref: opts.RefName, Before: opts.OldCommitID, After: opts.NewCommitID, CompareURL: conf.Server.ExternalURL + opts.Commits.CompareURL, Commits: apiCommits, Repo: opts.Repo.APIFormat(opts.Owner), Pusher: apiPusher, Sender: apiPusher, }, ) if err != nil { return errors.Wrap(err, "prepare webhooks") } data, err := jsoniter.Marshal(opts.Commits) if err != nil { return errors.Wrap(err, "marshal JSON") } return s.mirrorSyncAction(ctx, ActionMirrorSyncPush, opts.Owner, opts.Repo, opts.RefName, data) } // MirrorSyncCreate creates an action for mirror synchronization of a new // reference. func (s *ActionsStore) MirrorSyncCreate(ctx context.Context, owner *User, repo *Repository, refName string) error { return s.mirrorSyncAction(ctx, ActionMirrorSyncCreate, owner, repo, refName, nil) } // MirrorSyncDelete creates an action for mirror synchronization of a reference // deletion. func (s *ActionsStore) MirrorSyncDelete(ctx context.Context, owner *User, repo *Repository, refName string) error { return s.mirrorSyncAction(ctx, ActionMirrorSyncDelete, owner, repo, refName, nil) } // MergePullRequest creates an action for merging a pull request. func (s *ActionsStore) MergePullRequest(ctx context.Context, doer, owner *User, repo *Repository, pull *Issue) error { return s.notifyWatchers(ctx, &Action{ ActUserID: doer.ID, ActUserName: doer.Name, OpType: ActionMergePullRequest, Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title), RepoID: repo.ID, RepoUserName: owner.Name, RepoName: repo.Name, IsPrivate: repo.IsPrivate || repo.IsUnlisted, }, ) } // TransferRepo creates an action for transferring a repository to a new owner. func (s *ActionsStore) TransferRepo(ctx context.Context, doer, oldOwner, newOwner *User, repo *Repository) error { return s.notifyWatchers(ctx, &Action{ ActUserID: doer.ID, ActUserName: doer.Name, OpType: ActionTransferRepo, RepoID: repo.ID, RepoUserName: newOwner.Name, RepoName: repo.Name, IsPrivate: repo.IsPrivate || repo.IsUnlisted, Content: oldOwner.Name + "/" + repo.Name, }, ) } var ( // Same as GitHub, see https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue issueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"} issueReopenKeywords = []string{"reopen", "reopens", "reopened"} issueCloseKeywordsPattern = lazyregexp.New(assembleKeywordsPattern(issueCloseKeywords)) issueReopenKeywordsPattern = lazyregexp.New(assembleKeywordsPattern(issueReopenKeywords)) issueReferencePattern = lazyregexp.New(`(?i)(?:)(^| )\S*#\d+`) ) func assembleKeywordsPattern(words []string) string { return fmt.Sprintf(`(?i)(?:%s) \S+`, strings.Join(words, "|")) } // updateCommitReferencesToIssues checks if issues are manipulated by commit message. func updateCommitReferencesToIssues(doer *User, repo *Repository, commits []*PushCommit) error { trimRightNonDigits := func(c rune) bool { return !unicode.IsDigit(c) } // Commits are appended in the reverse order. for i := len(commits) - 1; i >= 0; i-- { c := commits[i] refMarked := make(map[int64]bool) for _, ref := range issueReferencePattern.FindAllString(c.Message, -1) { ref = strings.TrimSpace(ref) ref = strings.TrimRightFunc(ref, trimRightNonDigits) if ref == "" { continue } // Add repo name if missing if ref[0] == '#' { ref = fmt.Sprintf("%s%s", repo.FullName(), ref) } else if !strings.Contains(ref, "/") { // FIXME: We don't support User#ID syntax yet continue } issue, err := GetIssueByRef(ref) if err != nil { if IsErrIssueNotExist(err) { continue } return err } if refMarked[issue.ID] { continue } refMarked[issue.ID] = true msgLines := strings.Split(c.Message, "\n") shortMsg := msgLines[0] if len(msgLines) > 2 { shortMsg += "..." } message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, shortMsg) if err = CreateRefComment(doer, repo, issue, message, c.Sha1); err != nil { return err } } refMarked = make(map[int64]bool) // FIXME: Can merge this and the next for loop to a common function. for _, ref := range issueCloseKeywordsPattern.FindAllString(c.Message, -1) { ref = ref[strings.IndexByte(ref, byte(' '))+1:] ref = strings.TrimRightFunc(ref, trimRightNonDigits) if ref == "" { continue } // Add repo name if missing if ref[0] == '#' { ref = fmt.Sprintf("%s%s", repo.FullName(), ref) } else if !strings.Contains(ref, "/") { // FIXME: We don't support User#ID syntax yet continue } issue, err := GetIssueByRef(ref) if err != nil { if IsErrIssueNotExist(err) { continue } return err } if refMarked[issue.ID] { continue } refMarked[issue.ID] = true if issue.RepoID != repo.ID || issue.IsClosed { continue } if err = issue.ChangeStatus(doer, repo, true); err != nil { return err } } // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here. for _, ref := range issueReopenKeywordsPattern.FindAllString(c.Message, -1) { ref = ref[strings.IndexByte(ref, byte(' '))+1:] ref = strings.TrimRightFunc(ref, trimRightNonDigits) if ref == "" { continue } // Add repo name if missing if ref[0] == '#' { ref = fmt.Sprintf("%s%s", repo.FullName(), ref) } else if !strings.Contains(ref, "/") { // We don't support User#ID syntax yet // return ErrNotImplemented continue } issue, err := GetIssueByRef(ref) if err != nil { if IsErrIssueNotExist(err) { continue } return err } if refMarked[issue.ID] { continue } refMarked[issue.ID] = true if issue.RepoID != repo.ID || !issue.IsClosed { continue } if err = issue.ChangeStatus(doer, repo, false); err != nil { return err } } } return nil } type CommitRepoOptions struct { Owner *User Repo *Repository PusherName string RefFullName string OldCommitID string NewCommitID string Commits *PushCommits } // CommitRepo creates actions for pushing commits to the repository. An action // with the type ActionDeleteBranch is created if the push deletes a branch; an // action with the type ActionCommitRepo is created for a regular push. If the // regular push also creates a new branch, then another action with type // ActionCreateBranch is created. func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) error { err := newReposStore(s.db).Touch(ctx, opts.Repo.ID) if err != nil { return errors.Wrap(err, "touch repository") } pusher, err := newUsersStore(s.db).GetByUsername(ctx, opts.PusherName) if err != nil { return errors.Wrapf(err, "get pusher [name: %s]", opts.PusherName) } isNewRef := opts.OldCommitID == git.EmptyID isDelRef := opts.NewCommitID == git.EmptyID // If not the first commit, set the compare URL. if !isNewRef && !isDelRef { opts.Commits.CompareURL = repoutil.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID) } refName := git.RefShortName(opts.RefFullName) action := &Action{ ActUserID: pusher.ID, ActUserName: pusher.Name, RepoID: opts.Repo.ID, RepoUserName: opts.Owner.Name, RepoName: opts.Repo.Name, RefName: refName, IsPrivate: opts.Repo.IsPrivate || opts.Repo.IsUnlisted, } apiRepo := opts.Repo.APIFormat(opts.Owner) apiPusher := pusher.APIFormat() if isDelRef { err = PrepareWebhooks( opts.Repo, HookEventTypeDelete, &api.DeletePayload{ Ref: refName, RefType: "branch", PusherType: api.PUSHER_TYPE_USER, Repo: apiRepo, Sender: apiPusher, }, ) if err != nil { return errors.Wrap(err, "prepare webhooks for delete branch") } action.OpType = ActionDeleteBranch err = s.notifyWatchers(ctx, action) if err != nil { return errors.Wrap(err, "notify watchers") } // Delete branch doesn't have anything to push or compare return nil } // Only update issues via commits when internal issue tracker is enabled if opts.Repo.EnableIssues && !opts.Repo.EnableExternalTracker { if err = updateCommitReferencesToIssues(pusher, opts.Repo, opts.Commits.Commits); err != nil { log.Error("update commit references to issues: %v", err) } } if conf.UI.FeedMaxCommitNum > 0 && len(opts.Commits.Commits) > conf.UI.FeedMaxCommitNum { opts.Commits.Commits = opts.Commits.Commits[:conf.UI.FeedMaxCommitNum] } data, err := jsoniter.Marshal(opts.Commits) if err != nil { return errors.Wrap(err, "marshal JSON") } action.Content = string(data) var compareURL string if isNewRef { err = PrepareWebhooks( opts.Repo, HookEventTypeCreate, &api.CreatePayload{ Ref: refName, RefType: "branch", DefaultBranch: opts.Repo.DefaultBranch, Repo: apiRepo, Sender: apiPusher, }, ) if err != nil { return errors.Wrap(err, "prepare webhooks for new branch") } action.OpType = ActionCreateBranch err = s.notifyWatchers(ctx, action) if err != nil { return errors.Wrap(err, "notify watchers") } } else { compareURL = conf.Server.ExternalURL + opts.Commits.CompareURL } commits, err := opts.Commits.APIFormat(ctx, newUsersStore(s.db), repoutil.RepositoryPath(opts.Owner.Name, opts.Repo.Name), repoutil.HTMLURL(opts.Owner.Name, opts.Repo.Name), ) if err != nil { return errors.Wrap(err, "convert commits to API format") } err = PrepareWebhooks( opts.Repo, HookEventTypePush, &api.PushPayload{ Ref: opts.RefFullName, Before: opts.OldCommitID, After: opts.NewCommitID, CompareURL: compareURL, Commits: commits, Repo: apiRepo, Pusher: apiPusher, Sender: apiPusher, }, ) if err != nil { return errors.Wrap(err, "prepare webhooks for new commit") } action.OpType = ActionCommitRepo err = s.notifyWatchers(ctx, action) if err != nil { return errors.Wrap(err, "notify watchers") } return nil } type PushTagOptions struct { Owner *User Repo *Repository PusherName string RefFullName string NewCommitID string } // PushTag creates an action for pushing tags to the repository. An action with // the type ActionDeleteTag is created if the push deletes a tag. Otherwise, an // action with the type ActionPushTag is created for a regular push. func (s *ActionsStore) PushTag(ctx context.Context, opts PushTagOptions) error { err := newReposStore(s.db).Touch(ctx, opts.Repo.ID) if err != nil { return errors.Wrap(err, "touch repository") } pusher, err := newUsersStore(s.db).GetByUsername(ctx, opts.PusherName) if err != nil { return errors.Wrapf(err, "get pusher [name: %s]", opts.PusherName) } refName := git.RefShortName(opts.RefFullName) action := &Action{ ActUserID: pusher.ID, ActUserName: pusher.Name, RepoID: opts.Repo.ID, RepoUserName: opts.Owner.Name, RepoName: opts.Repo.Name, RefName: refName, IsPrivate: opts.Repo.IsPrivate || opts.Repo.IsUnlisted, } apiRepo := opts.Repo.APIFormat(opts.Owner) apiPusher := pusher.APIFormat() if opts.NewCommitID == git.EmptyID { err = PrepareWebhooks( opts.Repo, HookEventTypeDelete, &api.DeletePayload{ Ref: refName, RefType: "tag", PusherType: api.PUSHER_TYPE_USER, Repo: apiRepo, Sender: apiPusher, }, ) if err != nil { return errors.Wrap(err, "prepare webhooks for delete tag") } action.OpType = ActionDeleteTag err = s.notifyWatchers(ctx, action) if err != nil { return errors.Wrap(err, "notify watchers") } return nil } err = PrepareWebhooks( opts.Repo, HookEventTypeCreate, &api.CreatePayload{ Ref: refName, RefType: "tag", Sha: opts.NewCommitID, DefaultBranch: opts.Repo.DefaultBranch, Repo: apiRepo, Sender: apiPusher, }, ) if err != nil { return errors.Wrapf(err, "prepare webhooks for new tag") } action.OpType = ActionPushTag err = s.notifyWatchers(ctx, action) if err != nil { return errors.Wrap(err, "notify watchers") } return nil } // ActionType is the type of action. type ActionType int // ⚠️ WARNING: Only append to the end of list to maintain backward compatibility. const ( ActionCreateRepo ActionType = iota + 1 // 1 ActionRenameRepo // 2 ActionStarRepo // 3 ActionWatchRepo // 4 ActionCommitRepo // 5 ActionCreateIssue // 6 ActionCreatePullRequest // 7 ActionTransferRepo // 8 ActionPushTag // 9 ActionCommentIssue // 10 ActionMergePullRequest // 11 ActionCloseIssue // 12 ActionReopenIssue // 13 ActionClosePullRequest // 14 ActionReopenPullRequest // 15 ActionCreateBranch // 16 ActionDeleteBranch // 17 ActionDeleteTag // 18 ActionForkRepo // 19 ActionMirrorSyncPush // 20 ActionMirrorSyncCreate // 21 ActionMirrorSyncDelete // 22 ) // Action is a user operation to a repository. It implements template.Actioner // interface to be able to use it in template rendering. type Action struct { ID int64 `gorm:"primaryKey"` UserID int64 `gorm:"index"` // Receiver user ID OpType ActionType ActUserID int64 // Doer user ID ActUserName string // Doer user name ActAvatar string `xorm:"-" gorm:"-" json:"-"` RepoID int64 `xorm:"INDEX" gorm:"index"` RepoUserName string RepoName string RefName string IsPrivate bool `xorm:"NOT NULL DEFAULT false" gorm:"not null;default:FALSE"` Content string `xorm:"TEXT"` Created time.Time `xorm:"-" gorm:"-" json:"-"` CreatedUnix int64 } // BeforeCreate implements the GORM create hook. func (a *Action) BeforeCreate(tx *gorm.DB) error { if a.CreatedUnix <= 0 { a.CreatedUnix = tx.NowFunc().Unix() } return nil } // AfterFind implements the GORM query hook. func (a *Action) AfterFind(_ *gorm.DB) error { a.Created = time.Unix(a.CreatedUnix, 0).Local() return nil } func (a *Action) GetOpType() int { return int(a.OpType) } func (a *Action) GetActUserName() string { return a.ActUserName } func (a *Action) ShortActUserName() string { return strutil.Ellipsis(a.ActUserName, 20) } func (a *Action) GetRepoUserName() string { return a.RepoUserName } func (a *Action) ShortRepoUserName() string { return strutil.Ellipsis(a.RepoUserName, 20) } func (a *Action) GetRepoName() string { return a.RepoName } func (a *Action) ShortRepoName() string { return strutil.Ellipsis(a.RepoName, 33) } func (a *Action) GetRepoPath() string { return path.Join(a.RepoUserName, a.RepoName) } func (a *Action) ShortRepoPath() string { return path.Join(a.ShortRepoUserName(), a.ShortRepoName()) } func (a *Action) GetRepoLink() string { if conf.Server.Subpath != "" { return path.Join(conf.Server.Subpath, a.GetRepoPath()) } return "/" + a.GetRepoPath() } func (a *Action) GetBranch() string { return a.RefName } func (a *Action) GetContent() string { return a.Content } func (a *Action) GetCreate() time.Time { return a.Created } func (a *Action) GetIssueInfos() []string { return strings.SplitN(a.Content, "|", 2) } func (a *Action) GetIssueTitle() string { index, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64) issue, err := GetIssueByIndex(a.RepoID, index) if err != nil { log.Error("Failed to get issue title [repo_id: %d, index: %d]: %v", a.RepoID, index, err) return "error getting issue" } return issue.Title } func (a *Action) GetIssueContent() string { index, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64) issue, err := GetIssueByIndex(a.RepoID, index) if err != nil { log.Error("Failed to get issue content [repo_id: %d, index: %d]: %v", a.RepoID, index, err) return "error getting issue" } return issue.Content } // PushCommit contains information of a pushed commit. type PushCommit struct { Sha1 string Message string AuthorEmail string AuthorName string CommitterEmail string CommitterName string Timestamp time.Time } // PushCommits is a list of pushed commits. type PushCommits struct { Len int Commits []*PushCommit CompareURL string avatars map[string]string } // NewPushCommits returns a new PushCommits. func NewPushCommits() *PushCommits { return &PushCommits{ avatars: make(map[string]string), } } func (pcs *PushCommits) APIFormat(ctx context.Context, usersStore *UsersStore, repoPath, repoURL string) ([]*api.PayloadCommit, error) { // NOTE: We cache query results in case there are many commits in a single push. usernameByEmail := make(map[string]string) getUsernameByEmail := func(email string) (string, error) { username, ok := usernameByEmail[email] if ok { return username, nil } user, err := usersStore.GetByEmail(ctx, email) if err != nil { if IsErrUserNotExist(err) { usernameByEmail[email] = "" return "", nil } return "", err } usernameByEmail[email] = user.Name return user.Name, nil } commits := make([]*api.PayloadCommit, len(pcs.Commits)) for i, commit := range pcs.Commits { authorUsername, err := getUsernameByEmail(commit.AuthorEmail) if err != nil { return nil, errors.Wrap(err, "get author username") } committerUsername, err := getUsernameByEmail(commit.CommitterEmail) if err != nil { return nil, errors.Wrap(err, "get committer username") } nameStatus := &git.NameStatus{} if !testutil.InTest { nameStatus, err = git.ShowNameStatus(repoPath, commit.Sha1) if err != nil { return nil, errors.Wrapf(err, "show name status [commit_sha1: %s]", commit.Sha1) } } commits[i] = &api.PayloadCommit{ ID: commit.Sha1, Message: commit.Message, URL: fmt.Sprintf("%s/commit/%s", repoURL, commit.Sha1), Author: &api.PayloadUser{ Name: commit.AuthorName, Email: commit.AuthorEmail, UserName: authorUsername, }, Committer: &api.PayloadUser{ Name: commit.CommitterName, Email: commit.CommitterEmail, UserName: committerUsername, }, Added: nameStatus.Added, Removed: nameStatus.Removed, Modified: nameStatus.Modified, Timestamp: commit.Timestamp, } } return commits, nil } // AvatarLink tries to match user in database with email in order to show custom // avatars, and falls back to general avatar link. // // FIXME: This method does not belong to PushCommits, should be a pure template // function. func (pcs *PushCommits) AvatarLink(email string) string { _, ok := pcs.avatars[email] if !ok { u, err := Handle.Users().GetByEmail(context.Background(), email) if err != nil { pcs.avatars[email] = tool.AvatarLink(email) if !IsErrUserNotExist(err) { log.Error("Failed to get user [email: %s]: %v", email, err) } } else { pcs.avatars[email] = u.AvatarURLPath() } } return pcs.avatars[email] }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/lfs.go
internal/database/lfs.go
// Copyright 2020 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 database import ( "context" "errors" "fmt" "time" "gorm.io/gorm" "gogs.io/gogs/internal/errutil" "gogs.io/gogs/internal/lfsutil" ) // LFSObject is the relation between an LFS object and a repository. type LFSObject struct { RepoID int64 `gorm:"primaryKey;auto_increment:false"` OID lfsutil.OID `gorm:"primaryKey;column:oid"` Size int64 `gorm:"not null"` Storage lfsutil.Storage `gorm:"not null"` CreatedAt time.Time `gorm:"not null"` } // LFSStore is the storage layer for LFS objects. type LFSStore struct { db *gorm.DB } func newLFSStore(db *gorm.DB) *LFSStore { return &LFSStore{db: db} } // CreateObject creates an LFS object record in database. func (s *LFSStore) CreateObject(ctx context.Context, repoID int64, oid lfsutil.OID, size int64, storage lfsutil.Storage) error { object := &LFSObject{ RepoID: repoID, OID: oid, Size: size, Storage: storage, } return s.db.WithContext(ctx).Create(object).Error } type ErrLFSObjectNotExist struct { args errutil.Args } func IsErrLFSObjectNotExist(err error) bool { return errors.As(err, &ErrLFSObjectNotExist{}) } func (err ErrLFSObjectNotExist) Error() string { return fmt.Sprintf("LFS object does not exist: %v", err.args) } func (ErrLFSObjectNotExist) NotFound() bool { return true } // GetObjectByOID returns the LFS object with given OID. It returns // ErrLFSObjectNotExist when not found. func (s *LFSStore) GetObjectByOID(ctx context.Context, repoID int64, oid lfsutil.OID) (*LFSObject, error) { object := new(LFSObject) err := s.db.WithContext(ctx).Where("repo_id = ? AND oid = ?", repoID, oid).First(object).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, ErrLFSObjectNotExist{args: errutil.Args{"repoID": repoID, "oid": oid}} } return nil, err } return object, err } // GetObjectsByOIDs returns LFS objects found within "oids". The returned list // could have fewer elements if some oids were not found. func (s *LFSStore) GetObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsutil.OID) ([]*LFSObject, error) { if len(oids) == 0 { return []*LFSObject{}, nil } objects := make([]*LFSObject, 0, len(oids)) err := s.db.WithContext(ctx).Where("repo_id = ? AND oid IN (?)", repoID, oids).Find(&objects).Error if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err } return objects, nil }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false
gogs/gogs
https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/database/actions_test.go
internal/database/actions_test.go
// Copyright 2022 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 database import ( "context" "os" "testing" "time" "github.com/gogs/git-module" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gorm.io/gorm" "gogs.io/gogs/internal/conf" ) func TestIssueReferencePattern(t *testing.T) { tests := []struct { name string message string want []string }{ { name: "no match", message: "Hello world!", want: nil, }, { name: "contains issue numbers", message: "#123 is fixed, and #456 is WIP", want: []string{"#123", " #456"}, }, { name: "contains full issue references", message: "#123 is fixed, and user/repo#456 is WIP", want: []string{"#123", " user/repo#456"}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got := issueReferencePattern.FindAllString(test.message, -1) assert.Equal(t, test.want, got) }) } } func TestAction_BeforeCreate(t *testing.T) { now := time.Now() db := &gorm.DB{ Config: &gorm.Config{ SkipDefaultTransaction: true, NowFunc: func() time.Time { return now }, }, } t.Run("CreatedUnix has been set", func(t *testing.T) { action := &Action{ CreatedUnix: 1, } _ = action.BeforeCreate(db) assert.Equal(t, int64(1), action.CreatedUnix) }) t.Run("CreatedUnix has not been set", func(t *testing.T) { action := &Action{} _ = action.BeforeCreate(db) assert.Equal(t, db.NowFunc().Unix(), action.CreatedUnix) }) } func TestAction_AfterFind(t *testing.T) { now := time.Now() db := &gorm.DB{ Config: &gorm.Config{ SkipDefaultTransaction: true, NowFunc: func() time.Time { return now }, }, } action := &Action{ CreatedUnix: now.Unix(), } _ = action.AfterFind(db) assert.Equal(t, action.CreatedUnix, action.Created.Unix()) } func TestActions(t *testing.T) { if testing.Short() { t.Skip() } ctx := context.Background() t.Parallel() s := &ActionsStore{ db: newTestDB(t, "ActionsStore"), } for _, tc := range []struct { name string test func(t *testing.T, ctx context.Context, s *ActionsStore) }{ {"CommitRepo", actionsCommitRepo}, {"ListByOrganization", actionsListByOrganization}, {"ListByUser", actionsListByUser}, {"MergePullRequest", actionsMergePullRequest}, {"MirrorSyncCreate", actionsMirrorSyncCreate}, {"MirrorSyncDelete", actionsMirrorSyncDelete}, {"MirrorSyncPush", actionsMirrorSyncPush}, {"NewRepo", actionsNewRepo}, {"PushTag", actionsPushTag}, {"RenameRepo", actionsRenameRepo}, {"TransferRepo", actionsTransferRepo}, } { t.Run(tc.name, func(t *testing.T) { t.Cleanup(func() { err := clearTables(t, s.db) require.NoError(t, err) }) tc.test(t, ctx, s) }) if t.Failed() { break } } } func actionsCommitRepo(t *testing.T, ctx context.Context, s *ActionsStore) { alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) now := time.Unix(1588568886, 0).UTC() conf.SetMockSSH(t, conf.SSHOpts{}) t.Run("new commit", func(t *testing.T) { t.Cleanup(func() { err := s.db.Session(&gorm.Session{AllowGlobalUpdate: true}).WithContext(ctx).Delete(new(Action)).Error require.NoError(t, err) }) err = s.CommitRepo(ctx, CommitRepoOptions{ PusherName: alice.Name, Owner: alice, Repo: repo, RefFullName: "refs/heads/main", OldCommitID: "ca82a6dff817ec66f44342007202690a93763949", NewCommitID: "085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7", Commits: CommitsToPushCommits( []*git.Commit{ { ID: git.MustIDFromString("085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7"), Author: &git.Signature{ Name: "alice", Email: "alice@example.com", When: now, }, Committer: &git.Signature{ Name: "alice", Email: "alice@example.com", When: now, }, Message: "A random commit", }, }, ), }, ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionCommitRepo, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "main", IsPrivate: false, Content: `{"Len":1,"Commits":[{"Sha1":"085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7","Message":"A random commit","AuthorEmail":"alice@example.com","AuthorName":"alice","CommitterEmail":"alice@example.com","CommitterName":"alice","Timestamp":"2020-05-04T05:08:06Z"}],"CompareURL":"alice/example/compare/ca82a6dff817ec66f44342007202690a93763949...085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7"}`, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) }) t.Run("new ref", func(t *testing.T) { t.Cleanup(func() { err := s.db.Session(&gorm.Session{AllowGlobalUpdate: true}).WithContext(ctx).Delete(new(Action)).Error require.NoError(t, err) }) err = s.CommitRepo(ctx, CommitRepoOptions{ PusherName: alice.Name, Owner: alice, Repo: repo, RefFullName: "refs/heads/main", OldCommitID: git.EmptyID, NewCommitID: "085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7", Commits: CommitsToPushCommits( []*git.Commit{ { ID: git.MustIDFromString("085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7"), Author: &git.Signature{ Name: "alice", Email: "alice@example.com", When: now, }, Committer: &git.Signature{ Name: "alice", Email: "alice@example.com", When: now, }, Message: "A random commit", }, }, ), }, ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 2) got[0].ID = 0 got[1].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionCommitRepo, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "main", IsPrivate: false, Content: `{"Len":1,"Commits":[{"Sha1":"085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7","Message":"A random commit","AuthorEmail":"alice@example.com","AuthorName":"alice","CommitterEmail":"alice@example.com","CommitterName":"alice","Timestamp":"2020-05-04T05:08:06Z"}],"CompareURL":""}`, CreatedUnix: s.db.NowFunc().Unix(), }, { UserID: alice.ID, OpType: ActionCreateBranch, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "main", IsPrivate: false, Content: `{"Len":1,"Commits":[{"Sha1":"085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7","Message":"A random commit","AuthorEmail":"alice@example.com","AuthorName":"alice","CommitterEmail":"alice@example.com","CommitterName":"alice","Timestamp":"2020-05-04T05:08:06Z"}],"CompareURL":""}`, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) want[1].Created = time.Unix(want[1].CreatedUnix, 0) assert.Equal(t, want, got) }) t.Run("delete ref", func(t *testing.T) { t.Cleanup(func() { err := s.db.Session(&gorm.Session{AllowGlobalUpdate: true}).WithContext(ctx).Delete(new(Action)).Error require.NoError(t, err) }) err = s.CommitRepo(ctx, CommitRepoOptions{ PusherName: alice.Name, Owner: alice, Repo: repo, RefFullName: "refs/heads/main", OldCommitID: "ca82a6dff817ec66f44342007202690a93763949", NewCommitID: git.EmptyID, }, ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionDeleteBranch, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "main", IsPrivate: false, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) }) } func actionsListByOrganization(t *testing.T, ctx context.Context, s *ActionsStore) { if os.Getenv("GOGS_DATABASE_TYPE") != "postgres" { t.Skip("Skipping testing with not using PostgreSQL") return } conf.SetMockUI(t, conf.UIOpts{ User: conf.UIUserOpts{ NewsFeedPagingNum: 20, }, }, ) tests := []struct { name string orgID int64 actorID int64 afterID int64 want string }{ { name: "no afterID", orgID: 1, actorID: 1, afterID: 0, want: `SELECT * FROM "action" WHERE user_id = 1 AND (true OR id < 0) AND repo_id IN (SELECT repository.id FROM "repository" JOIN team_repo ON repository.id = team_repo.repo_id WHERE team_repo.team_id IN (SELECT team_id FROM "team_user" WHERE team_user.org_id = 1 AND uid = 1) OR (repository.is_private = false AND repository.is_unlisted = false)) ORDER BY id DESC LIMIT 20`, }, { name: "has afterID", orgID: 1, actorID: 1, afterID: 5, want: `SELECT * FROM "action" WHERE user_id = 1 AND (false OR id < 5) AND repo_id IN (SELECT repository.id FROM "repository" JOIN team_repo ON repository.id = team_repo.repo_id WHERE team_repo.team_id IN (SELECT team_id FROM "team_user" WHERE team_user.org_id = 1 AND uid = 1) OR (repository.is_private = false AND repository.is_unlisted = false)) ORDER BY id DESC LIMIT 20`, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got := s.db.ToSQL(func(tx *gorm.DB) *gorm.DB { return newActionsStore(tx).listByOrganization(ctx, test.orgID, test.actorID, test.afterID).Find(new(Action)) }) assert.Equal(t, test.want, got) }) } } func actionsListByUser(t *testing.T, ctx context.Context, s *ActionsStore) { if os.Getenv("GOGS_DATABASE_TYPE") != "postgres" { t.Skip("Skipping testing with not using PostgreSQL") return } conf.SetMockUI(t, conf.UIOpts{ User: conf.UIUserOpts{ NewsFeedPagingNum: 20, }, }, ) tests := []struct { name string userID int64 actorID int64 afterID int64 isProfile bool want string }{ { name: "same user no afterID not in profile", userID: 1, actorID: 1, afterID: 0, isProfile: false, want: `SELECT * FROM "action" WHERE user_id = 1 AND (true OR id < 0) AND (true OR (is_private = false AND act_user_id = 1)) ORDER BY id DESC LIMIT 20`, }, { name: "same user no afterID in profile", userID: 1, actorID: 1, afterID: 0, isProfile: true, want: `SELECT * FROM "action" WHERE user_id = 1 AND (true OR id < 0) AND (true OR (is_private = false AND act_user_id = 1)) ORDER BY id DESC LIMIT 20`, }, { name: "same user has afterID not in profile", userID: 1, actorID: 1, afterID: 5, isProfile: false, want: `SELECT * FROM "action" WHERE user_id = 1 AND (false OR id < 5) AND (true OR (is_private = false AND act_user_id = 1)) ORDER BY id DESC LIMIT 20`, }, { name: "different user no afterID in profile", userID: 1, actorID: 2, afterID: 0, isProfile: true, want: `SELECT * FROM "action" WHERE user_id = 1 AND (true OR id < 0) AND (false OR (is_private = false AND act_user_id = 1)) ORDER BY id DESC LIMIT 20`, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got := s.db.ToSQL(func(tx *gorm.DB) *gorm.DB { return newActionsStore(tx).listByUser(ctx, test.userID, test.actorID, test.afterID, test.isProfile).Find(new(Action)) }) assert.Equal(t, test.want, got) }) } } func actionsMergePullRequest(t *testing.T, ctx context.Context, s *ActionsStore) { alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) err = s.MergePullRequest(ctx, alice, alice, repo, &Issue{ Index: 1, Title: "Fix issue 1", }, ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionMergePullRequest, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, IsPrivate: false, Content: `1|Fix issue 1`, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) } func actionsMirrorSyncCreate(t *testing.T, ctx context.Context, s *ActionsStore) { alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) err = s.MirrorSyncCreate(ctx, alice, repo, "main", ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionMirrorSyncCreate, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "main", IsPrivate: false, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) } func actionsMirrorSyncDelete(t *testing.T, ctx context.Context, s *ActionsStore) { alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) err = s.MirrorSyncDelete(ctx, alice, repo, "main", ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionMirrorSyncDelete, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "main", IsPrivate: false, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) } func actionsMirrorSyncPush(t *testing.T, ctx context.Context, s *ActionsStore) { alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) now := time.Unix(1588568886, 0).UTC() err = s.MirrorSyncPush(ctx, MirrorSyncPushOptions{ Owner: alice, Repo: repo, RefName: "main", OldCommitID: "ca82a6dff817ec66f44342007202690a93763949", NewCommitID: "085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7", Commits: CommitsToPushCommits( []*git.Commit{ { ID: git.MustIDFromString("085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7"), Author: &git.Signature{ Name: "alice", Email: "alice@example.com", When: now, }, Committer: &git.Signature{ Name: "alice", Email: "alice@example.com", When: now, }, Message: "A random commit", }, }, ), }, ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionMirrorSyncPush, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "main", IsPrivate: false, Content: `{"Len":1,"Commits":[{"Sha1":"085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7","Message":"A random commit","AuthorEmail":"alice@example.com","AuthorName":"alice","CommitterEmail":"alice@example.com","CommitterName":"alice","Timestamp":"2020-05-04T05:08:06Z"}],"CompareURL":"alice/example/compare/ca82a6dff817ec66f44342007202690a93763949...085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7"}`, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) } func actionsNewRepo(t *testing.T, ctx context.Context, s *ActionsStore) { alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) t.Run("new repo", func(t *testing.T) { t.Cleanup(func() { err := s.db.Session(&gorm.Session{AllowGlobalUpdate: true}).WithContext(ctx).Delete(new(Action)).Error require.NoError(t, err) }) err = s.NewRepo(ctx, alice, alice, repo) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionCreateRepo, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, IsPrivate: false, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) }) t.Run("fork repo", func(t *testing.T) { t.Cleanup(func() { err := s.db.Session(&gorm.Session{AllowGlobalUpdate: true}).WithContext(ctx).Delete(new(Action)).Error require.NoError(t, err) }) repo.IsFork = true err = s.NewRepo(ctx, alice, alice, repo) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionForkRepo, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, IsPrivate: false, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) }) } func actionsPushTag(t *testing.T, ctx context.Context, s *ActionsStore) { // NOTE: We set a noop mock here to avoid data race with other tests that writes // to the mock server because this function holds a lock. conf.SetMockServer(t, conf.ServerOpts{}) conf.SetMockSSH(t, conf.SSHOpts{}) alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) t.Run("new tag", func(t *testing.T) { t.Cleanup(func() { err := s.db.Session(&gorm.Session{AllowGlobalUpdate: true}).WithContext(ctx).Delete(new(Action)).Error require.NoError(t, err) }) err = s.PushTag(ctx, PushTagOptions{ Owner: alice, Repo: repo, PusherName: alice.Name, RefFullName: "refs/tags/v1.0.0", NewCommitID: "085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7", }, ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionPushTag, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "v1.0.0", IsPrivate: false, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) }) t.Run("delete tag", func(t *testing.T) { t.Cleanup(func() { err := s.db.Session(&gorm.Session{AllowGlobalUpdate: true}).WithContext(ctx).Delete(new(Action)).Error require.NoError(t, err) }) err = s.PushTag(ctx, PushTagOptions{ Owner: alice, Repo: repo, PusherName: alice.Name, RefFullName: "refs/tags/v1.0.0", NewCommitID: git.EmptyID, }, ) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionDeleteTag, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, RefName: "v1.0.0", IsPrivate: false, CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) }) } func actionsRenameRepo(t *testing.T, ctx context.Context, s *ActionsStore) { alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) err = s.RenameRepo(ctx, alice, alice, "oldExample", repo) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionRenameRepo, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: alice.Name, RepoName: repo.Name, IsPrivate: false, Content: "oldExample", CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) } func actionsTransferRepo(t *testing.T, ctx context.Context, s *ActionsStore) { alice, err := newUsersStore(s.db).Create(ctx, "alice", "alice@example.com", CreateUserOptions{}) require.NoError(t, err) bob, err := newUsersStore(s.db).Create(ctx, "bob", "bob@example.com", CreateUserOptions{}) require.NoError(t, err) repo, err := newReposStore(s.db).Create(ctx, alice.ID, CreateRepoOptions{ Name: "example", }, ) require.NoError(t, err) err = s.TransferRepo(ctx, alice, alice, bob, repo) require.NoError(t, err) got, err := s.ListByUser(ctx, alice.ID, alice.ID, 0, false) require.NoError(t, err) require.Len(t, got, 1) got[0].ID = 0 want := []*Action{ { UserID: alice.ID, OpType: ActionTransferRepo, ActUserID: alice.ID, ActUserName: alice.Name, RepoID: repo.ID, RepoUserName: bob.Name, RepoName: repo.Name, IsPrivate: false, Content: "alice/example", CreatedUnix: s.db.NowFunc().Unix(), }, } want[0].Created = time.Unix(want[0].CreatedUnix, 0) assert.Equal(t, want, got) }
go
MIT
e68949dd1307d1b72a2fe885976ea0be72ee31d5
2026-01-07T08:35:43.578986Z
false