From 2a449bd4b12545b904cfdd591fcf17afebf6a3c6 Mon Sep 17 00:00:00 2001 From: Bwko Date: Mon, 21 Nov 2016 20:08:21 +0100 Subject: [PATCH 001/135] Fix typos --- models/issue.go | 2 +- models/login_source.go | 12 ++++++------ modules/auth/repo_form.go | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/models/issue.go b/models/issue.go index 09ecb2e6d3..00221b1add 100644 --- a/models/issue.go +++ b/models/issue.go @@ -650,7 +650,7 @@ func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) { } if len(opts.LableIDs) > 0 { - // During the session, SQLite3 dirver cannot handle retrieve objects after update something. + // During the session, SQLite3 driver cannot handle retrieve objects after update something. // So we have to get all needed labels first. labels := make([]*Label, 0, len(opts.LableIDs)) if err = e.In("id", opts.LableIDs).Find(&labels); err != nil { diff --git a/models/login_source.go b/models/login_source.go index 774cb7f4db..14af038fd9 100644 --- a/models/login_source.go +++ b/models/login_source.go @@ -292,8 +292,8 @@ func composeFullName(firstname, surname, username string) string { // LoginViaLDAP queries if login/password is valid against the LDAP directory pool, // and create a local user if success when enabled. -func LoginViaLDAP(user *User, login, passowrd string, source *LoginSource, autoRegister bool) (*User, error) { - username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, passowrd, source.Type == LoginDLDAP) +func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) { + username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP) if !succeed { // User not in LDAP, do nothing return nil, ErrUserNotExist{0, login, 0} @@ -505,7 +505,7 @@ func ExternalUserLogin(user *User, login, password string, source *LoginSource, } // UserSignIn validates user name and password. -func UserSignIn(username, passowrd string) (*User, error) { +func UserSignIn(username, password string) (*User, error) { var user *User if strings.Contains(username, "@") { user = &User{Email: strings.ToLower(username)} @@ -521,7 +521,7 @@ func UserSignIn(username, passowrd string) (*User, error) { if hasUser { switch user.LoginType { case LoginNoType, LoginPlain: - if user.ValidatePassword(passowrd) { + if user.ValidatePassword(password) { return user, nil } @@ -536,7 +536,7 @@ func UserSignIn(username, passowrd string) (*User, error) { return nil, ErrLoginSourceNotExist{user.LoginSource} } - return ExternalUserLogin(user, user.LoginName, passowrd, &source, false) + return ExternalUserLogin(user, user.LoginName, password, &source, false) } } @@ -546,7 +546,7 @@ func UserSignIn(username, passowrd string) (*User, error) { } for _, source := range sources { - authUser, err := ExternalUserLogin(nil, username, passowrd, source, true) + authUser, err := ExternalUserLogin(nil, username, password, source, true) if err == nil { return authUser, nil } diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 1f5330d23a..94c99d8fb9 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -52,7 +52,7 @@ func (f *MigrateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) bi } // ParseRemoteAddr checks if given remote address is valid, -// and returns composed URL with needed username and passowrd. +// and returns composed URL with needed username and password. // It also checks if given user has permission when remote address // is actually a local path. func (f MigrateRepoForm) ParseRemoteAddr(user *models.User) (string, error) { From 3a3782bb7fed768c1e832ff4c0a77f2f5281ed05 Mon Sep 17 00:00:00 2001 From: stroucki Date: Wed, 23 Nov 2016 19:52:55 -0500 Subject: [PATCH 002/135] Handle ssh key import better (#224) * Handle user ssh key input better ssh_key: when user submitted keys had a newline at the end, strings.Split would have created a slice with an empty last element, and the key type check would be incorrect. Perhaps a better way is to look for 'ssh-rsa' or 'ssh-dsa' at the beginning of the string, but this is simple. * ssh_key: correct indentation --- models/ssh_key.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/models/ssh_key.go b/models/ssh_key.go index 4a6acb8ecf..98fb2dcdbf 100644 --- a/models/ssh_key.go +++ b/models/ssh_key.go @@ -105,6 +105,8 @@ func extractTypeFromBase64Key(key string) (string, error) { func parseKeyString(content string) (string, error) { // Transform all legal line endings to a single "\n". content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content) + // remove trailing newline (and beginning spaces too) + content = strings.TrimSpace(content) lines := strings.Split(content, "\n") var keyType, keyContent, keyComment string From 3917ed45de063b4e8868610c82d8172020d572fd Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 24 Nov 2016 15:04:31 +0800 Subject: [PATCH 003/135] golint fixed for routers (#208) --- routers/api/v1/admin/org.go | 3 +- routers/api/v1/admin/org_repo.go | 3 ++ routers/api/v1/admin/org_team.go | 3 ++ routers/api/v1/admin/repo.go | 3 +- routers/api/v1/admin/user.go | 10 ++-- routers/api/v1/convert/convert.go | 10 +++- routers/api/v1/misc/markdown.go | 6 ++- routers/api/v1/org/org.go | 12 +++-- routers/api/v1/org/team.go | 1 + routers/api/v1/repo/branch.go | 6 ++- routers/api/v1/repo/collaborators.go | 1 + routers/api/v1/repo/file.go | 7 ++- routers/api/v1/repo/hook.go | 10 ++-- routers/api/v1/repo/issue.go | 4 ++ routers/api/v1/repo/issue_comment.go | 4 ++ routers/api/v1/repo/issue_label.go | 5 ++ routers/api/v1/repo/key.go | 14 +++-- routers/api/v1/repo/label.go | 5 ++ routers/api/v1/repo/milestone.go | 5 ++ routers/api/v1/repo/repo.go | 20 ++++--- routers/api/v1/user/app.go | 6 ++- routers/api/v1/user/email.go | 9 ++-- routers/api/v1/user/follower.go | 26 +++++---- routers/api/v1/user/key.go | 16 ++++-- routers/api/v1/user/user.go | 3 ++ routers/repo/commit.go | 29 ++++++---- routers/repo/download.go | 3 ++ routers/repo/editor.go | 57 ++++++++++++-------- routers/repo/http.go | 12 +++-- routers/repo/issue.go | 79 ++++++++++++++++++++-------- routers/repo/pull.go | 46 ++++++++++------ routers/repo/release.go | 26 +++++---- routers/repo/repo.go | 33 +++++++----- routers/repo/setting.go | 12 +++++ routers/repo/webhook.go | 20 +++++-- 35 files changed, 354 insertions(+), 155 deletions(-) diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go index 1162c96c5f..706e2cedeb 100644 --- a/routers/api/v1/admin/org.go +++ b/routers/api/v1/admin/org.go @@ -13,7 +13,8 @@ import ( "code.gitea.io/gitea/routers/api/v1/user" ) -// https://github.com/gogits/go-gogs-client/wiki/Administration-Organizations#create-a-new-organization +// CreateOrg api for create organization +// see https://github.com/gogits/go-gogs-client/wiki/Administration-Organizations#create-a-new-organization func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) { u := user.GetUserByParams(ctx) if ctx.Written() { diff --git a/routers/api/v1/admin/org_repo.go b/routers/api/v1/admin/org_repo.go index c7014dd7c0..8230c0acc4 100644 --- a/routers/api/v1/admin/org_repo.go +++ b/routers/api/v1/admin/org_repo.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/modules/context" ) +// GetRepositoryByParams api for getting repository by orgnizition ID and repo name func GetRepositoryByParams(ctx *context.APIContext) *models.Repository { repo, err := models.GetRepositoryByName(ctx.Org.Team.OrgID, ctx.Params(":reponame")) if err != nil { @@ -22,6 +23,7 @@ func GetRepositoryByParams(ctx *context.APIContext) *models.Repository { return repo } +// AddTeamRepository api for adding a repository to a team func AddTeamRepository(ctx *context.APIContext) { repo := GetRepositoryByParams(ctx) if ctx.Written() { @@ -35,6 +37,7 @@ func AddTeamRepository(ctx *context.APIContext) { ctx.Status(204) } +// RemoveTeamRepository api for removing a repository from a team func RemoveTeamRepository(ctx *context.APIContext) { repo := GetRepositoryByParams(ctx) if ctx.Written() { diff --git a/routers/api/v1/admin/org_team.go b/routers/api/v1/admin/org_team.go index b1964ff728..93af1ec427 100644 --- a/routers/api/v1/admin/org_team.go +++ b/routers/api/v1/admin/org_team.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/routers/api/v1/user" ) +// CreateTeam api for create a team func CreateTeam(ctx *context.APIContext, form api.CreateTeamOption) { team := &models.Team{ OrgID: ctx.Org.Organization.ID, @@ -32,6 +33,7 @@ func CreateTeam(ctx *context.APIContext, form api.CreateTeamOption) { ctx.JSON(201, convert.ToTeam(team)) } +// AddTeamMember api for add a member to a team func AddTeamMember(ctx *context.APIContext) { u := user.GetUserByParams(ctx) if ctx.Written() { @@ -45,6 +47,7 @@ func AddTeamMember(ctx *context.APIContext) { ctx.Status(204) } +// RemoveTeamMember api for remove one member from a team func RemoveTeamMember(ctx *context.APIContext) { u := user.GetUserByParams(ctx) if ctx.Written() { diff --git a/routers/api/v1/admin/repo.go b/routers/api/v1/admin/repo.go index 69187dc367..a52d462137 100644 --- a/routers/api/v1/admin/repo.go +++ b/routers/api/v1/admin/repo.go @@ -12,7 +12,8 @@ import ( "code.gitea.io/gitea/routers/api/v1/user" ) -// https://github.com/gogits/go-gogs-client/wiki/Administration-Repositories#create-a-new-repository +// CreateRepo api for creating a repository +// see https://github.com/gogits/go-gogs-client/wiki/Administration-Repositories#create-a-new-repository func CreateRepo(ctx *context.APIContext, form api.CreateRepoOption) { owner := user.GetUserByParams(ctx) if ctx.Written() { diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index c868c62104..0a6dc5d456 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -34,7 +34,8 @@ func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, l u.LoginName = loginName } -// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-new-user +// CreateUser api for creating a user +// see https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-new-user func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { u := &models.User{ Name: form.Username, @@ -71,7 +72,8 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { ctx.JSON(201, u.APIFormat()) } -// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#edit-an-existing-user +// EditUser api for modifying a user's information +// see https://github.com/gogits/go-gogs-client/wiki/Administration-Users#edit-an-existing-user func EditUser(ctx *context.APIContext, form api.EditUserOption) { u := user.GetUserByParams(ctx) if ctx.Written() { @@ -123,6 +125,7 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) { ctx.JSON(200, u.APIFormat()) } +// DeleteUser api for deleting a user // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#delete-a-user func DeleteUser(ctx *context.APIContext) { u := user.GetUserByParams(ctx) @@ -144,7 +147,8 @@ func DeleteUser(ctx *context.APIContext) { ctx.Status(204) } -// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-public-key-for-user +// CreatePublicKey api for creating a public key to a user +// see https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-public-key-for-user func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) { u := user.GetUserByParams(ctx) if ctx.Written() { diff --git a/routers/api/v1/convert/convert.go b/routers/api/v1/convert/convert.go index a736b827af..8608d17d99 100644 --- a/routers/api/v1/convert/convert.go +++ b/routers/api/v1/convert/convert.go @@ -9,12 +9,13 @@ import ( "github.com/Unknwon/com" - "code.gitea.io/git" api "code.gitea.io/sdk/gitea" + "code.gitea.io/git" "code.gitea.io/gitea/models" ) +// ToEmail convert models.EmailAddress to api.Email func ToEmail(email *models.EmailAddress) *api.Email { return &api.Email{ Email: email.Email, @@ -23,6 +24,7 @@ func ToEmail(email *models.EmailAddress) *api.Email { } } +// ToBranch convert a commit and branch to an api.Branch func ToBranch(b *models.Branch, c *git.Commit) *api.Branch { return &api.Branch{ Name: b.Name, @@ -30,6 +32,7 @@ func ToBranch(b *models.Branch, c *git.Commit) *api.Branch { } } +// ToCommit convert a commit to api.PayloadCommit func ToCommit(c *git.Commit) *api.PayloadCommit { authorUsername := "" author, err := models.GetUserByEmail(c.Author.Email) @@ -59,6 +62,7 @@ func ToCommit(c *git.Commit) *api.PayloadCommit { } } +// ToPublicKey convert models.PublicKey to api.PublicKey func ToPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey { return &api.PublicKey{ ID: key.ID, @@ -69,6 +73,7 @@ func ToPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey { } } +// ToHook convert models.Webhook to api.Hook func ToHook(repoLink string, w *models.Webhook) *api.Hook { config := map[string]string{ "url": w.URL, @@ -94,6 +99,7 @@ func ToHook(repoLink string, w *models.Webhook) *api.Hook { } } +// ToDeployKey convert models.DeployKey to api.DeployKey func ToDeployKey(apiLink string, key *models.DeployKey) *api.DeployKey { return &api.DeployKey{ ID: key.ID, @@ -105,6 +111,7 @@ func ToDeployKey(apiLink string, key *models.DeployKey) *api.DeployKey { } } +// ToOrganization convert models.User to api.Organization func ToOrganization(org *models.User) *api.Organization { return &api.Organization{ ID: org.ID, @@ -117,6 +124,7 @@ func ToOrganization(org *models.User) *api.Organization { } } +// ToTeam convert models.Team to api.Team func ToTeam(team *models.Team) *api.Team { return &api.Team{ ID: team.ID, diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index b4974ce466..23b5b269aa 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -11,7 +11,8 @@ import ( "code.gitea.io/gitea/modules/markdown" ) -// https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document +// Markdown render markdown document to HTML +// see https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document func Markdown(ctx *context.APIContext, form api.MarkdownOption) { if ctx.HasApiError() { ctx.Error(422, "", ctx.GetErrMsg()) @@ -31,7 +32,8 @@ func Markdown(ctx *context.APIContext, form api.MarkdownOption) { } } -// https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-a-markdown-document-in-raw-mode +// MarkdownRaw render raw markdown HTML +// see https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-a-markdown-document-in-raw-mode func MarkdownRaw(ctx *context.APIContext) { body, err := ctx.Req.Body().Bytes() if err != nil { diff --git a/routers/api/v1/org/org.go b/routers/api/v1/org/org.go index cc847af8db..328b97a223 100644 --- a/routers/api/v1/org/org.go +++ b/routers/api/v1/org/org.go @@ -26,12 +26,14 @@ func listUserOrgs(ctx *context.APIContext, u *models.User, all bool) { ctx.JSON(200, &apiOrgs) } -// https://github.com/gogits/go-gogs-client/wiki/Organizations#list-your-organizations +// ListMyOrgs list all my orgs +// see https://github.com/gogits/go-gogs-client/wiki/Organizations#list-your-organizations func ListMyOrgs(ctx *context.APIContext) { listUserOrgs(ctx, ctx.User, true) } -// https://github.com/gogits/go-gogs-client/wiki/Organizations#list-user-organizations +// ListUserOrgs list user's orgs +// see https://github.com/gogits/go-gogs-client/wiki/Organizations#list-user-organizations func ListUserOrgs(ctx *context.APIContext) { u := user.GetUserByParams(ctx) if ctx.Written() { @@ -40,12 +42,14 @@ func ListUserOrgs(ctx *context.APIContext) { listUserOrgs(ctx, u, false) } -// https://github.com/gogits/go-gogs-client/wiki/Organizations#get-an-organization +// Get get an organization +// see https://github.com/gogits/go-gogs-client/wiki/Organizations#get-an-organization func Get(ctx *context.APIContext) { ctx.JSON(200, convert.ToOrganization(ctx.Org.Organization)) } -// https://github.com/gogits/go-gogs-client/wiki/Organizations#edit-an-organization +// Edit change an organization's information +// see https://github.com/gogits/go-gogs-client/wiki/Organizations#edit-an-organization func Edit(ctx *context.APIContext, form api.EditOrgOption) { org := ctx.Org.Organization if !org.IsOwnedBy(ctx.User.ID) { diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index ae67461bee..f5b2e9dc55 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/routers/api/v1/convert" ) +// ListTeams list all the teams of an organization func ListTeams(ctx *context.APIContext) { org := ctx.Org.Organization if err := org.GetTeams(); err != nil { diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 39215ed462..3c73ae62c2 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -11,7 +11,8 @@ import ( "code.gitea.io/gitea/routers/api/v1/convert" ) -// https://github.com/gogits/go-gogs-client/wiki/Repositories#get-branch +// GetBranch get a branch of a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#get-branch func GetBranch(ctx *context.APIContext) { branch, err := ctx.Repo.Repository.GetBranch(ctx.Params(":branchname")) if err != nil { @@ -28,7 +29,8 @@ func GetBranch(ctx *context.APIContext) { ctx.JSON(200, convert.ToBranch(branch, c)) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories#list-branches +// ListBranches list all the branches of a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#list-branches func ListBranches(ctx *context.APIContext) { branches, err := ctx.Repo.Repository.GetBranches() if err != nil { diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index 4cad20b60c..a1e8ec6535 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/context" ) +// AddCollaborator add a collaborator of a repository func AddCollaborator(ctx *context.APIContext, form api.AddCollaboratorOption) { collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) if err != nil { diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 96948ea459..16a31f96c7 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -12,7 +12,8 @@ import ( "code.gitea.io/gitea/routers/repo" ) -// https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-raw-content +// GetRawFile get a file by path on a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-raw-content func GetRawFile(ctx *context.APIContext) { if !ctx.Repo.HasAccess() { ctx.Status(404) @@ -33,7 +34,8 @@ func GetRawFile(ctx *context.APIContext) { } } -// https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-archive +// GetArchive get archive of a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-archive func GetArchive(ctx *context.APIContext) { repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) gitRepo, err := git.OpenRepository(repoPath) @@ -46,6 +48,7 @@ func GetArchive(ctx *context.APIContext) { repo.Download(ctx.Context) } +// GetEditorconfig get editor config of a repository func GetEditorconfig(ctx *context.APIContext) { ec, err := ctx.Repo.GetEditorconfig() if err != nil { diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index 226b50db9f..30e1fad363 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -16,7 +16,8 @@ import ( "code.gitea.io/gitea/routers/api/v1/convert" ) -// https://github.com/gogits/go-gogs-client/wiki/Repositories#list-hooks +// ListHooks list all hooks of a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#list-hooks func ListHooks(ctx *context.APIContext) { hooks, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID) if err != nil { @@ -31,7 +32,8 @@ func ListHooks(ctx *context.APIContext) { ctx.JSON(200, &apiHooks) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories#create-a-hook +// CreateHook create a hook for a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#create-a-hook func CreateHook(ctx *context.APIContext, form api.CreateHookOption) { if !models.IsValidHookTaskType(form.Type) { ctx.Error(422, "", "Invalid hook type") @@ -97,7 +99,8 @@ func CreateHook(ctx *context.APIContext, form api.CreateHookOption) { ctx.JSON(201, convert.ToHook(ctx.Repo.RepoLink, w)) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories#edit-a-hook +// EditHook modify a hook of a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#edit-a-hook func EditHook(ctx *context.APIContext, form api.EditHookOption) { w, err := models.GetWebhookByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { @@ -165,6 +168,7 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) { ctx.JSON(200, convert.ToHook(ctx.Repo.RepoLink, w)) } +// DeleteHook delete a hook of a repository func DeleteHook(ctx *context.APIContext) { if err := models.DeleteWebhookByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { ctx.Error(500, "DeleteWebhookByRepoID", err) diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index c73bf5dbb5..354678c781 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// ListIssues list the issues of a repository func ListIssues(ctx *context.APIContext) { issues, err := models.Issues(&models.IssuesOptions{ RepoID: ctx.Repo.Repository.ID, @@ -39,6 +40,7 @@ func ListIssues(ctx *context.APIContext) { ctx.JSON(200, &apiIssues) } +// GetIssue get an issue of a repository func GetIssue(ctx *context.APIContext) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { @@ -52,6 +54,7 @@ func GetIssue(ctx *context.APIContext) { ctx.JSON(200, issue.APIFormat()) } +// CreateIssue create an issue of a repository func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { issue := &models.Issue{ RepoID: ctx.Repo.Repository.ID, @@ -101,6 +104,7 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { ctx.JSON(201, issue.APIFormat()) } +// EditIssue modify an issue of a repository func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { diff --git a/routers/api/v1/repo/issue_comment.go b/routers/api/v1/repo/issue_comment.go index cf9a3eae0f..06c7d2b1f5 100644 --- a/routers/api/v1/repo/issue_comment.go +++ b/routers/api/v1/repo/issue_comment.go @@ -1,6 +1,7 @@ // 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 ( @@ -12,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/context" ) +// ListIssueComments list all the comments of an issue func ListIssueComments(ctx *context.APIContext) { var since time.Time if len(ctx.Query("since")) > 0 { @@ -38,6 +40,7 @@ func ListIssueComments(ctx *context.APIContext) { ctx.JSON(200, &apiComments) } +// CreateIssueComment create a comment for an issue func CreateIssueComment(ctx *context.APIContext, form api.CreateIssueCommentOption) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { @@ -54,6 +57,7 @@ func CreateIssueComment(ctx *context.APIContext, form api.CreateIssueCommentOpti ctx.JSON(201, comment.APIFormat()) } +// EditIssueComment modify a comment of an issue func EditIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) { comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) if err != nil { diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go index 46d976253a..e91b8e9daf 100644 --- a/routers/api/v1/repo/issue_label.go +++ b/routers/api/v1/repo/issue_label.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/context" ) +// ListIssueLabels list all the labels of an issue func ListIssueLabels(ctx *context.APIContext) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { @@ -29,6 +30,7 @@ func ListIssueLabels(ctx *context.APIContext) { ctx.JSON(200, &apiLabels) } +// AddIssueLabels add labels for an issue func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { if !ctx.Repo.IsWriter() { ctx.Status(403) @@ -69,6 +71,7 @@ func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { ctx.JSON(200, &apiLabels) } +// DeleteIssueLabel delete a label for an issue func DeleteIssueLabel(ctx *context.APIContext) { if !ctx.Repo.IsWriter() { ctx.Status(403) @@ -103,6 +106,7 @@ func DeleteIssueLabel(ctx *context.APIContext) { ctx.Status(204) } +// ReplaceIssueLabels replace labels for an issue func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { if !ctx.Repo.IsWriter() { ctx.Status(403) @@ -143,6 +147,7 @@ func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { ctx.JSON(200, &apiLabels) } +// ClearIssueLabels delete all the labels for an issue func ClearIssueLabels(ctx *context.APIContext) { if !ctx.Repo.IsWriter() { ctx.Status(403) diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index 4d4240c290..51f080a385 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -19,7 +19,8 @@ func composeDeployKeysAPILink(repoPath string) string { return setting.AppUrl + "api/v1/repos/" + repoPath + "/keys/" } -// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#list-deploy-keys +// ListDeployKeys list all the deploy keys of a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#list-deploy-keys func ListDeployKeys(ctx *context.APIContext) { keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) if err != nil { @@ -40,7 +41,8 @@ func ListDeployKeys(ctx *context.APIContext) { ctx.JSON(200, &apiKeys) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#get-a-deploy-key +// GetDeployKey get a deploy key by id +// see https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#get-a-deploy-key func GetDeployKey(ctx *context.APIContext) { key, err := models.GetDeployKeyByID(ctx.ParamsInt64(":id")) if err != nil { @@ -61,6 +63,7 @@ func GetDeployKey(ctx *context.APIContext) { ctx.JSON(200, convert.ToDeployKey(apiLink, key)) } +// HandleCheckKeyStringError handle check key error func HandleCheckKeyStringError(ctx *context.APIContext, err error) { if models.IsErrKeyUnableVerify(err) { ctx.Error(422, "", "Unable to verify key content") @@ -69,6 +72,7 @@ func HandleCheckKeyStringError(ctx *context.APIContext, err error) { } } +// HandleAddKeyError handle add key error func HandleAddKeyError(ctx *context.APIContext, err error) { switch { case models.IsErrKeyAlreadyExist(err): @@ -80,7 +84,8 @@ func HandleAddKeyError(ctx *context.APIContext, err error) { } } -// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#add-a-new-deploy-key +// CreateDeployKey create deploy key for a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#add-a-new-deploy-key func CreateDeployKey(ctx *context.APIContext, form api.CreateKeyOption) { content, err := models.CheckPublicKeyString(form.Key) if err != nil { @@ -99,7 +104,8 @@ func CreateDeployKey(ctx *context.APIContext, form api.CreateKeyOption) { ctx.JSON(201, convert.ToDeployKey(apiLink, key)) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key +// DeleteDeploykey delete deploy key for a repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key func DeleteDeploykey(ctx *context.APIContext) { if err := models.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if models.IsErrKeyAccessDenied(err) { diff --git a/routers/api/v1/repo/label.go b/routers/api/v1/repo/label.go index 009e8d8a0b..383868beda 100644 --- a/routers/api/v1/repo/label.go +++ b/routers/api/v1/repo/label.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/context" ) +// ListLabels list all the labels of a repository func ListLabels(ctx *context.APIContext) { labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID) if err != nil { @@ -25,6 +26,7 @@ func ListLabels(ctx *context.APIContext) { ctx.JSON(200, &apiLabels) } +// GetLabel get label by repository and label id func GetLabel(ctx *context.APIContext) { label, err := models.GetLabelInRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { @@ -39,6 +41,7 @@ func GetLabel(ctx *context.APIContext) { ctx.JSON(200, label.APIFormat()) } +// CreateLabel create a label for a repository func CreateLabel(ctx *context.APIContext, form api.CreateLabelOption) { if !ctx.Repo.IsWriter() { ctx.Status(403) @@ -57,6 +60,7 @@ func CreateLabel(ctx *context.APIContext, form api.CreateLabelOption) { ctx.JSON(201, label.APIFormat()) } +// EditLabel modify a label for a repository func EditLabel(ctx *context.APIContext, form api.EditLabelOption) { if !ctx.Repo.IsWriter() { ctx.Status(403) @@ -86,6 +90,7 @@ func EditLabel(ctx *context.APIContext, form api.EditLabelOption) { ctx.JSON(200, label.APIFormat()) } +// DeleteLabel delete a label for a repository func DeleteLabel(ctx *context.APIContext) { if !ctx.Repo.IsWriter() { ctx.Status(403) diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go index 2c6a93f826..ef32ed8989 100644 --- a/routers/api/v1/repo/milestone.go +++ b/routers/api/v1/repo/milestone.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/context" ) +// ListMilestones list all the milestones for a repository func ListMilestones(ctx *context.APIContext) { milestones, err := models.GetMilestonesByRepoID(ctx.Repo.Repository.ID) if err != nil { @@ -27,6 +28,7 @@ func ListMilestones(ctx *context.APIContext) { ctx.JSON(200, &apiMilestones) } +// GetMilestone get a milestone for a repository func GetMilestone(ctx *context.APIContext) { milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { @@ -40,6 +42,7 @@ func GetMilestone(ctx *context.APIContext) { ctx.JSON(200, milestone.APIFormat()) } +// CreateMilestone create a milestone for a repository func CreateMilestone(ctx *context.APIContext, form api.CreateMilestoneOption) { if form.Deadline == nil { defaultDeadline, _ := time.ParseInLocation("2006-01-02", "9999-12-31", time.Local) @@ -60,6 +63,7 @@ func CreateMilestone(ctx *context.APIContext, form api.CreateMilestoneOption) { ctx.JSON(201, milestone.APIFormat()) } +// EditMilestone modify a milestone for a repository func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) { milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { @@ -88,6 +92,7 @@ func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) { ctx.JSON(200, milestone.APIFormat()) } +// DeleteMilestone delete a milestone for a repository func DeleteMilestone(ctx *context.APIContext) { if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { ctx.Error(500, "DeleteMilestoneByRepoID", err) diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 4353fb74ea..6ae513db16 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -17,7 +17,8 @@ import ( "code.gitea.io/gitea/routers/api/v1/convert" ) -// https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories +// Search repositories via options +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories func Search(ctx *context.APIContext) { opts := &models.SearchRepoOptions{ Keyword: path.Base(ctx.Query("q")), @@ -76,7 +77,8 @@ func Search(ctx *context.APIContext) { }) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories#list-your-repositories +// ListMyRepos list all my repositories +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#list-your-repositories func ListMyRepos(ctx *context.APIContext) { ownRepos, err := models.GetUserRepositories(ctx.User.ID, true, 1, ctx.User.NumRepos) if err != nil { @@ -109,6 +111,7 @@ func ListMyRepos(ctx *context.APIContext) { ctx.JSON(200, &repos) } +// CreateUserRepo create a repository for a user func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateRepoOption) { repo, err := models.CreateRepository(owner, models.CreateRepoOptions{ Name: opt.Name, @@ -138,7 +141,8 @@ func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateR ctx.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories#create +// Create create one repository of mine +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#create func Create(ctx *context.APIContext, opt api.CreateRepoOption) { // Shouldn't reach this condition, but just in case. if ctx.User.IsOrganization() { @@ -148,6 +152,7 @@ func Create(ctx *context.APIContext, opt api.CreateRepoOption) { CreateUserRepo(ctx, ctx.User, opt) } +// CreateOrgRepo create one repository of the organization func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) { org, err := models.GetOrgByName(ctx.Params(":org")) if err != nil { @@ -166,7 +171,8 @@ func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) { CreateUserRepo(ctx, org, opt) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate +// Migrate migrate remote git repository to gitea +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { ctxUser := ctx.User // Not equal means context user is an organization, @@ -238,13 +244,15 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { ctx.JSON(201, repo.APIFormat(&api.Permission{true, true, true})) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories#get +// Get get one repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#get func Get(ctx *context.APIContext) { repo := ctx.Repo.Repository ctx.JSON(200, repo.APIFormat(&api.Permission{true, true, true})) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories#delete +// Delete delete one repository +// see https://github.com/gogits/go-gogs-client/wiki/Repositories#delete func Delete(ctx *context.APIContext) { owner := ctx.Repo.Owner repo := ctx.Repo.Repository diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index e678aaff53..2955f78a77 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -11,7 +11,8 @@ import ( "code.gitea.io/gitea/modules/context" ) -// https://github.com/gogits/go-gogs-client/wiki/Users#list-access-tokens-for-a-user +// ListAccessTokens list all the access tokens +// see https://github.com/gogits/go-gogs-client/wiki/Users#list-access-tokens-for-a-user func ListAccessTokens(ctx *context.APIContext) { tokens, err := models.ListAccessTokens(ctx.User.ID) if err != nil { @@ -26,7 +27,8 @@ func ListAccessTokens(ctx *context.APIContext) { ctx.JSON(200, &apiTokens) } -// https://github.com/gogits/go-gogs-client/wiki/Users#create-a-access-token +// CreateAccessToken create access tokens +// see https://github.com/gogits/go-gogs-client/wiki/Users#create-a-access-token func CreateAccessToken(ctx *context.APIContext, form api.CreateAccessTokenOption) { t := &models.AccessToken{ UID: ctx.User.ID, diff --git a/routers/api/v1/user/email.go b/routers/api/v1/user/email.go index 2503d01a44..f42fc11cf6 100644 --- a/routers/api/v1/user/email.go +++ b/routers/api/v1/user/email.go @@ -13,7 +13,8 @@ import ( "code.gitea.io/gitea/routers/api/v1/convert" ) -// https://github.com/gogits/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user +// ListEmails list all the emails of mine +// see https://github.com/gogits/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user func ListEmails(ctx *context.APIContext) { emails, err := models.GetEmailAddresses(ctx.User.ID) if err != nil { @@ -27,7 +28,8 @@ func ListEmails(ctx *context.APIContext) { ctx.JSON(200, &apiEmails) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Emails#add-email-addresses +// AddEmail add email for me +// see https://github.com/gogits/go-gogs-client/wiki/Users-Emails#add-email-addresses func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { if len(form.Emails) == 0 { ctx.Status(422) @@ -59,7 +61,8 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { ctx.JSON(201, &apiEmails) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Emails#delete-email-addresses +// DeleteEmail delete email +// see https://github.com/gogits/go-gogs-client/wiki/Users-Emails#delete-email-addresses func DeleteEmail(ctx *context.APIContext, form api.CreateEmailOption) { if len(form.Emails) == 0 { ctx.Status(204) diff --git a/routers/api/v1/user/follower.go b/routers/api/v1/user/follower.go index 594c365177..ff043c9de9 100644 --- a/routers/api/v1/user/follower.go +++ b/routers/api/v1/user/follower.go @@ -11,7 +11,7 @@ import ( "code.gitea.io/gitea/modules/context" ) -func responseApiUsers(ctx *context.APIContext, users []*models.User) { +func responseAPIUsers(ctx *context.APIContext, users []*models.User) { apiUsers := make([]*api.User, len(users)) for i := range users { apiUsers[i] = users[i].APIFormat() @@ -25,14 +25,16 @@ func listUserFollowers(ctx *context.APIContext, u *models.User) { ctx.Error(500, "GetUserFollowers", err) return } - responseApiUsers(ctx, users) + responseAPIUsers(ctx, users) } +// ListMyFollowers list all my followers func ListMyFollowers(ctx *context.APIContext) { listUserFollowers(ctx, ctx.User) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-followers-of-a-user +// ListFollowers list user's followers +// see https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-followers-of-a-user func ListFollowers(ctx *context.APIContext) { u := GetUserByParams(ctx) if ctx.Written() { @@ -47,14 +49,16 @@ func listUserFollowing(ctx *context.APIContext, u *models.User) { ctx.Error(500, "GetFollowing", err) return } - responseApiUsers(ctx, users) + responseAPIUsers(ctx, users) } +// ListMyFollowing list all my followings func ListMyFollowing(ctx *context.APIContext) { listUserFollowing(ctx, ctx.User) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-users-followed-by-another-user +// ListFollowing list user's followings +// see https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-users-followed-by-another-user func ListFollowing(ctx *context.APIContext) { u := GetUserByParams(ctx) if ctx.Written() { @@ -71,7 +75,8 @@ func checkUserFollowing(ctx *context.APIContext, u *models.User, followID int64) } } -// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-you-are-following-a-user +// CheckMyFollowing check if the repo is followed by me +// see https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-you-are-following-a-user func CheckMyFollowing(ctx *context.APIContext) { target := GetUserByParams(ctx) if ctx.Written() { @@ -80,7 +85,8 @@ func CheckMyFollowing(ctx *context.APIContext) { checkUserFollowing(ctx, ctx.User, target.ID) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-one-user-follows-another +// CheckFollowing check if the repo is followed by user +// see https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-one-user-follows-another func CheckFollowing(ctx *context.APIContext) { u := GetUserByParams(ctx) if ctx.Written() { @@ -93,7 +99,8 @@ func CheckFollowing(ctx *context.APIContext) { checkUserFollowing(ctx, u, target.ID) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#follow-a-user +// Follow follow one repository +// see https://github.com/gogits/go-gogs-client/wiki/Users-Followers#follow-a-user func Follow(ctx *context.APIContext) { target := GetUserByParams(ctx) if ctx.Written() { @@ -106,7 +113,8 @@ func Follow(ctx *context.APIContext) { ctx.Status(204) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#unfollow-a-user +// Unfollow unfollow one repository +// see https://github.com/gogits/go-gogs-client/wiki/Users-Followers#unfollow-a-user func Unfollow(ctx *context.APIContext) { target := GetUserByParams(ctx) if ctx.Written() { diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index 6df405a16c..c743b5deab 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/routers/api/v1/repo" ) +// GetUserByParamsName get user by name func GetUserByParamsName(ctx *context.APIContext, name string) *models.User { user, err := models.GetUserByName(ctx.Params(name)) if err != nil { @@ -52,12 +53,14 @@ func listPublicKeys(ctx *context.APIContext, uid int64) { ctx.JSON(200, &apiKeys) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-your-public-keys +// ListMyPublicKeys list all my public keys +// see https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-your-public-keys func ListMyPublicKeys(ctx *context.APIContext) { listPublicKeys(ctx, ctx.User.ID) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user +// ListPublicKeys list all user's public keys +// see https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user func ListPublicKeys(ctx *context.APIContext) { user := GetUserByParams(ctx) if ctx.Written() { @@ -66,7 +69,8 @@ func ListPublicKeys(ctx *context.APIContext) { listPublicKeys(ctx, user.ID) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#get-a-single-public-key +// GetPublicKey get one public key +// see https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#get-a-single-public-key func GetPublicKey(ctx *context.APIContext) { key, err := models.GetPublicKeyByID(ctx.ParamsInt64(":id")) if err != nil { @@ -99,12 +103,14 @@ func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid ctx.JSON(201, convert.ToPublicKey(apiLink, key)) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#create-a-public-key +// CreatePublicKey create one public key for me +// see https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#create-a-public-key func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) { CreateUserPublicKey(ctx, form, ctx.User.ID) } -// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key +// DeletePublicKey delete one public key of mine +// see https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key func DeletePublicKey(ctx *context.APIContext) { if err := models.DeletePublicKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if models.IsErrKeyAccessDenied(err) { diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index c6a454cc4a..ef0a5b212e 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/context" ) +// Search search users func Search(ctx *context.APIContext) { opts := &models.SearchUserOptions{ Keyword: ctx.Query("q"), @@ -51,6 +52,7 @@ func Search(ctx *context.APIContext) { }) } +// GetInfo get user's information func GetInfo(ctx *context.APIContext) { u, err := models.GetUserByName(ctx.Params(":username")) if err != nil { @@ -69,6 +71,7 @@ func GetInfo(ctx *context.APIContext) { ctx.JSON(200, u.APIFormat()) } +// GetAuthenticatedUser get curent user's information func GetAuthenticatedUser(ctx *context.APIContext) { ctx.JSON(200, ctx.User.APIFormat()) } diff --git a/routers/repo/commit.go b/routers/repo/commit.go index 9706779ee5..7f41158633 100644 --- a/routers/repo/commit.go +++ b/routers/repo/commit.go @@ -17,10 +17,11 @@ import ( ) const ( - COMMITS base.TplName = "repo/commits" - DIFF base.TplName = "repo/diff/page" + tplCommits base.TplName = "repo/commits" + tplDiff base.TplName = "repo/diff/page" ) +// RefCommits render commits page func RefCommits(ctx *context.Context) { switch { case len(ctx.Repo.TreePath) == 0: @@ -32,7 +33,7 @@ func RefCommits(ctx *context.Context) { } } -func RenderIssueLinks(oldCommits *list.List, repoLink string) *list.List { +func renderIssueLinks(oldCommits *list.List, repoLink string) *list.List { newCommits := list.New() for e := oldCommits.Front(); e != nil; e = e.Next() { c := e.Value.(*git.Commit) @@ -41,6 +42,7 @@ func RenderIssueLinks(oldCommits *list.List, repoLink string) *list.List { return newCommits } +// Commits render branch's commits func Commits(ctx *context.Context) { ctx.Data["PageIsCommits"] = true @@ -62,7 +64,7 @@ func Commits(ctx *context.Context) { ctx.Handle(500, "CommitsByRange", err) return } - commits = RenderIssueLinks(commits, ctx.Repo.RepoLink) + commits = renderIssueLinks(commits, ctx.Repo.RepoLink) commits = models.ValidateCommitsWithEmails(commits) ctx.Data["Commits"] = commits @@ -70,9 +72,10 @@ func Commits(ctx *context.Context) { ctx.Data["Reponame"] = ctx.Repo.Repository.Name ctx.Data["CommitCount"] = commitsCount ctx.Data["Branch"] = ctx.Repo.BranchName - ctx.HTML(200, COMMITS) + ctx.HTML(200, tplCommits) } +// SearchCommits render commits filtered by keyword func SearchCommits(ctx *context.Context) { ctx.Data["PageIsCommits"] = true @@ -87,7 +90,7 @@ func SearchCommits(ctx *context.Context) { ctx.Handle(500, "SearchCommits", err) return } - commits = RenderIssueLinks(commits, ctx.Repo.RepoLink) + commits = renderIssueLinks(commits, ctx.Repo.RepoLink) commits = models.ValidateCommitsWithEmails(commits) ctx.Data["Commits"] = commits @@ -96,9 +99,10 @@ func SearchCommits(ctx *context.Context) { ctx.Data["Reponame"] = ctx.Repo.Repository.Name ctx.Data["CommitCount"] = commits.Len() ctx.Data["Branch"] = ctx.Repo.BranchName - ctx.HTML(200, COMMITS) + ctx.HTML(200, tplCommits) } +// FileHistory show a file's reversions func FileHistory(ctx *context.Context) { ctx.Data["IsRepoToolbarCommits"] = true @@ -129,7 +133,7 @@ func FileHistory(ctx *context.Context) { ctx.Handle(500, "CommitsByFileAndRange", err) return } - commits = RenderIssueLinks(commits, ctx.Repo.RepoLink) + commits = renderIssueLinks(commits, ctx.Repo.RepoLink) commits = models.ValidateCommitsWithEmails(commits) ctx.Data["Commits"] = commits @@ -138,9 +142,10 @@ func FileHistory(ctx *context.Context) { ctx.Data["FileName"] = fileName ctx.Data["CommitCount"] = commitsCount ctx.Data["Branch"] = branchName - ctx.HTML(200, COMMITS) + ctx.HTML(200, tplCommits) } +// Diff show different from current commit to previous commit func Diff(ctx *context.Context) { ctx.Data["PageIsDiff"] = true ctx.Data["RequireHighlightJS"] = true @@ -194,9 +199,10 @@ func Diff(ctx *context.Context) { ctx.Data["BeforeSourcePath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "src", parents[0]) } ctx.Data["RawPath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "raw", commitID) - ctx.HTML(200, DIFF) + ctx.HTML(200, tplDiff) } +// RawDiff dumps diff results of repository in given commit ID to io.Writer func RawDiff(ctx *context.Context) { if err := models.GetRawDiff( models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name), @@ -209,6 +215,7 @@ func RawDiff(ctx *context.Context) { } } +// CompareDiff show different from one commit to another commit func CompareDiff(ctx *context.Context) { ctx.Data["IsRepoToolbarCommits"] = true ctx.Data["IsDiffCompare"] = true @@ -253,5 +260,5 @@ func CompareDiff(ctx *context.Context) { ctx.Data["SourcePath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "src", afterCommitID) ctx.Data["BeforeSourcePath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "src", beforeCommitID) ctx.Data["RawPath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "raw", afterCommitID) - ctx.HTML(200, DIFF) + ctx.HTML(200, tplDiff) } diff --git a/routers/repo/download.go b/routers/repo/download.go index 654cc01399..3adab315d4 100644 --- a/routers/repo/download.go +++ b/routers/repo/download.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/context" ) +// ServeData download file from io.Reader func ServeData(ctx *context.Context, name string, reader io.Reader) error { buf := make([]byte, 1024) n, _ := reader.Read(buf) @@ -34,6 +35,7 @@ func ServeData(ctx *context.Context, name string, reader io.Reader) error { return err } +// ServeBlob download a git.Blob func ServeBlob(ctx *context.Context, blob *git.Blob) error { dataRc, err := blob.Data() if err != nil { @@ -43,6 +45,7 @@ func ServeBlob(ctx *context.Context, blob *git.Blob) error { return ServeData(ctx, ctx.Repo.TreePath, dataRc) } +// SingleDownload download a file by repos path func SingleDownload(ctx *context.Context) { blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath) if err != nil { diff --git a/routers/repo/editor.go b/routers/repo/editor.go index fca5430173..d0d528e250 100644 --- a/routers/repo/editor.go +++ b/routers/repo/editor.go @@ -22,10 +22,10 @@ import ( ) const ( - EDIT_FILE base.TplName = "repo/editor/edit" - EDIT_DIFF_PREVIEW base.TplName = "repo/editor/diff_preview" - DELETE_FILE base.TplName = "repo/editor/delete" - UPLOAD_FILE base.TplName = "repo/editor/upload" + tplEditFile base.TplName = "repo/editor/edit" + tplEditDiffPreview base.TplName = "repo/editor/diff_preview" + tplDeleteFile base.TplName = "repo/editor/delete" + tplUploadFile base.TplName = "repo/editor/upload" ) func editFile(ctx *context.Context, isNewFile bool) { @@ -98,13 +98,15 @@ func editFile(ctx *context.Context, isNewFile bool) { ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",") ctx.Data["EditorconfigURLPrefix"] = fmt.Sprintf("%s/api/v1/repos/%s/editorconfig/", setting.AppSubUrl, ctx.Repo.Repository.FullName()) - ctx.HTML(200, EDIT_FILE) + ctx.HTML(200, tplEditFile) } +// EditFile render edit file page func EditFile(ctx *context.Context) { editFile(ctx, false) } +// NewFile render create file page func NewFile(ctx *context.Context) { editFile(ctx, true) } @@ -146,20 +148,20 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",") if ctx.HasError() { - ctx.HTML(200, EDIT_FILE) + ctx.HTML(200, tplEditFile) return } if len(form.TreePath) == 0 { ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.filename_cannot_be_empty"), EDIT_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.filename_cannot_be_empty"), tplEditFile, &form) return } if oldBranchName != branchName { if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { ctx.Data["Err_NewBranchName"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), EDIT_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), tplEditFile, &form) return } } @@ -180,13 +182,13 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo if index != len(treeNames)-1 { if !entry.IsDir() { ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), EDIT_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), tplEditFile, &form) return } } else { if entry.IsDir() { ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", part), EDIT_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.filename_is_a_directory", part), tplEditFile, &form) return } } @@ -197,7 +199,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo if err != nil { if git.IsErrNotExist(err) { ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), EDIT_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), tplEditFile, &form) } else { ctx.Handle(500, "GetTreeEntryByPath", err) } @@ -212,7 +214,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo for _, file := range files { if file == form.TreePath { - ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+lastCommit+"..."+ctx.Repo.CommitID), EDIT_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.file_changed_while_editing", ctx.Repo.RepoLink+"/compare/"+lastCommit+"..."+ctx.Repo.CommitID), tplEditFile, &form) return } } @@ -230,7 +232,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo } if entry != nil { ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.file_already_exists", form.TreePath), EDIT_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.file_already_exists", form.TreePath), tplEditFile, &form) return } } @@ -260,21 +262,24 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo IsNewFile: isNewFile, }); err != nil { ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.fail_to_update_file", form.TreePath, err), EDIT_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.fail_to_update_file", form.TreePath, err), tplEditFile, &form) return } ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(form.TreePath)) } +// EditFilePost response for editing file func EditFilePost(ctx *context.Context, form auth.EditRepoFileForm) { editFilePost(ctx, form, false) } +// NewFilePost response for creating file func NewFilePost(ctx *context.Context, form auth.EditRepoFileForm) { editFilePost(ctx, form, true) } +// DiffPreviewPost render preview diff page func DiffPreviewPost(ctx *context.Context, form auth.EditPreviewDiffForm) { treePath := ctx.Repo.TreePath @@ -299,9 +304,10 @@ func DiffPreviewPost(ctx *context.Context, form auth.EditPreviewDiffForm) { } ctx.Data["File"] = diff.Files[0] - ctx.HTML(200, EDIT_DIFF_PREVIEW) + ctx.HTML(200, tplEditDiffPreview) } +// DeleteFile render delete file page func DeleteFile(ctx *context.Context) { ctx.Data["PageIsDelete"] = true ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName @@ -310,9 +316,10 @@ func DeleteFile(ctx *context.Context) { ctx.Data["commit_message"] = "" ctx.Data["commit_choice"] = "direct" ctx.Data["new_branch_name"] = "" - ctx.HTML(200, DELETE_FILE) + ctx.HTML(200, tplDeleteFile) } +// DeleteFilePost response for deleting file func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) { ctx.Data["PageIsDelete"] = true ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName @@ -330,14 +337,14 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) { ctx.Data["new_branch_name"] = branchName if ctx.HasError() { - ctx.HTML(200, DELETE_FILE) + ctx.HTML(200, tplDeleteFile) return } if oldBranchName != branchName { if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { ctx.Data["Err_NewBranchName"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), DELETE_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), tplDeleteFile, &form) return } } @@ -374,6 +381,7 @@ func renderUploadSettings(ctx *context.Context) { ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles } +// UploadFile render upload file page func UploadFile(ctx *context.Context) { ctx.Data["PageIsUpload"] = true renderUploadSettings(ctx) @@ -391,9 +399,10 @@ func UploadFile(ctx *context.Context) { ctx.Data["commit_choice"] = "direct" ctx.Data["new_branch_name"] = "" - ctx.HTML(200, UPLOAD_FILE) + ctx.HTML(200, tplUploadFile) } +// UploadFilePost response for uploading file func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) { ctx.Data["PageIsUpload"] = true renderUploadSettings(ctx) @@ -422,14 +431,14 @@ func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) { ctx.Data["new_branch_name"] = branchName if ctx.HasError() { - ctx.HTML(200, UPLOAD_FILE) + ctx.HTML(200, tplUploadFile) return } if oldBranchName != branchName { if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil { ctx.Data["Err_NewBranchName"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), tplUploadFile, &form) return } } @@ -451,7 +460,7 @@ func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) { // User can only upload files to a directory. if !entry.IsDir() { ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), tplUploadFile, &form) return } } @@ -475,13 +484,14 @@ func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) { Files: form.Files, }); err != nil { ctx.Data["Err_TreePath"] = true - ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", form.TreePath, err), UPLOAD_FILE, &form) + ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", form.TreePath, err), tplUploadFile, &form) return } ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + form.TreePath) } +// UploadFileToServer upload file to server file dir not git func UploadFileToServer(ctx *context.Context) { file, header, err := ctx.Req.FormFile("file") if err != nil { @@ -525,6 +535,7 @@ func UploadFileToServer(ctx *context.Context) { }) } +// RemoveUploadFileFromServer remove file from server file dir func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) { if len(form.File) == 0 { ctx.Status(204) diff --git a/routers/repo/http.go b/routers/repo/http.go index a51fa9f176..91438812a6 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -29,6 +29,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// HTTP implmentation git smart HTTP protocol func HTTP(ctx *context.Context) { username := ctx.Params(":username") reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git") @@ -170,7 +171,7 @@ func HTTP(ctx *context.Context) { return } - var lastLine int64 = 0 + var lastLine int64 for { head := input[lastLine : lastLine+2] if head[0] == '0' && head[1] == '0' { @@ -193,15 +194,15 @@ func HTTP(ctx *context.Context) { fields := strings.Fields(string(line)) if len(fields) >= 3 { - oldCommitId := fields[0][4:] - newCommitId := fields[1] + oldCommitID := fields[0][4:] + newCommitID := fields[1] refFullName := fields[2] // FIXME: handle error. if err = models.PushUpdate(models.PushUpdateOptions{ RefFullName: refFullName, - OldCommitID: oldCommitId, - NewCommitID: newCommitId, + OldCommitID: oldCommitID, + NewCommitID: newCommitID, PusherID: authUser.ID, PusherName: authUser.Name, RepoUserName: username, @@ -474,6 +475,7 @@ func getGitRepoPath(subdir string) (string, error) { return fpath, nil } +// HTTPBackend middleware for git smart HTTP protocol func HTTPBackend(ctx *context.Context, cfg *serviceConfig) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { for _, route := range routes { diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 3b5abf8962..62bfd3a569 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -27,23 +27,25 @@ import ( ) const ( - ISSUES base.TplName = "repo/issue/list" - ISSUE_NEW base.TplName = "repo/issue/new" - ISSUE_VIEW base.TplName = "repo/issue/view" + tplIssues base.TplName = "repo/issue/list" + tplIssueNew base.TplName = "repo/issue/new" + tplIssueView base.TplName = "repo/issue/view" - LABELS base.TplName = "repo/issue/labels" + tplLabels base.TplName = "repo/issue/labels" - MILESTONE base.TplName = "repo/issue/milestones" - MILESTONE_NEW base.TplName = "repo/issue/milestone_new" - MILESTONE_EDIT base.TplName = "repo/issue/milestone_edit" + tplMilestone base.TplName = "repo/issue/milestones" + tplMilestoneNew base.TplName = "repo/issue/milestone_new" + tplMilestoneEdit base.TplName = "repo/issue/milestone_edit" - ISSUE_TEMPLATE_KEY = "IssueTemplate" + issueTemplateKey = "IssueTemplate" ) var ( + // ErrFileTypeForbidden not allowed file type error ErrFileTypeForbidden = errors.New("File type is not allowed") - ErrTooManyFiles = errors.New("Maximum number of files to upload exceeded") - + // ErrTooManyFiles upload too many files + ErrTooManyFiles = errors.New("Maximum number of files to upload exceeded") + // IssueTemplateCandidates issue templates IssueTemplateCandidates = []string{ "ISSUE_TEMPLATE.md", ".gogs/ISSUE_TEMPLATE.md", @@ -51,6 +53,7 @@ var ( } ) +// MustEnableIssues check if repository enable internal issues func MustEnableIssues(ctx *context.Context) { if !ctx.Repo.Repository.EnableIssues { ctx.Handle(404, "MustEnableIssues", nil) @@ -63,6 +66,7 @@ func MustEnableIssues(ctx *context.Context) { } } +// MustAllowPulls check if repository enable pull requests func MustAllowPulls(ctx *context.Context) { if !ctx.Repo.Repository.AllowsPulls() { ctx.Handle(404, "MustAllowPulls", nil) @@ -76,6 +80,7 @@ func MustAllowPulls(ctx *context.Context) { } } +// RetrieveLabels find all the labels of a repository func RetrieveLabels(ctx *context.Context) { labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID) if err != nil { @@ -89,6 +94,7 @@ func RetrieveLabels(ctx *context.Context) { ctx.Data["NumLabels"] = len(labels) } +// Issues render issues page func Issues(ctx *context.Context) { isPullList := ctx.Params(":type") == "pulls" if isPullList { @@ -244,7 +250,7 @@ func Issues(ctx *context.Context) { ctx.Data["State"] = "open" } - ctx.HTML(200, ISSUES) + ctx.HTML(200, tplIssues) } func renderAttachmentSettings(ctx *context.Context) { @@ -255,6 +261,7 @@ func renderAttachmentSettings(ctx *context.Context) { ctx.Data["AttachmentMaxFiles"] = setting.AttachmentMaxFiles } +// RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) { var err error ctx.Data["OpenMilestones"], err = models.GetMilestones(repo.ID, -1, false) @@ -275,6 +282,7 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repos } } +// RetrieveRepoMetas find all the meta information of a repository func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository) []*models.Label { if !ctx.Repo.IsWriter() { return nil @@ -332,12 +340,13 @@ func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles } } +// NewIssue render createing issue page func NewIssue(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.issues.new") ctx.Data["PageIsIssueList"] = true ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireSimpleMDE"] = true - setTemplateIfExists(ctx, ISSUE_TEMPLATE_KEY, IssueTemplateCandidates) + setTemplateIfExists(ctx, issueTemplateKey, IssueTemplateCandidates) renderAttachmentSettings(ctx) RetrieveRepoMetas(ctx, ctx.Repo.Repository) @@ -345,9 +354,10 @@ func NewIssue(ctx *context.Context) { return } - ctx.HTML(200, ISSUE_NEW) + ctx.HTML(200, tplIssueNew) } +// ValidateRepoMetas check and returns repository's meta informations func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64, int64, int64) { var ( repo = ctx.Repo.Repository @@ -402,6 +412,7 @@ func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64 return labelIDs, milestoneID, assigneeID } +// NewIssuePost response for creating new issue func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) { ctx.Data["Title"] = ctx.Tr("repo.issues.new") ctx.Data["PageIsIssueList"] = true @@ -424,7 +435,7 @@ func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) { } if ctx.HasError() { - ctx.HTML(200, ISSUE_NEW) + ctx.HTML(200, tplIssueNew) return } @@ -446,6 +457,7 @@ func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) { ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) } +// UploadIssueAttachment response for uploading issue's attachment func UploadIssueAttachment(ctx *context.Context) { if !setting.AttachmentEnabled { ctx.Error(404, "attachment is not enabled") @@ -493,6 +505,7 @@ func UploadIssueAttachment(ctx *context.Context) { }) } +// ViewIssue render issue view page func ViewIssue(ctx *context.Context) { ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireDropzone"] = true @@ -639,7 +652,7 @@ func ViewIssue(ctx *context.Context) { ctx.Data["Issue"] = issue ctx.Data["IsIssueOwner"] = ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID)) ctx.Data["SignInLink"] = setting.AppSubUrl + "/user/login?redirect_to=" + ctx.Data["Link"].(string) - ctx.HTML(200, ISSUE_VIEW) + ctx.HTML(200, tplIssueView) } func getActionIssue(ctx *context.Context) *models.Issue { @@ -655,6 +668,7 @@ func getActionIssue(ctx *context.Context) *models.Issue { return issue } +// UpdateIssueTitle change issue's title func UpdateIssueTitle(ctx *context.Context) { issue := getActionIssue(ctx) if ctx.Written() { @@ -682,6 +696,7 @@ func UpdateIssueTitle(ctx *context.Context) { }) } +// UpdateIssueContent change issue's content func UpdateIssueContent(ctx *context.Context) { issue := getActionIssue(ctx) if ctx.Written() { @@ -704,6 +719,7 @@ func UpdateIssueContent(ctx *context.Context) { }) } +// UpdateIssueLabel change issue's labels func UpdateIssueLabel(ctx *context.Context) { issue := getActionIssue(ctx) if ctx.Written() { @@ -745,6 +761,7 @@ func UpdateIssueLabel(ctx *context.Context) { }) } +// UpdateIssueMilestone change issue's milestone func UpdateIssueMilestone(ctx *context.Context) { issue := getActionIssue(ctx) if ctx.Written() { @@ -772,6 +789,7 @@ func UpdateIssueMilestone(ctx *context.Context) { }) } +// UpdateIssueAssignee change issue's assignee func UpdateIssueAssignee(ctx *context.Context) { issue := getActionIssue(ctx) if ctx.Written() { @@ -796,6 +814,7 @@ func UpdateIssueAssignee(ctx *context.Context) { }) } +// NewComment create a comment for issue func NewComment(ctx *context.Context, form auth.CreateCommentForm) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { @@ -882,6 +901,7 @@ func NewComment(ctx *context.Context, form auth.CreateCommentForm) { log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID) } +// UpdateCommentContent change comment of issue's content func UpdateCommentContent(ctx *context.Context) { comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) if err != nil { @@ -914,6 +934,7 @@ func UpdateCommentContent(ctx *context.Context) { }) } +// DeleteComment delete comment of issue func DeleteComment(ctx *context.Context) { comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) if err != nil { @@ -937,15 +958,17 @@ func DeleteComment(ctx *context.Context) { ctx.Status(200) } +// Labels render issue's labels page func Labels(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.labels") ctx.Data["PageIsIssueList"] = true ctx.Data["PageIsLabels"] = true ctx.Data["RequireMinicolors"] = true ctx.Data["LabelTemplates"] = models.LabelTemplates - ctx.HTML(200, LABELS) + ctx.HTML(200, tplLabels) } +// InitializeLabels init labels for a repository func InitializeLabels(ctx *context.Context, form auth.InitializeLabelsForm) { if ctx.HasError() { ctx.Redirect(ctx.Repo.RepoLink + "/labels") @@ -973,6 +996,7 @@ func InitializeLabels(ctx *context.Context, form auth.InitializeLabelsForm) { ctx.Redirect(ctx.Repo.RepoLink + "/labels") } +// NewLabel create new label for repository func NewLabel(ctx *context.Context, form auth.CreateLabelForm) { ctx.Data["Title"] = ctx.Tr("repo.labels") ctx.Data["PageIsLabels"] = true @@ -995,6 +1019,7 @@ func NewLabel(ctx *context.Context, form auth.CreateLabelForm) { ctx.Redirect(ctx.Repo.RepoLink + "/labels") } +// UpdateLabel update a label's name and color func UpdateLabel(ctx *context.Context, form auth.CreateLabelForm) { l, err := models.GetLabelByID(form.ID) if err != nil { @@ -1016,6 +1041,7 @@ func UpdateLabel(ctx *context.Context, form auth.CreateLabelForm) { ctx.Redirect(ctx.Repo.RepoLink + "/labels") } +// DeleteLabel delete a label func DeleteLabel(ctx *context.Context) { if err := models.DeleteLabel(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteLabel: " + err.Error()) @@ -1029,6 +1055,7 @@ func DeleteLabel(ctx *context.Context) { return } +// Milestones render milestones page func Milestones(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.milestones") ctx.Data["PageIsIssueList"] = true @@ -1069,18 +1096,20 @@ func Milestones(ctx *context.Context) { } ctx.Data["IsShowClosed"] = isShowClosed - ctx.HTML(200, MILESTONE) + ctx.HTML(200, tplMilestone) } +// NewMilestone render creating milestone page func NewMilestone(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.milestones.new") ctx.Data["PageIsIssueList"] = true ctx.Data["PageIsMilestones"] = true ctx.Data["RequireDatetimepicker"] = true ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) - ctx.HTML(200, MILESTONE_NEW) + ctx.HTML(200, tplMilestoneNew) } +// NewMilestonePost response for creating milestone func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { ctx.Data["Title"] = ctx.Tr("repo.milestones.new") ctx.Data["PageIsIssueList"] = true @@ -1089,7 +1118,7 @@ func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) if ctx.HasError() { - ctx.HTML(200, MILESTONE_NEW) + ctx.HTML(200, tplMilestoneNew) return } @@ -1099,7 +1128,7 @@ func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local) if err != nil { ctx.Data["Err_Deadline"] = true - ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form) + ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form) return } @@ -1117,6 +1146,7 @@ func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { ctx.Redirect(ctx.Repo.RepoLink + "/milestones") } +// EditMilestone render edting milestone page func EditMilestone(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.milestones.edit") ctx.Data["PageIsMilestones"] = true @@ -1138,9 +1168,10 @@ func EditMilestone(ctx *context.Context) { if len(m.DeadlineString) > 0 { ctx.Data["deadline"] = m.DeadlineString } - ctx.HTML(200, MILESTONE_NEW) + ctx.HTML(200, tplMilestoneNew) } +// EditMilestonePost response for edting milestone func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { ctx.Data["Title"] = ctx.Tr("repo.milestones.edit") ctx.Data["PageIsMilestones"] = true @@ -1149,7 +1180,7 @@ func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language()) if ctx.HasError() { - ctx.HTML(200, MILESTONE_NEW) + ctx.HTML(200, tplMilestoneNew) return } @@ -1159,7 +1190,7 @@ func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local) if err != nil { ctx.Data["Err_Deadline"] = true - ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form) + ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form) return } @@ -1184,6 +1215,7 @@ func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) { ctx.Redirect(ctx.Repo.RepoLink + "/milestones") } +// ChangeMilestonStatus response for change a milestone's status func ChangeMilestonStatus(ctx *context.Context) { m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { @@ -1218,6 +1250,7 @@ func ChangeMilestonStatus(ctx *context.Context) { } } +// DeleteMilestone delete a milestone func DeleteMilestone(ctx *context.Context) { if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteMilestoneByRepoID: " + err.Error()) diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 6e99dfaed0..c8969b98f2 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -21,16 +21,16 @@ import ( ) const ( - FORK base.TplName = "repo/pulls/fork" - COMPARE_PULL base.TplName = "repo/pulls/compare" - PULL_COMMITS base.TplName = "repo/pulls/commits" - PULL_FILES base.TplName = "repo/pulls/files" + tplFork base.TplName = "repo/pulls/fork" + tplComparePull base.TplName = "repo/pulls/compare" + tplPullCommits base.TplName = "repo/pulls/commits" + tplPullFiles base.TplName = "repo/pulls/files" - PULL_REQUEST_TEMPLATE_KEY = "PullRequestTemplate" + pullRequestTemplateKey = "PullRequestTemplate" ) var ( - PullRequestTemplateCandidates = []string{ + pullRequestTemplateCandidates = []string{ "PULL_REQUEST.md", ".gogs/PULL_REQUEST.md", ".github/PULL_REQUEST.md", @@ -72,6 +72,7 @@ func getForkRepository(ctx *context.Context) *models.Repository { return forkRepo } +// Fork render repository fork page func Fork(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("new_fork") @@ -81,9 +82,10 @@ func Fork(ctx *context.Context) { } ctx.Data["ContextUser"] = ctx.User - ctx.HTML(200, FORK) + ctx.HTML(200, tplFork) } +// ForkPost response for forking a repository func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_fork") @@ -99,7 +101,7 @@ func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["ContextUser"] = ctxUser if ctx.HasError() { - ctx.HTML(200, FORK) + ctx.HTML(200, tplFork) return } @@ -122,11 +124,11 @@ func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["Err_RepoName"] = true switch { case models.IsErrRepoAlreadyExist(err): - ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), FORK, &form) + ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form) case models.IsErrNameReserved(err): - ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &form) + ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplFork, &form) case models.IsErrNamePatternNotAllowed(err): - ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &form) + ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplFork, &form) default: ctx.Handle(500, "ForkPost", err) } @@ -171,6 +173,7 @@ func checkPullInfo(ctx *context.Context) *models.Issue { return issue } +// PrepareMergedViewPullInfo show meta information for a merged pull request view page func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) { pull := issue.PullRequest ctx.Data["HasMerged"] = true @@ -190,6 +193,7 @@ func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) { } } +// PrepareViewPullInfo show meta information for a pull request preview page func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullRequestInfo { repo := ctx.Repo.Repository pull := issue.PullRequest @@ -242,6 +246,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullReq return prInfo } +// ViewPullCommits show commits for a pull request func ViewPullCommits(ctx *context.Context) { ctx.Data["PageIsPullList"] = true ctx.Data["PageIsPullCommits"] = true @@ -291,9 +296,10 @@ func ViewPullCommits(ctx *context.Context) { ctx.Data["Commits"] = commits ctx.Data["CommitCount"] = commits.Len() - ctx.HTML(200, PULL_COMMITS) + ctx.HTML(200, tplPullCommits) } +// ViewPullFiles render pull request changed files list page func ViewPullFiles(ctx *context.Context) { ctx.Data["PageIsPullList"] = true ctx.Data["PageIsPullFiles"] = true @@ -375,9 +381,10 @@ func ViewPullFiles(ctx *context.Context) { ctx.Data["RawPath"] = setting.AppSubUrl + "/" + path.Join(headTarget, "raw", endCommitID) ctx.Data["RequireHighlightJS"] = true - ctx.HTML(200, PULL_FILES) + ctx.HTML(200, tplPullFiles) } +// MergePullRequest response for merging pull request func MergePullRequest(ctx *context.Context) { issue := checkPullInfo(ctx) if ctx.Written() { @@ -414,6 +421,7 @@ func MergePullRequest(ctx *context.Context) { ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) } +// ParseCompareInfo parse compare info between two commit for preparing pull request func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) { baseRepo := ctx.Repo.Repository @@ -520,6 +528,7 @@ func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, * return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch } +// PrepareCompareDiff render pull request preview diff page func PrepareCompareDiff( ctx *context.Context, headUser *models.User, @@ -578,12 +587,13 @@ func PrepareCompareDiff( return false } +// CompareAndPullRequest render pull request preview page func CompareAndPullRequest(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes") ctx.Data["PageIsComparePull"] = true ctx.Data["IsDiffCompare"] = true ctx.Data["RequireHighlightJS"] = true - setTemplateIfExists(ctx, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates) + setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates) renderAttachmentSettings(ctx) headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx) @@ -600,7 +610,7 @@ func CompareAndPullRequest(ctx *context.Context) { } else { ctx.Data["HasPullRequest"] = true ctx.Data["PullRequest"] = pr - ctx.HTML(200, COMPARE_PULL) + ctx.HTML(200, tplComparePull) return } @@ -617,9 +627,10 @@ func CompareAndPullRequest(ctx *context.Context) { } } - ctx.HTML(200, COMPARE_PULL) + ctx.HTML(200, tplComparePull) } +// CompareAndPullRequestPost response for creating pull request func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) { ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes") ctx.Data["PageIsComparePull"] = true @@ -656,7 +667,7 @@ func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) return } - ctx.HTML(200, COMPARE_PULL) + ctx.HTML(200, tplComparePull) return } @@ -702,6 +713,7 @@ func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index)) } +// TriggerTask response for a trigger task request func TriggerTask(ctx *context.Context) { pusherID := ctx.QueryInt64("pusher") branch := ctx.Query("branch") diff --git a/routers/repo/release.go b/routers/repo/release.go index 187952c2e6..7616d9e79e 100644 --- a/routers/repo/release.go +++ b/routers/repo/release.go @@ -17,8 +17,8 @@ import ( ) const ( - RELEASES base.TplName = "repo/release/list" - RELEASE_NEW base.TplName = "repo/release/new" + tplReleases base.TplName = "repo/release/list" + tplReleaseNew base.TplName = "repo/release/new" ) // calReleaseNumCommitsBehind calculates given release has how many commits behind release target. @@ -49,6 +49,7 @@ func calReleaseNumCommitsBehind(repoCtx *context.Repository, release *models.Rel return nil } +// Releases render releases list page func Releases(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.release.releases") ctx.Data["PageIsReleaseList"] = true @@ -150,27 +151,29 @@ func Releases(ctx *context.Context) { ctx.Data["Page"] = pager models.SortReleases(tags) ctx.Data["Releases"] = tags - ctx.HTML(200, RELEASES) + ctx.HTML(200, tplReleases) } +// NewRelease render creating release page func NewRelease(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.release.new_release") ctx.Data["PageIsReleaseList"] = true ctx.Data["tag_target"] = ctx.Repo.Repository.DefaultBranch - ctx.HTML(200, RELEASE_NEW) + ctx.HTML(200, tplReleaseNew) } +// NewReleasePost response for creating a release func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) { ctx.Data["Title"] = ctx.Tr("repo.release.new_release") ctx.Data["PageIsReleaseList"] = true if ctx.HasError() { - ctx.HTML(200, RELEASE_NEW) + ctx.HTML(200, tplReleaseNew) return } if !ctx.Repo.GitRepo.IsBranchExist(form.Target) { - ctx.RenderWithErr(ctx.Tr("form.target_branch_not_exist"), RELEASE_NEW, &form) + ctx.RenderWithErr(ctx.Tr("form.target_branch_not_exist"), tplReleaseNew, &form) return } @@ -213,9 +216,9 @@ func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) { ctx.Data["Err_TagName"] = true switch { case models.IsErrReleaseAlreadyExist(err): - ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_already_exist"), RELEASE_NEW, &form) + ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_already_exist"), tplReleaseNew, &form) case models.IsErrInvalidTagName(err): - ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_invalid"), RELEASE_NEW, &form) + ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_invalid"), tplReleaseNew, &form) default: ctx.Handle(500, "CreateRelease", err) } @@ -226,6 +229,7 @@ func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) { ctx.Redirect(ctx.Repo.RepoLink + "/releases") } +// EditRelease render release edit page func EditRelease(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.release.edit_release") ctx.Data["PageIsReleaseList"] = true @@ -249,9 +253,10 @@ func EditRelease(ctx *context.Context) { ctx.Data["prerelease"] = rel.IsPrerelease ctx.Data["IsDraft"] = rel.IsDraft - ctx.HTML(200, RELEASE_NEW) + ctx.HTML(200, tplReleaseNew) } +// EditReleasePost response for edit release func EditReleasePost(ctx *context.Context, form auth.EditReleaseForm) { ctx.Data["Title"] = ctx.Tr("repo.release.edit_release") ctx.Data["PageIsReleaseList"] = true @@ -274,7 +279,7 @@ func EditReleasePost(ctx *context.Context, form auth.EditReleaseForm) { ctx.Data["prerelease"] = rel.IsPrerelease if ctx.HasError() { - ctx.HTML(200, RELEASE_NEW) + ctx.HTML(200, tplReleaseNew) return } @@ -289,6 +294,7 @@ func EditReleasePost(ctx *context.Context, form auth.EditReleaseForm) { ctx.Redirect(ctx.Repo.RepoLink + "/releases") } +// DeleteRelease delete a release func DeleteRelease(ctx *context.Context) { if err := models.DeleteReleaseByID(ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteReleaseByID: " + err.Error()) diff --git a/routers/repo/repo.go b/routers/repo/repo.go index c3e9faf499..fdf4cd5594 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -23,10 +23,11 @@ import ( ) const ( - CREATE base.TplName = "repo/create" - MIGRATE base.TplName = "repo/migrate" + tplCreate base.TplName = "repo/create" + tplMigrate base.TplName = "repo/migrate" ) +// MustBeNotBare render when a repo is a bare git dir func MustBeNotBare(ctx *context.Context) { if ctx.Repo.Repository.IsBare { ctx.Handle(404, "MustBeNotBare", nil) @@ -64,6 +65,7 @@ func checkContextUser(ctx *context.Context, uid int64) *models.User { return org } +// Create render creating repository page func Create(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("new_repo") @@ -81,7 +83,7 @@ func Create(ctx *context.Context) { } ctx.Data["ContextUser"] = ctxUser - ctx.HTML(200, CREATE) + ctx.HTML(200, tplCreate) } func handleCreateError(ctx *context.Context, owner *models.User, err error, name string, tpl base.TplName, form interface{}) { @@ -102,6 +104,7 @@ func handleCreateError(ctx *context.Context, owner *models.User, err error, name } } +// CreatePost response for creating repository func CreatePost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_repo") @@ -116,7 +119,7 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["ContextUser"] = ctxUser if ctx.HasError() { - ctx.HTML(200, CREATE) + ctx.HTML(200, tplCreate) return } @@ -141,9 +144,10 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) { } } - handleCreateError(ctx, ctxUser, err, "CreatePost", CREATE, &form) + handleCreateError(ctx, ctxUser, err, "CreatePost", tplCreate, &form) } +// Migrate render migration of repository page func Migrate(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("new_migrate") ctx.Data["private"] = ctx.User.LastRepoVisibility @@ -156,9 +160,10 @@ func Migrate(ctx *context.Context) { } ctx.Data["ContextUser"] = ctxUser - ctx.HTML(200, MIGRATE) + ctx.HTML(200, tplMigrate) } +// MigratePost response for migrating from external git repository func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_migrate") @@ -169,7 +174,7 @@ func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) { ctx.Data["ContextUser"] = ctxUser if ctx.HasError() { - ctx.HTML(200, MIGRATE) + ctx.HTML(200, tplMigrate) return } @@ -180,11 +185,11 @@ func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) { addrErr := err.(models.ErrInvalidCloneAddr) switch { case addrErr.IsURLError: - ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &form) + ctx.RenderWithErr(ctx.Tr("form.url_error"), tplMigrate, &form) case addrErr.IsPermissionDenied: - ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), MIGRATE, &form) + ctx.RenderWithErr(ctx.Tr("repo.migrate.permission_denied"), tplMigrate, &form) case addrErr.IsInvalidPath: - ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &form) + ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), tplMigrate, &form) default: ctx.Handle(500, "Unknown error", err) } @@ -216,17 +221,18 @@ func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) { if strings.Contains(err.Error(), "Authentication failed") || strings.Contains(err.Error(), "could not read Username") { ctx.Data["Err_Auth"] = true - ctx.RenderWithErr(ctx.Tr("form.auth_failed", models.HandleCloneUserCredentials(err.Error(), true)), MIGRATE, &form) + ctx.RenderWithErr(ctx.Tr("form.auth_failed", models.HandleCloneUserCredentials(err.Error(), true)), tplMigrate, &form) return } else if strings.Contains(err.Error(), "fatal:") { ctx.Data["Err_CloneAddr"] = true - ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", models.HandleCloneUserCredentials(err.Error(), true)), MIGRATE, &form) + ctx.RenderWithErr(ctx.Tr("repo.migrate.failed", models.HandleCloneUserCredentials(err.Error(), true)), tplMigrate, &form) return } - handleCreateError(ctx, ctxUser, err, "MigratePost", MIGRATE, &form) + handleCreateError(ctx, ctxUser, err, "MigratePost", tplMigrate, &form) } +// Action response for actions to a repository func Action(ctx *context.Context) { var err error switch ctx.Params(":action") { @@ -261,6 +267,7 @@ func Action(ctx *context.Context) { ctx.Redirect(redirectTo) } +// Download download an archive of a repository func Download(ctx *context.Context) { var ( uri = ctx.Params("*") diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 736a7fdf9a..2b8c5a2315 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -26,12 +26,14 @@ const ( tplDeployKeys base.TplName = "repo/settings/deploy_keys" ) +// Settings show a repository's settings page func Settings(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsOptions"] = true ctx.HTML(200, tplSettingsOptions) } +// SettingsPost response for changes of a repository func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsOptions"] = true @@ -293,6 +295,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) { } } +// Collaboration render a repository's collaboration page func Collaboration(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsCollaboration"] = true @@ -307,6 +310,7 @@ func Collaboration(ctx *context.Context) { ctx.HTML(200, tplCollaboration) } +// CollaborationPost response for actions for a collaboration of a repository func CollaborationPost(ctx *context.Context) { name := strings.ToLower(ctx.Query("collaborator")) if len(name) == 0 || ctx.Repo.Owner.LowerName == name { @@ -352,6 +356,7 @@ func CollaborationPost(ctx *context.Context) { ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) } +// ChangeCollaborationAccessMode response for changing access of a collaboration func ChangeCollaborationAccessMode(ctx *context.Context) { if err := ctx.Repo.Repository.ChangeCollaborationAccessMode( ctx.QueryInt64("uid"), @@ -360,6 +365,7 @@ func ChangeCollaborationAccessMode(ctx *context.Context) { } } +// DeleteCollaboration delete a collaboration for a repository func DeleteCollaboration(ctx *context.Context) { if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteCollaboration: " + err.Error()) @@ -396,6 +402,7 @@ func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) return owner, repo } +// GitHooks hooks of a repository func GitHooks(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.githooks") ctx.Data["PageIsSettingsGitHooks"] = true @@ -410,6 +417,7 @@ func GitHooks(ctx *context.Context) { ctx.HTML(200, tplGithooks) } +// GitHooksEdit render for editing a hook of repository page func GitHooksEdit(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.githooks") ctx.Data["PageIsSettingsGitHooks"] = true @@ -428,6 +436,7 @@ func GitHooksEdit(ctx *context.Context) { ctx.HTML(200, tplGithookEdit) } +// GitHooksEditPost response for editing a git hook of a repository func GitHooksEditPost(ctx *context.Context) { name := ctx.Params(":name") hook, err := ctx.Repo.GitRepo.GetHook(name) @@ -447,6 +456,7 @@ func GitHooksEditPost(ctx *context.Context) { ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git") } +// DeployKeys render the deploy keys list of a repository page func DeployKeys(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") ctx.Data["PageIsSettingsKeys"] = true @@ -461,6 +471,7 @@ func DeployKeys(ctx *context.Context) { ctx.HTML(200, tplDeployKeys) } +// DeployKeysPost response for adding a deploy key of a repository func DeployKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys") ctx.Data["PageIsSettingsKeys"] = true @@ -511,6 +522,7 @@ func DeployKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) { ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys") } +// DeleteDeployKey response for deleting a deploy key func DeleteDeployKey(ctx *context.Context) { if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteDeployKey: " + err.Error()) diff --git a/routers/repo/webhook.go b/routers/repo/webhook.go index 3f292397b9..33ad834c95 100644 --- a/routers/repo/webhook.go +++ b/routers/repo/webhook.go @@ -28,6 +28,7 @@ const ( tplOrgHookNew base.TplName = "org/settings/hook_new" ) +// Webhooks render web hooks list page func Webhooks(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.hooks") ctx.Data["PageIsSettingsHooks"] = true @@ -44,7 +45,7 @@ func Webhooks(ctx *context.Context) { ctx.HTML(200, tplHooks) } -type OrgRepoCtx struct { +type orgRepoCtx struct { OrgID int64 RepoID int64 Link string @@ -52,9 +53,9 @@ type OrgRepoCtx struct { } // getOrgRepoCtx determines whether this is a repo context or organization context. -func getOrgRepoCtx(ctx *context.Context) (*OrgRepoCtx, error) { +func getOrgRepoCtx(ctx *context.Context) (*orgRepoCtx, error) { if len(ctx.Repo.RepoLink) > 0 { - return &OrgRepoCtx{ + return &orgRepoCtx{ RepoID: ctx.Repo.Repository.ID, Link: ctx.Repo.RepoLink, NewTemplate: tplHookNew, @@ -62,7 +63,7 @@ func getOrgRepoCtx(ctx *context.Context) (*OrgRepoCtx, error) { } if len(ctx.Org.OrgLink) > 0 { - return &OrgRepoCtx{ + return &orgRepoCtx{ OrgID: ctx.Org.Organization.ID, Link: ctx.Org.OrgLink, NewTemplate: tplOrgHookNew, @@ -81,6 +82,7 @@ func checkHookType(ctx *context.Context) string { return hookType } +// WebhooksNew render creating webhook page func WebhooksNew(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") ctx.Data["PageIsSettingsHooks"] = true @@ -102,6 +104,7 @@ func WebhooksNew(ctx *context.Context) { ctx.HTML(200, orCtx.NewTemplate) } +// ParseHookEvent convert web form content to models.HookEvent func ParseHookEvent(form auth.WebhookForm) *models.HookEvent { return &models.HookEvent{ PushOnly: form.PushOnly(), @@ -115,6 +118,7 @@ func ParseHookEvent(form auth.WebhookForm) *models.HookEvent { } } +// WebHooksNewPost response for creating webhook func WebHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook") ctx.Data["PageIsSettingsHooks"] = true @@ -161,6 +165,7 @@ func WebHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) { ctx.Redirect(orCtx.Link + "/settings/hooks") } +// SlackHooksNewPost response for creating slack hook func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsHooks"] = true @@ -211,7 +216,7 @@ func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) { ctx.Redirect(orCtx.Link + "/settings/hooks") } -func checkWebhook(ctx *context.Context) (*OrgRepoCtx, *models.Webhook) { +func checkWebhook(ctx *context.Context) (*orgRepoCtx, *models.Webhook) { ctx.Data["RequireHighlightJS"] = true orCtx, err := getOrgRepoCtx(ctx) @@ -251,6 +256,7 @@ func checkWebhook(ctx *context.Context) (*OrgRepoCtx, *models.Webhook) { return orCtx, w } +// WebHooksEdit render editing web hook page func WebHooksEdit(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook") ctx.Data["PageIsSettingsHooks"] = true @@ -265,6 +271,7 @@ func WebHooksEdit(ctx *context.Context) { ctx.HTML(200, orCtx.NewTemplate) } +// WebHooksEditPost response for editing web hook func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook") ctx.Data["PageIsSettingsHooks"] = true @@ -303,6 +310,7 @@ func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) { ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) } +// SlackHooksEditPost reponse for editing slack hook func SlackHooksEditPost(ctx *context.Context, form auth.NewSlackHookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsHooks"] = true @@ -346,6 +354,7 @@ func SlackHooksEditPost(ctx *context.Context, form auth.NewSlackHookForm) { ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) } +// TestWebhook test if web hook is work fine func TestWebhook(ctx *context.Context) { // Grab latest commit or fake one if it's empty repository. commit := ctx.Repo.Commit @@ -393,6 +402,7 @@ func TestWebhook(ctx *context.Context) { } } +// DeleteWebhook delete a webhook func DeleteWebhook(ctx *context.Context) { if err := models.DeleteWebhookByRepoID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error()) From fb3bb69ec6b062a7ac260208ef2c9a3711d15de1 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 24 Nov 2016 15:17:44 +0800 Subject: [PATCH 004/135] golint fixed for modules/base --- modules/base/base.go | 2 ++ modules/base/tool.go | 21 ++++++++++++++------- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/modules/base/base.go b/modules/base/base.go index 5c5632dee8..0ba72c328e 100644 --- a/modules/base/base.go +++ b/modules/base/base.go @@ -4,8 +4,10 @@ package base +// DocURL api doc url const DocURL = "https://godoc.org/github.com/go-gitea/go-sdk/gitea" type ( + // TplName template relative path type TplName string ) diff --git a/modules/base/tool.go b/modules/base/tool.go index bacdeb2924..db065afd8c 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -36,7 +36,7 @@ func EncodeMD5(str string) string { return hex.EncodeToString(m.Sum(nil)) } -// Encode string to sha1 hex value. +// EncodeSha1 string to sha1 hex value. func EncodeSha1(str string) string { h := sha1.New() h.Write([]byte(str)) @@ -49,6 +49,7 @@ func ShortSha(sha1 string) string { return TruncateString(sha1, 10) } +// DetectEncoding detect the encoding of content func DetectEncoding(content []byte) (string, error) { if utf8.Valid(content) { log.Debug("Detected encoding: utf-8 (fast)") @@ -65,6 +66,7 @@ func DetectEncoding(content []byte) (string, error) { return result.Charset, err } +// BasicAuthDecode decode basic auth string func BasicAuthDecode(encoded string) (string, string, error) { s, err := base64.StdEncoding.DecodeString(encoded) if err != nil { @@ -75,6 +77,7 @@ func BasicAuthDecode(encoded string) (string, string, error) { return auth[0], auth[1], nil } +// BasicAuthEncode encode basic auth string func BasicAuthEncode(username, password string) string { return base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) } @@ -94,7 +97,7 @@ func GetRandomString(n int, alphabets ...byte) string { return string(bytes) } -// http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto +// PBKDF2 http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto // FIXME: use https://godoc.org/golang.org/x/crypto/pbkdf2? func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte { prf := hmac.New(h, password) @@ -133,7 +136,7 @@ func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte return dk[:keyLen] } -// verify time limit code +// VerifyTimeLimitCode verify time limit code func VerifyTimeLimitCode(data string, minutes int, code string) bool { if len(code) <= 18 { return false @@ -160,9 +163,10 @@ func VerifyTimeLimitCode(data string, minutes int, code string) bool { return false } +// TimeLimitCodeLength default value for time limit code const TimeLimitCodeLength = 12 + 6 + 40 -// create a time limit code +// CreateTimeLimitCode create a time limit code // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string { format := "200601021504" @@ -355,6 +359,7 @@ func timeSince(then time.Time, lang string) string { } } +// RawTimeSince retrieves i18n key of time since t func RawTimeSince(t time.Time, lang string) string { return timeSince(t, lang) } @@ -364,6 +369,7 @@ func TimeSince(t time.Time, lang string) template.HTML { return template.HTML(fmt.Sprintf(`%s`, t.Format(setting.TimeFormat), timeSince(t, lang))) } +// Storage space size types const ( Byte = 1 KByte = Byte * 1024 @@ -413,7 +419,7 @@ func FileSize(s int64) string { func Subtract(left interface{}, right interface{}) interface{} { var rleft, rright int64 var fleft, fright float64 - var isInt bool = true + var isInt = true switch left.(type) { case int: rleft = int64(left.(int)) @@ -454,9 +460,8 @@ func Subtract(left interface{}, right interface{}) interface{} { if isInt { return rleft - rright - } else { - return fleft + float64(rleft) - (fright + float64(rright)) } + return fleft + float64(rleft) - (fright + float64(rright)) } // EllipsisString returns a truncated short string, @@ -521,10 +526,12 @@ func IsTextFile(data []byte) bool { return strings.Index(http.DetectContentType(data), "text/") != -1 } +// IsImageFile detectes if data is an image format func IsImageFile(data []byte) bool { return strings.Index(http.DetectContentType(data), "image/") != -1 } +// IsPDFFile detectes if data is a pdf format func IsPDFFile(data []byte) bool { return strings.Index(http.DetectContentType(data), "application/pdf") != -1 } From 6ed7f269f198b5a57e5bc7eca6ddec4980417899 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 24 Nov 2016 15:40:16 +0800 Subject: [PATCH 005/135] Move init functions from routers/install to routers/init (#230) * move init functions from routers/install to routers/init * copyright typo --- routers/init.go | 82 ++++++++++++++++++++++++++++++++++++++++++++++ routers/install.go | 69 -------------------------------------- 2 files changed, 82 insertions(+), 69 deletions(-) create mode 100644 routers/init.go diff --git a/routers/init.go b/routers/init.go new file mode 100644 index 0000000000..07f84a25fb --- /dev/null +++ b/routers/init.go @@ -0,0 +1,82 @@ +// Copyright 2016 The Gitea 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 routers + +import ( + "path" + "strings" + + "code.gitea.io/git" + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/cron" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/mailer" + "code.gitea.io/gitea/modules/markdown" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/ssh" + "code.gitea.io/gitea/modules/template/highlight" + macaron "gopkg.in/macaron.v1" +) + +func checkRunMode() { + switch setting.Cfg.Section("").Key("RUN_MODE").String() { + case "prod": + macaron.Env = macaron.PROD + macaron.ColorLog = false + setting.ProdMode = true + default: + git.Debug = true + } + log.Info("Run Mode: %s", strings.Title(macaron.Env)) +} + +// NewServices init new services +func NewServices() { + setting.NewServices() + mailer.NewContext() +} + +// GlobalInit is for global configuration reload-able. +func GlobalInit() { + setting.NewContext() + log.Trace("Custom path: %s", setting.CustomPath) + log.Trace("Log path: %s", setting.LogRootPath) + models.LoadConfigs() + NewServices() + + if setting.InstallLock { + highlight.NewContext() + markdown.BuildSanitizer() + if err := models.NewEngine(); err != nil { + log.Fatal(4, "Fail to initialize ORM engine: %v", err) + } + models.HasEngine = true + + models.LoadRepoConfig() + models.NewRepoContext() + + // Booting long running goroutines. + cron.NewContext() + models.InitSyncMirrors() + models.InitDeliverHooks() + models.InitTestPullRequests() + log.NewGitLogger(path.Join(setting.LogRootPath, "http.log")) + } + if models.EnableSQLite3 { + log.Info("SQLite3 Supported") + } + if models.EnableTiDB { + log.Info("TiDB Supported") + } + if setting.SupportMiniWinService { + log.Info("Builtin Windows Service Supported") + } + checkRunMode() + + if setting.InstallLock && setting.SSH.StartBuiltinServer { + ssh.Listen(setting.SSH.ListenPort) + log.Info("SSH server started on :%v", setting.SSH.ListenPort) + } +} diff --git a/routers/install.go b/routers/install.go index 5cc2136449..ab9c835507 100644 --- a/routers/install.go +++ b/routers/install.go @@ -15,21 +15,13 @@ import ( "github.com/Unknwon/com" "github.com/go-xorm/xorm" "gopkg.in/ini.v1" - "gopkg.in/macaron.v1" - - "code.gitea.io/git" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/cron" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/mailer" - "code.gitea.io/gitea/modules/markdown" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/ssh" - "code.gitea.io/gitea/modules/template/highlight" "code.gitea.io/gitea/modules/user" ) @@ -38,67 +30,6 @@ const ( tplInstall base.TplName = "install" ) -func checkRunMode() { - switch setting.Cfg.Section("").Key("RUN_MODE").String() { - case "prod": - macaron.Env = macaron.PROD - macaron.ColorLog = false - setting.ProdMode = true - default: - git.Debug = true - } - log.Info("Run Mode: %s", strings.Title(macaron.Env)) -} - -// NewServices init new services -func NewServices() { - setting.NewServices() - mailer.NewContext() -} - -// GlobalInit is for global configuration reload-able. -func GlobalInit() { - setting.NewContext() - log.Trace("Custom path: %s", setting.CustomPath) - log.Trace("Log path: %s", setting.LogRootPath) - models.LoadConfigs() - NewServices() - - if setting.InstallLock { - highlight.NewContext() - markdown.BuildSanitizer() - if err := models.NewEngine(); err != nil { - log.Fatal(4, "Fail to initialize ORM engine: %v", err) - } - models.HasEngine = true - - models.LoadRepoConfig() - models.NewRepoContext() - - // Booting long running goroutines. - cron.NewContext() - models.InitSyncMirrors() - models.InitDeliverHooks() - models.InitTestPullRequests() - log.NewGitLogger(path.Join(setting.LogRootPath, "http.log")) - } - if models.EnableSQLite3 { - log.Info("SQLite3 Supported") - } - if models.EnableTiDB { - log.Info("TiDB Supported") - } - if setting.SupportMiniWinService { - log.Info("Builtin Windows Service Supported") - } - checkRunMode() - - if setting.InstallLock && setting.SSH.StartBuiltinServer { - ssh.Listen(setting.SSH.ListenPort) - log.Info("SSH server started on :%v", setting.SSH.ListenPort) - } -} - // InstallInit prepare for rendering installation page func InstallInit(ctx *context.Context) { if setting.InstallLock { From ad3d6b7fffd9ee1380e7149cc2c5bfc7c3396891 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Tue, 15 Nov 2016 08:06:31 +0100 Subject: [PATCH 006/135] Lint and document manager api --- modules/process/manager.go | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/modules/process/manager.go b/modules/process/manager.go index 4510a823cf..2748c14bb4 100644 --- a/modules/process/manager.go +++ b/modules/process/manager.go @@ -15,13 +15,14 @@ import ( ) var ( + // ErrExecTimeout represent a timeout error ErrExecTimeout = errors.New("Process execution timeout") -) -// Common timeout. -var ( + // DefaultTimeout is the timeout used by Exec* family + // of function when timeout parameter is omitted or + // passed as -1 // NOTE: could be custom in config file for default. - DEFAULT = 60 * time.Second + DefaultTimeout = 60 * time.Second ) // Process represents a working process inherit from Gogs. @@ -51,10 +52,13 @@ func Add(desc string, cmd *exec.Cmd) int64 { return pid } -// Exec starts executing a command in given path, it records its process and timeout. +// ExecDir runs a command in given path and waits for its completion +// up to the given timeout (or DefaultTimeout if -1 is given). +// Returns its complete stdout and stderr +// outputs and an error, if any (including timeout) func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) (string, string, error) { if timeout == -1 { - timeout = DEFAULT + timeout = DefaultTimeout } bufOut := new(bytes.Buffer) @@ -89,12 +93,17 @@ func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) ( return bufOut.String(), bufErr.String(), err } -// Exec starts executing a command, it records its process and timeout. +// ExecTimeout runs a command and waits for its completion +// up to the given timeout (or DefaultTimeout if -1 is given). +// Returns its complete stdout and stderr +// outputs and an error, if any (including timeout) func ExecTimeout(timeout time.Duration, desc, cmdName string, args ...string) (string, string, error) { return ExecDir(timeout, "", desc, cmdName, args...) } -// Exec starts executing a command, it records its process and has default timeout. +// Exec runs a command and waits for its completion +// up to DefaultTimeout. Returns its complete stdout and stderr +// outputs and an error, if any (including timeout) func Exec(desc, cmdName string, args ...string) (string, string, error) { return ExecDir(-1, "", desc, cmdName, args...) } From 5301a5db3a8c6d1e45a95b17877b7ac4b113062a Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Fri, 18 Nov 2016 09:57:30 +0100 Subject: [PATCH 007/135] Have the deault 'all' rule just build Clean and test are saner being seperate targets --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 7c318f9dec..a57f6610af 100644 --- a/Makefile +++ b/Makefile @@ -30,7 +30,7 @@ else endif .PHONY: all -all: clean test build +all: build .PHONY: clean clean: From 4dd1eb57bd205f52ce3be3b04e9b2c6f70d39544 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Tue, 22 Nov 2016 12:24:39 +0100 Subject: [PATCH 008/135] Lint issue.go --- models/issue.go | 113 ++++++++++++++++++++++++++++++------------------ 1 file changed, 70 insertions(+), 43 deletions(-) diff --git a/models/issue.go b/models/issue.go index 09ecb2e6d3..7876d3ec88 100644 --- a/models/issue.go +++ b/models/issue.go @@ -25,7 +25,7 @@ import ( ) var ( - ErrMissingIssueNumber = errors.New("No issue number specified") + errMissingIssueNumber = errors.New("No issue number specified") ) // Issue represents an issue or pull request of repository. @@ -62,16 +62,19 @@ type Issue struct { Comments []*Comment `xorm:"-"` } +// BeforeInsert ... func (issue *Issue) BeforeInsert() { issue.CreatedUnix = time.Now().Unix() issue.UpdatedUnix = issue.CreatedUnix } +// BeforeUpdate ... func (issue *Issue) BeforeUpdate() { issue.UpdatedUnix = time.Now().Unix() issue.DeadlineUnix = issue.Deadline.Unix() } +// AfterSet ... func (issue *Issue) AfterSet(colName string, _ xorm.Cell) { switch colName { case "deadline_unix": @@ -83,6 +86,7 @@ func (issue *Issue) AfterSet(colName string, _ xorm.Cell) { } } +// loadAttributes ... func (issue *Issue) loadAttributes(e Engine) (err error) { if issue.Repo == nil { issue.Repo, err = getRepositoryByID(e, issue.RepoID) @@ -150,10 +154,12 @@ func (issue *Issue) loadAttributes(e Engine) (err error) { return nil } +// LoadAttributes ... func (issue *Issue) LoadAttributes() error { return issue.loadAttributes(x) } +// HTMLURL ... func (issue *Issue) HTMLURL() string { var path string if issue.IsPull { @@ -165,14 +171,14 @@ func (issue *Issue) HTMLURL() string { } // State returns string representation of issue status. -func (i *Issue) State() api.StateType { - if i.IsClosed { +func (issue *Issue) State() api.StateType { + if issue.IsClosed { return api.STATE_CLOSED } return api.STATE_OPEN } -// This method assumes some fields assigned with values: +// APIFormat assumes some fields assigned with values: // Required - Poster, Labels, // Optional - Milestone, Assignee, PullRequest func (issue *Issue) APIFormat() *api.Issue { @@ -213,24 +219,25 @@ func (issue *Issue) APIFormat() *api.Issue { } // HashTag returns unique hash tag for issue. -func (i *Issue) HashTag() string { - return "issue-" + com.ToStr(i.ID) +func (issue *Issue) HashTag() string { + return "issue-" + com.ToStr(issue.ID) } // IsPoster returns true if given user by ID is the poster. -func (i *Issue) IsPoster(uid int64) bool { - return i.PosterID == uid +func (issue *Issue) IsPoster(uid int64) bool { + return issue.PosterID == uid } -func (i *Issue) hasLabel(e Engine, labelID int64) bool { - return hasIssueLabel(e, i.ID, labelID) +func (issue *Issue) hasLabel(e Engine, labelID int64) bool { + return hasIssueLabel(e, issue.ID, labelID) } // HasLabel returns true if issue has been labeled by given ID. -func (i *Issue) HasLabel(labelID int64) bool { - return i.hasLabel(x, labelID) +func (issue *Issue) HasLabel(labelID int64) bool { + return issue.hasLabel(x, labelID) } +// sendLabelUpdatedWebhook ... func (issue *Issue) sendLabelUpdatedWebhook(doer *User) { var err error if issue.IsPull { @@ -254,8 +261,9 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) { } } -func (i *Issue) addLabel(e *xorm.Session, label *Label) error { - return newIssueLabel(e, i, label) +// addLabel ... +func (issue *Issue) addLabel(e *xorm.Session, label *Label) error { + return newIssueLabel(e, issue, label) } // AddLabel adds a new label to the issue. @@ -268,6 +276,7 @@ func (issue *Issue) AddLabel(doer *User, label *Label) error { return nil } +// addLabels ... func (issue *Issue) addLabels(e *xorm.Session, labels []*Label) error { return newIssueLabels(e, issue, labels) } @@ -282,6 +291,7 @@ func (issue *Issue) AddLabels(doer *User, labels []*Label) error { return nil } +// getLabels ... func (issue *Issue) getLabels(e Engine) (err error) { if len(issue.Labels) > 0 { return nil @@ -294,6 +304,7 @@ func (issue *Issue) getLabels(e Engine) (err error) { return nil } +// removeLabel ... func (issue *Issue) removeLabel(e *xorm.Session, label *Label) error { return deleteIssueLabel(e, issue, label) } @@ -308,6 +319,7 @@ func (issue *Issue) RemoveLabel(doer *User, label *Label) error { return nil } +// clearLabels ... func (issue *Issue) clearLabels(e *xorm.Session) (err error) { if err = issue.getLabels(e); err != nil { return fmt.Errorf("getLabels: %v", err) @@ -322,6 +334,7 @@ func (issue *Issue) clearLabels(e *xorm.Session) (err error) { return nil } +// ClearLabels ... func (issue *Issue) ClearLabels(doer *User) (err error) { sess := x.NewSession() defer sessionRelease(sess) @@ -377,12 +390,13 @@ func (issue *Issue) ReplaceLabels(labels []*Label) (err error) { return sess.Commit() } -func (i *Issue) GetAssignee() (err error) { - if i.AssigneeID == 0 || i.Assignee != nil { +// GetAssignee ... +func (issue *Issue) GetAssignee() (err error) { + if issue.AssigneeID == 0 || issue.Assignee != nil { return nil } - i.Assignee, err = GetUserByID(i.AssigneeID) + issue.Assignee, err = GetUserByID(issue.AssigneeID) if IsErrUserNotExist(err) { return nil } @@ -390,8 +404,8 @@ func (i *Issue) GetAssignee() (err error) { } // ReadBy sets issue to be read by given user. -func (i *Issue) ReadBy(uid int64) error { - return UpdateIssueUserByRead(uid, i.ID) +func (issue *Issue) ReadBy(uid int64) error { + return UpdateIssueUserByRead(uid, issue.ID) } func updateIssueCols(e Engine, issue *Issue, cols ...string) error { @@ -404,41 +418,42 @@ func UpdateIssueCols(issue *Issue, cols ...string) error { return updateIssueCols(x, issue, cols...) } -func (i *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) { +// changeStatus ... +func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) { // Nothing should be performed if current status is same as target status - if i.IsClosed == isClosed { + if issue.IsClosed == isClosed { return nil } - i.IsClosed = isClosed + issue.IsClosed = isClosed - if err = updateIssueCols(e, i, "is_closed"); err != nil { + if err = updateIssueCols(e, issue, "is_closed"); err != nil { return err - } else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil { + } else if err = updateIssueUsersByStatus(e, issue.ID, isClosed); err != nil { return err } // Update issue count of labels - if err = i.getLabels(e); err != nil { + if err = issue.getLabels(e); err != nil { return err } - for idx := range i.Labels { - if i.IsClosed { - i.Labels[idx].NumClosedIssues++ + for idx := range issue.Labels { + if issue.IsClosed { + issue.Labels[idx].NumClosedIssues++ } else { - i.Labels[idx].NumClosedIssues-- + issue.Labels[idx].NumClosedIssues-- } - if err = updateLabel(e, i.Labels[idx]); err != nil { + if err = updateLabel(e, issue.Labels[idx]); err != nil { return err } } // Update issue count of milestone - if err = changeMilestoneIssueStats(e, i); err != nil { + if err = changeMilestoneIssueStats(e, issue); err != nil { return err } // New action comment - if _, err = createStatusComment(e, doer, repo, i); err != nil { + if _, err = createStatusComment(e, doer, repo, issue); err != nil { return err } @@ -486,6 +501,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e return nil } +// ChangeTitle ... func (issue *Issue) ChangeTitle(doer *User, title string) (err error) { oldTitle := issue.Title issue.Title = title @@ -517,6 +533,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) { return nil } +// ChangeContent ... func (issue *Issue) ChangeContent(doer *User, content string) (err error) { oldContent := issue.Content issue.Content = content @@ -548,6 +565,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) { return nil } +// ChangeAssignee ... func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) { issue.AssigneeID = assigneeID if err = UpdateIssueUserByAssignee(issue); err != nil { @@ -586,6 +604,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) { return nil } +// NewIssueOptions ... type NewIssueOptions struct { Repo *Repository Issue *Issue @@ -735,7 +754,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) func GetIssueByRef(ref string) (*Issue, error) { n := strings.IndexByte(ref, byte('#')) if n == -1 { - return nil, ErrMissingIssueNumber + return nil, errMissingIssueNumber } index, err := com.StrTo(ref[n+1:]).Int64() @@ -756,7 +775,7 @@ func GetIssueByRef(ref string) (*Issue, error) { return issue, issue.LoadAttributes() } -// GetIssueByIndex returns raw issue without loading attributes by index in a repository. +// GetRawIssueByIndex returns raw issue without loading attributes by index in a repository. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) { issue := &Issue{ RepoID: repoID, @@ -796,6 +815,7 @@ func GetIssueByID(id int64) (*Issue, error) { return getIssueByID(x, id) } +// IssuesOptions ... type IssuesOptions struct { UserID int64 AssigneeID int64 @@ -967,9 +987,9 @@ func NewIssueUsers(repo *Repository, issue *Issue) (err error) { } // PairsContains returns true when pairs list contains given issue. -func PairsContains(ius []*IssueUser, issueId, uid int64) int { +func PairsContains(ius []*IssueUser, issueID, uid int64) int { for i := range ius { - if ius[i].IssueID == issueId && + if ius[i].IssueID == issueID && ius[i].UID == uid { return i } @@ -1092,6 +1112,7 @@ func parseCountResult(results []map[string][]byte) int64 { return 0 } +// IssueStatsOptions ... type IssueStatsOptions struct { RepoID int64 UserID int64 @@ -1350,10 +1371,12 @@ type Milestone struct { ClosedDateUnix int64 } +// BeforeInsert ... func (m *Milestone) BeforeInsert() { m.DeadlineUnix = m.Deadline.Unix() } +// BeforeUpdate ... func (m *Milestone) BeforeUpdate() { if m.NumIssues > 0 { m.Completeness = m.NumClosedIssues * 100 / m.NumIssues @@ -1365,6 +1388,7 @@ func (m *Milestone) BeforeUpdate() { m.ClosedDateUnix = m.ClosedDate.Unix() } +// AfterSet ... func (m *Milestone) AfterSet(colName string, _ xorm.Cell) { switch colName { case "num_closed_issues": @@ -1394,6 +1418,7 @@ func (m *Milestone) State() api.StateType { return api.STATE_OPEN } +// APIFormat ... func (m *Milestone) APIFormat() *api.Milestone { apiMilestone := &api.Milestone{ ID: m.ID, @@ -1444,7 +1469,7 @@ func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) { return m, nil } -// GetWebhookByRepoID returns the milestone in a repository. +// GetMilestoneByRepoID returns the milestone in a repository. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) { return getMilestoneByRepoID(x, repoID, id) } @@ -1676,10 +1701,12 @@ type Attachment struct { CreatedUnix int64 } +// BeforeInsert ... func (a *Attachment) BeforeInsert() { a.CreatedUnix = time.Now().Unix() } +// AfterSet ... func (a *Attachment) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": @@ -1693,8 +1720,8 @@ func AttachmentLocalPath(uuid string) string { } // LocalPath returns where attachment is stored in local file system. -func (attach *Attachment) LocalPath() string { - return AttachmentLocalPath(attach.UUID) +func (a *Attachment) LocalPath() string { + return AttachmentLocalPath(a.UUID) } // NewAttachment creates a new attachment object. @@ -1794,8 +1821,8 @@ func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) { } // DeleteAttachmentsByIssue deletes all attachments associated with the given issue. -func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) { - attachments, err := GetAttachmentsByIssueID(issueId) +func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) { + attachments, err := GetAttachmentsByIssueID(issueID) if err != nil { return 0, err @@ -1805,8 +1832,8 @@ func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) { } // DeleteAttachmentsByComment deletes all attachments associated with the given comment. -func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) { - attachments, err := GetAttachmentsByCommentID(commentId) +func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) { + attachments, err := GetAttachmentsByCommentID(commentID) if err != nil { return 0, err From 6e644726d0fb064edc1ba5031bd447799338bf9c Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Tue, 22 Nov 2016 12:08:23 +0100 Subject: [PATCH 009/135] Lint git_diff.go Semi-automatic linting (don't really document things) --- models/git_diff.go | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/models/git_diff.go b/models/git_diff.go index 7d4f5db7f5..8bdce68221 100644 --- a/models/git_diff.go +++ b/models/git_diff.go @@ -28,8 +28,10 @@ import ( "golang.org/x/text/transform" ) +// DiffLineType ... type DiffLineType uint8 +// DiffLineType possible values. const ( DiffLinePlain DiffLineType = iota + 1 DiffLineAdd @@ -37,8 +39,10 @@ const ( DiffLineSection ) +// DiffFileType ... type DiffFileType uint8 +// DiffFileType possible values. const ( DiffFileAdd DiffFileType = iota + 1 DiffFileChange @@ -46,6 +50,7 @@ const ( DiffFileRename ) +// DiffLine ... type DiffLine struct { LeftIdx int RightIdx int @@ -53,10 +58,12 @@ type DiffLine struct { Content string } +// GetType ... func (d *DiffLine) GetType() int { return int(d.Type) } +// DiffSection ... type DiffSection struct { Name string Lines []*DiffLine @@ -68,6 +75,7 @@ var ( codeTagSuffix = []byte("") ) +// diffToHTML ... func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTML { buf := bytes.NewBuffer(nil) @@ -97,7 +105,7 @@ func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTM return template.HTML(buf.Bytes()) } -// get an specific line by type (add or del) and file line number +// GetLine gets a specific line by type (add or del) and file line number func (diffSection *DiffSection) GetLine(lineType DiffLineType, idx int) *DiffLine { var ( difference = 0 @@ -142,11 +150,12 @@ LOOP: var diffMatchPatch = diffmatchpatch.New() +// init ... func init() { diffMatchPatch.DiffEditCost = 100 } -// computes inline diff for the given line +// GetComputedInlineDiffFor computes inline diff for the given line. func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) template.HTML { if setting.Git.DisableDiffHighlight { return template.HTML(html.EscapeString(diffLine.Content[1:])) @@ -183,6 +192,7 @@ func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) tem return diffToHTML(diffRecord, diffLine.Type) } +// DiffFile ... type DiffFile struct { Name string OldName string @@ -198,26 +208,31 @@ type DiffFile struct { IsIncomplete bool } +// GetType returns type of diff file. func (diffFile *DiffFile) GetType() int { return int(diffFile.Type) } +// GetHighlightClass ... func (diffFile *DiffFile) GetHighlightClass() string { return highlight.FileNameToHighlightClass(diffFile.Name) } +// Diff ... type Diff struct { TotalAddition, TotalDeletion int Files []*DiffFile IsIncomplete bool } +// NumFiles ... func (diff *Diff) NumFiles() int { return len(diff.Files) } -const DIFF_HEAD = "diff --git " +const cmdDiffHead = "diff --git " +// ParsePatch ... // TODO: move this function to gogits/git-module func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*Diff, error) { var ( @@ -307,19 +322,19 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (* } // Get new file. - if strings.HasPrefix(line, DIFF_HEAD) { + if strings.HasPrefix(line, cmdDiffHead) { middle := -1 // Note: In case file name is surrounded by double quotes (it happens only in git-shell). // e.g. diff --git "a/xxx" "b/xxx" - hasQuote := line[len(DIFF_HEAD)] == '"' + hasQuote := line[len(cmdDiffHead)] == '"' if hasQuote { middle = strings.Index(line, ` "b/`) } else { middle = strings.Index(line, " b/") } - beg := len(DIFF_HEAD) + beg := len(cmdDiffHead) a := line[beg+2 : middle] b := line[middle+3:] if hasQuote { @@ -405,6 +420,7 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (* return diff, nil } +// GetDiffRange ... func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacteres, maxFiles int) (*Diff, error) { gitRepo, err := git.OpenRepository(repoPath) if err != nil { @@ -456,8 +472,10 @@ func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxL return diff, nil } +// RawDiffType ... type RawDiffType string +// RawDiffType possible values. const ( RawDiffNormal RawDiffType = "diff" RawDiffPatch RawDiffType = "patch" @@ -465,6 +483,7 @@ const ( // GetRawDiff dumps diff results of repository in given commit ID to io.Writer. // TODO: move this function to gogits/git-module +// GetRawDiff ... func GetRawDiff(repoPath, commitID string, diffType RawDiffType, writer io.Writer) error { repo, err := git.OpenRepository(repoPath) if err != nil { @@ -509,6 +528,7 @@ func GetRawDiff(repoPath, commitID string, diffType RawDiffType, writer io.Write return nil } +// GetDiffCommit ... func GetDiffCommit(repoPath, commitID string, maxLines, maxLineCharacteres, maxFiles int) (*Diff, error) { return GetDiffRange(repoPath, "", commitID, maxLines, maxLineCharacteres, maxFiles) } From 170f2e98cc7b102fb8d3df8496616ee823eee6ea Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Tue, 22 Nov 2016 12:00:36 +0100 Subject: [PATCH 010/135] Lint error.go This was done semi-programmatically, not really documenting anything --- models/error.go | 82 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/models/error.go b/models/error.go index 459954545a..cafe11a154 100644 --- a/models/error.go +++ b/models/error.go @@ -8,10 +8,12 @@ import ( "fmt" ) +// ErrNameReserved ... type ErrNameReserved struct { Name string } +// IsErrNameReserved ... func IsErrNameReserved(err error) bool { _, ok := err.(ErrNameReserved) return ok @@ -21,10 +23,12 @@ func (err ErrNameReserved) Error() string { return fmt.Sprintf("name is reserved [name: %s]", err.Name) } +// ErrNamePatternNotAllowed ... type ErrNamePatternNotAllowed struct { Pattern string } +// IsErrNamePatternNotAllowed ... func IsErrNamePatternNotAllowed(err error) bool { _, ok := err.(ErrNamePatternNotAllowed) return ok @@ -41,10 +45,12 @@ func (err ErrNamePatternNotAllowed) Error() string { // |______//____ >\___ >__| // \/ \/ +// ErrUserAlreadyExist ... type ErrUserAlreadyExist struct { Name string } +// IsErrUserAlreadyExist ... func IsErrUserAlreadyExist(err error) bool { _, ok := err.(ErrUserAlreadyExist) return ok @@ -54,12 +60,14 @@ func (err ErrUserAlreadyExist) Error() string { return fmt.Sprintf("user already exists [name: %s]", err.Name) } +// ErrUserNotExist ... type ErrUserNotExist struct { UID int64 Name string KeyID int64 } +// IsErrUserNotExist ... func IsErrUserNotExist(err error) bool { _, ok := err.(ErrUserNotExist) return ok @@ -69,10 +77,12 @@ func (err ErrUserNotExist) Error() string { return fmt.Sprintf("user does not exist [uid: %d, name: %s, keyid: %d]", err.UID, err.Name, err.KeyID) } +// ErrEmailAlreadyUsed ... type ErrEmailAlreadyUsed struct { Email string } +// IsErrEmailAlreadyUsed ... func IsErrEmailAlreadyUsed(err error) bool { _, ok := err.(ErrEmailAlreadyUsed) return ok @@ -82,10 +92,12 @@ func (err ErrEmailAlreadyUsed) Error() string { return fmt.Sprintf("e-mail has been used [email: %s]", err.Email) } +// ErrUserOwnRepos ... type ErrUserOwnRepos struct { UID int64 } +// IsErrUserOwnRepos ... func IsErrUserOwnRepos(err error) bool { _, ok := err.(ErrUserOwnRepos) return ok @@ -95,10 +107,12 @@ func (err ErrUserOwnRepos) Error() string { return fmt.Sprintf("user still has ownership of repositories [uid: %d]", err.UID) } +// ErrUserHasOrgs ... type ErrUserHasOrgs struct { UID int64 } +// IsErrUserHasOrgs ... func IsErrUserHasOrgs(err error) bool { _, ok := err.(ErrUserHasOrgs) return ok @@ -108,10 +122,12 @@ func (err ErrUserHasOrgs) Error() string { return fmt.Sprintf("user still has membership of organizations [uid: %d]", err.UID) } +// ErrReachLimitOfRepo ... type ErrReachLimitOfRepo struct { Limit int } +// IsErrReachLimitOfRepo ... func IsErrReachLimitOfRepo(err error) bool { _, ok := err.(ErrReachLimitOfRepo) return ok @@ -128,10 +144,12 @@ func (err ErrReachLimitOfRepo) Error() string { // \__/\ / |__|__|_ \__| // \/ \/ +// ErrWikiAlreadyExist ... type ErrWikiAlreadyExist struct { Title string } +// IsErrWikiAlreadyExist ... func IsErrWikiAlreadyExist(err error) bool { _, ok := err.(ErrWikiAlreadyExist) return ok @@ -148,10 +166,12 @@ func (err ErrWikiAlreadyExist) Error() string { // |____| |____/|___ /____/__|\___ > |____|__ \___ > ____| // \/ \/ \/ \/\/ +// ErrKeyUnableVerify ... type ErrKeyUnableVerify struct { Result string } +// IsErrKeyUnableVerify ... func IsErrKeyUnableVerify(err error) bool { _, ok := err.(ErrKeyUnableVerify) return ok @@ -161,10 +181,12 @@ func (err ErrKeyUnableVerify) Error() string { return fmt.Sprintf("Unable to verify key content [result: %s]", err.Result) } +// ErrKeyNotExist ... type ErrKeyNotExist struct { ID int64 } +// IsErrKeyNotExist ... func IsErrKeyNotExist(err error) bool { _, ok := err.(ErrKeyNotExist) return ok @@ -174,11 +196,13 @@ func (err ErrKeyNotExist) Error() string { return fmt.Sprintf("public key does not exist [id: %d]", err.ID) } +// ErrKeyAlreadyExist ... type ErrKeyAlreadyExist struct { OwnerID int64 Content string } +// IsErrKeyAlreadyExist ... func IsErrKeyAlreadyExist(err error) bool { _, ok := err.(ErrKeyAlreadyExist) return ok @@ -188,11 +212,13 @@ func (err ErrKeyAlreadyExist) Error() string { return fmt.Sprintf("public key already exists [owner_id: %d, content: %s]", err.OwnerID, err.Content) } +// ErrKeyNameAlreadyUsed ... type ErrKeyNameAlreadyUsed struct { OwnerID int64 Name string } +// IsErrKeyNameAlreadyUsed ... func IsErrKeyNameAlreadyUsed(err error) bool { _, ok := err.(ErrKeyNameAlreadyUsed) return ok @@ -202,12 +228,14 @@ func (err ErrKeyNameAlreadyUsed) Error() string { return fmt.Sprintf("public key already exists [owner_id: %d, name: %s]", err.OwnerID, err.Name) } +// ErrKeyAccessDenied ... type ErrKeyAccessDenied struct { UserID int64 KeyID int64 Note string } +// IsErrKeyAccessDenied ... func IsErrKeyAccessDenied(err error) bool { _, ok := err.(ErrKeyAccessDenied) return ok @@ -218,12 +246,14 @@ func (err ErrKeyAccessDenied) Error() string { err.UserID, err.KeyID, err.Note) } +// ErrDeployKeyNotExist ... type ErrDeployKeyNotExist struct { ID int64 KeyID int64 RepoID int64 } +// IsErrDeployKeyNotExist ... func IsErrDeployKeyNotExist(err error) bool { _, ok := err.(ErrDeployKeyNotExist) return ok @@ -233,11 +263,13 @@ func (err ErrDeployKeyNotExist) Error() string { return fmt.Sprintf("Deploy key does not exist [id: %d, key_id: %d, repo_id: %d]", err.ID, err.KeyID, err.RepoID) } +// ErrDeployKeyAlreadyExist ... type ErrDeployKeyAlreadyExist struct { KeyID int64 RepoID int64 } +// IsErrDeployKeyAlreadyExist ... func IsErrDeployKeyAlreadyExist(err error) bool { _, ok := err.(ErrDeployKeyAlreadyExist) return ok @@ -247,11 +279,13 @@ func (err ErrDeployKeyAlreadyExist) Error() string { return fmt.Sprintf("public key already exists [key_id: %d, repo_id: %d]", err.KeyID, err.RepoID) } +// ErrDeployKeyNameAlreadyUsed ... type ErrDeployKeyNameAlreadyUsed struct { RepoID int64 Name string } +// IsErrDeployKeyNameAlreadyUsed ... func IsErrDeployKeyNameAlreadyUsed(err error) bool { _, ok := err.(ErrDeployKeyNameAlreadyUsed) return ok @@ -268,10 +302,12 @@ func (err ErrDeployKeyNameAlreadyUsed) Error() string { // \____|__ /\___ >___ >___ >____ >____ > |____| \____/|__|_ \\___ >___| / // \/ \/ \/ \/ \/ \/ \/ \/ \/ +// ErrAccessTokenNotExist ... type ErrAccessTokenNotExist struct { SHA string } +// IsErrAccessTokenNotExist ... func IsErrAccessTokenNotExist(err error) bool { _, ok := err.(ErrAccessTokenNotExist) return ok @@ -281,9 +317,11 @@ func (err ErrAccessTokenNotExist) Error() string { return fmt.Sprintf("access token does not exist [sha: %s]", err.SHA) } +// ErrAccessTokenEmpty ... type ErrAccessTokenEmpty struct { } +// IsErrAccessTokenEmpty ... func IsErrAccessTokenEmpty(err error) bool { _, ok := err.(ErrAccessTokenEmpty) return ok @@ -300,10 +338,12 @@ func (err ErrAccessTokenEmpty) Error() string { // \_______ /__| \___ (____ /___| /__/_____ \(____ /__| |__|\____/|___| / // \/ /_____/ \/ \/ \/ \/ \/ +// ErrLastOrgOwner ... type ErrLastOrgOwner struct { UID int64 } +// IsErrLastOrgOwner ... func IsErrLastOrgOwner(err error) bool { _, ok := err.(ErrLastOrgOwner) return ok @@ -320,12 +360,14 @@ func (err ErrLastOrgOwner) Error() string { // |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____| // \/ \/|__| \/ \/ +// ErrRepoNotExist ... type ErrRepoNotExist struct { ID int64 UID int64 Name string } +// IsErrRepoNotExist ... func IsErrRepoNotExist(err error) bool { _, ok := err.(ErrRepoNotExist) return ok @@ -335,11 +377,13 @@ func (err ErrRepoNotExist) Error() string { return fmt.Sprintf("repository does not exist [id: %d, uid: %d, name: %s]", err.ID, err.UID, err.Name) } +// ErrRepoAlreadyExist ... type ErrRepoAlreadyExist struct { Uname string Name string } +// IsErrRepoAlreadyExist ... func IsErrRepoAlreadyExist(err error) bool { _, ok := err.(ErrRepoAlreadyExist) return ok @@ -349,12 +393,14 @@ func (err ErrRepoAlreadyExist) Error() string { return fmt.Sprintf("repository already exists [uname: %s, name: %s]", err.Uname, err.Name) } +// ErrInvalidCloneAddr ... type ErrInvalidCloneAddr struct { IsURLError bool IsInvalidPath bool IsPermissionDenied bool } +// IsErrInvalidCloneAddr ... func IsErrInvalidCloneAddr(err error) bool { _, ok := err.(ErrInvalidCloneAddr) return ok @@ -365,10 +411,12 @@ func (err ErrInvalidCloneAddr) Error() string { err.IsURLError, err.IsInvalidPath, err.IsPermissionDenied) } +// ErrUpdateTaskNotExist ... type ErrUpdateTaskNotExist struct { UUID string } +// IsErrUpdateTaskNotExist ... func IsErrUpdateTaskNotExist(err error) bool { _, ok := err.(ErrUpdateTaskNotExist) return ok @@ -378,10 +426,12 @@ func (err ErrUpdateTaskNotExist) Error() string { return fmt.Sprintf("update task does not exist [uuid: %s]", err.UUID) } +// ErrReleaseAlreadyExist ... type ErrReleaseAlreadyExist struct { TagName string } +// IsErrReleaseAlreadyExist ... func IsErrReleaseAlreadyExist(err error) bool { _, ok := err.(ErrReleaseAlreadyExist) return ok @@ -391,11 +441,13 @@ func (err ErrReleaseAlreadyExist) Error() string { return fmt.Sprintf("release tag already exist [tag_name: %s]", err.TagName) } +// ErrReleaseNotExist ... type ErrReleaseNotExist struct { ID int64 TagName string } +// IsErrReleaseNotExist ... func IsErrReleaseNotExist(err error) bool { _, ok := err.(ErrReleaseNotExist) return ok @@ -405,10 +457,12 @@ func (err ErrReleaseNotExist) Error() string { return fmt.Sprintf("release tag does not exist [id: %d, tag_name: %s]", err.ID, err.TagName) } +// ErrInvalidTagName ... type ErrInvalidTagName struct { TagName string } +// IsErrInvalidTagName ... func IsErrInvalidTagName(err error) bool { _, ok := err.(ErrInvalidTagName) return ok @@ -418,10 +472,12 @@ func (err ErrInvalidTagName) Error() string { return fmt.Sprintf("release tag name is not valid [tag_name: %s]", err.TagName) } +// ErrRepoFileAlreadyExist ... type ErrRepoFileAlreadyExist struct { FileName string } +// IsErrRepoFileAlreadyExist ... func IsErrRepoFileAlreadyExist(err error) bool { _, ok := err.(ErrRepoFileAlreadyExist) return ok @@ -438,10 +494,12 @@ func (err ErrRepoFileAlreadyExist) Error() string { // |______ / |__| (____ /___| /\___ >___| / // \/ \/ \/ \/ \/ +// ErrBranchNotExist ... type ErrBranchNotExist struct { Name string } +// IsErrBranchNotExist ... func IsErrBranchNotExist(err error) bool { _, ok := err.(ErrBranchNotExist) return ok @@ -458,10 +516,12 @@ func (err ErrBranchNotExist) Error() string { // \__/\ / \___ >___ /___| /\____/ \____/|__|_ \ // \/ \/ \/ \/ \/ +// ErrWebhookNotExist ... type ErrWebhookNotExist struct { ID int64 } +// IsErrWebhookNotExist ... func IsErrWebhookNotExist(err error) bool { _, ok := err.(ErrWebhookNotExist) return ok @@ -478,12 +538,14 @@ func (err ErrWebhookNotExist) Error() string { // |___/____ >____ >____/ \___ > // \/ \/ \/ +// ErrIssueNotExist ... type ErrIssueNotExist struct { ID int64 RepoID int64 Index int64 } +// IsErrIssueNotExist ... func IsErrIssueNotExist(err error) bool { _, ok := err.(ErrIssueNotExist) return ok @@ -500,6 +562,7 @@ func (err ErrIssueNotExist) Error() string { // |____| |____/|____/____/____|_ /\___ >__ |____/ \___ >____ > |__| // \/ \/ |__| \/ \/ +// ErrPullRequestNotExist ... type ErrPullRequestNotExist struct { ID int64 IssueID int64 @@ -509,6 +572,7 @@ type ErrPullRequestNotExist struct { BaseBranch string } +// IsErrPullRequestNotExist ... func IsErrPullRequestNotExist(err error) bool { _, ok := err.(ErrPullRequestNotExist) return ok @@ -526,11 +590,13 @@ func (err ErrPullRequestNotExist) Error() string { // \______ /\____/|__|_| /__|_| /\___ >___| /__| // \/ \/ \/ \/ \/ +// ErrCommentNotExist ... type ErrCommentNotExist struct { ID int64 IssueID int64 } +// IsErrCommentNotExist ... func IsErrCommentNotExist(err error) bool { _, ok := err.(ErrCommentNotExist) return ok @@ -547,11 +613,13 @@ func (err ErrCommentNotExist) Error() string { // |_______ (____ /___ /\___ >____/ // \/ \/ \/ \/ +// ErrLabelNotExist ... type ErrLabelNotExist struct { LabelID int64 RepoID int64 } +// IsErrLabelNotExist ... func IsErrLabelNotExist(err error) bool { _, ok := err.(ErrLabelNotExist) return ok @@ -568,11 +636,13 @@ func (err ErrLabelNotExist) Error() string { // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ > // \/ \/ \/ \/ \/ +// ErrMilestoneNotExist ... type ErrMilestoneNotExist struct { ID int64 RepoID int64 } +// IsErrMilestoneNotExist ... func IsErrMilestoneNotExist(err error) bool { _, ok := err.(ErrMilestoneNotExist) return ok @@ -589,11 +659,13 @@ func (err ErrMilestoneNotExist) Error() string { // \____|__ /__| |__| (____ /\___ >___| /__|_| /\___ >___| /__| // \/ \/ \/ \/ \/ \/ \/ +// ErrAttachmentNotExist ... type ErrAttachmentNotExist struct { ID int64 UUID string } +// IsErrAttachmentNotExist ... func IsErrAttachmentNotExist(err error) bool { _, ok := err.(ErrAttachmentNotExist) return ok @@ -610,10 +682,12 @@ func (err ErrAttachmentNotExist) Error() string { // |_______ \____/\___ /|__|___| / /_______ /\____/|____/ |__| \___ >___ > // \/ /_____/ \/ \/ \/ \/ +// ErrLoginSourceNotExist ... type ErrLoginSourceNotExist struct { ID int64 } +// IsErrLoginSourceNotExist ... func IsErrLoginSourceNotExist(err error) bool { _, ok := err.(ErrLoginSourceNotExist) return ok @@ -623,10 +697,12 @@ func (err ErrLoginSourceNotExist) Error() string { return fmt.Sprintf("login source does not exist [id: %d]", err.ID) } +// ErrLoginSourceAlreadyExist ... type ErrLoginSourceAlreadyExist struct { Name string } +// IsErrLoginSourceAlreadyExist ... func IsErrLoginSourceAlreadyExist(err error) bool { _, ok := err.(ErrLoginSourceAlreadyExist) return ok @@ -636,10 +712,12 @@ func (err ErrLoginSourceAlreadyExist) Error() string { return fmt.Sprintf("login source already exists [name: %s]", err.Name) } +// ErrLoginSourceInUse ... type ErrLoginSourceInUse struct { ID int64 } +// IsErrLoginSourceInUse ... func IsErrLoginSourceInUse(err error) bool { _, ok := err.(ErrLoginSourceInUse) return ok @@ -656,11 +734,13 @@ func (err ErrLoginSourceInUse) Error() string { // |____| \___ >____ /__|_| / // \/ \/ \/ +// ErrTeamAlreadyExist ... type ErrTeamAlreadyExist struct { OrgID int64 Name string } +// IsErrTeamAlreadyExist ... func IsErrTeamAlreadyExist(err error) bool { _, ok := err.(ErrTeamAlreadyExist) return ok @@ -678,11 +758,13 @@ func (err ErrTeamAlreadyExist) Error() string { // |__| \/ \/ // +// ErrUploadNotExist ... type ErrUploadNotExist struct { ID int64 UUID string } +// IsErrUploadNotExist ... func IsErrUploadNotExist(err error) bool { _, ok := err.(ErrAttachmentNotExist) return ok From dd9d0f3732bf35c45fae2799c243b87099445ef5 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Tue, 22 Nov 2016 11:43:30 +0100 Subject: [PATCH 011/135] Lint action.go --- models/action.go | 80 +++++++++++++++++++++++++++++++++++------------- models/pull.go | 2 +- 2 files changed, 60 insertions(+), 22 deletions(-) diff --git a/models/action.go b/models/action.go index 29cf74a800..72d988955b 100644 --- a/models/action.go +++ b/models/action.go @@ -24,8 +24,10 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// ActionType represents the type of an action. type ActionType int +// Possible action types. const ( ActionCreateRepo ActionType = iota + 1 // 1 ActionRenameRepo // 2 @@ -45,12 +47,13 @@ const ( ) var ( - // Same as Github. See https://help.github.com/articles/closing-issues-via-commit-messages - IssueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"} - IssueReopenKeywords = []string{"reopen", "reopens", "reopened"} + // Same as Github. See + // https://help.github.com/articles/closing-issues-via-commit-messages + issueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"} + issueReopenKeywords = []string{"reopen", "reopens", "reopened"} - IssueCloseKeywordsPat, IssueReopenKeywordsPat *regexp.Regexp - IssueReferenceKeywordsPat *regexp.Regexp + issueCloseKeywordsPat, issueReopenKeywordsPat *regexp.Regexp + issueReferenceKeywordsPat *regexp.Regexp ) func assembleKeywordsPattern(words []string) string { @@ -58,13 +61,14 @@ func assembleKeywordsPattern(words []string) string { } func init() { - IssueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords)) - IssueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords)) - IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`) + issueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueCloseKeywords)) + issueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueReopenKeywords)) + issueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`) } -// Action represents user operation type and other information to repository., -// it implemented interface base.Actioner so that can be used in template render. +// Action represents user operation type and other information to +// repository. It implemented interface base.Actioner so that can be +// used in template render. type Action struct { ID int64 `xorm:"pk autoincr"` UserID int64 // Receiver user id. @@ -82,10 +86,13 @@ type Action struct { CreatedUnix int64 } +// BeforeInsert will be invoked by XORM before inserting a record +// representing this object. func (a *Action) BeforeInsert() { a.CreatedUnix = time.Now().Unix() } +// AfterSet updates the webhook object upon setting a column. func (a *Action) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": @@ -93,42 +100,57 @@ func (a *Action) AfterSet(colName string, _ xorm.Cell) { } } +// GetOpType gets the ActionType of this action. +// TODO: change return type to ActionType ? func (a *Action) GetOpType() int { return int(a.OpType) } +// GetActUserName gets the action's user name. func (a *Action) GetActUserName() string { return a.ActUserName } +// ShortActUserName gets the action's user name trimmed to max 20 +// chars. func (a *Action) ShortActUserName() string { return base.EllipsisString(a.ActUserName, 20) } +// GetRepoUserName returns the name of the action repository owner. func (a *Action) GetRepoUserName() string { return a.RepoUserName } +// ShortRepoUserName returns the name of the action repository owner +// trimmed to max 20 chars. func (a *Action) ShortRepoUserName() string { return base.EllipsisString(a.RepoUserName, 20) } +// GetRepoName returns the name of the action repository. func (a *Action) GetRepoName() string { return a.RepoName } +// ShortRepoName returns the name of the action repository +// trimmed to max 33 chars. func (a *Action) ShortRepoName() string { return base.EllipsisString(a.RepoName, 33) } +// GetRepoPath returns the virtual path to the action repository. func (a *Action) GetRepoPath() string { return path.Join(a.RepoUserName, a.RepoName) } +// ShortRepoPath returns the virtual path to the action repository +// trimed to max 20 + 1 + 33 chars. func (a *Action) ShortRepoPath() string { return path.Join(a.ShortRepoUserName(), a.ShortRepoName()) } +// GetRepoLink returns relative link to action repository. func (a *Action) GetRepoLink() string { if len(setting.AppSubUrl) > 0 { return path.Join(setting.AppSubUrl, a.GetRepoPath()) @@ -136,22 +158,29 @@ func (a *Action) GetRepoLink() string { return "/" + a.GetRepoPath() } +// GetBranch returns the action's repository branch. func (a *Action) GetBranch() string { return a.RefName } +// GetContent returns the action's content. func (a *Action) GetContent() string { return a.Content } +// GetCreate returns the action creation time. func (a *Action) GetCreate() time.Time { return a.Created } +// GetIssueInfos returns a list of issues associated with +// the action. func (a *Action) GetIssueInfos() []string { return strings.SplitN(a.Content, "|", 2) } +// GetIssueTitle returns the title of first issue associated +// with the action. func (a *Action) GetIssueTitle() string { index := com.StrTo(a.GetIssueInfos()[0]).MustInt64() issue, err := GetIssueByIndex(a.RepoID, index) @@ -162,6 +191,8 @@ func (a *Action) GetIssueTitle() string { return issue.Title } +// GetIssueContent returns the content of first issue associated with +// this action. func (a *Action) GetIssueContent() string { index := com.StrTo(a.GetIssueInfos()[0]).MustInt64() issue, err := GetIssueByIndex(a.RepoID, index) @@ -221,6 +252,7 @@ func issueIndexTrimRight(c rune) bool { return !unicode.IsDigit(c) } +// PushCommit represents a commit in a push operation. type PushCommit struct { Sha1 string Message string @@ -231,6 +263,7 @@ type PushCommit struct { Timestamp time.Time } +// PushCommits represents list of commits in a push operation. type PushCommits struct { Len int Commits []*PushCommit @@ -239,13 +272,16 @@ type PushCommits struct { avatars map[string]string } +// NewPushCommits creates a new PushCommits object. func NewPushCommits() *PushCommits { return &PushCommits{ avatars: make(map[string]string), } } -func (pc *PushCommits) ToApiPayloadCommits(repoLink string) []*api.PayloadCommit { +// ToAPIPayloadCommits converts a PushCommits object to +// api.PayloadCommit format. +func (pc *PushCommits) ToAPIPayloadCommits(repoLink string) []*api.PayloadCommit { commits := make([]*api.PayloadCommit, len(pc.Commits)) for i, commit := range pc.Commits { authorUsername := "" @@ -281,21 +317,21 @@ func (pc *PushCommits) ToApiPayloadCommits(repoLink string) []*api.PayloadCommit // AvatarLink tries to match user in database with e-mail // in order to show custom avatar, and falls back to general avatar link. -func (push *PushCommits) AvatarLink(email string) string { - _, ok := push.avatars[email] +func (pc *PushCommits) AvatarLink(email string) string { + _, ok := pc.avatars[email] if !ok { u, err := GetUserByEmail(email) if err != nil { - push.avatars[email] = base.AvatarLink(email) + pc.avatars[email] = base.AvatarLink(email) if !IsErrUserNotExist(err) { log.Error(4, "GetUserByEmail: %v", err) } } else { - push.avatars[email] = u.RelAvatarLink() + pc.avatars[email] = u.RelAvatarLink() } } - return push.avatars[email] + return pc.avatars[email] } // UpdateIssuesCommit checks if issues are manipulated by commit message. @@ -305,7 +341,7 @@ func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) err c := commits[i] refMarked := make(map[int64]bool) - for _, ref := range IssueReferenceKeywordsPat.FindAllString(c.Message, -1) { + for _, ref := range issueReferenceKeywordsPat.FindAllString(c.Message, -1) { ref = ref[strings.IndexByte(ref, byte(' '))+1:] ref = strings.TrimRightFunc(ref, issueIndexTrimRight) @@ -343,7 +379,7 @@ func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) err refMarked = make(map[int64]bool) // FIXME: can merge this one and next one to a common function. - for _, ref := range IssueCloseKeywordsPat.FindAllString(c.Message, -1) { + for _, ref := range issueCloseKeywordsPat.FindAllString(c.Message, -1) { ref = ref[strings.IndexByte(ref, byte(' '))+1:] ref = strings.TrimRightFunc(ref, issueIndexTrimRight) @@ -383,7 +419,7 @@ func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) err } // It is conflict to have close and reopen at same time, so refsMarkd doesn't need to reinit here. - for _, ref := range IssueReopenKeywordsPat.FindAllString(c.Message, -1) { + for _, ref := range issueReopenKeywordsPat.FindAllString(c.Message, -1) { ref = ref[strings.IndexByte(ref, byte(' '))+1:] ref = strings.TrimRightFunc(ref, issueIndexTrimRight) @@ -425,6 +461,7 @@ func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) err return nil } +// CommitRepoActionOptions represent options of a new commit action. type CommitRepoActionOptions struct { PusherName string RepoOwnerID int64 @@ -435,7 +472,8 @@ type CommitRepoActionOptions struct { Commits *PushCommits } -// CommitRepoAction adds new commit actio to the repository, and prepare corresponding webhooks. +// CommitRepoAction adds new commit action to the repository, and prepare +// corresponding webhooks. func CommitRepoAction(opts CommitRepoActionOptions) error { pusher, err := GetUserByName(opts.PusherName) if err != nil { @@ -509,7 +547,7 @@ func CommitRepoAction(opts CommitRepoActionOptions) error { Before: opts.OldCommitID, After: opts.NewCommitID, CompareURL: setting.AppUrl + opts.Commits.CompareURL, - Commits: opts.Commits.ToApiPayloadCommits(repo.HTMLURL()), + Commits: opts.Commits.ToAPIPayloadCommits(repo.HTMLURL()), Repo: apiRepo, Pusher: apiPusher, Sender: apiPusher, diff --git a/models/pull.go b/models/pull.go index 4b7034ce4d..d1ff974371 100644 --- a/models/pull.go +++ b/models/pull.go @@ -318,7 +318,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error Before: pr.MergeBase, After: pr.MergedCommitID, CompareURL: setting.AppUrl + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID), - Commits: ListToPushCommits(l).ToApiPayloadCommits(pr.BaseRepo.HTMLURL()), + Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()), Repo: pr.BaseRepo.APIFormat(nil), Pusher: pr.HeadRepo.MustOwner().APIFormat(), Sender: doer.APIFormat(), From 0a61d54a9ce7f9f9e24a651afd5f281659bfe186 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Thu, 24 Nov 2016 09:20:28 +0100 Subject: [PATCH 012/135] Expand documentation a bit more --- models/error.go | 165 ++++++++++++++++++++++++------------------------ 1 file changed, 83 insertions(+), 82 deletions(-) diff --git a/models/error.go b/models/error.go index cafe11a154..33815cdc96 100644 --- a/models/error.go +++ b/models/error.go @@ -8,12 +8,12 @@ import ( "fmt" ) -// ErrNameReserved ... +// ErrNameReserved represents a "reserved name" error. type ErrNameReserved struct { Name string } -// IsErrNameReserved ... +// IsErrNameReserved checks if an error is a ErrNameReserved. func IsErrNameReserved(err error) bool { _, ok := err.(ErrNameReserved) return ok @@ -23,12 +23,13 @@ func (err ErrNameReserved) Error() string { return fmt.Sprintf("name is reserved [name: %s]", err.Name) } -// ErrNamePatternNotAllowed ... +// ErrNamePatternNotAllowed represents a "pattern not allowed" error. type ErrNamePatternNotAllowed struct { Pattern string } -// IsErrNamePatternNotAllowed ... +// IsErrNamePatternNotAllowed checks if an error is an +// ErrNamePatternNotAllowed. func IsErrNamePatternNotAllowed(err error) bool { _, ok := err.(ErrNamePatternNotAllowed) return ok @@ -45,12 +46,12 @@ func (err ErrNamePatternNotAllowed) Error() string { // |______//____ >\___ >__| // \/ \/ -// ErrUserAlreadyExist ... +// ErrUserAlreadyExist represents a "user already exists" error. type ErrUserAlreadyExist struct { Name string } -// IsErrUserAlreadyExist ... +// IsErrUserAlreadyExist checks if an error is a ErrUserAlreadyExists. func IsErrUserAlreadyExist(err error) bool { _, ok := err.(ErrUserAlreadyExist) return ok @@ -60,14 +61,14 @@ func (err ErrUserAlreadyExist) Error() string { return fmt.Sprintf("user already exists [name: %s]", err.Name) } -// ErrUserNotExist ... +// ErrUserNotExist represents a "UserNotExist" kind of error. type ErrUserNotExist struct { UID int64 Name string KeyID int64 } -// IsErrUserNotExist ... +// IsErrUserNotExist checks if an error is a ErrUserNotExist. func IsErrUserNotExist(err error) bool { _, ok := err.(ErrUserNotExist) return ok @@ -77,12 +78,12 @@ func (err ErrUserNotExist) Error() string { return fmt.Sprintf("user does not exist [uid: %d, name: %s, keyid: %d]", err.UID, err.Name, err.KeyID) } -// ErrEmailAlreadyUsed ... +// ErrEmailAlreadyUsed represents a "EmailAlreadyUsed" kind of error. type ErrEmailAlreadyUsed struct { Email string } -// IsErrEmailAlreadyUsed ... +// IsErrEmailAlreadyUsed checks if an error is a ErrEmailAlreadyUsed. func IsErrEmailAlreadyUsed(err error) bool { _, ok := err.(ErrEmailAlreadyUsed) return ok @@ -92,12 +93,12 @@ func (err ErrEmailAlreadyUsed) Error() string { return fmt.Sprintf("e-mail has been used [email: %s]", err.Email) } -// ErrUserOwnRepos ... +// ErrUserOwnRepos represents a "UserOwnRepos" kind of error. type ErrUserOwnRepos struct { UID int64 } -// IsErrUserOwnRepos ... +// IsErrUserOwnRepos checks if an error is a ErrUserOwnRepos. func IsErrUserOwnRepos(err error) bool { _, ok := err.(ErrUserOwnRepos) return ok @@ -107,12 +108,12 @@ func (err ErrUserOwnRepos) Error() string { return fmt.Sprintf("user still has ownership of repositories [uid: %d]", err.UID) } -// ErrUserHasOrgs ... +// ErrUserHasOrgs represents a "UserHasOrgs" kind of error. type ErrUserHasOrgs struct { UID int64 } -// IsErrUserHasOrgs ... +// IsErrUserHasOrgs checks if an error is a ErrUserHasOrgs. func IsErrUserHasOrgs(err error) bool { _, ok := err.(ErrUserHasOrgs) return ok @@ -122,12 +123,12 @@ func (err ErrUserHasOrgs) Error() string { return fmt.Sprintf("user still has membership of organizations [uid: %d]", err.UID) } -// ErrReachLimitOfRepo ... +// ErrReachLimitOfRepo represents a "ReachLimitOfRepo" kind of error. type ErrReachLimitOfRepo struct { Limit int } -// IsErrReachLimitOfRepo ... +// IsErrReachLimitOfRepo checks if an error is a ErrReachLimitOfRepo. func IsErrReachLimitOfRepo(err error) bool { _, ok := err.(ErrReachLimitOfRepo) return ok @@ -144,12 +145,12 @@ func (err ErrReachLimitOfRepo) Error() string { // \__/\ / |__|__|_ \__| // \/ \/ -// ErrWikiAlreadyExist ... +// ErrWikiAlreadyExist represents a "WikiAlreadyExist" kind of error. type ErrWikiAlreadyExist struct { Title string } -// IsErrWikiAlreadyExist ... +// IsErrWikiAlreadyExist checks if an error is a ErrWikiAlreadyExist. func IsErrWikiAlreadyExist(err error) bool { _, ok := err.(ErrWikiAlreadyExist) return ok @@ -166,12 +167,12 @@ func (err ErrWikiAlreadyExist) Error() string { // |____| |____/|___ /____/__|\___ > |____|__ \___ > ____| // \/ \/ \/ \/\/ -// ErrKeyUnableVerify ... +// ErrKeyUnableVerify represents a "KeyUnableVerify" kind of error. type ErrKeyUnableVerify struct { Result string } -// IsErrKeyUnableVerify ... +// IsErrKeyUnableVerify checks if an error is a ErrKeyUnableVerify. func IsErrKeyUnableVerify(err error) bool { _, ok := err.(ErrKeyUnableVerify) return ok @@ -181,12 +182,12 @@ func (err ErrKeyUnableVerify) Error() string { return fmt.Sprintf("Unable to verify key content [result: %s]", err.Result) } -// ErrKeyNotExist ... +// ErrKeyNotExist represents a "KeyNotExist" kind of error. type ErrKeyNotExist struct { ID int64 } -// IsErrKeyNotExist ... +// IsErrKeyNotExist checks if an error is a ErrKeyNotExist. func IsErrKeyNotExist(err error) bool { _, ok := err.(ErrKeyNotExist) return ok @@ -196,13 +197,13 @@ func (err ErrKeyNotExist) Error() string { return fmt.Sprintf("public key does not exist [id: %d]", err.ID) } -// ErrKeyAlreadyExist ... +// ErrKeyAlreadyExist represents a "KeyAlreadyExist" kind of error. type ErrKeyAlreadyExist struct { OwnerID int64 Content string } -// IsErrKeyAlreadyExist ... +// IsErrKeyAlreadyExist checks if an error is a ErrKeyAlreadyExist. func IsErrKeyAlreadyExist(err error) bool { _, ok := err.(ErrKeyAlreadyExist) return ok @@ -212,13 +213,13 @@ func (err ErrKeyAlreadyExist) Error() string { return fmt.Sprintf("public key already exists [owner_id: %d, content: %s]", err.OwnerID, err.Content) } -// ErrKeyNameAlreadyUsed ... +// ErrKeyNameAlreadyUsed represents a "KeyNameAlreadyUsed" kind of error. type ErrKeyNameAlreadyUsed struct { OwnerID int64 Name string } -// IsErrKeyNameAlreadyUsed ... +// IsErrKeyNameAlreadyUsed checks if an error is a ErrKeyNameAlreadyUsed. func IsErrKeyNameAlreadyUsed(err error) bool { _, ok := err.(ErrKeyNameAlreadyUsed) return ok @@ -228,14 +229,14 @@ func (err ErrKeyNameAlreadyUsed) Error() string { return fmt.Sprintf("public key already exists [owner_id: %d, name: %s]", err.OwnerID, err.Name) } -// ErrKeyAccessDenied ... +// ErrKeyAccessDenied represents a "KeyAccessDenied" kind of error. type ErrKeyAccessDenied struct { UserID int64 KeyID int64 Note string } -// IsErrKeyAccessDenied ... +// IsErrKeyAccessDenied checks if an error is a ErrKeyAccessDenied. func IsErrKeyAccessDenied(err error) bool { _, ok := err.(ErrKeyAccessDenied) return ok @@ -246,14 +247,14 @@ func (err ErrKeyAccessDenied) Error() string { err.UserID, err.KeyID, err.Note) } -// ErrDeployKeyNotExist ... +// ErrDeployKeyNotExist represents a "DeployKeyNotExist" kind of error. type ErrDeployKeyNotExist struct { ID int64 KeyID int64 RepoID int64 } -// IsErrDeployKeyNotExist ... +// IsErrDeployKeyNotExist checks if an error is a ErrDeployKeyNotExist. func IsErrDeployKeyNotExist(err error) bool { _, ok := err.(ErrDeployKeyNotExist) return ok @@ -263,13 +264,13 @@ func (err ErrDeployKeyNotExist) Error() string { return fmt.Sprintf("Deploy key does not exist [id: %d, key_id: %d, repo_id: %d]", err.ID, err.KeyID, err.RepoID) } -// ErrDeployKeyAlreadyExist ... +// ErrDeployKeyAlreadyExist represents a "DeployKeyAlreadyExist" kind of error. type ErrDeployKeyAlreadyExist struct { KeyID int64 RepoID int64 } -// IsErrDeployKeyAlreadyExist ... +// IsErrDeployKeyAlreadyExist checks if an error is a ErrDeployKeyAlreadyExist. func IsErrDeployKeyAlreadyExist(err error) bool { _, ok := err.(ErrDeployKeyAlreadyExist) return ok @@ -279,13 +280,13 @@ func (err ErrDeployKeyAlreadyExist) Error() string { return fmt.Sprintf("public key already exists [key_id: %d, repo_id: %d]", err.KeyID, err.RepoID) } -// ErrDeployKeyNameAlreadyUsed ... +// ErrDeployKeyNameAlreadyUsed represents a "DeployKeyNameAlreadyUsed" kind of error. type ErrDeployKeyNameAlreadyUsed struct { RepoID int64 Name string } -// IsErrDeployKeyNameAlreadyUsed ... +// IsErrDeployKeyNameAlreadyUsed checks if an error is a ErrDeployKeyNameAlreadyUsed. func IsErrDeployKeyNameAlreadyUsed(err error) bool { _, ok := err.(ErrDeployKeyNameAlreadyUsed) return ok @@ -302,12 +303,12 @@ func (err ErrDeployKeyNameAlreadyUsed) Error() string { // \____|__ /\___ >___ >___ >____ >____ > |____| \____/|__|_ \\___ >___| / // \/ \/ \/ \/ \/ \/ \/ \/ \/ -// ErrAccessTokenNotExist ... +// ErrAccessTokenNotExist represents a "AccessTokenNotExist" kind of error. type ErrAccessTokenNotExist struct { SHA string } -// IsErrAccessTokenNotExist ... +// IsErrAccessTokenNotExist checks if an error is a ErrAccessTokenNotExist. func IsErrAccessTokenNotExist(err error) bool { _, ok := err.(ErrAccessTokenNotExist) return ok @@ -317,11 +318,11 @@ func (err ErrAccessTokenNotExist) Error() string { return fmt.Sprintf("access token does not exist [sha: %s]", err.SHA) } -// ErrAccessTokenEmpty ... +// ErrAccessTokenEmpty represents a "AccessTokenEmpty" kind of error. type ErrAccessTokenEmpty struct { } -// IsErrAccessTokenEmpty ... +// IsErrAccessTokenEmpty checks if an error is a ErrAccessTokenEmpty. func IsErrAccessTokenEmpty(err error) bool { _, ok := err.(ErrAccessTokenEmpty) return ok @@ -338,12 +339,12 @@ func (err ErrAccessTokenEmpty) Error() string { // \_______ /__| \___ (____ /___| /__/_____ \(____ /__| |__|\____/|___| / // \/ /_____/ \/ \/ \/ \/ \/ -// ErrLastOrgOwner ... +// ErrLastOrgOwner represents a "LastOrgOwner" kind of error. type ErrLastOrgOwner struct { UID int64 } -// IsErrLastOrgOwner ... +// IsErrLastOrgOwner checks if an error is a ErrLastOrgOwner. func IsErrLastOrgOwner(err error) bool { _, ok := err.(ErrLastOrgOwner) return ok @@ -360,14 +361,14 @@ func (err ErrLastOrgOwner) Error() string { // |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____| // \/ \/|__| \/ \/ -// ErrRepoNotExist ... +// ErrRepoNotExist represents a "RepoNotExist" kind of error. type ErrRepoNotExist struct { ID int64 UID int64 Name string } -// IsErrRepoNotExist ... +// IsErrRepoNotExist checks if an error is a ErrRepoNotExist. func IsErrRepoNotExist(err error) bool { _, ok := err.(ErrRepoNotExist) return ok @@ -377,13 +378,13 @@ func (err ErrRepoNotExist) Error() string { return fmt.Sprintf("repository does not exist [id: %d, uid: %d, name: %s]", err.ID, err.UID, err.Name) } -// ErrRepoAlreadyExist ... +// ErrRepoAlreadyExist represents a "RepoAlreadyExist" kind of error. type ErrRepoAlreadyExist struct { Uname string Name string } -// IsErrRepoAlreadyExist ... +// IsErrRepoAlreadyExist checks if an error is a ErrRepoAlreadyExist. func IsErrRepoAlreadyExist(err error) bool { _, ok := err.(ErrRepoAlreadyExist) return ok @@ -393,14 +394,14 @@ func (err ErrRepoAlreadyExist) Error() string { return fmt.Sprintf("repository already exists [uname: %s, name: %s]", err.Uname, err.Name) } -// ErrInvalidCloneAddr ... +// ErrInvalidCloneAddr represents a "InvalidCloneAddr" kind of error. type ErrInvalidCloneAddr struct { IsURLError bool IsInvalidPath bool IsPermissionDenied bool } -// IsErrInvalidCloneAddr ... +// IsErrInvalidCloneAddr checks if an error is a ErrInvalidCloneAddr. func IsErrInvalidCloneAddr(err error) bool { _, ok := err.(ErrInvalidCloneAddr) return ok @@ -411,12 +412,12 @@ func (err ErrInvalidCloneAddr) Error() string { err.IsURLError, err.IsInvalidPath, err.IsPermissionDenied) } -// ErrUpdateTaskNotExist ... +// ErrUpdateTaskNotExist represents a "UpdateTaskNotExist" kind of error. type ErrUpdateTaskNotExist struct { UUID string } -// IsErrUpdateTaskNotExist ... +// IsErrUpdateTaskNotExist checks if an error is a ErrUpdateTaskNotExist. func IsErrUpdateTaskNotExist(err error) bool { _, ok := err.(ErrUpdateTaskNotExist) return ok @@ -426,12 +427,12 @@ func (err ErrUpdateTaskNotExist) Error() string { return fmt.Sprintf("update task does not exist [uuid: %s]", err.UUID) } -// ErrReleaseAlreadyExist ... +// ErrReleaseAlreadyExist represents a "ReleaseAlreadyExist" kind of error. type ErrReleaseAlreadyExist struct { TagName string } -// IsErrReleaseAlreadyExist ... +// IsErrReleaseAlreadyExist checks if an error is a ErrReleaseAlreadyExist. func IsErrReleaseAlreadyExist(err error) bool { _, ok := err.(ErrReleaseAlreadyExist) return ok @@ -441,13 +442,13 @@ func (err ErrReleaseAlreadyExist) Error() string { return fmt.Sprintf("release tag already exist [tag_name: %s]", err.TagName) } -// ErrReleaseNotExist ... +// ErrReleaseNotExist represents a "ReleaseNotExist" kind of error. type ErrReleaseNotExist struct { ID int64 TagName string } -// IsErrReleaseNotExist ... +// IsErrReleaseNotExist checks if an error is a ErrReleaseNotExist. func IsErrReleaseNotExist(err error) bool { _, ok := err.(ErrReleaseNotExist) return ok @@ -457,12 +458,12 @@ func (err ErrReleaseNotExist) Error() string { return fmt.Sprintf("release tag does not exist [id: %d, tag_name: %s]", err.ID, err.TagName) } -// ErrInvalidTagName ... +// ErrInvalidTagName represents a "InvalidTagName" kind of error. type ErrInvalidTagName struct { TagName string } -// IsErrInvalidTagName ... +// IsErrInvalidTagName checks if an error is a ErrInvalidTagName. func IsErrInvalidTagName(err error) bool { _, ok := err.(ErrInvalidTagName) return ok @@ -472,12 +473,12 @@ func (err ErrInvalidTagName) Error() string { return fmt.Sprintf("release tag name is not valid [tag_name: %s]", err.TagName) } -// ErrRepoFileAlreadyExist ... +// ErrRepoFileAlreadyExist represents a "RepoFileAlreadyExist" kind of error. type ErrRepoFileAlreadyExist struct { FileName string } -// IsErrRepoFileAlreadyExist ... +// IsErrRepoFileAlreadyExist checks if an error is a ErrRepoFileAlreadyExist. func IsErrRepoFileAlreadyExist(err error) bool { _, ok := err.(ErrRepoFileAlreadyExist) return ok @@ -494,12 +495,12 @@ func (err ErrRepoFileAlreadyExist) Error() string { // |______ / |__| (____ /___| /\___ >___| / // \/ \/ \/ \/ \/ -// ErrBranchNotExist ... +// ErrBranchNotExist represents a "BranchNotExist" kind of error. type ErrBranchNotExist struct { Name string } -// IsErrBranchNotExist ... +// IsErrBranchNotExist checks if an error is a ErrBranchNotExist. func IsErrBranchNotExist(err error) bool { _, ok := err.(ErrBranchNotExist) return ok @@ -516,12 +517,12 @@ func (err ErrBranchNotExist) Error() string { // \__/\ / \___ >___ /___| /\____/ \____/|__|_ \ // \/ \/ \/ \/ \/ -// ErrWebhookNotExist ... +// ErrWebhookNotExist represents a "WebhookNotExist" kind of error. type ErrWebhookNotExist struct { ID int64 } -// IsErrWebhookNotExist ... +// IsErrWebhookNotExist checks if an error is a ErrWebhookNotExist. func IsErrWebhookNotExist(err error) bool { _, ok := err.(ErrWebhookNotExist) return ok @@ -538,14 +539,14 @@ func (err ErrWebhookNotExist) Error() string { // |___/____ >____ >____/ \___ > // \/ \/ \/ -// ErrIssueNotExist ... +// ErrIssueNotExist represents a "IssueNotExist" kind of error. type ErrIssueNotExist struct { ID int64 RepoID int64 Index int64 } -// IsErrIssueNotExist ... +// IsErrIssueNotExist checks if an error is a ErrIssueNotExist. func IsErrIssueNotExist(err error) bool { _, ok := err.(ErrIssueNotExist) return ok @@ -562,7 +563,7 @@ func (err ErrIssueNotExist) Error() string { // |____| |____/|____/____/____|_ /\___ >__ |____/ \___ >____ > |__| // \/ \/ |__| \/ \/ -// ErrPullRequestNotExist ... +// ErrPullRequestNotExist represents a "PullRequestNotExist" kind of error. type ErrPullRequestNotExist struct { ID int64 IssueID int64 @@ -572,7 +573,7 @@ type ErrPullRequestNotExist struct { BaseBranch string } -// IsErrPullRequestNotExist ... +// IsErrPullRequestNotExist checks if an error is a ErrPullRequestNotExist. func IsErrPullRequestNotExist(err error) bool { _, ok := err.(ErrPullRequestNotExist) return ok @@ -590,13 +591,13 @@ func (err ErrPullRequestNotExist) Error() string { // \______ /\____/|__|_| /__|_| /\___ >___| /__| // \/ \/ \/ \/ \/ -// ErrCommentNotExist ... +// ErrCommentNotExist represents a "CommentNotExist" kind of error. type ErrCommentNotExist struct { ID int64 IssueID int64 } -// IsErrCommentNotExist ... +// IsErrCommentNotExist checks if an error is a ErrCommentNotExist. func IsErrCommentNotExist(err error) bool { _, ok := err.(ErrCommentNotExist) return ok @@ -613,13 +614,13 @@ func (err ErrCommentNotExist) Error() string { // |_______ (____ /___ /\___ >____/ // \/ \/ \/ \/ -// ErrLabelNotExist ... +// ErrLabelNotExist represents a "LabelNotExist" kind of error. type ErrLabelNotExist struct { LabelID int64 RepoID int64 } -// IsErrLabelNotExist ... +// IsErrLabelNotExist checks if an error is a ErrLabelNotExist. func IsErrLabelNotExist(err error) bool { _, ok := err.(ErrLabelNotExist) return ok @@ -636,13 +637,13 @@ func (err ErrLabelNotExist) Error() string { // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ > // \/ \/ \/ \/ \/ -// ErrMilestoneNotExist ... +// ErrMilestoneNotExist represents a "MilestoneNotExist" kind of error. type ErrMilestoneNotExist struct { ID int64 RepoID int64 } -// IsErrMilestoneNotExist ... +// IsErrMilestoneNotExist checks if an error is a ErrMilestoneNotExist. func IsErrMilestoneNotExist(err error) bool { _, ok := err.(ErrMilestoneNotExist) return ok @@ -659,13 +660,13 @@ func (err ErrMilestoneNotExist) Error() string { // \____|__ /__| |__| (____ /\___ >___| /__|_| /\___ >___| /__| // \/ \/ \/ \/ \/ \/ \/ -// ErrAttachmentNotExist ... +// ErrAttachmentNotExist represents a "AttachmentNotExist" kind of error. type ErrAttachmentNotExist struct { ID int64 UUID string } -// IsErrAttachmentNotExist ... +// IsErrAttachmentNotExist checks if an error is a ErrAttachmentNotExist. func IsErrAttachmentNotExist(err error) bool { _, ok := err.(ErrAttachmentNotExist) return ok @@ -682,12 +683,12 @@ func (err ErrAttachmentNotExist) Error() string { // |_______ \____/\___ /|__|___| / /_______ /\____/|____/ |__| \___ >___ > // \/ /_____/ \/ \/ \/ \/ -// ErrLoginSourceNotExist ... +// ErrLoginSourceNotExist represents a "LoginSourceNotExist" kind of error. type ErrLoginSourceNotExist struct { ID int64 } -// IsErrLoginSourceNotExist ... +// IsErrLoginSourceNotExist checks if an error is a ErrLoginSourceNotExist. func IsErrLoginSourceNotExist(err error) bool { _, ok := err.(ErrLoginSourceNotExist) return ok @@ -697,12 +698,12 @@ func (err ErrLoginSourceNotExist) Error() string { return fmt.Sprintf("login source does not exist [id: %d]", err.ID) } -// ErrLoginSourceAlreadyExist ... +// ErrLoginSourceAlreadyExist represents a "LoginSourceAlreadyExist" kind of error. type ErrLoginSourceAlreadyExist struct { Name string } -// IsErrLoginSourceAlreadyExist ... +// IsErrLoginSourceAlreadyExist checks if an error is a ErrLoginSourceAlreadyExist. func IsErrLoginSourceAlreadyExist(err error) bool { _, ok := err.(ErrLoginSourceAlreadyExist) return ok @@ -712,12 +713,12 @@ func (err ErrLoginSourceAlreadyExist) Error() string { return fmt.Sprintf("login source already exists [name: %s]", err.Name) } -// ErrLoginSourceInUse ... +// ErrLoginSourceInUse represents a "LoginSourceInUse" kind of error. type ErrLoginSourceInUse struct { ID int64 } -// IsErrLoginSourceInUse ... +// IsErrLoginSourceInUse checks if an error is a ErrLoginSourceInUse. func IsErrLoginSourceInUse(err error) bool { _, ok := err.(ErrLoginSourceInUse) return ok @@ -734,13 +735,13 @@ func (err ErrLoginSourceInUse) Error() string { // |____| \___ >____ /__|_| / // \/ \/ \/ -// ErrTeamAlreadyExist ... +// ErrTeamAlreadyExist represents a "TeamAlreadyExist" kind of error. type ErrTeamAlreadyExist struct { OrgID int64 Name string } -// IsErrTeamAlreadyExist ... +// IsErrTeamAlreadyExist checks if an error is a ErrTeamAlreadyExist. func IsErrTeamAlreadyExist(err error) bool { _, ok := err.(ErrTeamAlreadyExist) return ok @@ -758,13 +759,13 @@ func (err ErrTeamAlreadyExist) Error() string { // |__| \/ \/ // -// ErrUploadNotExist ... +// ErrUploadNotExist represents a "UploadNotExist" kind of error. type ErrUploadNotExist struct { ID int64 UUID string } -// IsErrUploadNotExist ... +// IsErrUploadNotExist checks if an error is a ErrUploadNotExist. func IsErrUploadNotExist(err error) bool { _, ok := err.(ErrAttachmentNotExist) return ok From 3fba29c571573ed1488d299647a4a81080ce486d Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Thu, 24 Nov 2016 09:30:08 +0100 Subject: [PATCH 013/135] Expand documentations --- models/git_diff.go | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/models/git_diff.go b/models/git_diff.go index 8bdce68221..b8f9cacec9 100644 --- a/models/git_diff.go +++ b/models/git_diff.go @@ -28,7 +28,7 @@ import ( "golang.org/x/text/transform" ) -// DiffLineType ... +// DiffLineType represents the type of a DiffLine. type DiffLineType uint8 // DiffLineType possible values. @@ -39,7 +39,7 @@ const ( DiffLineSection ) -// DiffFileType ... +// DiffFileType represents the type of a DiffFile. type DiffFileType uint8 // DiffFileType possible values. @@ -50,7 +50,7 @@ const ( DiffFileRename ) -// DiffLine ... +// DiffLine represents a line difference in a DiffSection. type DiffLine struct { LeftIdx int RightIdx int @@ -58,12 +58,12 @@ type DiffLine struct { Content string } -// GetType ... +// GetType returns the type of a DiffLine. func (d *DiffLine) GetType() int { return int(d.Type) } -// DiffSection ... +// DiffSection represents a section of a DiffFile. type DiffSection struct { Name string Lines []*DiffLine @@ -75,7 +75,6 @@ var ( codeTagSuffix = []byte("") ) -// diffToHTML ... func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTML { buf := bytes.NewBuffer(nil) @@ -150,7 +149,6 @@ LOOP: var diffMatchPatch = diffmatchpatch.New() -// init ... func init() { diffMatchPatch.DiffEditCost = 100 } @@ -192,7 +190,7 @@ func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) tem return diffToHTML(diffRecord, diffLine.Type) } -// DiffFile ... +// DiffFile represents a file diff. type DiffFile struct { Name string OldName string @@ -213,26 +211,27 @@ func (diffFile *DiffFile) GetType() int { return int(diffFile.Type) } -// GetHighlightClass ... +// GetHighlightClass returns highlight class for a filename. func (diffFile *DiffFile) GetHighlightClass() string { return highlight.FileNameToHighlightClass(diffFile.Name) } -// Diff ... +// Diff represents a difference between two git trees. type Diff struct { TotalAddition, TotalDeletion int Files []*DiffFile IsIncomplete bool } -// NumFiles ... +// NumFiles returns number of files changes in a diff. func (diff *Diff) NumFiles() int { return len(diff.Files) } const cmdDiffHead = "diff --git " -// ParsePatch ... +// ParsePatch builds a Diff object from a io.Reader and some +// parameters. // TODO: move this function to gogits/git-module func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*Diff, error) { var ( @@ -420,7 +419,9 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (* return diff, nil } -// GetDiffRange ... +// GetDiffRange builds a Diff between two commits of a repository. +// passing the empty string as beforeCommitID returns a diff from the +// parent commit. func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacteres, maxFiles int) (*Diff, error) { gitRepo, err := git.OpenRepository(repoPath) if err != nil { @@ -472,7 +473,7 @@ func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxL return diff, nil } -// RawDiffType ... +// RawDiffType type of a raw diff. type RawDiffType string // RawDiffType possible values. @@ -483,7 +484,6 @@ const ( // GetRawDiff dumps diff results of repository in given commit ID to io.Writer. // TODO: move this function to gogits/git-module -// GetRawDiff ... func GetRawDiff(repoPath, commitID string, diffType RawDiffType, writer io.Writer) error { repo, err := git.OpenRepository(repoPath) if err != nil { @@ -528,7 +528,7 @@ func GetRawDiff(repoPath, commitID string, diffType RawDiffType, writer io.Write return nil } -// GetDiffCommit ... +// GetDiffCommit builds a Diff representing the given commitID. func GetDiffCommit(repoPath, commitID string, maxLines, maxLineCharacteres, maxFiles int) (*Diff, error) { return GetDiffRange(repoPath, "", commitID, maxLines, maxLineCharacteres, maxFiles) } From 8aa960f1292dc11d32b017feda646e4758fde37c Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Thu, 24 Nov 2016 09:41:11 +0100 Subject: [PATCH 014/135] Actually document the missing bits --- models/issue.go | 54 ++++++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/models/issue.go b/models/issue.go index 7876d3ec88..e5beaedadf 100644 --- a/models/issue.go +++ b/models/issue.go @@ -62,19 +62,20 @@ type Issue struct { Comments []*Comment `xorm:"-"` } -// BeforeInsert ... +// BeforeInsert is invoked from XORM before inserting an object of this type. func (issue *Issue) BeforeInsert() { issue.CreatedUnix = time.Now().Unix() issue.UpdatedUnix = issue.CreatedUnix } -// BeforeUpdate ... +// BeforeUpdate is invoked from XORM before updating this object. func (issue *Issue) BeforeUpdate() { issue.UpdatedUnix = time.Now().Unix() issue.DeadlineUnix = issue.Deadline.Unix() } -// AfterSet ... +// AfterSet is invoked from XORM after setting the value of a field of +// this object. func (issue *Issue) AfterSet(colName string, _ xorm.Cell) { switch colName { case "deadline_unix": @@ -86,7 +87,6 @@ func (issue *Issue) AfterSet(colName string, _ xorm.Cell) { } } -// loadAttributes ... func (issue *Issue) loadAttributes(e Engine) (err error) { if issue.Repo == nil { issue.Repo, err = getRepositoryByID(e, issue.RepoID) @@ -154,12 +154,12 @@ func (issue *Issue) loadAttributes(e Engine) (err error) { return nil } -// LoadAttributes ... +// LoadAttributes loads the attribute of this issue. func (issue *Issue) LoadAttributes() error { return issue.loadAttributes(x) } -// HTMLURL ... +// HTMLURL returns the absolute URL to this issue. func (issue *Issue) HTMLURL() string { var path string if issue.IsPull { @@ -237,7 +237,6 @@ func (issue *Issue) HasLabel(labelID int64) bool { return issue.hasLabel(x, labelID) } -// sendLabelUpdatedWebhook ... func (issue *Issue) sendLabelUpdatedWebhook(doer *User) { var err error if issue.IsPull { @@ -261,7 +260,6 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) { } } -// addLabel ... func (issue *Issue) addLabel(e *xorm.Session, label *Label) error { return newIssueLabel(e, issue, label) } @@ -276,7 +274,6 @@ func (issue *Issue) AddLabel(doer *User, label *Label) error { return nil } -// addLabels ... func (issue *Issue) addLabels(e *xorm.Session, labels []*Label) error { return newIssueLabels(e, issue, labels) } @@ -291,7 +288,6 @@ func (issue *Issue) AddLabels(doer *User, labels []*Label) error { return nil } -// getLabels ... func (issue *Issue) getLabels(e Engine) (err error) { if len(issue.Labels) > 0 { return nil @@ -304,7 +300,6 @@ func (issue *Issue) getLabels(e Engine) (err error) { return nil } -// removeLabel ... func (issue *Issue) removeLabel(e *xorm.Session, label *Label) error { return deleteIssueLabel(e, issue, label) } @@ -319,7 +314,6 @@ func (issue *Issue) RemoveLabel(doer *User, label *Label) error { return nil } -// clearLabels ... func (issue *Issue) clearLabels(e *xorm.Session) (err error) { if err = issue.getLabels(e); err != nil { return fmt.Errorf("getLabels: %v", err) @@ -334,7 +328,8 @@ func (issue *Issue) clearLabels(e *xorm.Session) (err error) { return nil } -// ClearLabels ... +// ClearLabels removes all issue labels as the given user. +// Triggers appropriate WebHooks, if any. func (issue *Issue) ClearLabels(doer *User) (err error) { sess := x.NewSession() defer sessionRelease(sess) @@ -374,6 +369,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) { } // ReplaceLabels removes all current labels and add new labels to the issue. +// Triggers appropriate WebHooks, if any. func (issue *Issue) ReplaceLabels(labels []*Label) (err error) { sess := x.NewSession() defer sessionRelease(sess) @@ -390,7 +386,7 @@ func (issue *Issue) ReplaceLabels(labels []*Label) (err error) { return sess.Commit() } -// GetAssignee ... +// GetAssignee sets the Assignee attribute of this issue. func (issue *Issue) GetAssignee() (err error) { if issue.AssigneeID == 0 || issue.Assignee != nil { return nil @@ -418,7 +414,6 @@ func UpdateIssueCols(issue *Issue, cols ...string) error { return updateIssueCols(x, issue, cols...) } -// changeStatus ... func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) { // Nothing should be performed if current status is same as target status if issue.IsClosed == isClosed { @@ -501,7 +496,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e return nil } -// ChangeTitle ... +// ChangeTitle changes the title of this issue, as the given user. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) { oldTitle := issue.Title issue.Title = title @@ -533,7 +528,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) { return nil } -// ChangeContent ... +// ChangeContent changes issue content, as the given user. func (issue *Issue) ChangeContent(doer *User, content string) (err error) { oldContent := issue.Content issue.Content = content @@ -565,7 +560,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) { return nil } -// ChangeAssignee ... +// ChangeAssignee changes the Asssignee field of this issue. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) { issue.AssigneeID = assigneeID if err = UpdateIssueUserByAssignee(issue); err != nil { @@ -604,7 +599,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) { return nil } -// NewIssueOptions ... +// NewIssueOptions represents the options of a new issue. type NewIssueOptions struct { Repo *Repository Issue *Issue @@ -815,7 +810,7 @@ func GetIssueByID(id int64) (*Issue, error) { return getIssueByID(x, id) } -// IssuesOptions ... +// IssuesOptions represents options of an issue. type IssuesOptions struct { UserID int64 AssigneeID int64 @@ -1112,7 +1107,7 @@ func parseCountResult(results []map[string][]byte) int64 { return 0 } -// IssueStatsOptions ... +// IssueStatsOptions contains parameters accepted by GetIssueStats. type IssueStatsOptions struct { RepoID int64 UserID int64 @@ -1371,12 +1366,12 @@ type Milestone struct { ClosedDateUnix int64 } -// BeforeInsert ... +// BeforeInsert is invoked from XORM before inserting an object of this type. func (m *Milestone) BeforeInsert() { m.DeadlineUnix = m.Deadline.Unix() } -// BeforeUpdate ... +// BeforeUpdate is invoked from XORM before updating this object. func (m *Milestone) BeforeUpdate() { if m.NumIssues > 0 { m.Completeness = m.NumClosedIssues * 100 / m.NumIssues @@ -1388,7 +1383,8 @@ func (m *Milestone) BeforeUpdate() { m.ClosedDateUnix = m.ClosedDate.Unix() } -// AfterSet ... +// AfterSet is invoked from XORM after setting the value of a field of +// this object. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) { switch colName { case "num_closed_issues": @@ -1418,7 +1414,7 @@ func (m *Milestone) State() api.StateType { return api.STATE_OPEN } -// APIFormat ... +// APIFormat returns this Milestone in API format. func (m *Milestone) APIFormat() *api.Milestone { apiMilestone := &api.Milestone{ ID: m.ID, @@ -1701,12 +1697,13 @@ type Attachment struct { CreatedUnix int64 } -// BeforeInsert ... +// BeforeInsert is invoked from XORM before inserting an object of this type. func (a *Attachment) BeforeInsert() { a.CreatedUnix = time.Now().Unix() } -// AfterSet ... +// AfterSet is invoked from XORM after setting the value of a field of +// this object. func (a *Attachment) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": @@ -1714,7 +1711,8 @@ func (a *Attachment) AfterSet(colName string, _ xorm.Cell) { } } -// AttachmentLocalPath returns where attachment is stored in local file system based on given UUID. +// AttachmentLocalPath returns where attachment is stored in local file +// system based on given UUID. func AttachmentLocalPath(uuid string) string { return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid) } From 46ecb0a14d6e4f0e8fb1d312133a14fe2f295aed Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 24 Nov 2016 17:37:11 +0800 Subject: [PATCH 015/135] golint fixed for modules/user --- modules/user/user.go | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/user/user.go b/modules/user/user.go index 972629eae3..b9911e6f52 100644 --- a/modules/user/user.go +++ b/modules/user/user.go @@ -6,6 +6,7 @@ package user import "os" +// CurrentUsername return current login OS user name func CurrentUsername() string { curUserName := os.Getenv("USER") if len(curUserName) > 0 { From ff0d1bd602c725726ce60b5964c62003c75312b9 Mon Sep 17 00:00:00 2001 From: Bwko Date: Wed, 23 Nov 2016 22:06:56 +0100 Subject: [PATCH 016/135] Added short-hash support to downloads --- routers/repo/repo.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/repo/repo.go b/routers/repo/repo.go index c3e9faf499..50564bd426 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -311,7 +311,7 @@ func Download(ctx *context.Context) { ctx.Handle(500, "GetTagCommit", err) return } - } else if len(refName) == 40 { + } else if len(refName) >= 4 && len(refName) <= 40 { commit, err = gitRepo.GetCommit(refName) if err != nil { ctx.Handle(404, "GetCommit", nil) From 1c3044b873c4197215f16921c1bfba12b05933e1 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Thu, 24 Nov 2016 12:34:38 +0100 Subject: [PATCH 017/135] Lint models/login_source.go --- models/login_source.go | 56 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/models/login_source.go b/models/login_source.go index 774cb7f4db..2d4076fc01 100644 --- a/models/login_source.go +++ b/models/login_source.go @@ -24,6 +24,7 @@ import ( "code.gitea.io/gitea/modules/log" ) +// LoginType represents an login type. type LoginType int // Note: new type must append to the end of list to maintain compatibility. @@ -36,6 +37,7 @@ const ( LoginDLDAP // 5 ) +// LoginNames contains the name of LoginType values. var LoginNames = map[LoginType]string{ LoginLDAP: "LDAP (via BindDN)", LoginDLDAP: "LDAP (simple auth)", // Via direct bind @@ -43,6 +45,7 @@ var LoginNames = map[LoginType]string{ LoginPAM: "PAM", } +// SecurityProtocolNames contains the name of SecurityProtocol values. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{ ldap.SecurityProtocolUnencrypted: "Unencrypted", ldap.SecurityProtocolLDAPS: "LDAPS", @@ -56,22 +59,28 @@ var ( _ core.Conversion = &PAMConfig{} ) +// LDAPConfig holds configuration for LDAP login source. type LDAPConfig struct { *ldap.Source } +// FromDB fills up a LDAPConfig from serialized format. func (cfg *LDAPConfig) FromDB(bs []byte) error { return json.Unmarshal(bs, &cfg) } +// ToDB exports a LDAPConfig to a serialized format. func (cfg *LDAPConfig) ToDB() ([]byte, error) { return json.Marshal(cfg) } +// SecurityProtocolName returns the name of configured security +// protocol. func (cfg *LDAPConfig) SecurityProtocolName() string { return SecurityProtocolNames[cfg.SecurityProtocol] } +// SMTPConfig holds configuration for the SMTP login source. type SMTPConfig struct { Auth string Host string @@ -81,22 +90,27 @@ type SMTPConfig struct { SkipVerify bool } +// FromDB fills up an SMTPConfig from serialized format. func (cfg *SMTPConfig) FromDB(bs []byte) error { return json.Unmarshal(bs, cfg) } +// ToDB exports an SMTPConfig to a serialized format. func (cfg *SMTPConfig) ToDB() ([]byte, error) { return json.Marshal(cfg) } +// PAMConfig holds configuration for the PAM login source. type PAMConfig struct { ServiceName string // pam service (e.g. system-auth) } +// FromDB fills up a PAMConfig from serialized format. func (cfg *PAMConfig) FromDB(bs []byte) error { return json.Unmarshal(bs, &cfg) } +// ToDB exports a PAMConfig to a serialized format. func (cfg *PAMConfig) ToDB() ([]byte, error) { return json.Marshal(cfg) } @@ -115,13 +129,15 @@ type LoginSource struct { UpdatedUnix int64 } -func (s *LoginSource) BeforeInsert() { - s.CreatedUnix = time.Now().Unix() - s.UpdatedUnix = s.CreatedUnix +// BeforeInsert is invoked from XORM before inserting an object of this type. +func (source *LoginSource) BeforeInsert() { + source.CreatedUnix = time.Now().Unix() + source.UpdatedUnix = source.CreatedUnix } -func (s *LoginSource) BeforeUpdate() { - s.UpdatedUnix = time.Now().Unix() +// BeforeUpdate is invoked from XORM before updating this object. +func (source *LoginSource) BeforeUpdate() { + source.UpdatedUnix = time.Now().Unix() } // Cell2Int64 converts a xorm.Cell type to int64, @@ -135,6 +151,7 @@ func Cell2Int64(val xorm.Cell) int64 { return (*val).(int64) } +// BeforeSet is invoked from XORM before setting the value of a field of this object. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) { switch colName { case "type": @@ -151,41 +168,49 @@ func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) { } } -func (s *LoginSource) AfterSet(colName string, _ xorm.Cell) { +// AfterSet is invoked from XORM after setting the value of a field of this object. +func (source *LoginSource) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": - s.Created = time.Unix(s.CreatedUnix, 0).Local() + source.Created = time.Unix(source.CreatedUnix, 0).Local() case "updated_unix": - s.Updated = time.Unix(s.UpdatedUnix, 0).Local() + source.Updated = time.Unix(source.UpdatedUnix, 0).Local() } } +// TypeName return name of this login source type. func (source *LoginSource) TypeName() string { return LoginNames[source.Type] } +// IsLDAP returns true of this source is of the LDAP type. func (source *LoginSource) IsLDAP() bool { return source.Type == LoginLDAP } +// IsDLDAP returns true of this source is of the DLDAP type. func (source *LoginSource) IsDLDAP() bool { return source.Type == LoginDLDAP } +// IsSMTP returns true of this source is of the SMTP type. func (source *LoginSource) IsSMTP() bool { return source.Type == LoginSMTP } +// IsPAM returns true of this source is of the PAM type. func (source *LoginSource) IsPAM() bool { return source.Type == LoginPAM } +// HasTLS returns true of this source supports TLS. func (source *LoginSource) HasTLS() bool { return ((source.IsLDAP() || source.IsDLDAP()) && source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) || source.IsSMTP() } +// UseTLS returns true of this source is configured to use TLS. func (source *LoginSource) UseTLS() bool { switch source.Type { case LoginLDAP, LoginDLDAP: @@ -197,6 +222,8 @@ func (source *LoginSource) UseTLS() bool { return false } +// SkipVerify returns true if this source is configured to skip SSL +// verification. func (source *LoginSource) SkipVerify() bool { switch source.Type { case LoginLDAP, LoginDLDAP: @@ -208,17 +235,23 @@ func (source *LoginSource) SkipVerify() bool { return false } +// LDAP returns LDAPConfig for this source, if of LDAP type. func (source *LoginSource) LDAP() *LDAPConfig { return source.Cfg.(*LDAPConfig) } +// SMTP returns SMTPConfig for this source, if of SMTP type. func (source *LoginSource) SMTP() *SMTPConfig { return source.Cfg.(*SMTPConfig) } +// PAM returns PAMConfig for this source, if of PAM type. func (source *LoginSource) PAM() *PAMConfig { return source.Cfg.(*PAMConfig) } + +// CreateLoginSource inserts a LoginSource in the DB if not already +// existing with the given name. func CreateLoginSource(source *LoginSource) error { has, err := x.Get(&LoginSource{Name: source.Name}) if err != nil { @@ -231,6 +264,7 @@ func CreateLoginSource(source *LoginSource) error { return err } +// LoginSources returns a slice of all login sources found in DB. func LoginSources() ([]*LoginSource, error) { auths := make([]*LoginSource, 0, 5) return auths, x.Find(&auths) @@ -248,11 +282,13 @@ func GetLoginSourceByID(id int64) (*LoginSource, error) { return source, nil } +// UpdateSource updates a LoginSource record in DB. func UpdateSource(source *LoginSource) error { _, err := x.Id(source.ID).AllCols().Update(source) return err } +// DeleteSource deletes a LoginSource record in DB. func DeleteSource(source *LoginSource) error { count, err := x.Count(&User{LoginSource: source.ID}) if err != nil { @@ -357,13 +393,16 @@ func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) { return nil, nil } +// SMTP authentication type names. const ( SMTPPlain = "PLAIN" SMTPLogin = "LOGIN" ) +// SMTPAuths contains available SMTP authentication type names. var SMTPAuths = []string{SMTPPlain, SMTPLogin} +// SMTPAuth performs an SMTP authentication. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error { c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)) if err != nil { @@ -487,6 +526,7 @@ func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMCon return user, CreateUser(user) } +// ExternalUserLogin attempts a login using external source types. func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) { if !source.IsActived { return nil, ErrLoginSourceNotActived From cc8c57458fa0f1e6c1189e9eeff32d98eda7e681 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Thu, 24 Nov 2016 14:38:37 +0100 Subject: [PATCH 018/135] Really use go install on make install --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index a57f6610af..d7d37106c5 100644 --- a/Makefile +++ b/Makefile @@ -66,8 +66,8 @@ test: check: test .PHONY: install -install: $(BIN)/$(EXECUTABLE) - cp $< $(GOPATH)/bin/ +install: $(wildcard *.go) + go install -v -tags '$(TAGS)' -ldflags '-s -w $(LDFLAGS)' .PHONY: build build: $(BIN)/$(EXECUTABLE) From cd7e6618707477c554ac37d56cf4565851c81d3c Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Thu, 24 Nov 2016 14:40:56 +0100 Subject: [PATCH 019/135] Added dummy tasks for mysql and pgsql tests --- Makefile | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Makefile b/Makefile index a57f6610af..7370d53cbe 100644 --- a/Makefile +++ b/Makefile @@ -62,6 +62,14 @@ lint: test: for PKG in $(PACKAGES); do go test -cover -coverprofile $$GOPATH/src/$$PKG/coverage.out $$PKG || exit 1; done; +.PHONY: test-mysql +test-mysql: + @echo "Not integrated yet!" + +.PHONY: test-pgsql +test-pgsql: + @echo "Not integrated yet!" + .PHONY: check check: test From fd13b71fb2d6f4f1fbb05da8d9e179d708637f74 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Thu, 24 Nov 2016 14:41:30 +0100 Subject: [PATCH 020/135] Added drone instead of travis detection to makefile --- Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 7370d53cbe..88eafb0488 100644 --- a/Makefile +++ b/Makefile @@ -19,11 +19,11 @@ PACKAGES ?= $(shell go list ./... | grep -v /vendor/) TAGS ?= -ifneq ($(TRAVIS_TAG),) - VERSION ?= $(TRAVIS_TAG) +ifneq ($(DRONE_TAG),) + VERSION ?= $(DRONE_TAG) else - ifneq ($(TRAVIS_BRANCH),) - VERSION ?= $(TRAVIS_BRANCH) + ifneq ($(DRONE_BRANCH),) + VERSION ?= $(DRONE_BRANCH) else VERSION ?= master endif From cb0b91cdc952a1f70c89182b066a62d0140ece1e Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Thu, 24 Nov 2016 14:41:59 +0100 Subject: [PATCH 021/135] Dropped travis config --- .travis.yml | 36 ------------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index fd97313c75..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,36 +0,0 @@ -language: go - -go_import_path: code.gitea.io/gitea - -go: - - 1.6 - - 1.7 - -env: - TAGS: cert sqlite pam miniwinsvc - -before_install: - - sudo apt-get update -qq - - sudo apt-get install -y libpam-dev - -script: - - make clean - - make vet - - # - make lint - - - make test - - make build - -after_success: - - bash <(curl -s https://codecov.io/bash) - -notifications: - webhooks: - on_success: change - on_failure: always - on_start: never - urls: - - https://webhooks.gitter.im/e/ee6b822f3cf54c98e70c - - https://webhooks.gitter.im/e/87428658ef177ce8a7e4 - - https://webhooks.gitter.im/e/a1d2b69804dfda72187e From 4c0397432660adb1204975f4156c55e9bc204ba0 Mon Sep 17 00:00:00 2001 From: Matthias Loibl Date: Sun, 6 Nov 2016 18:32:54 +0100 Subject: [PATCH 022/135] Create a first draft for .drone.yml --- .drone.yml | 118 +++++++++++++++++++++++++++++++++++++++++++++++++ .drone.yml.sig | 1 + 2 files changed, 119 insertions(+) create mode 100644 .drone.yml create mode 100644 .drone.yml.sig diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000000..fdc0afea45 --- /dev/null +++ b/.drone.yml @@ -0,0 +1,118 @@ +workspace: + base: /srv/app + path: src/code.gitea.io/gitea + +pipeline: + test: + image: webhippie/golang:edge + pull: true + environment: + CGO_ENABLED: 0 + TAGS: cert sqlite pam miniwinsvc + commands: + - apk -U add linux-pam-dev openssh-client + + - make clean + - make vet +# - make lint fails currently with 500 errors + - make test + - make build + + mysql: + image: webhippie/golang:edge + pull: true + commands: + - make test-mysql + when: + event: push + + pgsql: + image: webhippie/golang:edge + pull: true + commands: + - make test-pgsql + when: + event: push + + updater: + image: karalabe/xgo-latest:latest + pull: true + commands: + - make publish + when: + event: [ push, tag ] + branch: [ master, refs/tags/* ] + + coverage: + image: plugins/coverage + server: https://coverage.gitea.io + + docker1: + image: plugins/docker + repo: gitea/gitea + tags: [ '${TAG}' ] + when: + event: tag + branch: refs/tags/* + + docker2: + image: plugins/docker + repo: gitea/gitea + tags: [ 'latest' ] + when: + event: push + branch: master + + release1: + image: plugins/s3 + path_style: true + source: dist/release/ + target: /lgtm/master + when: + event: push + branch: master + + release2: + image: plugins/s3 + path_style: true + source: dist/release/ + target: /lgtm/$$TAG + when: + event: tag + branch: refs/tags/* + + release3: + image: plugins/s3 + path_style: true + source: dist/latest/ + target: /lgtm/latest + when: + event: tag + branch: refs/tags/* + + github: + image: plugins/github-release + files: + - dist/release/* + when: + event: tag + branch: refs/tags/* + + gitter: + image: plugins/gitter + +services: + mysqlsvc: + image: mysql:5.7 + environment: + - MYSQL_DATABASE=test + - MYSQL_ALLOW_EMPTY_PASSWORD=yes + when: + event: push + + pgsqlsvc: + image: postgres:9.5 + environment: + - POSTGRES_DB=test + when: + event: push diff --git a/.drone.yml.sig b/.drone.yml.sig new file mode 100644 index 0000000000..1437e0f45b --- /dev/null +++ b/.drone.yml.sig @@ -0,0 +1 @@ +eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDAKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAoKICAgICAgLSBtYWtlIGNsZWFuCiAgICAgIC0gbWFrZSB2ZXQKIyAgICAgIC0gbWFrZSBsaW50IGZhaWxzIGN1cnJlbnRseSB3aXRoIDUwMCBlcnJvcnMKICAgICAgLSBtYWtlIHRlc3QKICAgICAgLSBtYWtlIGJ1aWxkCgogIG15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCgogIHBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCgogIHVwZGF0ZXI6CiAgICBpbWFnZToga2FyYWxhYmUveGdvLWxhdGVzdDpsYXRlc3QKICAgIHB1bGw6IHRydWUKICAgIGNvbW1hbmRzOgogICAgICAtIG1ha2UgcHVibGlzaAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciwgcmVmcy90YWdzLyogXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KCiAgZG9ja2VyMToKICAgIGltYWdlOiBwbHVnaW5zL2RvY2tlcgogICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAgIHRhZ3M6IFsgJyR7VEFHfScgXQogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCgogIGRvY2tlcjI6CiAgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAgIHJlcG86IGdpdGVhL2dpdGVhCiAgICB0YWdzOiBbICdsYXRlc3QnIF0KICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCiAgICAgIGJyYW5jaDogbWFzdGVyCgogIHJlbGVhc2UxOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLwogICAgdGFyZ2V0OiAvbGd0bS9tYXN0ZXIKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCiAgICAgIGJyYW5jaDogbWFzdGVyCgogIHJlbGVhc2UyOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLwogICAgdGFyZ2V0OiAvbGd0bS8kJFRBRwogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCgogIHJlbGVhc2UzOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9sYXRlc3QvCiAgICB0YXJnZXQ6IC9sZ3RtL2xhdGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCgogIGdpdGh1YjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdGh1Yi1yZWxlYXNlCiAgICBmaWxlczoKICAgICAgLSBkaXN0L3JlbGVhc2UvKgogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCgogIGdpdHRlcjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdHRlcgoKc2VydmljZXM6CiAgbXlzcWxzdmM6CiAgICBpbWFnZTogbXlzcWw6NS43CiAgICBlbnZpcm9ubWVudDoKICAgICAgLSBNWVNRTF9EQVRBQkFTRT10ZXN0CiAgICAgIC0gTVlTUUxfQUxMT1dfRU1QVFlfUEFTU1dPUkQ9eWVzCiAgICB3aGVuOgogICAgICBldmVudDogcHVzaAoKICBwZ3NxbHN2YzoKICAgIGltYWdlOiBwb3N0Z3Jlczo5LjUKICAgIGVudmlyb25tZW50OgogICAgICAtIFBPU1RHUkVTX0RCPXRlc3QKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCg.opfoV7bpz1nSKIymq-VjF68P3dhGlvRg9z1NjMDf7Bg \ No newline at end of file From fd090dc29b2482b60fb821912be2859209aeb1a5 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Thu, 24 Nov 2016 14:48:40 +0100 Subject: [PATCH 023/135] Added matrix drone builds --- .drone.yml | 50 ++++++++++++++++++++++++++++++++++++-------------- .drone.yml.sig | 2 +- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/.drone.yml b/.drone.yml index fdc0afea45..f4608b7661 100644 --- a/.drone.yml +++ b/.drone.yml @@ -4,30 +4,30 @@ workspace: pipeline: test: - image: webhippie/golang:edge + image: webhippie/golang:${GO_VERSION} pull: true environment: - CGO_ENABLED: 0 + CGO_ENABLED: 1 TAGS: cert sqlite pam miniwinsvc commands: - apk -U add linux-pam-dev openssh-client - make clean - make vet -# - make lint fails currently with 500 errors + # - make lint - make test - make build - mysql: - image: webhippie/golang:edge + test-mysql: + image: webhippie/golang:${GO_VERSION} pull: true commands: - make test-mysql when: event: push - pgsql: - image: webhippie/golang:edge + test-pgsql: + image: webhippie/golang:${GO_VERSION} pull: true commands: - make test-pgsql @@ -42,28 +42,37 @@ pipeline: when: event: [ push, tag ] branch: [ master, refs/tags/* ] + matrix: + GO_VERSION: 1.7 coverage: image: plugins/coverage server: https://coverage.gitea.io + when: + matrix: + GO_VERSION: 1.7 - docker1: + docker: image: plugins/docker repo: gitea/gitea tags: [ '${TAG}' ] when: event: tag branch: refs/tags/* + matrix: + GO_VERSION: 1.7 - docker2: + docker: image: plugins/docker repo: gitea/gitea tags: [ 'latest' ] when: event: push branch: master + matrix: + GO_VERSION: 1.7 - release1: + release: image: plugins/s3 path_style: true source: dist/release/ @@ -71,8 +80,10 @@ pipeline: when: event: push branch: master + matrix: + GO_VERSION: 1.7 - release2: + release: image: plugins/s3 path_style: true source: dist/release/ @@ -80,8 +91,10 @@ pipeline: when: event: tag branch: refs/tags/* + matrix: + GO_VERSION: 1.7 - release3: + latest: image: plugins/s3 path_style: true source: dist/latest/ @@ -89,6 +102,8 @@ pipeline: when: event: tag branch: refs/tags/* + matrix: + GO_VERSION: 1.7 github: image: plugins/github-release @@ -97,12 +112,14 @@ pipeline: when: event: tag branch: refs/tags/* + matrix: + GO_VERSION: 1.7 gitter: image: plugins/gitter services: - mysqlsvc: + mysql: image: mysql:5.7 environment: - MYSQL_DATABASE=test @@ -110,9 +127,14 @@ services: when: event: push - pgsqlsvc: + pgsql: image: postgres:9.5 environment: - POSTGRES_DB=test when: event: push + +matrix: + GO_VERSION: + - 1.6 + - 1.7 diff --git a/.drone.yml.sig b/.drone.yml.sig index 1437e0f45b..978c1cd5f4 100644 --- a/.drone.yml.sig +++ b/.drone.yml.sig @@ -1 +1 @@ -eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDAKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAoKICAgICAgLSBtYWtlIGNsZWFuCiAgICAgIC0gbWFrZSB2ZXQKIyAgICAgIC0gbWFrZSBsaW50IGZhaWxzIGN1cnJlbnRseSB3aXRoIDUwMCBlcnJvcnMKICAgICAgLSBtYWtlIHRlc3QKICAgICAgLSBtYWtlIGJ1aWxkCgogIG15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCgogIHBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCgogIHVwZGF0ZXI6CiAgICBpbWFnZToga2FyYWxhYmUveGdvLWxhdGVzdDpsYXRlc3QKICAgIHB1bGw6IHRydWUKICAgIGNvbW1hbmRzOgogICAgICAtIG1ha2UgcHVibGlzaAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciwgcmVmcy90YWdzLyogXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KCiAgZG9ja2VyMToKICAgIGltYWdlOiBwbHVnaW5zL2RvY2tlcgogICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAgIHRhZ3M6IFsgJyR7VEFHfScgXQogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCgogIGRvY2tlcjI6CiAgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAgIHJlcG86IGdpdGVhL2dpdGVhCiAgICB0YWdzOiBbICdsYXRlc3QnIF0KICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCiAgICAgIGJyYW5jaDogbWFzdGVyCgogIHJlbGVhc2UxOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLwogICAgdGFyZ2V0OiAvbGd0bS9tYXN0ZXIKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCiAgICAgIGJyYW5jaDogbWFzdGVyCgogIHJlbGVhc2UyOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLwogICAgdGFyZ2V0OiAvbGd0bS8kJFRBRwogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCgogIHJlbGVhc2UzOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9sYXRlc3QvCiAgICB0YXJnZXQ6IC9sZ3RtL2xhdGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCgogIGdpdGh1YjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdGh1Yi1yZWxlYXNlCiAgICBmaWxlczoKICAgICAgLSBkaXN0L3JlbGVhc2UvKgogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCgogIGdpdHRlcjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdHRlcgoKc2VydmljZXM6CiAgbXlzcWxzdmM6CiAgICBpbWFnZTogbXlzcWw6NS43CiAgICBlbnZpcm9ubWVudDoKICAgICAgLSBNWVNRTF9EQVRBQkFTRT10ZXN0CiAgICAgIC0gTVlTUUxfQUxMT1dfRU1QVFlfUEFTU1dPUkQ9eWVzCiAgICB3aGVuOgogICAgICBldmVudDogcHVzaAoKICBwZ3NxbHN2YzoKICAgIGltYWdlOiBwb3N0Z3Jlczo5LjUKICAgIGVudmlyb25tZW50OgogICAgICAtIFBPU1RHUkVTX0RCPXRlc3QKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCg.opfoV7bpz1nSKIymq-VjF68P3dhGlvRg9z1NjMDf7Bg \ No newline at end of file +eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzoke0dPX1ZFUlNJT059CiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAoKICAgICAgLSBtYWtlIGNsZWFuCiAgICAgIC0gbWFrZSB2ZXQKICAgICAgIyAtIG1ha2UgbGludAogICAgICAtIG1ha2UgdGVzdAogICAgICAtIG1ha2UgYnVpbGQKCiAgdGVzdC1teXNxbDoKICAgIGltYWdlOiB3ZWJoaXBwaWUvZ29sYW5nOiR7R09fVkVSU0lPTn0KICAgIHB1bGw6IHRydWUKICAgIGNvbW1hbmRzOgogICAgIC0gbWFrZSB0ZXN0LW15c3FsCiAgICB3aGVuOgogICAgICBldmVudDogcHVzaAoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6JHtHT19WRVJTSU9OfQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCgogIHVwZGF0ZXI6CiAgICBpbWFnZToga2FyYWxhYmUveGdvLWxhdGVzdDpsYXRlc3QKICAgIHB1bGw6IHRydWUKICAgIGNvbW1hbmRzOgogICAgICAtIG1ha2UgcHVibGlzaAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciwgcmVmcy90YWdzLyogXQogICAgICBtYXRyaXg6CiAgICAgICAgR09fVkVSU0lPTjogMS43CgogIGNvdmVyYWdlOgogICAgaW1hZ2U6IHBsdWdpbnMvY292ZXJhZ2UKICAgIHNlcnZlcjogaHR0cHM6Ly9jb3ZlcmFnZS5naXRlYS5pbwogICAgd2hlbjoKICAgICAgbWF0cml4OgogICAgICAgIEdPX1ZFUlNJT046IDEuNwoKICBkb2NrZXI6CiAgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAgIHJlcG86IGdpdGVhL2dpdGVhCiAgICB0YWdzOiBbICcke1RBR30nIF0KICAgIHdoZW46CiAgICAgIGV2ZW50OiB0YWcKICAgICAgYnJhbmNoOiByZWZzL3RhZ3MvKgogICAgICBtYXRyaXg6CiAgICAgICAgR09fVkVSU0lPTjogMS43CgogIGRvY2tlcjoKICAgIGltYWdlOiBwbHVnaW5zL2RvY2tlcgogICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAgIHRhZ3M6IFsgJ2xhdGVzdCcgXQogICAgd2hlbjoKICAgICAgZXZlbnQ6IHB1c2gKICAgICAgYnJhbmNoOiBtYXN0ZXIKICAgICAgbWF0cml4OgogICAgICAgIEdPX1ZFUlNJT046IDEuNwoKICByZWxlYXNlOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLwogICAgdGFyZ2V0OiAvbGd0bS9tYXN0ZXIKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCiAgICAgIGJyYW5jaDogbWFzdGVyCiAgICAgIG1hdHJpeDoKICAgICAgICBHT19WRVJTSU9OOiAxLjcKCiAgcmVsZWFzZToKICAgIGltYWdlOiBwbHVnaW5zL3MzCiAgICBwYXRoX3N0eWxlOiB0cnVlCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8KICAgIHRhcmdldDogL2xndG0vJCRUQUcKICAgIHdoZW46CiAgICAgIGV2ZW50OiB0YWcKICAgICAgYnJhbmNoOiByZWZzL3RhZ3MvKgogICAgICBtYXRyaXg6CiAgICAgICAgR09fVkVSU0lPTjogMS43CgogIGxhdGVzdDoKICAgIGltYWdlOiBwbHVnaW5zL3MzCiAgICBwYXRoX3N0eWxlOiB0cnVlCiAgICBzb3VyY2U6IGRpc3QvbGF0ZXN0LwogICAgdGFyZ2V0OiAvbGd0bS9sYXRlc3QKICAgIHdoZW46CiAgICAgIGV2ZW50OiB0YWcKICAgICAgYnJhbmNoOiByZWZzL3RhZ3MvKgogICAgICBtYXRyaXg6CiAgICAgICAgR09fVkVSU0lPTjogMS43CgogIGdpdGh1YjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdGh1Yi1yZWxlYXNlCiAgICBmaWxlczoKICAgICAgLSBkaXN0L3JlbGVhc2UvKgogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCiAgICAgIG1hdHJpeDoKICAgICAgICBHT19WRVJTSU9OOiAxLjcKCiAgZ2l0dGVyOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0dGVyCgpzZXJ2aWNlczoKICBteXNxbDoKICAgIGltYWdlOiBteXNxbDo1LjcKICAgIGVudmlyb25tZW50OgogICAgICAtIE1ZU1FMX0RBVEFCQVNFPXRlc3QKICAgICAgLSBNWVNRTF9BTExPV19FTVBUWV9QQVNTV09SRD15ZXMKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCgogIHBnc3FsOgogICAgaW1hZ2U6IHBvc3RncmVzOjkuNQogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gUE9TVEdSRVNfREI9dGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IHB1c2gKCm1hdHJpeDoKICBHT19WRVJTSU9OOgogICAgLSAxLjYKICAgIC0gMS43Cg.oE18Ibc0sX6XpnJXhtJvch7hW9cJNXCeGu7O59UW5-w \ No newline at end of file From 450969c158d36e40b28b89f4fcb0ed89f885ea01 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 24 Nov 2016 22:30:36 +0800 Subject: [PATCH 024/135] test database is connect OK after db config initialized (#239) --- models/models.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/models/models.go b/models/models.go index a95468e036..3a83929a77 100644 --- a/models/models.go +++ b/models/models.go @@ -196,6 +196,10 @@ func NewEngine() (err error) { return err } + if err = x.Ping(); err != nil { + return err + } + if err = migrations.Migrate(x); err != nil { return fmt.Errorf("migrate: %v", err) } From ece19f4a5e948a1e0fab7a1a0d64f39d5ad8d9d3 Mon Sep 17 00:00:00 2001 From: Bwko Date: Thu, 24 Nov 2016 22:02:54 +0100 Subject: [PATCH 025/135] Lint models/release.go --- models/release.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/models/release.go b/models/release.go index a60376d978..c047b2f557 100644 --- a/models/release.go +++ b/models/release.go @@ -38,12 +38,14 @@ type Release struct { CreatedUnix int64 } +// BeforeInsert is invoked from XORM before inserting an object of this type. func (r *Release) BeforeInsert() { if r.CreatedUnix == 0 { r.CreatedUnix = time.Now().Unix() } } +// AfterSet is invoked from XORM after setting the value of a field of this object. func (r *Release) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": @@ -151,15 +153,15 @@ func GetReleasesByRepoID(repoID int64, page, pageSize int) (rels []*Release, err return rels, err } -type ReleaseSorter struct { +type releaseSorter struct { rels []*Release } -func (rs *ReleaseSorter) Len() int { +func (rs *releaseSorter) Len() int { return len(rs.rels) } -func (rs *ReleaseSorter) Less(i, j int) bool { +func (rs *releaseSorter) Less(i, j int) bool { diffNum := rs.rels[i].NumCommits - rs.rels[j].NumCommits if diffNum != 0 { return diffNum > 0 @@ -167,13 +169,13 @@ func (rs *ReleaseSorter) Less(i, j int) bool { return rs.rels[i].Created.After(rs.rels[j].Created) } -func (rs *ReleaseSorter) Swap(i, j int) { +func (rs *releaseSorter) Swap(i, j int) { rs.rels[i], rs.rels[j] = rs.rels[j], rs.rels[i] } // SortReleases sorts releases by number of commits and created time. func SortReleases(rels []*Release) { - sorter := &ReleaseSorter{rels: rels} + sorter := &releaseSorter{rels: rels} sort.Sort(sorter) } From d8e11a8eaa0a8712024426348d4f7b430cea9e3a Mon Sep 17 00:00:00 2001 From: Bwko Date: Thu, 24 Nov 2016 21:54:00 +0100 Subject: [PATCH 026/135] Lint models/admin.go --- models/admin.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/models/admin.go b/models/admin.go index 14a0e8d009..058e9be8a8 100644 --- a/models/admin.go +++ b/models/admin.go @@ -18,9 +18,11 @@ import ( "code.gitea.io/gitea/modules/setting" ) +//NoticeType describes the notice type type NoticeType int const ( + //NoticeRepository type NoticeRepository NoticeType = iota + 1 ) @@ -33,10 +35,12 @@ type Notice struct { CreatedUnix int64 } +// BeforeInsert is invoked from XORM before inserting an object of this type. func (n *Notice) BeforeInsert() { n.CreatedUnix = time.Now().Unix() } +// AfterSet is invoked from XORM after setting the value of a field of this object. func (n *Notice) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": From 6a28909f40ad1ff20d325d9be4ada87e5b75ce53 Mon Sep 17 00:00:00 2001 From: Andrey Nering Date: Thu, 24 Nov 2016 23:25:34 -0200 Subject: [PATCH 027/135] CONTRIBUTING.md: link to "Faster reviews" document (#229) * CONTRIBUTING.md: link to "Faster reviews" document * CONTRIBUTING.md: small fixes --- CONTRIBUTING.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3f6ded7e16..752e02015f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -76,6 +76,19 @@ who makes the change even if an owners or a maintainer. We use github's pull request workflow to do that and use [lgtm](http://lgtm.co) to ensure every PR is reviewed by at least 2 maintainers. +Please try to make your pull request easy to review for us. Please read the +["How to get faster PR reviews"](https://github.com/kubernetes/kubernetes/blob/master/docs/devel/faster_reviews.md), +guide, it got useful tips for any project you may want to contribute. See some +of the points: + +- Make small pull requests. The smaller, the faster to review and the more + likely it will be merged soon. +- Don't make changes unrelated to your PR. Maybe there are typos on some + comments, maybe refactoring would welcome on a function... but if that is not + related to you PR, please make *another* PR for that. +- Split big pull requests in multiple. An incremental change will be faster to + review than a huge PR. + ## Sign your work The sign-off is a simple line at the end of the explanation for the From 2e565bc1c474466bd74b3475b9d1f3ff6c0c30b2 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 25 Nov 2016 09:44:04 +0800 Subject: [PATCH 028/135] Golint fixed for modules/mailer --- modules/mailer/mailer.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go index 209a9918ac..3dc2c4e531 100644 --- a/modules/mailer/mailer.go +++ b/modules/mailer/mailer.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// Message mail body and log info type Message struct { Info string // Message information for log purpose. *gomail.Message @@ -61,15 +62,17 @@ type loginAuth struct { username, password string } -// SMTP AUTH LOGIN Auth Handler +// LoginAuth SMTP AUTH LOGIN Auth Handler func LoginAuth(username, password string) smtp.Auth { return &loginAuth{username, password} } +// Start start SMTP login auth func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { return "LOGIN", []byte{}, nil } +// Next next step of SMTP login auth func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) { if more { switch string(fromServer) { @@ -84,9 +87,11 @@ func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) { return nil, nil } +// Sender mail sender type Sender struct { } +// Send send email func (s *Sender) Send(from string, to []string, msg io.WriterTo) error { opts := setting.MailService @@ -208,6 +213,7 @@ func processMailQueue() { var mailQueue chan *Message +// NewContext start mail queue service func NewContext() { // Need to check if mailQueue is nil because in during reinstall (user had installed // before but swithed install lock off), this function will be called again @@ -220,6 +226,7 @@ func NewContext() { go processMailQueue() } +// SendAsync send mail asynchronous func SendAsync(msg *Message) { go func() { mailQueue <- msg From 304bbd3f251bf158ca437472e860d7b18d5483a3 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 25 Nov 2016 09:58:05 +0800 Subject: [PATCH 029/135] golint fixed for modules/markdown --- models/repo.go | 8 ++++---- modules/markdown/markdown.go | 20 +++++++++++--------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/models/repo.go b/models/repo.go index 20671cb019..b3e08a93e8 100644 --- a/models/repo.go +++ b/models/repo.go @@ -224,7 +224,7 @@ func (repo *Repository) AfterSet(colName string, _ xorm.Cell) { repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones case "external_tracker_style": if len(repo.ExternalTrackerStyle) == 0 { - repo.ExternalTrackerStyle = markdown.ISSUE_NAME_STYLE_NUMERIC + repo.ExternalTrackerStyle = markdown.IssueNameStyleNumeric } case "created_unix": repo.Created = time.Unix(repo.CreatedUnix, 0).Local() @@ -310,10 +310,10 @@ func (repo *Repository) ComposeMetas() map[string]string { "repo": repo.Name, } switch repo.ExternalTrackerStyle { - case markdown.ISSUE_NAME_STYLE_ALPHANUMERIC: - repo.ExternalMetas["style"] = markdown.ISSUE_NAME_STYLE_ALPHANUMERIC + case markdown.IssueNameStyleAlphanumeric: + repo.ExternalMetas["style"] = markdown.IssueNameStyleAlphanumeric default: - repo.ExternalMetas["style"] = markdown.ISSUE_NAME_STYLE_NUMERIC + repo.ExternalMetas["style"] = markdown.IssueNameStyleNumeric } } diff --git a/modules/markdown/markdown.go b/modules/markdown/markdown.go index 58bb8f417f..e46f172d3e 100644 --- a/modules/markdown/markdown.go +++ b/modules/markdown/markdown.go @@ -22,11 +22,13 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// Issue name styles const ( - ISSUE_NAME_STYLE_NUMERIC = "numeric" - ISSUE_NAME_STYLE_ALPHANUMERIC = "alphanumeric" + IssueNameStyleNumeric = "numeric" + IssueNameStyleAlphanumeric = "alphanumeric" ) +// Sanitizer markdown sanitizer var Sanitizer = bluemonday.UGCPolicy() // BuildSanitizer initializes sanitizer with allowed attributes based on settings. @@ -163,7 +165,7 @@ func (r *Renderer) AutoLink(out *bytes.Buffer, link []byte, kind int) { } // ListItem defines how list items should be processed to produce corresponding HTML elements. -func (options *Renderer) ListItem(out *bytes.Buffer, text []byte, flags int) { +func (r *Renderer) ListItem(out *bytes.Buffer, text []byte, flags int) { // Detect procedures to draw checkboxes. switch { case bytes.HasPrefix(text, []byte("[ ] ")): @@ -171,7 +173,7 @@ func (options *Renderer) ListItem(out *bytes.Buffer, text []byte, flags int) { case bytes.HasPrefix(text, []byte("[x] ")): text = append([]byte(``), text[3:]...) } - options.Renderer.ListItem(out, text, flags) + r.Renderer.ListItem(out, text, flags) } // Note: this section is for purpose of increase performance and @@ -235,7 +237,7 @@ func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string urlPrefix = cutoutVerbosePrefix(urlPrefix) pattern := IssueNumericPattern - if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC { + if metas["style"] == IssueNameStyleAlphanumeric { pattern = IssueAlphanumericPattern } @@ -249,7 +251,7 @@ func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string link = fmt.Sprintf(`%s`, urlPrefix, m[1:], m) } else { // Support for external issue tracker - if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC { + if metas["style"] == IssueNameStyleAlphanumeric { metas["index"] = string(m) } else { metas["index"] = string(m[1:]) @@ -322,10 +324,10 @@ var noEndTags = []string{"img", "input", "br", "hr"} // PostProcess treats different types of HTML differently, // and only renders special links for plain text blocks. -func PostProcess(rawHtml []byte, urlPrefix string, metas map[string]string) []byte { +func PostProcess(rawHTML []byte, urlPrefix string, metas map[string]string) []byte { startTags := make([]string, 0, 5) var buf bytes.Buffer - tokenizer := html.NewTokenizer(bytes.NewReader(rawHtml)) + tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML)) OUTER_LOOP: for html.ErrorToken != tokenizer.Next() { @@ -387,7 +389,7 @@ OUTER_LOOP: // If we are not at the end of the input, then some other parsing error has occurred, // so return the input verbatim. - return rawHtml + return rawHTML } // Render renders Markdown to HTML with special links. From 229ec927b953cf80b5eecb03d412a9634b83a25a Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 25 Nov 2016 14:23:48 +0800 Subject: [PATCH 030/135] Golint fixed for modules/template --- modules/template/highlight/highlight.go | 1 + modules/template/template.go | 39 ++++++++++++++++--------- routers/repo/editor.go | 2 +- routers/repo/view.go | 2 +- 4 files changed, 28 insertions(+), 16 deletions(-) diff --git a/modules/template/highlight/highlight.go b/modules/template/highlight/highlight.go index 7dcb672da6..39b5d6d153 100644 --- a/modules/template/highlight/highlight.go +++ b/modules/template/highlight/highlight.go @@ -64,6 +64,7 @@ var ( highlightMapping = map[string]string{} ) +// NewContext loads highlight map func NewContext() { keys := setting.Cfg.Section("highlight.mapping").Keys() for i := range keys { diff --git a/modules/template/template.go b/modules/template/template.go index 03fa0f5217..baf1a7ab92 100644 --- a/modules/template/template.go +++ b/modules/template/template.go @@ -26,6 +26,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// NewFuncMap returns functions for injecting to templates func NewFuncMap() []template.FuncMap { return []template.FuncMap{map[string]interface{}{ "GoVer": func() string { @@ -119,14 +120,17 @@ func NewFuncMap() []template.FuncMap { }} } +// Safe render raw as HTML func Safe(raw string) template.HTML { return template.HTML(raw) } +// Str2html render Markdown text to HTML func Str2html(raw string) template.HTML { return template.HTML(markdown.Sanitizer.Sanitize(raw)) } +// List traversings the list func List(l *list.List) chan interface{} { e := l.Front() c := make(chan interface{}) @@ -140,21 +144,23 @@ func List(l *list.List) chan interface{} { return c } +// Sha1 returns sha1 sum of string func Sha1(str string) string { return base.EncodeSha1(str) } -func ToUTF8WithErr(content []byte) (error, string) { +// ToUTF8WithErr converts content to UTF8 encoding +func ToUTF8WithErr(content []byte) (string, error) { charsetLabel, err := base.DetectEncoding(content) if err != nil { - return err, "" + return "", err } else if charsetLabel == "UTF-8" { - return nil, string(content) + return string(content), nil } encoding, _ := charset.Lookup(charsetLabel) if encoding == nil { - return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content) + return string(content), fmt.Errorf("Unknown encoding: %s", charsetLabel) } // If there is an error, we concatenate the nicely decoded part and the @@ -164,19 +170,20 @@ func ToUTF8WithErr(content []byte) (error, string) { result = result + string(content[n:]) } - return err, result + return result, err } +// ToUTF8 converts content to UTF8 encoding and ignore error func ToUTF8(content string) string { - _, res := ToUTF8WithErr([]byte(content)) + res, _ := ToUTF8WithErr([]byte(content)) return res } -// Replaces all prefixes 'old' in 's' with 'new'. +// ReplaceLeft replaces all prefixes 'old' in 's' with 'new'. func ReplaceLeft(s, old, new string) string { - old_len, new_len, i, n := len(old), len(new), 0, 0 - for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 { - i += old_len + oldLen, newLen, i, n := len(old), len(new), 0, 0 + for ; i < len(s) && strings.HasPrefix(s[i:], old); n++ { + i += oldLen } // simple optimization @@ -185,12 +192,12 @@ func ReplaceLeft(s, old, new string) string { } // allocating space for the new string - newLen := n*new_len + len(s[i:]) - replacement := make([]byte, newLen, newLen) + curLen := n*newLen + len(s[i:]) + replacement := make([]byte, curLen, curLen) j := 0 - for ; j < n*new_len; j += new_len { - copy(replacement[j:j+new_len], new) + for ; j < n*newLen; j += newLen { + copy(replacement[j:j+newLen], new) } copy(replacement[j:], s[i:]) @@ -222,6 +229,7 @@ func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]stri return template.HTML(fullMessage) } +// Actioner describes an action type Actioner interface { GetOpType() int GetActUserName() string @@ -260,6 +268,7 @@ func ActionIcon(opType int) string { } } +// ActionContent2Commits converts action content to push commits func ActionContent2Commits(act Actioner) *models.PushCommits { push := models.NewPushCommits() if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil { @@ -268,6 +277,7 @@ func ActionContent2Commits(act Actioner) *models.PushCommits { return push } +// DiffTypeToStr returns diff type name func DiffTypeToStr(diffType int) string { diffTypes := map[int]string{ 1: "add", 2: "modify", 3: "del", 4: "rename", @@ -275,6 +285,7 @@ func DiffTypeToStr(diffType int) string { return diffTypes[diffType] } +// DiffLineTypeToStr returns diff line type name func DiffLineTypeToStr(diffType int) string { switch diffType { case 2: diff --git a/routers/repo/editor.go b/routers/repo/editor.go index d0d528e250..92a41f0147 100644 --- a/routers/repo/editor.go +++ b/routers/repo/editor.go @@ -74,7 +74,7 @@ func editFile(ctx *context.Context, isNewFile bool) { d, _ := ioutil.ReadAll(dataRc) buf = append(buf, d...) - if err, content := template.ToUTF8WithErr(buf); err != nil { + if content, err := template.ToUTF8WithErr(buf); err != nil { if err != nil { log.Error(4, "ToUTF8WithErr: %v", err) } diff --git a/routers/repo/view.go b/routers/repo/view.go index 7303e44126..3ef3716f27 100644 --- a/routers/repo/view.go +++ b/routers/repo/view.go @@ -164,7 +164,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st } else { // Building code view blocks with line number on server side. var fileContent string - if err, content := template.ToUTF8WithErr(buf); err != nil { + if content, err := template.ToUTF8WithErr(buf); err != nil { if err != nil { log.Error(4, "ToUTF8WithErr: %s", err) } From bd5ea3e222ef7c940c66532052f6ef14f9af2bd3 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 25 Nov 2016 14:32:09 +0800 Subject: [PATCH 031/135] Golint fixed for modules/httplib --- modules/httplib/httplib.go | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/modules/httplib/httplib.go b/modules/httplib/httplib.go index ff03195c8f..c4e613f765 100644 --- a/modules/httplib/httplib.go +++ b/modules/httplib/httplib.go @@ -36,7 +36,7 @@ func createDefaultCookie() { defaultCookieJar, _ = cookiejar.New(nil) } -// Overwrite default settings +// SetDefaultSetting overwrites default settings func SetDefaultSetting(setting Settings) { settingMutex.Lock() defer settingMutex.Unlock() @@ -49,7 +49,7 @@ func SetDefaultSetting(setting Settings) { } } -// return *Request with specific method +// newRequest returns *Request with specific method func newRequest(url, method string) *Request { var resp http.Response req := http.Request{ @@ -87,18 +87,19 @@ func Head(url string) *Request { return newRequest(url, "HEAD") } +// Settings is the default settings for http client type Settings struct { ShowDebug bool UserAgent string ConnectTimeout time.Duration ReadWriteTimeout time.Duration - TlsClientConfig *tls.Config + TLSClientConfig *tls.Config Proxy func(*http.Request) (*url.URL, error) Transport http.RoundTripper EnableCookie bool } -// HttpRequest provides more useful methods for requesting one url than http.Request. +// Request provides more useful methods for requesting one url than http.Request. type Request struct { url string req *http.Request @@ -109,7 +110,7 @@ type Request struct { body []byte } -// Change request settings +// Setting changes request settings func (r *Request) Setting(setting Settings) *Request { r.setting = setting return r @@ -148,7 +149,7 @@ func (r *Request) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *Re // SetTLSClientConfig sets tls connection configurations if visiting https url. func (r *Request) SetTLSClientConfig(config *tls.Config) *Request { - r.setting.TlsClientConfig = config + r.setting.TLSClientConfig = config return r } @@ -158,11 +159,12 @@ func (r *Request) Header(key, value string) *Request { return r } +// Headers returns headers in request. func (r *Request) Headers() http.Header { return r.req.Header } -// Set the protocol version for incoming requests. +// SetProtocolVersion sets the protocol version for incoming requests. // Client requests always use HTTP/1.1. func (r *Request) SetProtocolVersion(vers string) *Request { if len(vers) == 0 { @@ -185,13 +187,13 @@ func (r *Request) SetCookie(cookie *http.Cookie) *Request { return r } -// Set transport to +// SetTransport sets transport to func (r *Request) SetTransport(transport http.RoundTripper) *Request { r.setting.Transport = transport return r } -// Set http proxy +// SetProxy sets http proxy // example: // // func(req *http.Request) (*url.URL, error) { @@ -210,6 +212,7 @@ func (r *Request) Param(key, value string) *Request { return r } +// PostFile uploads file via http func (r *Request) PostFile(formname, filename string) *Request { r.files[formname] = filename return r @@ -301,7 +304,7 @@ func (r *Request) getResponse() (*http.Response, error) { if trans == nil { // create default transport trans = &http.Transport{ - TLSClientConfig: r.setting.TlsClientConfig, + TLSClientConfig: r.setting.TLSClientConfig, Proxy: r.setting.Proxy, Dial: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout), } @@ -309,7 +312,7 @@ func (r *Request) getResponse() (*http.Response, error) { // if r.transport is *http.Transport then set the settings. if t, ok := trans.(*http.Transport); ok { if t.TLSClientConfig == nil { - t.TLSClientConfig = r.setting.TlsClientConfig + t.TLSClientConfig = r.setting.TLSClientConfig } if t.Proxy == nil { t.Proxy = r.setting.Proxy @@ -409,9 +412,9 @@ func (r *Request) ToFile(filename string) error { return err } -// ToJson returns the map that marshals from the body bytes as json in response . +// ToJSON returns the map that marshals from the body bytes as json in response . // it calls Response inner. -func (r *Request) ToJson(v interface{}) error { +func (r *Request) ToJSON(v interface{}) error { data, err := r.Bytes() if err != nil { return err @@ -420,9 +423,9 @@ func (r *Request) ToJson(v interface{}) error { return err } -// ToXml returns the map that marshals from the body bytes as xml in response . +// ToXML returns the map that marshals from the body bytes as xml in response . // it calls Response inner. -func (r *Request) ToXml(v interface{}) error { +func (r *Request) ToXML(v interface{}) error { data, err := r.Bytes() if err != nil { return err From faabc76fd68b0ecccba1dc8dae47220b28cce05a Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 25 Nov 2016 14:51:01 +0800 Subject: [PATCH 032/135] Golint fixed for modules/context --- modules/context/api.go | 2 ++ modules/context/api_org.go | 1 + modules/context/auth.go | 2 ++ modules/context/context.go | 7 +++++-- modules/context/org.go | 3 +++ modules/context/repo.go | 6 ++++++ routers/api/v1/misc/markdown.go | 2 +- 7 files changed, 20 insertions(+), 3 deletions(-) diff --git a/modules/context/api.go b/modules/context/api.go index 0da1823797..2823d696d2 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -16,6 +16,7 @@ import ( macaron "gopkg.in/macaron.v1" ) +// APIContext is a specific macaron context for API service type APIContext struct { *Context Org *APIOrganization @@ -63,6 +64,7 @@ func (ctx *APIContext) SetLinkHeader(total, pageSize int) { } } +// APIContexter returns apicontext as macaron middleware func APIContexter() macaron.Handler { return func(c *Context) { ctx := &APIContext{ diff --git a/modules/context/api_org.go b/modules/context/api_org.go index bb6d14e26e..3a2c8c559d 100644 --- a/modules/context/api_org.go +++ b/modules/context/api_org.go @@ -8,6 +8,7 @@ import ( "code.gitea.io/gitea/models" ) +// APIOrganization contains organization and team type APIOrganization struct { Organization *models.User Team *models.Team diff --git a/modules/context/auth.go b/modules/context/auth.go index ff3d395541..0e5ae93a87 100644 --- a/modules/context/auth.go +++ b/modules/context/auth.go @@ -13,6 +13,7 @@ import ( macaron "gopkg.in/macaron.v1" ) +// ToggleOptions contains required or check options type ToggleOptions struct { SignInRequired bool SignOutRequired bool @@ -20,6 +21,7 @@ type ToggleOptions struct { DisableCSRF bool } +// Toggle returns toggle options as middleware func Toggle(options *ToggleOptions) macaron.Handler { return func(ctx *Context) { // Cannot view any page before installation. diff --git a/modules/context/context.go b/modules/context/context.go index fd3798b508..0535da995a 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -40,8 +40,8 @@ type Context struct { Org *Organization } -// HasError returns true if error occurs in form validation. -func (ctx *Context) HasApiError() bool { +// HasAPIError returns true if error occurs in form validation. +func (ctx *Context) HasAPIError() bool { hasErr, ok := ctx.Data["HasError"] if !ok { return false @@ -49,6 +49,7 @@ func (ctx *Context) HasApiError() bool { return hasErr.(bool) } +// GetErrMsg returns error message func (ctx *Context) GetErrMsg() string { return ctx.Data["ErrorMsg"].(string) } @@ -116,6 +117,7 @@ func (ctx *Context) NotFoundOrServerError(title string, errck func(error) bool, ctx.Handle(500, title, err) } +// HandleText handles HTTP status code func (ctx *Context) HandleText(status int, title string) { if (status/100 == 4) || (status/100 == 5) { log.Error(4, "%s", title) @@ -123,6 +125,7 @@ func (ctx *Context) HandleText(status int, title string) { ctx.PlainText(status, []byte(title)) } +// ServeContent serves content to http request func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) { modtime := time.Now() for _, p := range params { diff --git a/modules/context/org.go b/modules/context/org.go index 50919ef97e..d31d9773a0 100644 --- a/modules/context/org.go +++ b/modules/context/org.go @@ -12,6 +12,7 @@ import ( macaron "gopkg.in/macaron.v1" ) +// Organization contains organization context type Organization struct { IsOwner bool IsMember bool @@ -23,6 +24,7 @@ type Organization struct { Team *models.Team } +// HandleOrgAssignment handles organization assignment func HandleOrgAssignment(ctx *Context, args ...bool) { var ( requireMember bool @@ -145,6 +147,7 @@ func HandleOrgAssignment(ctx *Context, args ...bool) { } } +// OrgAssignment returns a macaron middleware to handle organization assignment func OrgAssignment(args ...bool) macaron.Handler { return func(ctx *Context) { HandleOrgAssignment(ctx, args...) diff --git a/modules/context/repo.go b/modules/context/repo.go index e3683a1498..6135ac46ae 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -19,6 +19,7 @@ import ( macaron "gopkg.in/macaron.v1" ) +// PullRequest contains informations to make a pull request type PullRequest struct { BaseRepo *models.Repository Allowed bool @@ -26,6 +27,7 @@ type PullRequest struct { HeadInfo string // [:] } +// Repository contains informations to operate a repository type Repository struct { AccessMode models.AccessMode IsWatching bool @@ -96,6 +98,7 @@ func (r *Repository) GetEditorconfig() (*editorconfig.Editorconfig, error) { return editorconfig.ParseBytes(data) } +// RetrieveBaseRepo retrieves base repository func RetrieveBaseRepo(ctx *Context, repo *models.Repository) { // Non-fork repository will not return error in this method. if err := repo.GetBaseRepo(); err != nil { @@ -130,6 +133,7 @@ func earlyResponseForGoGetMeta(ctx *Context) { }))) } +// RepoAssignment returns a macaron to handle repository assignment func RepoAssignment(args ...bool) macaron.Handler { return func(ctx *Context) { var ( @@ -446,6 +450,7 @@ func RepoRef() macaron.Handler { } } +// RequireRepoAdmin returns a macaron middleware for requiring repository admin permission func RequireRepoAdmin() macaron.Handler { return func(ctx *Context) { if !ctx.IsSigned || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) { @@ -455,6 +460,7 @@ func RequireRepoAdmin() macaron.Handler { } } +// RequireRepoWriter returns a macaron middleware for requiring repository write permission func RequireRepoWriter() macaron.Handler { return func(ctx *Context) { if !ctx.IsSigned || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) { diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index 23b5b269aa..1a0c003e7f 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -14,7 +14,7 @@ import ( // Markdown render markdown document to HTML // see https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document func Markdown(ctx *context.APIContext, form api.MarkdownOption) { - if ctx.HasApiError() { + if ctx.HasAPIError() { ctx.Error(422, "", ctx.GetErrMsg()) return } From 33a2ac38301e07ab78cbee07788e80668ca5b6fa Mon Sep 17 00:00:00 2001 From: Bwko Date: Thu, 24 Nov 2016 22:35:47 +0100 Subject: [PATCH 033/135] Lint models/update.go & webhook_slack.go --- models/update.go | 5 +++++ models/webhook_slack.go | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/models/update.go b/models/update.go index 41aa98e0a3..789b99e7b2 100644 --- a/models/update.go +++ b/models/update.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/modules/log" ) +// UpdateTask defines an UpdateTask type UpdateTask struct { ID int64 `xorm:"pk autoincr"` UUID string `xorm:"index"` @@ -23,6 +24,7 @@ type UpdateTask struct { NewCommitID string } +// AddUpdateTask adds an UpdateTask func AddUpdateTask(task *UpdateTask) error { _, err := x.Insert(task) return err @@ -42,6 +44,7 @@ func GetUpdateTaskByUUID(uuid string) (*UpdateTask, error) { return task, nil } +// DeleteUpdateTaskByUUID deletes an UpdateTask from the database func DeleteUpdateTaskByUUID(uuid string) error { _, err := x.Delete(&UpdateTask{UUID: uuid}) return err @@ -60,6 +63,7 @@ func CommitToPushCommit(commit *git.Commit) *PushCommit { } } +// ListToPushCommits transforms a list.List to PushCommits type. func ListToPushCommits(l *list.List) *PushCommits { commits := make([]*PushCommit, 0) var actEmail string @@ -73,6 +77,7 @@ func ListToPushCommits(l *list.List) *PushCommits { return &PushCommits{l.Len(), commits, "", nil} } +// PushUpdateOptions defines the push update options type PushUpdateOptions struct { PusherID int64 PusherName string diff --git a/models/webhook_slack.go b/models/webhook_slack.go index 9b70b09354..f6b2a70f93 100644 --- a/models/webhook_slack.go +++ b/models/webhook_slack.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// SlackMeta contains the slack metdata type SlackMeta struct { Channel string `json:"channel"` Username string `json:"username"` @@ -23,6 +24,7 @@ type SlackMeta struct { Color string `json:"color"` } +// SlackPayload contains the information about the slack channel type SlackPayload struct { Channel string `json:"channel"` Text string `json:"text"` @@ -33,6 +35,7 @@ type SlackPayload struct { Attachments []SlackAttachment `json:"attachments"` } +// SlackAttachment contains the slack message type SlackAttachment struct { Fallback string `json:"fallback"` Color string `json:"color"` @@ -40,8 +43,10 @@ type SlackAttachment struct { Text string `json:"text"` } +// SetSecret sets the slack secret func (p *SlackPayload) SetSecret(_ string) {} +// JSONPayload Marshals the SlackPayload to json func (p *SlackPayload) JSONPayload() ([]byte, error) { data, err := json.MarshalIndent(p, "", " ") if err != nil { @@ -50,6 +55,7 @@ func (p *SlackPayload) JSONPayload() ([]byte, error) { return data, nil } +// SlackTextFormatter replaces &, <, > with HTML characters // see: https://api.slack.com/docs/formatting func SlackTextFormatter(s string) string { // replace & < > @@ -59,6 +65,7 @@ func SlackTextFormatter(s string) string { return s } +// SlackShortTextFormatter replaces &, <, > with HTML characters func SlackShortTextFormatter(s string) string { s = strings.Split(s, "\n")[0] // replace & < > @@ -68,6 +75,7 @@ func SlackShortTextFormatter(s string) string { return s } +// SlackLinkFormatter creates a link compatablie with slack func SlackLinkFormatter(url string, text string) string { return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text)) } @@ -181,6 +189,7 @@ func getSlackPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) (*S }, nil } +// GetSlackPayload converts a slack webhook into a SlackPayload func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (*SlackPayload, error) { s := new(SlackPayload) From 76604d8f9008dd4e42500a6febd09475483d4057 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 25 Nov 2016 16:02:10 +0800 Subject: [PATCH 034/135] fixed test build error --- models/repo_test.go | 12 ++++++------ modules/markdown/markdown_test.go | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/models/repo_test.go b/models/repo_test.go index fdf3a07baf..70ad1c1f0e 100644 --- a/models/repo_test.go +++ b/models/repo_test.go @@ -24,7 +24,7 @@ func TestRepo(t *testing.T) { Convey("It should be nil even if other settings are present", func() { repo.EnableExternalTracker = false repo.ExternalTrackerFormat = "http://someurl.com/{user}/{repo}/{issue}" - repo.ExternalTrackerStyle = markdown.ISSUE_NAME_STYLE_NUMERIC + repo.ExternalTrackerStyle = markdown.IssueNameStyleNumeric So(repo.ComposeMetas(), ShouldEqual, map[string]string(nil)) }) }) @@ -33,17 +33,17 @@ func TestRepo(t *testing.T) { repo.EnableExternalTracker = true Convey("It should default to numeric issue style", func() { metas := repo.ComposeMetas() - So(metas["style"], ShouldEqual, markdown.ISSUE_NAME_STYLE_NUMERIC) + So(metas["style"], ShouldEqual, markdown.IssueNameStyleNumeric) }) Convey("It should pass through numeric issue style setting", func() { - repo.ExternalTrackerStyle = markdown.ISSUE_NAME_STYLE_NUMERIC + repo.ExternalTrackerStyle = markdown.IssueNameStyleNumeric metas := repo.ComposeMetas() - So(metas["style"], ShouldEqual, markdown.ISSUE_NAME_STYLE_NUMERIC) + So(metas["style"], ShouldEqual, markdown.IssueNameStyleNumeric) }) Convey("It should pass through alphanumeric issue style setting", func() { - repo.ExternalTrackerStyle = markdown.ISSUE_NAME_STYLE_ALPHANUMERIC + repo.ExternalTrackerStyle = markdown.IssueNameStyleAlphanumeric metas := repo.ComposeMetas() - So(metas["style"], ShouldEqual, markdown.ISSUE_NAME_STYLE_ALPHANUMERIC) + So(metas["style"], ShouldEqual, markdown.IssueNameStyleAlphanumeric) }) Convey("It should contain the user name", func() { metas := repo.ComposeMetas() diff --git a/modules/markdown/markdown_test.go b/modules/markdown/markdown_test.go index 9a7bc25fa1..3fc260bf1f 100644 --- a/modules/markdown/markdown_test.go +++ b/modules/markdown/markdown_test.go @@ -95,7 +95,7 @@ func TestMarkdown(t *testing.T) { metas["format"] = "https://someurl.com/{user}/{repo}/{index}" metas["user"] = "someuser" metas["repo"] = "somerepo" - metas["style"] = ISSUE_NAME_STYLE_NUMERIC + metas["style"] = IssueNameStyleNumeric Convey("should not render anything when there are no mentions", func() { testCases := []string{ @@ -167,7 +167,7 @@ func TestMarkdown(t *testing.T) { metas["format"] = "https://someurl.com/{user}/{repo}/?b={index}" metas["user"] = "someuser" metas["repo"] = "somerepo" - metas["style"] = ISSUE_NAME_STYLE_ALPHANUMERIC + metas["style"] = IssueNameStyleAlphanumeric Convey("It should not render anything when there are no mentions", func() { testCases := []string{ "", From 081c2a9395706e24bb396bf2aa9ac8a92d0a8f40 Mon Sep 17 00:00:00 2001 From: Bwko Date: Fri, 25 Nov 2016 09:03:52 +0100 Subject: [PATCH 035/135] Lint models/token.go (#244) --- models/token.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/models/token.go b/models/token.go index 42e0af7be2..03ea554fbb 100644 --- a/models/token.go +++ b/models/token.go @@ -28,14 +28,17 @@ type AccessToken struct { HasUsed bool `xorm:"-"` } +// BeforeInsert will be invoked by XORM before inserting a record representing this object. func (t *AccessToken) BeforeInsert() { t.CreatedUnix = time.Now().Unix() } +// BeforeUpdate is invoked from XORM before updating this object. func (t *AccessToken) BeforeUpdate() { t.UpdatedUnix = time.Now().Unix() } +// AfterSet is invoked from XORM after setting the value of a field of this object. func (t *AccessToken) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": From c0ca6644ade5ce21d8c7601439d94ea1fed7443d Mon Sep 17 00:00:00 2001 From: Bwko Date: Fri, 25 Nov 2016 09:11:12 +0100 Subject: [PATCH 036/135] Lint/issue &mail (#243) * Lint models/release.go * Lint models/ issue_label, issue_mail & mail.go --- models/issue_label.go | 7 ++++--- models/issue_mail.go | 2 +- models/mail.go | 41 +++++++++++++++++++++++------------------ models/release.go | 12 +++++++----- 4 files changed, 35 insertions(+), 27 deletions(-) diff --git a/models/issue_label.go b/models/issue_label.go index 3eed8ed985..befe3f192a 100644 --- a/models/issue_label.go +++ b/models/issue_label.go @@ -62,6 +62,7 @@ type Label struct { IsChecked bool `xorm:"-"` } +// APIFormat converts a Label to the api.Label format func (label *Label) APIFormat() *api.Label { return &api.Label{ ID: label.ID, @@ -77,9 +78,9 @@ func (label *Label) CalOpenIssues() { // ForegroundColor calculates the text color for labels based // on their background color. -func (l *Label) ForegroundColor() template.CSS { - if strings.HasPrefix(l.Color, "#") { - if color, err := strconv.ParseUint(l.Color[1:], 16, 64); err == nil { +func (label *Label) ForegroundColor() template.CSS { + if strings.HasPrefix(label.Color, "#") { + if color, err := strconv.ParseUint(label.Color[1:], 16, 64); err == nil { r := float32(0xFF & (color >> 16)) g := float32(0xFF & (color >> 8)) b := float32(0xFF & color) diff --git a/models/issue_mail.go b/models/issue_mail.go index 424c0ca1ee..56c1e0c278 100644 --- a/models/issue_mail.go +++ b/models/issue_mail.go @@ -14,7 +14,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) -func (issue *Issue) MailSubject() string { +func (issue *Issue) mailSubject() string { return fmt.Sprintf("[%s] %s (#%d)", issue.Repo.Name, issue.Title, issue.Index) } diff --git a/models/mail.go b/models/mail.go index e13aedd264..f89e38e625 100644 --- a/models/mail.go +++ b/models/mail.go @@ -20,23 +20,24 @@ import ( ) const ( - MailAuthActivate base.TplName = "auth/activate" - MailAuthActivateEmail base.TplName = "auth/activate_email" - MailAuthResetPassword base.TplName = "auth/reset_passwd" - MailAuthRegisterNotify base.TplName = "auth/register_notify" + mailAuthActivate base.TplName = "auth/activate" + mailAuthActivateEmail base.TplName = "auth/activate_email" + mailAuthResetPassword base.TplName = "auth/reset_passwd" + mailAuthRegisterNotify base.TplName = "auth/register_notify" - MailIssueComment base.TplName = "issue/comment" - MailIssueMention base.TplName = "issue/mention" + mailIssueComment base.TplName = "issue/comment" + mailIssueMention base.TplName = "issue/mention" - MailNotifyCollaborator base.TplName = "notify/collaborator" + mailNotifyCollaborator base.TplName = "notify/collaborator" ) -type MailRender interface { +type mailRenderInterface interface { HTMLString(string, interface{}, ...macaron.HTMLOptions) (string, error) } -var mailRender MailRender +var mailRender mailRenderInterface +// InitMailRender initializes the macaron mail renderer func InitMailRender(dir, appendDir string, funcMap []template.FuncMap) { opt := &macaron.RenderOptions{ Directory: dir, @@ -53,10 +54,12 @@ func InitMailRender(dir, appendDir string, funcMap []template.FuncMap) { } } +// SendTestMail sends a test mail func SendTestMail(email string) error { return gomail.Send(&mailer.Sender{}, mailer.NewMessage([]string{email}, "Gogs Test Email!", "Gogs Test Email!").Message) } +// SendUserMail sends a mail to the user func SendUserMail(c *macaron.Context, u *User, tpl base.TplName, code, subject, info string) { data := map[string]interface{}{ "Username": u.DisplayName(), @@ -76,15 +79,17 @@ func SendUserMail(c *macaron.Context, u *User, tpl base.TplName, code, subject, mailer.SendAsync(msg) } +// SendActivateAccountMail sends an activation mail to the user func SendActivateAccountMail(c *macaron.Context, u *User) { - SendUserMail(c, u, MailAuthActivate, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account") + SendUserMail(c, u, mailAuthActivate, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account") } +// SendResetPasswordMail sends a password reset mail to the user func SendResetPasswordMail(c *macaron.Context, u *User) { - SendUserMail(c, u, MailAuthResetPassword, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password") + SendUserMail(c, u, mailAuthResetPassword, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password") } -// SendActivateAccountMail sends confirmation email. +// SendActivateEmailMail sends confirmation email. func SendActivateEmailMail(c *macaron.Context, u *User, email *EmailAddress) { data := map[string]interface{}{ "Username": u.DisplayName(), @@ -92,7 +97,7 @@ func SendActivateEmailMail(c *macaron.Context, u *User, email *EmailAddress) { "Code": u.GenerateEmailActivateCode(email.Email), "Email": email.Email, } - body, err := mailRender.HTMLString(string(MailAuthActivateEmail), data) + body, err := mailRender.HTMLString(string(mailAuthActivateEmail), data) if err != nil { log.Error(3, "HTMLString: %v", err) return @@ -109,7 +114,7 @@ func SendRegisterNotifyMail(c *macaron.Context, u *User) { data := map[string]interface{}{ "Username": u.DisplayName(), } - body, err := mailRender.HTMLString(string(MailAuthRegisterNotify), data) + body, err := mailRender.HTMLString(string(mailAuthRegisterNotify), data) if err != nil { log.Error(3, "HTMLString: %v", err) return @@ -131,7 +136,7 @@ func SendCollaboratorMail(u, doer *User, repo *Repository) { "RepoName": repoName, "Link": repo.HTMLURL(), } - body, err := mailRender.HTMLString(string(MailNotifyCollaborator), data) + body, err := mailRender.HTMLString(string(mailNotifyCollaborator), data) if err != nil { log.Error(3, "HTMLString: %v", err) return @@ -152,7 +157,7 @@ func composeTplData(subject, body, link string) map[string]interface{} { } func composeIssueMessage(issue *Issue, doer *User, tplName base.TplName, tos []string, info string) *mailer.Message { - subject := issue.MailSubject() + subject := issue.mailSubject() body := string(markdown.RenderSpecialLink([]byte(issue.Content), issue.Repo.HTMLURL(), issue.Repo.ComposeMetas())) data := composeTplData(subject, body, issue.HTMLURL()) data["Doer"] = doer @@ -171,7 +176,7 @@ func SendIssueCommentMail(issue *Issue, doer *User, tos []string) { return } - mailer.SendAsync(composeIssueMessage(issue, doer, MailIssueComment, tos, "issue comment")) + mailer.SendAsync(composeIssueMessage(issue, doer, mailIssueComment, tos, "issue comment")) } // SendIssueMentionMail composes and sends issue mention emails to target receivers. @@ -179,5 +184,5 @@ func SendIssueMentionMail(issue *Issue, doer *User, tos []string) { if len(tos) == 0 { return } - mailer.SendAsync(composeIssueMessage(issue, doer, MailIssueMention, tos, "issue mention")) + mailer.SendAsync(composeIssueMessage(issue, doer, mailIssueMention, tos, "issue mention")) } diff --git a/models/release.go b/models/release.go index a60376d978..c047b2f557 100644 --- a/models/release.go +++ b/models/release.go @@ -38,12 +38,14 @@ type Release struct { CreatedUnix int64 } +// BeforeInsert is invoked from XORM before inserting an object of this type. func (r *Release) BeforeInsert() { if r.CreatedUnix == 0 { r.CreatedUnix = time.Now().Unix() } } +// AfterSet is invoked from XORM after setting the value of a field of this object. func (r *Release) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": @@ -151,15 +153,15 @@ func GetReleasesByRepoID(repoID int64, page, pageSize int) (rels []*Release, err return rels, err } -type ReleaseSorter struct { +type releaseSorter struct { rels []*Release } -func (rs *ReleaseSorter) Len() int { +func (rs *releaseSorter) Len() int { return len(rs.rels) } -func (rs *ReleaseSorter) Less(i, j int) bool { +func (rs *releaseSorter) Less(i, j int) bool { diffNum := rs.rels[i].NumCommits - rs.rels[j].NumCommits if diffNum != 0 { return diffNum > 0 @@ -167,13 +169,13 @@ func (rs *ReleaseSorter) Less(i, j int) bool { return rs.rels[i].Created.After(rs.rels[j].Created) } -func (rs *ReleaseSorter) Swap(i, j int) { +func (rs *releaseSorter) Swap(i, j int) { rs.rels[i], rs.rels[j] = rs.rels[j], rs.rels[i] } // SortReleases sorts releases by number of commits and created time. func SortReleases(rels []*Release) { - sorter := &ReleaseSorter{rels: rels} + sorter := &releaseSorter{rels: rels} sort.Sort(sorter) } From 900a21008cc1284e9bc30a6f322a739cff9b503f Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Fri, 25 Nov 2016 09:12:06 +0100 Subject: [PATCH 037/135] Added errcheck make task (#242) --- Makefile | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Makefile b/Makefile index a33d54ca21..51ba3758c5 100644 --- a/Makefile +++ b/Makefile @@ -51,6 +51,13 @@ fmt: vet: go vet $(PACKAGES) +.PHONY: errcheck +errcheck: + @which errcheck > /dev/null; if [ $$? -ne 0 ]; then \ + go get -u github.com/kisielk/errcheck; \ + fi + errcheck $(PACKAGES) + .PHONY: lint lint: @which golint > /dev/null; if [ $$? -ne 0 ]; then \ From b47051e59bd8cba3d6bedbc95e2b2c8aa7dd6365 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 25 Nov 2016 16:19:24 +0800 Subject: [PATCH 038/135] golint fixed for modules/cron --- modules/cron/cron.go | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/cron/cron.go b/modules/cron/cron.go index 80eb24b539..e1110d787b 100644 --- a/modules/cron/cron.go +++ b/modules/cron/cron.go @@ -16,6 +16,7 @@ import ( var c = cron.New() +// NewContext begins cron tasks func NewContext() { var ( entry *cron.Entry From 3c87c57d969dad4d600e2df73cb4ce1e9dcbd7f4 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 25 Nov 2016 16:37:04 +0800 Subject: [PATCH 039/135] golint fixed for modules/avatar --- models/user.go | 2 +- modules/avatar/avatar.go | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/models/user.go b/models/user.go index e8c5c91680..6c0223e6ee 100644 --- a/models/user.go +++ b/models/user.go @@ -355,7 +355,7 @@ func (u *User) UploadAvatar(data []byte) error { return fmt.Errorf("Decode: %v", err) } - m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor) + m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor) sess := x.NewSession() defer sessionRelease(sess) diff --git a/modules/avatar/avatar.go b/modules/avatar/avatar.go index a8c3826d15..f426978b32 100644 --- a/modules/avatar/avatar.go +++ b/modules/avatar/avatar.go @@ -14,9 +14,10 @@ import ( "github.com/issue9/identicon" ) -const AVATAR_SIZE = 290 +// AvatarSize returns avatar's size +const AvatarSize = 290 -// RandomImage generates and returns a random avatar image unique to input data +// RandomImageSize generates and returns a random avatar image unique to input data // in custom size (height and width). func RandomImageSize(size int, data []byte) (image.Image, error) { randExtent := len(palette.WebSafe) - 32 @@ -39,5 +40,5 @@ func RandomImageSize(size int, data []byte) (image.Image, error) { // RandomImage generates and returns a random avatar image unique to input data // in default size (height and width). func RandomImage(data []byte) (image.Image, error) { - return RandomImageSize(AVATAR_SIZE, data) + return RandomImageSize(AvatarSize, data) } From 5b17661c5d52dcb3d23b0316b3a52f9ec7744783 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Thu, 24 Nov 2016 21:43:05 +0100 Subject: [PATCH 040/135] Updated badges for drone and similar to lgtm --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 901d03bf47..5ee2aec120 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # Gitea - Git with a cup of tea -[![Build Status](https://travis-ci.org/go-gitea/gitea.svg?branch=master)](https://travis-ci.org/go-gitea/gitea) -[![codecov](https://codecov.io/gh/go-gitea/gitea/branch/master/graph/badge.svg)](https://codecov.io/gh/go-gitea/gitea) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-gitea/gitea)](https://goreportcard.com/report/github.com/go-gitea/gitea) -[![GoDoc](https://godoc.org/github.com/go-gitea/gitea?status.svg)](https://godoc.org/github.com/go-gitea/gitea) -[![](https://images.microbadger.com/badges/image/gitea/gitea.svg)](http://microbadger.com/images/gitea/gitea "Get your own image badge on microbadger.com") +[![Build Status](http://drone.gitea.io/api/badges/go-gitea/gitea/status.svg)](http://drone.gitea.io/go-gitea/gitea) [![Join the chat at https://gitter.im/go-gitea/gitea](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-gitea/gitea?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![](https://images.microbadger.com/badges/image/gitea/gitea.svg)](http://microbadger.com/images/gitea/gitea "Get your own image badge on microbadger.com") +[![Coverage Status](https://coverage.gitea.io/badges/go-gitea/gitea/coverage.svg)](https://coverage.gitea.io/go-gitea/gitea) +[![Go Report Card](https://goreportcard.com/badge/code.gitea.io/gitea)](https://goreportcard.com/report/code.gitea.io/gitea) +[![GoDoc](https://godoc.org/code.gitea.io/gitea?status.svg)](https://godoc.org/code.gitea.io/gitea) ![](https://github.com/go-gitea/gitea/blob/master/public/img/gitea-large-resize.png?raw=true) From 755ed847409aef81dd09fec6179a37e837ff16ad Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Fri, 25 Nov 2016 01:32:43 +0100 Subject: [PATCH 041/135] Be more explicit and dropped matrix builds from drone --- .drone.yml | 79 +++++++++++++++++++------------------------------- .drone.yml.sig | 2 +- 2 files changed, 31 insertions(+), 50 deletions(-) diff --git a/.drone.yml b/.drone.yml index f4608b7661..6b18b8f063 100644 --- a/.drone.yml +++ b/.drone.yml @@ -4,35 +4,42 @@ workspace: pipeline: test: - image: webhippie/golang:${GO_VERSION} + image: webhippie/golang:edge pull: true environment: CGO_ENABLED: 1 TAGS: cert sqlite pam miniwinsvc commands: - apk -U add linux-pam-dev openssh-client - - make clean - make vet # - make lint - make test - make build + when: + event: [ push, tag, pull_request ] test-mysql: - image: webhippie/golang:${GO_VERSION} + image: webhippie/golang:edge pull: true commands: - make test-mysql when: - event: push + event: [ push ] test-pgsql: - image: webhippie/golang:${GO_VERSION} + image: webhippie/golang:edge pull: true commands: - make test-pgsql when: - event: push + event: [ push ] + + coverage: + image: plugins/coverage + server: https://coverage.gitea.io + when: + event: [ push, tag, pull_request ] updater: image: karalabe/xgo-latest:latest @@ -42,78 +49,57 @@ pipeline: when: event: [ push, tag ] branch: [ master, refs/tags/* ] - matrix: - GO_VERSION: 1.7 - - coverage: - image: plugins/coverage - server: https://coverage.gitea.io - when: - matrix: - GO_VERSION: 1.7 docker: image: plugins/docker repo: gitea/gitea tags: [ '${TAG}' ] when: - event: tag - branch: refs/tags/* - matrix: - GO_VERSION: 1.7 + event: [ tag ] + branch: [ refs/tags/* ] docker: image: plugins/docker repo: gitea/gitea tags: [ 'latest' ] when: - event: push - branch: master - matrix: - GO_VERSION: 1.7 + event: [ push ] + branch: [ master ] release: image: plugins/s3 path_style: true source: dist/release/ - target: /lgtm/master + target: /gitea/master when: - event: push - branch: master - matrix: - GO_VERSION: 1.7 + event: [ push ] + branch: [ master ] release: image: plugins/s3 path_style: true source: dist/release/ - target: /lgtm/$$TAG + target: /gitea/$$TAG when: - event: tag - branch: refs/tags/* - matrix: - GO_VERSION: 1.7 + event: [ tag ] + branch: [ refs/tags/* ] latest: image: plugins/s3 path_style: true source: dist/latest/ - target: /lgtm/latest + target: /gitea/latest when: - event: tag - branch: refs/tags/* - matrix: - GO_VERSION: 1.7 + event: [ tag ] + branch: [ refs/tags/* ] github: image: plugins/github-release files: - dist/release/* when: - event: tag - branch: refs/tags/* - matrix: - GO_VERSION: 1.7 + event: [ tag ] + branch: [ refs/tags/* ] gitter: image: plugins/gitter @@ -125,16 +111,11 @@ services: - MYSQL_DATABASE=test - MYSQL_ALLOW_EMPTY_PASSWORD=yes when: - event: push + event: [ push ] pgsql: image: postgres:9.5 environment: - POSTGRES_DB=test when: - event: push - -matrix: - GO_VERSION: - - 1.6 - - 1.7 + event: [ push ] diff --git a/.drone.yml.sig b/.drone.yml.sig index 978c1cd5f4..3c50d1fa85 100644 --- a/.drone.yml.sig +++ b/.drone.yml.sig @@ -1 +1 @@ -eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzoke0dPX1ZFUlNJT059CiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAoKICAgICAgLSBtYWtlIGNsZWFuCiAgICAgIC0gbWFrZSB2ZXQKICAgICAgIyAtIG1ha2UgbGludAogICAgICAtIG1ha2UgdGVzdAogICAgICAtIG1ha2UgYnVpbGQKCiAgdGVzdC1teXNxbDoKICAgIGltYWdlOiB3ZWJoaXBwaWUvZ29sYW5nOiR7R09fVkVSU0lPTn0KICAgIHB1bGw6IHRydWUKICAgIGNvbW1hbmRzOgogICAgIC0gbWFrZSB0ZXN0LW15c3FsCiAgICB3aGVuOgogICAgICBldmVudDogcHVzaAoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6JHtHT19WRVJTSU9OfQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCgogIHVwZGF0ZXI6CiAgICBpbWFnZToga2FyYWxhYmUveGdvLWxhdGVzdDpsYXRlc3QKICAgIHB1bGw6IHRydWUKICAgIGNvbW1hbmRzOgogICAgICAtIG1ha2UgcHVibGlzaAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciwgcmVmcy90YWdzLyogXQogICAgICBtYXRyaXg6CiAgICAgICAgR09fVkVSU0lPTjogMS43CgogIGNvdmVyYWdlOgogICAgaW1hZ2U6IHBsdWdpbnMvY292ZXJhZ2UKICAgIHNlcnZlcjogaHR0cHM6Ly9jb3ZlcmFnZS5naXRlYS5pbwogICAgd2hlbjoKICAgICAgbWF0cml4OgogICAgICAgIEdPX1ZFUlNJT046IDEuNwoKICBkb2NrZXI6CiAgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAgIHJlcG86IGdpdGVhL2dpdGVhCiAgICB0YWdzOiBbICcke1RBR30nIF0KICAgIHdoZW46CiAgICAgIGV2ZW50OiB0YWcKICAgICAgYnJhbmNoOiByZWZzL3RhZ3MvKgogICAgICBtYXRyaXg6CiAgICAgICAgR09fVkVSU0lPTjogMS43CgogIGRvY2tlcjoKICAgIGltYWdlOiBwbHVnaW5zL2RvY2tlcgogICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAgIHRhZ3M6IFsgJ2xhdGVzdCcgXQogICAgd2hlbjoKICAgICAgZXZlbnQ6IHB1c2gKICAgICAgYnJhbmNoOiBtYXN0ZXIKICAgICAgbWF0cml4OgogICAgICAgIEdPX1ZFUlNJT046IDEuNwoKICByZWxlYXNlOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLwogICAgdGFyZ2V0OiAvbGd0bS9tYXN0ZXIKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCiAgICAgIGJyYW5jaDogbWFzdGVyCiAgICAgIG1hdHJpeDoKICAgICAgICBHT19WRVJTSU9OOiAxLjcKCiAgcmVsZWFzZToKICAgIGltYWdlOiBwbHVnaW5zL3MzCiAgICBwYXRoX3N0eWxlOiB0cnVlCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8KICAgIHRhcmdldDogL2xndG0vJCRUQUcKICAgIHdoZW46CiAgICAgIGV2ZW50OiB0YWcKICAgICAgYnJhbmNoOiByZWZzL3RhZ3MvKgogICAgICBtYXRyaXg6CiAgICAgICAgR09fVkVSU0lPTjogMS43CgogIGxhdGVzdDoKICAgIGltYWdlOiBwbHVnaW5zL3MzCiAgICBwYXRoX3N0eWxlOiB0cnVlCiAgICBzb3VyY2U6IGRpc3QvbGF0ZXN0LwogICAgdGFyZ2V0OiAvbGd0bS9sYXRlc3QKICAgIHdoZW46CiAgICAgIGV2ZW50OiB0YWcKICAgICAgYnJhbmNoOiByZWZzL3RhZ3MvKgogICAgICBtYXRyaXg6CiAgICAgICAgR09fVkVSU0lPTjogMS43CgogIGdpdGh1YjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdGh1Yi1yZWxlYXNlCiAgICBmaWxlczoKICAgICAgLSBkaXN0L3JlbGVhc2UvKgogICAgd2hlbjoKICAgICAgZXZlbnQ6IHRhZwogICAgICBicmFuY2g6IHJlZnMvdGFncy8qCiAgICAgIG1hdHJpeDoKICAgICAgICBHT19WRVJTSU9OOiAxLjcKCiAgZ2l0dGVyOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0dGVyCgpzZXJ2aWNlczoKICBteXNxbDoKICAgIGltYWdlOiBteXNxbDo1LjcKICAgIGVudmlyb25tZW50OgogICAgICAtIE1ZU1FMX0RBVEFCQVNFPXRlc3QKICAgICAgLSBNWVNRTF9BTExPV19FTVBUWV9QQVNTV09SRD15ZXMKICAgIHdoZW46CiAgICAgIGV2ZW50OiBwdXNoCgogIHBnc3FsOgogICAgaW1hZ2U6IHBvc3RncmVzOjkuNQogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gUE9TVEdSRVNfREI9dGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IHB1c2gKCm1hdHJpeDoKICBHT19WRVJTSU9OOgogICAgLSAxLjYKICAgIC0gMS43Cg.oE18Ibc0sX6XpnJXhtJvch7hW9cJNXCeGu7O59UW5-w \ No newline at end of file +eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogIGRvY2tlcjoKICAgIGltYWdlOiBwbHVnaW5zL2RvY2tlcgogICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAgIHRhZ3M6IFsgJyR7VEFHfScgXQogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZG9ja2VyOgogICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgICByZXBvOiBnaXRlYS9naXRlYQogICAgdGFnczogWyAnbGF0ZXN0JyBdCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc291cmNlOiBkaXN0L3JlbGVhc2UvCiAgICB0YXJnZXQ6IC9naXRlYS9tYXN0ZXIKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQogICAgICBicmFuY2g6IFsgbWFzdGVyIF0KCiAgcmVsZWFzZToKICAgIGltYWdlOiBwbHVnaW5zL3MzCiAgICBwYXRoX3N0eWxlOiB0cnVlCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8KICAgIHRhcmdldDogL2dpdGVhLyQkVEFHCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBsYXRlc3Q6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc291cmNlOiBkaXN0L2xhdGVzdC8KICAgIHRhcmdldDogL2dpdGVhL2xhdGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZ2l0aHViOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0aHViLXJlbGVhc2UKICAgIGZpbGVzOgogICAgICAtIGRpc3QvcmVsZWFzZS8qCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBnaXR0ZXI6CiAgICBpbWFnZTogcGx1Z2lucy9naXR0ZXIKCnNlcnZpY2VzOgogIG15c3FsOgogICAgaW1hZ2U6IG15c3FsOjUuNwogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gTVlTUUxfREFUQUJBU0U9dGVzdAogICAgICAtIE1ZU1FMX0FMTE9XX0VNUFRZX1BBU1NXT1JEPXllcwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCgogIHBnc3FsOgogICAgaW1hZ2U6IHBvc3RncmVzOjkuNQogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gUE9TVEdSRVNfREI9dGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCg.dC-vI_1n8rn3ax9-N1RFXBlS9KxYnOvOP-enDFQrKmA \ No newline at end of file From 3ae7955d152ecc2c3504ce4ff9a1924520118b0b Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Fri, 25 Nov 2016 09:49:12 +0100 Subject: [PATCH 042/135] Disable broken docker build for now --- .drone.yml | 28 ++++++++++++++-------------- .drone.yml.sig | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.drone.yml b/.drone.yml index 6b18b8f063..91d9e01d93 100644 --- a/.drone.yml +++ b/.drone.yml @@ -50,21 +50,21 @@ pipeline: event: [ push, tag ] branch: [ master, refs/tags/* ] - docker: - image: plugins/docker - repo: gitea/gitea - tags: [ '${TAG}' ] - when: - event: [ tag ] - branch: [ refs/tags/* ] + # docker: + # image: plugins/docker + # repo: gitea/gitea + # tags: [ '${TAG}' ] + # when: + # event: [ tag ] + # branch: [ refs/tags/* ] - docker: - image: plugins/docker - repo: gitea/gitea - tags: [ 'latest' ] - when: - event: [ push ] - branch: [ master ] + # docker: + # image: plugins/docker + # repo: gitea/gitea + # tags: [ 'latest' ] + # when: + # event: [ push ] + # branch: [ master ] release: image: plugins/s3 diff --git a/.drone.yml.sig b/.drone.yml.sig index 3c50d1fa85..412677ccf2 100644 --- a/.drone.yml.sig +++ b/.drone.yml.sig @@ -1 +1 @@ -eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogIGRvY2tlcjoKICAgIGltYWdlOiBwbHVnaW5zL2RvY2tlcgogICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAgIHRhZ3M6IFsgJyR7VEFHfScgXQogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZG9ja2VyOgogICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgICByZXBvOiBnaXRlYS9naXRlYQogICAgdGFnczogWyAnbGF0ZXN0JyBdCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc291cmNlOiBkaXN0L3JlbGVhc2UvCiAgICB0YXJnZXQ6IC9naXRlYS9tYXN0ZXIKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQogICAgICBicmFuY2g6IFsgbWFzdGVyIF0KCiAgcmVsZWFzZToKICAgIGltYWdlOiBwbHVnaW5zL3MzCiAgICBwYXRoX3N0eWxlOiB0cnVlCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8KICAgIHRhcmdldDogL2dpdGVhLyQkVEFHCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBsYXRlc3Q6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc291cmNlOiBkaXN0L2xhdGVzdC8KICAgIHRhcmdldDogL2dpdGVhL2xhdGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZ2l0aHViOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0aHViLXJlbGVhc2UKICAgIGZpbGVzOgogICAgICAtIGRpc3QvcmVsZWFzZS8qCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBnaXR0ZXI6CiAgICBpbWFnZTogcGx1Z2lucy9naXR0ZXIKCnNlcnZpY2VzOgogIG15c3FsOgogICAgaW1hZ2U6IG15c3FsOjUuNwogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gTVlTUUxfREFUQUJBU0U9dGVzdAogICAgICAtIE1ZU1FMX0FMTE9XX0VNUFRZX1BBU1NXT1JEPXllcwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCgogIHBnc3FsOgogICAgaW1hZ2U6IHBvc3RncmVzOjkuNQogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gUE9TVEdSRVNfREI9dGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCg.dC-vI_1n8rn3ax9-N1RFXBlS9KxYnOvOP-enDFQrKmA \ No newline at end of file +eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogICMgZG9ja2VyOgogICMgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAjICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAjICAgdGFnczogWyAnJHtUQUd9JyBdCiAgIyAgIHdoZW46CiAgIyAgICAgZXZlbnQ6IFsgdGFnIF0KICAjICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICAjIGRvY2tlcjoKICAjICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgIyAgIHJlcG86IGdpdGVhL2dpdGVhCiAgIyAgIHRhZ3M6IFsgJ2xhdGVzdCcgXQogICMgICB3aGVuOgogICMgICAgIGV2ZW50OiBbIHB1c2ggXQogICMgICAgIGJyYW5jaDogWyBtYXN0ZXIgXQoKICByZWxlYXNlOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLwogICAgdGFyZ2V0OiAvZ2l0ZWEvbWFzdGVyCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc291cmNlOiBkaXN0L3JlbGVhc2UvCiAgICB0YXJnZXQ6IC9naXRlYS8kJFRBRwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgbGF0ZXN0OgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9sYXRlc3QvCiAgICB0YXJnZXQ6IC9naXRlYS9sYXRlc3QKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHRhZyBdCiAgICAgIGJyYW5jaDogWyByZWZzL3RhZ3MvKiBdCgogIGdpdGh1YjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdGh1Yi1yZWxlYXNlCiAgICBmaWxlczoKICAgICAgLSBkaXN0L3JlbGVhc2UvKgogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZ2l0dGVyOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0dGVyCgpzZXJ2aWNlczoKICBteXNxbDoKICAgIGltYWdlOiBteXNxbDo1LjcKICAgIGVudmlyb25tZW50OgogICAgICAtIE1ZU1FMX0RBVEFCQVNFPXRlc3QKICAgICAgLSBNWVNRTF9BTExPV19FTVBUWV9QQVNTV09SRD15ZXMKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBwZ3NxbDoKICAgIGltYWdlOiBwb3N0Z3Jlczo5LjUKICAgIGVudmlyb25tZW50OgogICAgICAtIFBPU1RHUkVTX0RCPXRlc3QKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQo.prVy6IgBNIsbJGs7nrii2QoiAQ9ELnL2ThtQ-owHGHw \ No newline at end of file From 0accc935a331114069f56a09f3373a67f573714d Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Fri, 25 Nov 2016 10:53:48 +0100 Subject: [PATCH 043/135] Fixed s3 publishing within drone --- .drone.yml | 9 ++++++--- .drone.yml.sig | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.drone.yml b/.drone.yml index 91d9e01d93..c94e5eb16f 100644 --- a/.drone.yml +++ b/.drone.yml @@ -69,7 +69,8 @@ pipeline: release: image: plugins/s3 path_style: true - source: dist/release/ + strip_prefix: dist/release/ + source: dist/release/* target: /gitea/master when: event: [ push ] @@ -78,7 +79,8 @@ pipeline: release: image: plugins/s3 path_style: true - source: dist/release/ + strip_prefix: dist/release/ + source: dist/release/* target: /gitea/$$TAG when: event: [ tag ] @@ -87,7 +89,8 @@ pipeline: latest: image: plugins/s3 path_style: true - source: dist/latest/ + strip_prefix: dist/latest/ + source: dist/latest/* target: /gitea/latest when: event: [ tag ] diff --git a/.drone.yml.sig b/.drone.yml.sig index 412677ccf2..8a1df72345 100644 --- a/.drone.yml.sig +++ b/.drone.yml.sig @@ -1 +1 @@ -eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogICMgZG9ja2VyOgogICMgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAjICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAjICAgdGFnczogWyAnJHtUQUd9JyBdCiAgIyAgIHdoZW46CiAgIyAgICAgZXZlbnQ6IFsgdGFnIF0KICAjICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICAjIGRvY2tlcjoKICAjICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgIyAgIHJlcG86IGdpdGVhL2dpdGVhCiAgIyAgIHRhZ3M6IFsgJ2xhdGVzdCcgXQogICMgICB3aGVuOgogICMgICAgIGV2ZW50OiBbIHB1c2ggXQogICMgICAgIGJyYW5jaDogWyBtYXN0ZXIgXQoKICByZWxlYXNlOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLwogICAgdGFyZ2V0OiAvZ2l0ZWEvbWFzdGVyCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc291cmNlOiBkaXN0L3JlbGVhc2UvCiAgICB0YXJnZXQ6IC9naXRlYS8kJFRBRwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgbGF0ZXN0OgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHNvdXJjZTogZGlzdC9sYXRlc3QvCiAgICB0YXJnZXQ6IC9naXRlYS9sYXRlc3QKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHRhZyBdCiAgICAgIGJyYW5jaDogWyByZWZzL3RhZ3MvKiBdCgogIGdpdGh1YjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdGh1Yi1yZWxlYXNlCiAgICBmaWxlczoKICAgICAgLSBkaXN0L3JlbGVhc2UvKgogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZ2l0dGVyOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0dGVyCgpzZXJ2aWNlczoKICBteXNxbDoKICAgIGltYWdlOiBteXNxbDo1LjcKICAgIGVudmlyb25tZW50OgogICAgICAtIE1ZU1FMX0RBVEFCQVNFPXRlc3QKICAgICAgLSBNWVNRTF9BTExPV19FTVBUWV9QQVNTV09SRD15ZXMKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBwZ3NxbDoKICAgIGltYWdlOiBwb3N0Z3Jlczo5LjUKICAgIGVudmlyb25tZW50OgogICAgICAtIFBPU1RHUkVTX0RCPXRlc3QKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQo.prVy6IgBNIsbJGs7nrii2QoiAQ9ELnL2ThtQ-owHGHw \ No newline at end of file +eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogICMgZG9ja2VyOgogICMgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAjICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAjICAgdGFnczogWyAnJHtUQUd9JyBdCiAgIyAgIHdoZW46CiAgIyAgICAgZXZlbnQ6IFsgdGFnIF0KICAjICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICAjIGRvY2tlcjoKICAjICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgIyAgIHJlcG86IGdpdGVhL2dpdGVhCiAgIyAgIHRhZ3M6IFsgJ2xhdGVzdCcgXQogICMgICB3aGVuOgogICMgICAgIGV2ZW50OiBbIHB1c2ggXQogICMgICAgIGJyYW5jaDogWyBtYXN0ZXIgXQoKICByZWxlYXNlOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHN0cmlwX3ByZWZpeDogZGlzdC9yZWxlYXNlLwogICAgc291cmNlOiBkaXN0L3JlbGVhc2UvKgogICAgdGFyZ2V0OiAvZ2l0ZWEvbWFzdGVyCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc3RyaXBfcHJlZml4OiBkaXN0L3JlbGVhc2UvCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8qCiAgICB0YXJnZXQ6IC9naXRlYS8kJFRBRwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgbGF0ZXN0OgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHN0cmlwX3ByZWZpeDogZGlzdC9sYXRlc3QvCiAgICBzb3VyY2U6IGRpc3QvbGF0ZXN0LyoKICAgIHRhcmdldDogL2dpdGVhL2xhdGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZ2l0aHViOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0aHViLXJlbGVhc2UKICAgIGZpbGVzOgogICAgICAtIGRpc3QvcmVsZWFzZS8qCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBnaXR0ZXI6CiAgICBpbWFnZTogcGx1Z2lucy9naXR0ZXIKCnNlcnZpY2VzOgogIG15c3FsOgogICAgaW1hZ2U6IG15c3FsOjUuNwogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gTVlTUUxfREFUQUJBU0U9dGVzdAogICAgICAtIE1ZU1FMX0FMTE9XX0VNUFRZX1BBU1NXT1JEPXllcwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCgogIHBnc3FsOgogICAgaW1hZ2U6IHBvc3RncmVzOjkuNQogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gUE9TVEdSRVNfREI9dGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCg.tytRaswKB1pd16nbd6Gt6HE6uwlDf7EkoHJG1hzIjGc \ No newline at end of file From 65549863bc6a69c0d68019a771d3942c165f2a4c Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Fri, 25 Nov 2016 13:07:19 +0100 Subject: [PATCH 044/135] Dropped latest publishing from drone --- .drone.yml | 10 ---------- .drone.yml.sig | 2 +- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/.drone.yml b/.drone.yml index c94e5eb16f..ad99c6ea21 100644 --- a/.drone.yml +++ b/.drone.yml @@ -86,16 +86,6 @@ pipeline: event: [ tag ] branch: [ refs/tags/* ] - latest: - image: plugins/s3 - path_style: true - strip_prefix: dist/latest/ - source: dist/latest/* - target: /gitea/latest - when: - event: [ tag ] - branch: [ refs/tags/* ] - github: image: plugins/github-release files: diff --git a/.drone.yml.sig b/.drone.yml.sig index 8a1df72345..998c0e19f3 100644 --- a/.drone.yml.sig +++ b/.drone.yml.sig @@ -1 +1 @@ -eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogICMgZG9ja2VyOgogICMgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAjICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAjICAgdGFnczogWyAnJHtUQUd9JyBdCiAgIyAgIHdoZW46CiAgIyAgICAgZXZlbnQ6IFsgdGFnIF0KICAjICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICAjIGRvY2tlcjoKICAjICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgIyAgIHJlcG86IGdpdGVhL2dpdGVhCiAgIyAgIHRhZ3M6IFsgJ2xhdGVzdCcgXQogICMgICB3aGVuOgogICMgICAgIGV2ZW50OiBbIHB1c2ggXQogICMgICAgIGJyYW5jaDogWyBtYXN0ZXIgXQoKICByZWxlYXNlOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHN0cmlwX3ByZWZpeDogZGlzdC9yZWxlYXNlLwogICAgc291cmNlOiBkaXN0L3JlbGVhc2UvKgogICAgdGFyZ2V0OiAvZ2l0ZWEvbWFzdGVyCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc3RyaXBfcHJlZml4OiBkaXN0L3JlbGVhc2UvCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8qCiAgICB0YXJnZXQ6IC9naXRlYS8kJFRBRwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgbGF0ZXN0OgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHN0cmlwX3ByZWZpeDogZGlzdC9sYXRlc3QvCiAgICBzb3VyY2U6IGRpc3QvbGF0ZXN0LyoKICAgIHRhcmdldDogL2dpdGVhL2xhdGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZ2l0aHViOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0aHViLXJlbGVhc2UKICAgIGZpbGVzOgogICAgICAtIGRpc3QvcmVsZWFzZS8qCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBnaXR0ZXI6CiAgICBpbWFnZTogcGx1Z2lucy9naXR0ZXIKCnNlcnZpY2VzOgogIG15c3FsOgogICAgaW1hZ2U6IG15c3FsOjUuNwogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gTVlTUUxfREFUQUJBU0U9dGVzdAogICAgICAtIE1ZU1FMX0FMTE9XX0VNUFRZX1BBU1NXT1JEPXllcwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCgogIHBnc3FsOgogICAgaW1hZ2U6IHBvc3RncmVzOjkuNQogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gUE9TVEdSRVNfREI9dGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCg.tytRaswKB1pd16nbd6Gt6HE6uwlDf7EkoHJG1hzIjGc \ No newline at end of file +eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogICMgZG9ja2VyOgogICMgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAjICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAjICAgdGFnczogWyAnJHtUQUd9JyBdCiAgIyAgIHdoZW46CiAgIyAgICAgZXZlbnQ6IFsgdGFnIF0KICAjICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICAjIGRvY2tlcjoKICAjICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgIyAgIHJlcG86IGdpdGVhL2dpdGVhCiAgIyAgIHRhZ3M6IFsgJ2xhdGVzdCcgXQogICMgICB3aGVuOgogICMgICAgIGV2ZW50OiBbIHB1c2ggXQogICMgICAgIGJyYW5jaDogWyBtYXN0ZXIgXQoKICByZWxlYXNlOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHN0cmlwX3ByZWZpeDogZGlzdC9yZWxlYXNlLwogICAgc291cmNlOiBkaXN0L3JlbGVhc2UvKgogICAgdGFyZ2V0OiAvZ2l0ZWEvbWFzdGVyCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc3RyaXBfcHJlZml4OiBkaXN0L3JlbGVhc2UvCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8qCiAgICB0YXJnZXQ6IC9naXRlYS8kJFRBRwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZ2l0aHViOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0aHViLXJlbGVhc2UKICAgIGZpbGVzOgogICAgICAtIGRpc3QvcmVsZWFzZS8qCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBnaXR0ZXI6CiAgICBpbWFnZTogcGx1Z2lucy9naXR0ZXIKCnNlcnZpY2VzOgogIG15c3FsOgogICAgaW1hZ2U6IG15c3FsOjUuNwogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gTVlTUUxfREFUQUJBU0U9dGVzdAogICAgICAtIE1ZU1FMX0FMTE9XX0VNUFRZX1BBU1NXT1JEPXllcwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCgogIHBnc3FsOgogICAgaW1hZ2U6IHBvc3RncmVzOjkuNQogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gUE9TVEdSRVNfREI9dGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCg.CJAqrylL68UPxR-wlKhIL9waJKRhw6isiol_f9Lx5ao \ No newline at end of file From 066f515a47d024e874408c979732a42bfc72a2a8 Mon Sep 17 00:00:00 2001 From: Bwko Date: Sat, 26 Nov 2016 01:03:06 +0100 Subject: [PATCH 045/135] Lint models/user_email.go --- models/user_mail.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/models/user_mail.go b/models/user_mail.go index c6ade3fa43..3fc4f4ae89 100644 --- a/models/user_mail.go +++ b/models/user_mail.go @@ -9,7 +9,7 @@ import ( "strings" ) -// EmailAdresses is the list of all email addresses of a user. Can contain the +// EmailAddress is the list of all email addresses of a user. Can contain the // primary email address, but is not obligatory. type EmailAddress struct { ID int64 `xorm:"pk autoincr"` @@ -81,10 +81,12 @@ func addEmailAddress(e Engine, email *EmailAddress) error { return err } +// AddEmailAddress adds an email adress to given user. func AddEmailAddress(email *EmailAddress) error { return addEmailAddress(x, email) } +// AddEmailAddresses adds an email adress to given user. func AddEmailAddresses(emails []*EmailAddress) error { if len(emails) == 0 { return nil @@ -108,6 +110,7 @@ func AddEmailAddresses(emails []*EmailAddress) error { return nil } +// Activate activates the email adress to given user. func (email *EmailAddress) Activate() error { user, err := GetUserByID(email.UID) if err != nil { @@ -134,6 +137,7 @@ func (email *EmailAddress) Activate() error { return sess.Commit() } +// DeleteEmailAddress deletes an email adress of given user. func DeleteEmailAddress(email *EmailAddress) (err error) { if email.ID > 0 { _, err = x.Id(email.ID).Delete(new(EmailAddress)) @@ -145,6 +149,7 @@ func DeleteEmailAddress(email *EmailAddress) (err error) { return err } +// DeleteEmailAddresses deletes multiple email adresses func DeleteEmailAddresses(emails []*EmailAddress) (err error) { for i := range emails { if err = DeleteEmailAddress(emails[i]); err != nil { @@ -155,6 +160,7 @@ func DeleteEmailAddresses(emails []*EmailAddress) (err error) { return nil } +// MakeEmailPrimary sets primary email adress of given user. func MakeEmailPrimary(email *EmailAddress) error { has, err := x.Get(email) if err != nil { From 2bb1601d7c34afff8751cd6ef26e6667e1bcb3df Mon Sep 17 00:00:00 2001 From: Bwko Date: Sat, 26 Nov 2016 01:07:57 +0100 Subject: [PATCH 046/135] Lint models/access.go --- models/access.go | 46 ++++++++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/models/access.go b/models/access.go index d18e759fec..b591e0c9db 100644 --- a/models/access.go +++ b/models/access.go @@ -10,14 +10,20 @@ import ( "code.gitea.io/gitea/modules/log" ) +// AccessMode specifies the users access mode type AccessMode int const ( - AccessModeNone AccessMode = iota // 0 - AccessModeRead // 1 - AccessModeWrite // 2 - AccessModeAdmin // 3 - AccessModeOwner // 4 + // AccessModeNone no access + AccessModeNone AccessMode = iota // 0 + // AccessModeRead read access + AccessModeRead // 1 + // AccessModeWrite write access + AccessModeWrite // 2 + // AccessModeAdmin admin access + AccessModeAdmin // 3 + // AccessModeOwner owner access + AccessModeOwner // 4 ) func (mode AccessMode) String() string { @@ -57,21 +63,21 @@ type Access struct { Mode AccessMode } -func accessLevel(e Engine, u *User, repo *Repository) (AccessMode, error) { +func accessLevel(e Engine, user *User, repo *Repository) (AccessMode, error) { mode := AccessModeNone if !repo.IsPrivate { mode = AccessModeRead } - if u == nil { + if user == nil { return mode, nil } - if u.ID == repo.OwnerID { + if user.ID == repo.OwnerID { return AccessModeOwner, nil } - a := &Access{UserID: u.ID, RepoID: repo.ID} + a := &Access{UserID: user.ID, RepoID: repo.ID} if has, err := e.Get(a); !has || err != nil { return mode, err } @@ -80,24 +86,24 @@ func accessLevel(e Engine, u *User, repo *Repository) (AccessMode, error) { // AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the // user does not have access. User can be nil! -func AccessLevel(u *User, repo *Repository) (AccessMode, error) { - return accessLevel(x, u, repo) +func AccessLevel(user *User, repo *Repository) (AccessMode, error) { + return accessLevel(x, user, repo) } -func hasAccess(e Engine, u *User, repo *Repository, testMode AccessMode) (bool, error) { - mode, err := accessLevel(e, u, repo) +func hasAccess(e Engine, user *User, repo *Repository, testMode AccessMode) (bool, error) { + mode, err := accessLevel(e, user, repo) return testMode <= mode, err } // HasAccess returns true if someone has the request access level. User can be nil! -func HasAccess(u *User, repo *Repository, testMode AccessMode) (bool, error) { - return hasAccess(x, u, repo, testMode) +func HasAccess(user *User, repo *Repository, testMode AccessMode) (bool, error) { + return hasAccess(x, user, repo, testMode) } // GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own. -func (u *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) { +func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) { accesses := make([]*Access, 0, 10) - if err := x.Find(&accesses, &Access{UserID: u.ID}); err != nil { + if err := x.Find(&accesses, &Access{UserID: user.ID}); err != nil { return nil, err } @@ -113,7 +119,7 @@ func (u *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) { } if err = repo.GetOwner(); err != nil { return nil, err - } else if repo.OwnerID == u.ID { + } else if repo.OwnerID == user.ID { continue } repos[repo] = access.Mode @@ -245,6 +251,6 @@ func (repo *Repository) recalculateAccesses(e Engine) error { } // RecalculateAccesses recalculates all accesses for repository. -func (r *Repository) RecalculateAccesses() error { - return r.recalculateAccesses(x) +func (repo *Repository) RecalculateAccesses() error { + return repo.recalculateAccesses(x) } From 6cde041080ad503216784d513770a3683243a14b Mon Sep 17 00:00:00 2001 From: Bwko Date: Sat, 26 Nov 2016 01:36:03 +0100 Subject: [PATCH 047/135] Lint models/ssh_key.go --- models/ssh_key.go | 55 +++++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/models/ssh_key.go b/models/ssh_key.go index 98fb2dcdbf..53a31f6f8d 100644 --- a/models/ssh_key.go +++ b/models/ssh_key.go @@ -33,10 +33,13 @@ const ( var sshOpLocker sync.Mutex +// KeyType specifies the key type type KeyType int const ( + // KeyTypeUser specifies the user key KeyTypeUser = iota + 1 + // KeyTypeDeploy specifies the deploy key KeyTypeDeploy ) @@ -58,28 +61,31 @@ type PublicKey struct { HasUsed bool `xorm:"-"` } -func (k *PublicKey) BeforeInsert() { - k.CreatedUnix = time.Now().Unix() +// BeforeInsert will be invoked by XORM before inserting a record +func (key *PublicKey) BeforeInsert() { + key.CreatedUnix = time.Now().Unix() } -func (k *PublicKey) BeforeUpdate() { - k.UpdatedUnix = time.Now().Unix() +// BeforeUpdate is invoked from XORM before updating this object. +func (key *PublicKey) BeforeUpdate() { + key.UpdatedUnix = time.Now().Unix() } -func (k *PublicKey) AfterSet(colName string, _ xorm.Cell) { +// AfterSet is invoked from XORM after setting the value of a field of this object. +func (key *PublicKey) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": - k.Created = time.Unix(k.CreatedUnix, 0).Local() + key.Created = time.Unix(key.CreatedUnix, 0).Local() case "updated_unix": - k.Updated = time.Unix(k.UpdatedUnix, 0).Local() - k.HasUsed = k.Updated.After(k.Created) - k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now()) + key.Updated = time.Unix(key.UpdatedUnix, 0).Local() + key.HasUsed = key.Updated.After(key.Created) + key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now()) } } // OmitEmail returns content of public key without email address. -func (k *PublicKey) OmitEmail() string { - return strings.Join(strings.Split(k.Content, " ")[:2], " ") +func (key *PublicKey) OmitEmail() string { + return strings.Join(strings.Split(key.Content, " ")[:2], " ") } // AuthorizedString returns formatted public key string for authorized_keys file. @@ -573,32 +579,35 @@ type DeployKey struct { HasUsed bool `xorm:"-"` } -func (k *DeployKey) BeforeInsert() { - k.CreatedUnix = time.Now().Unix() +// BeforeInsert will be invoked by XORM before inserting a record +func (key *DeployKey) BeforeInsert() { + key.CreatedUnix = time.Now().Unix() } -func (k *DeployKey) BeforeUpdate() { - k.UpdatedUnix = time.Now().Unix() +// BeforeUpdate is invoked from XORM before updating this object. +func (key *DeployKey) BeforeUpdate() { + key.UpdatedUnix = time.Now().Unix() } -func (k *DeployKey) AfterSet(colName string, _ xorm.Cell) { +// AfterSet is invoked from XORM after setting the value of a field of this object. +func (key *DeployKey) AfterSet(colName string, _ xorm.Cell) { switch colName { case "created_unix": - k.Created = time.Unix(k.CreatedUnix, 0).Local() + key.Created = time.Unix(key.CreatedUnix, 0).Local() case "updated_unix": - k.Updated = time.Unix(k.UpdatedUnix, 0).Local() - k.HasUsed = k.Updated.After(k.Created) - k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now()) + key.Updated = time.Unix(key.UpdatedUnix, 0).Local() + key.HasUsed = key.Updated.After(key.Created) + key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now()) } } // GetContent gets associated public key content. -func (k *DeployKey) GetContent() error { - pkey, err := GetPublicKeyByID(k.KeyID) +func (key *DeployKey) GetContent() error { + pkey, err := GetPublicKeyByID(key.KeyID) if err != nil { return err } - k.Content = pkey.Content + key.Content = pkey.Content return nil } From ce8c9ef58060c64894229d2f11aed98517e39fbf Mon Sep 17 00:00:00 2001 From: Bwko Date: Sat, 26 Nov 2016 01:40:35 +0100 Subject: [PATCH 048/135] Lint models/repo_branch.go --- models/repo_branch.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/models/repo_branch.go b/models/repo_branch.go index 075e590fdf..fcfd3e8ecb 100644 --- a/models/repo_branch.go +++ b/models/repo_branch.go @@ -8,11 +8,13 @@ import ( "code.gitea.io/git" ) +// Branch holds the branch information type Branch struct { Path string Name string } +// GetBranchesByPath returns a branch by it's path func GetBranchesByPath(path string) ([]*Branch, error) { gitRepo, err := git.OpenRepository(path) if err != nil { @@ -34,24 +36,27 @@ func GetBranchesByPath(path string) ([]*Branch, error) { return branches, nil } -func (repo *Repository) GetBranch(br string) (*Branch, error) { - if !git.IsBranchExist(repo.RepoPath(), br) { - return nil, &ErrBranchNotExist{br} +// GetBranch returns a branch by it's name +func (repo *Repository) GetBranch(branch string) (*Branch, error) { + if !git.IsBranchExist(repo.RepoPath(), branch) { + return nil, &ErrBranchNotExist{branch} } return &Branch{ Path: repo.RepoPath(), - Name: br, + Name: branch, }, nil } +// GetBranches returns all the branches of a repository func (repo *Repository) GetBranches() ([]*Branch, error) { return GetBranchesByPath(repo.RepoPath()) } -func (br *Branch) GetCommit() (*git.Commit, error) { - gitRepo, err := git.OpenRepository(br.Path) +// GetCommit returns all the commits of a branch +func (branch *Branch) GetCommit() (*git.Commit, error) { + gitRepo, err := git.OpenRepository(branch.Path) if err != nil { return nil, err } - return gitRepo.GetBranchCommit(br.Name) + return gitRepo.GetBranchCommit(branch.Name) } From 7bf7042013f7c78ceb581e9bf30ee1cee2e8a0bc Mon Sep 17 00:00:00 2001 From: Bwko Date: Sat, 26 Nov 2016 01:30:21 +0100 Subject: [PATCH 049/135] Lint models/repo_mirror.go --- models/repo_mirror.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/models/repo_mirror.go b/models/repo_mirror.go index fceffd43b7..23cbedaa0c 100644 --- a/models/repo_mirror.go +++ b/models/repo_mirror.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/modules/sync" ) +// MirrorQueue holds an UniqueQueue object of the mirror var MirrorQueue = sync.NewUniqueQueue(setting.Repository.MirrorQueueLength) // Mirror represents mirror information of a repository. @@ -37,16 +38,19 @@ type Mirror struct { address string `xorm:"-"` } +// BeforeInsert will be invoked by XORM before inserting a record func (m *Mirror) BeforeInsert() { m.UpdatedUnix = time.Now().Unix() m.NextUpdateUnix = m.NextUpdate.Unix() } +// BeforeUpdate is invoked from XORM before updating this object. func (m *Mirror) BeforeUpdate() { m.UpdatedUnix = time.Now().Unix() m.NextUpdateUnix = m.NextUpdate.Unix() } +// AfterSet is invoked from XORM after setting the value of a field of this object. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) { var err error switch colName { @@ -180,10 +184,12 @@ func updateMirror(e Engine, m *Mirror) error { return err } +// UpdateMirror updates the mirror func UpdateMirror(m *Mirror) error { return updateMirror(x, m) } +// DeleteMirrorByRepoID deletes a mirror by repoID func DeleteMirrorByRepoID(repoID int64) error { _, err := x.Delete(&Mirror{RepoID: repoID}) return err @@ -241,6 +247,7 @@ func SyncMirrors() { } } +// InitSyncMirrors initializes a go routine to sync the mirros func InitSyncMirrors() { go SyncMirrors() } From 0b9cf10340ec4c0beb1e732ea08b31d38448f31e Mon Sep 17 00:00:00 2001 From: Bwko Date: Sat, 26 Nov 2016 01:20:18 +0100 Subject: [PATCH 050/135] Lint models/org.go & models.go --- models/models.go | 26 +++++++++++++++++++++----- models/org.go | 30 ++++++++++++++++-------------- 2 files changed, 37 insertions(+), 19 deletions(-) diff --git a/models/models.go b/models/models.go index 3a83929a77..0b02de54d4 100644 --- a/models/models.go +++ b/models/models.go @@ -13,9 +13,12 @@ import ( "path" "strings" + // Needed for the MySQL driver _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/core" "github.com/go-xorm/xorm" + + // Needed for the Postgresql driver _ "github.com/lib/pq" "code.gitea.io/gitea/models/migrations" @@ -45,16 +48,22 @@ func sessionRelease(sess *xorm.Session) { } var ( - x *xorm.Engine - tables []interface{} + x *xorm.Engine + tables []interface{} + + // HasEngine specifies if we have a xorm.Engine HasEngine bool + // DbCfg holds the database settings DbCfg struct { Type, Host, Name, User, Passwd, Path, SSLMode string } + // EnableSQLite3 use SQLite3 EnableSQLite3 bool - EnableTiDB bool + + // EnableTiDB enable TiDB + EnableTiDB bool ) func init() { @@ -69,12 +78,13 @@ func init() { new(Team), new(OrgUser), new(TeamUser), new(TeamRepo), new(Notice), new(EmailAddress)) - gonicNames := []string{"SSL"} + gonicNames := []string{"SSL", "UID"} for _, name := range gonicNames { core.LintGonicMapper[name] = true } } +// LoadConfigs loads the database settings func LoadConfigs() { sec := setting.Cfg.Section("database") DbCfg.Type = sec.Key("DB_TYPE").String() @@ -115,7 +125,7 @@ func parsePostgreSQLHostPort(info string) (string, string) { func getEngine() (*xorm.Engine, error) { connStr := "" - var Param string = "?" + var Param = "?" if strings.Contains(DbCfg.Name, Param) { Param = "&" } @@ -159,6 +169,7 @@ func getEngine() (*xorm.Engine, error) { return xorm.NewEngine(DbCfg.Type, connStr) } +// NewTestEngine sets a new test xorm.Engine func NewTestEngine(x *xorm.Engine) (err error) { x, err = getEngine() if err != nil { @@ -169,6 +180,7 @@ func NewTestEngine(x *xorm.Engine) (err error) { return x.StoreEngine("InnoDB").Sync2(tables...) } +// SetEngine sets the xorm.Engine func SetEngine() (err error) { x, err = getEngine() if err != nil { @@ -191,6 +203,7 @@ func SetEngine() (err error) { return nil } +// NewEngine initializes a new xorm.Engine func NewEngine() (err error) { if err = SetEngine(); err != nil { return err @@ -211,6 +224,7 @@ func NewEngine() (err error) { return nil } +// Statistic contains the database statistics type Statistic struct { Counter struct { User, Org, PublicKey, @@ -222,6 +236,7 @@ type Statistic struct { } } +// GetStatistic returns the database statistics func GetStatistic() (stats Statistic) { stats.Counter.User = CountUsers() stats.Counter.Org = CountOrganizations() @@ -248,6 +263,7 @@ func GetStatistic() (stats Statistic) { return } +// Ping tests if database is alive func Ping() error { return x.Ping() } diff --git a/models/org.go b/models/org.go index 7b251b2020..1d2ff1300f 100644 --- a/models/org.go +++ b/models/org.go @@ -15,7 +15,9 @@ import ( ) var ( - ErrOrgNotExist = errors.New("Organization does not exist") + // ErrOrgNotExist organization does not exist + ErrOrgNotExist = errors.New("Organization does not exist") + // ErrTeamNotExist team does not exist ErrTeamNotExist = errors.New("Team does not exist") ) @@ -68,7 +70,7 @@ func (org *User) GetMembers() error { var ids = make([]int64, len(ous)) for i, ou := range ous { - ids[i] = ou.Uid + ids[i] = ou.UID } org.Members, err = GetUsersByIDs(ids) return err @@ -127,7 +129,7 @@ func CreateOrganization(org, owner *User) (err error) { // Add initial creator to organization and owner team. if _, err = sess.Insert(&OrgUser{ - Uid: owner.ID, + UID: owner.ID, OrgID: org.ID, IsOwner: true, NumTeams: 1, @@ -235,7 +237,7 @@ func DeleteOrganization(org *User) (err error) { // OrgUser represents an organization-user relation. type OrgUser struct { ID int64 `xorm:"pk autoincr"` - Uid int64 `xorm:"INDEX UNIQUE(s)"` + UID int64 `xorm:"INDEX UNIQUE(s)"` OrgID int64 `xorm:"INDEX UNIQUE(s)"` IsPublic bool IsOwner bool @@ -243,29 +245,29 @@ type OrgUser struct { } // IsOrganizationOwner returns true if given user is in the owner team. -func IsOrganizationOwner(orgId, uid int64) bool { +func IsOrganizationOwner(orgID, uid int64) bool { has, _ := x. Where("is_owner=?", true). And("uid=?", uid). - And("org_id=?", orgId). + And("org_id=?", orgID). Get(new(OrgUser)) return has } // IsOrganizationMember returns true if given user is member of organization. -func IsOrganizationMember(orgId, uid int64) bool { +func IsOrganizationMember(orgID, uid int64) bool { has, _ := x. Where("uid=?", uid). - And("org_id=?", orgId). + And("org_id=?", orgID). Get(new(OrgUser)) return has } // IsPublicMembership returns true if given user public his/her membership. -func IsPublicMembership(orgId, uid int64) bool { +func IsPublicMembership(orgID, uid int64) bool { has, _ := x. Where("uid=?", uid). - And("org_id=?", orgId). + And("org_id=?", orgID). And("is_public=?", true). Get(new(OrgUser)) return has @@ -311,7 +313,7 @@ func GetOwnedOrgsByUserID(userID int64) ([]*User, error) { return getOwnedOrgsByUserID(sess, userID) } -// GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by +// GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by // given user ID, ordered descending by the given condition. func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) { sess := x.NewSession() @@ -374,7 +376,7 @@ func AddOrgUser(orgID, uid int64) error { } ou := &OrgUser{ - Uid: uid, + UID: uid, OrgID: orgID, } @@ -512,7 +514,7 @@ func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) { return teamIDs, nil } -// GetTeams returns all teams that belong to organization, +// GetUserTeams returns all teams that belong to user, // and that the user has joined. func (org *User) GetUserTeams(userID int64) ([]*Team, error) { return org.getUserTeams(x, userID) @@ -560,7 +562,7 @@ func (org *User) GetUserRepositories(userID int64, page, pageSize int) ([]*Repos return repos, repoCount, nil } -// GetUserRepositories returns mirror repositories of the organization +// GetUserMirrorRepositories returns mirror repositories of the user // that the user with the given userID has access to. func (org *User) GetUserMirrorRepositories(userID int64) ([]*Repository, error) { teamIDs, err := org.GetUserTeamIDs(userID) From 3228544c31943ee11957d204fc6904e112be8fcb Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 26 Nov 2016 19:53:29 +0800 Subject: [PATCH 051/135] golint fixed for modules/log --- modules/log/conn.go | 11 +++++---- modules/log/console.go | 15 ++++++++--- modules/log/file.go | 56 +++++++++++++++++++++--------------------- modules/log/log.go | 24 ++++++++++++++++-- modules/log/smtp.go | 36 ++++++++++++++------------- 5 files changed, 86 insertions(+), 56 deletions(-) diff --git a/modules/log/conn.go b/modules/log/conn.go index c104a16c93..b1801d08f7 100644 --- a/modules/log/conn.go +++ b/modules/log/conn.go @@ -23,20 +23,20 @@ type ConnWriter struct { Level int `json:"level"` } -// create new ConnWrite returning as LoggerInterface. +// NewConn creates new ConnWrite returning as LoggerInterface. func NewConn() LoggerInterface { conn := new(ConnWriter) conn.Level = TRACE return conn } -// init connection writer with json config. +// Init inits connection writer with json config. // json config only need key "level". func (cw *ConnWriter) Init(jsonconfig string) error { return json.Unmarshal([]byte(jsonconfig), cw) } -// write message in connection. +// WriteMsg writes message in connection. // if connection is down, try to re-connect. func (cw *ConnWriter) WriteMsg(msg string, skip, level int) error { if cw.Level > level { @@ -55,10 +55,11 @@ func (cw *ConnWriter) WriteMsg(msg string, skip, level int) error { return nil } -func (_ *ConnWriter) Flush() { +// Flush no things for this implementation +func (cw *ConnWriter) Flush() { } -// destroy connection writer and close tcp listener. +// Destroy destroy connection writer and close tcp listener. func (cw *ConnWriter) Destroy() { if cw.innerWriter == nil { return diff --git a/modules/log/console.go b/modules/log/console.go index f5a8b96fd7..04991243fc 100644 --- a/modules/log/console.go +++ b/modules/log/console.go @@ -11,8 +11,10 @@ import ( "runtime" ) +// Brush brush type type Brush func(string) string +// NewBrush create a brush according color func NewBrush(color string) Brush { pre := "\033[" reset := "\033[0m" @@ -37,7 +39,7 @@ type ConsoleWriter struct { Level int `json:"level"` } -// create ConsoleWriter returning as LoggerInterface. +// NewConsole create ConsoleWriter returning as LoggerInterface. func NewConsole() LoggerInterface { return &ConsoleWriter{ lg: log.New(os.Stdout, "", log.Ldate|log.Ltime), @@ -45,10 +47,14 @@ func NewConsole() LoggerInterface { } } +// Init inits connection writer with json config. +// json config only need key "level". func (cw *ConsoleWriter) Init(config string) error { return json.Unmarshal([]byte(config), cw) } +// WriteMsg writes message in console. +// if OS is windows, ignore colors. func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error { if cw.Level > level { return nil @@ -61,11 +67,12 @@ func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error { return nil } -func (_ *ConsoleWriter) Flush() { - +// Flush when log should be flushed +func (cw *ConsoleWriter) Flush() { } -func (_ *ConsoleWriter) Destroy() { +// Destroy when writer is destroy +func (cw *ConsoleWriter) Destroy() { } func init() { diff --git a/modules/log/file.go b/modules/log/file.go index e9402815f0..563abc28f8 100644 --- a/modules/log/file.go +++ b/modules/log/file.go @@ -25,17 +25,17 @@ type FileLogWriter struct { // The opened file Filename string `json:"filename"` - Maxlines int `json:"maxlines"` - maxlines_curlines int + Maxlines int `json:"maxlines"` + maxlinesCurlines int // Rotate at size - Maxsize int `json:"maxsize"` - maxsize_cursize int + Maxsize int `json:"maxsize"` + maxsizeCursize int // Rotate daily - Daily bool `json:"daily"` - Maxdays int64 `json:"maxdays"` - daily_opendate int + Daily bool `json:"daily"` + Maxdays int64 `json:"maxdays"` + dailyOpenDate int Rotate bool `json:"rotate"` @@ -44,20 +44,20 @@ type FileLogWriter struct { Level int `json:"level"` } -// an *os.File writer with locker. +// MuxWriter an *os.File writer with locker. type MuxWriter struct { sync.Mutex fd *os.File } -// write to os.File. +// Write writes to os.File. func (l *MuxWriter) Write(b []byte) (int, error) { l.Lock() defer l.Unlock() return l.fd.Write(b) } -// set os.File in writer. +// SetFd sets os.File in writer. func (l *MuxWriter) SetFd(fd *os.File) { if l.fd != nil { l.fd.Close() @@ -65,7 +65,7 @@ func (l *MuxWriter) SetFd(fd *os.File) { l.fd = fd } -// create a FileLogWriter returning as LoggerInterface. +// NewFileWriter create a FileLogWriter returning as LoggerInterface. func NewFileWriter() LoggerInterface { w := &FileLogWriter{ Filename: "", @@ -103,7 +103,7 @@ func (w *FileLogWriter) Init(config string) error { return w.StartLogger() } -// start file logger. create log file and set to locker-inside file writer. +// StartLogger start file logger. create log file and set to locker-inside file writer. func (w *FileLogWriter) StartLogger() error { fd, err := w.createLogFile() if err != nil { @@ -119,19 +119,19 @@ func (w *FileLogWriter) StartLogger() error { func (w *FileLogWriter) docheck(size int) { w.startLock.Lock() defer w.startLock.Unlock() - if w.Rotate && ((w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) || - (w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) || - (w.Daily && time.Now().Day() != w.daily_opendate)) { + if w.Rotate && ((w.Maxlines > 0 && w.maxlinesCurlines >= w.Maxlines) || + (w.Maxsize > 0 && w.maxsizeCursize >= w.Maxsize) || + (w.Daily && time.Now().Day() != w.dailyOpenDate)) { if err := w.DoRotate(); err != nil { fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err) return } } - w.maxlines_curlines++ - w.maxsize_cursize += size + w.maxlinesCurlines++ + w.maxsizeCursize += size } -// write logger message into file. +// WriteMsg writes logger message into file. func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error { if level < w.Level { return nil @@ -151,18 +151,18 @@ func (w *FileLogWriter) initFd() error { fd := w.mw.fd finfo, err := fd.Stat() if err != nil { - return fmt.Errorf("get stat: %s\n", err) + return fmt.Errorf("get stat: %s", err) } - w.maxsize_cursize = int(finfo.Size()) - w.daily_opendate = time.Now().Day() + w.maxsizeCursize = int(finfo.Size()) + w.dailyOpenDate = time.Now().Day() if finfo.Size() > 0 { content, err := ioutil.ReadFile(w.Filename) if err != nil { return err } - w.maxlines_curlines = len(strings.Split(string(content), "\n")) + w.maxlinesCurlines = len(strings.Split(string(content), "\n")) } else { - w.maxlines_curlines = 0 + w.maxlinesCurlines = 0 } return nil } @@ -181,7 +181,7 @@ func (w *FileLogWriter) DoRotate() error { } // return error if the last file checked still existed if err == nil { - return fmt.Errorf("rotate: cannot find free log number to rename %s\n", w.Filename) + return fmt.Errorf("rotate: cannot find free log number to rename %s", w.Filename) } // block Logger's io.Writer @@ -194,12 +194,12 @@ func (w *FileLogWriter) DoRotate() error { // close fd before rename // Rename the file to its newfound home if err = os.Rename(w.Filename, fname); err != nil { - return fmt.Errorf("Rotate: %s\n", err) + return fmt.Errorf("Rotate: %s", err) } // re-start logger if err = w.StartLogger(); err != nil { - return fmt.Errorf("Rotate StartLogger: %s\n", err) + return fmt.Errorf("Rotate StartLogger: %s", err) } go w.deleteOldLog() @@ -226,12 +226,12 @@ func (w *FileLogWriter) deleteOldLog() { }) } -// destroy file logger, close file writer. +// Destroy destroy file logger, close file writer. func (w *FileLogWriter) Destroy() { w.mw.fd.Close() } -// flush file logger. +// Flush flush file logger. // there are no buffering messages in file logger in memory. // flush file means sync file from disk. func (w *FileLogWriter) Flush() { diff --git a/modules/log/log.go b/modules/log/log.go index 41be414051..5a9efe6a28 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -15,10 +15,12 @@ import ( ) var ( - loggers []*Logger + loggers []*Logger + // GitLogger logger for git GitLogger *Logger ) +// NewLogger create a logger func NewLogger(bufLen int64, mode, config string) { logger := newLogger(bufLen) @@ -37,6 +39,7 @@ func NewLogger(bufLen int64, mode, config string) { } } +// NewGitLogger create a logger for git // FIXME: use same log level as other loggers. func NewGitLogger(logPath string) { os.MkdirAll(path.Dir(logPath), os.ModePerm) @@ -44,42 +47,49 @@ func NewGitLogger(logPath string) { GitLogger.SetLogger("file", fmt.Sprintf(`{"level":0,"filename":"%s","rotate":false}`, logPath)) } +// Trace records trace log func Trace(format string, v ...interface{}) { for _, logger := range loggers { logger.Trace(format, v...) } } +// Debug records debug log func Debug(format string, v ...interface{}) { for _, logger := range loggers { logger.Debug(format, v...) } } +// Info records info log func Info(format string, v ...interface{}) { for _, logger := range loggers { logger.Info(format, v...) } } +// Warn records warnning log func Warn(format string, v ...interface{}) { for _, logger := range loggers { logger.Warn(format, v...) } } +// Error records error log func Error(skip int, format string, v ...interface{}) { for _, logger := range loggers { logger.Error(skip, format, v...) } } +// Critical records critical log func Critical(skip int, format string, v ...interface{}) { for _, logger := range loggers { logger.Critical(skip, format, v...) } } +// Fatal records error log and exit process func Fatal(skip int, format string, v ...interface{}) { Error(skip, format, v...) for _, l := range loggers { @@ -88,6 +98,7 @@ func Fatal(skip int, format string, v ...interface{}) { os.Exit(1) } +// Close closes all the loggers func Close() { for _, l := range loggers { l.Close() @@ -101,8 +112,10 @@ func Close() { // |___|___| /__| \___ >__| |__| (____ /\___ >___ > // \/ \/ \/ \/ \/ -type LogLevel int +// LogLevel level type for log +//type LogLevel int +// log levels const ( TRACE = iota DEBUG @@ -274,36 +287,43 @@ func (l *Logger) Close() { } } +// Trace records trace log func (l *Logger) Trace(format string, v ...interface{}) { msg := fmt.Sprintf("[T] "+format, v...) l.writerMsg(0, TRACE, msg) } +// Debug records debug log func (l *Logger) Debug(format string, v ...interface{}) { msg := fmt.Sprintf("[D] "+format, v...) l.writerMsg(0, DEBUG, msg) } +// Info records information log func (l *Logger) Info(format string, v ...interface{}) { msg := fmt.Sprintf("[I] "+format, v...) l.writerMsg(0, INFO, msg) } +// Warn records warnning log func (l *Logger) Warn(format string, v ...interface{}) { msg := fmt.Sprintf("[W] "+format, v...) l.writerMsg(0, WARN, msg) } +// Error records error log func (l *Logger) Error(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[E] "+format, v...) l.writerMsg(skip, ERROR, msg) } +// Critical records critical log func (l *Logger) Critical(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[C] "+format, v...) l.writerMsg(skip, CRITICAL, msg) } +// Fatal records error log and exit the process func (l *Logger) Fatal(skip int, format string, v ...interface{}) { msg := fmt.Sprintf("[F] "+format, v...) l.writerMsg(skip, FATAL, msg) diff --git a/modules/log/smtp.go b/modules/log/smtp.go index 0c87f0c704..760b8e8bd7 100644 --- a/modules/log/smtp.go +++ b/modules/log/smtp.go @@ -16,7 +16,7 @@ const ( subjectPhrase = "Diagnostic message from server" ) -// smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server. +// SMTPWriter implements LoggerInterface and is used to send emails via given SMTP-server. type SMTPWriter struct { Username string `json:"Username"` Password string `json:"password"` @@ -26,12 +26,12 @@ type SMTPWriter struct { Level int `json:"level"` } -// create smtp writer. +// NewSMTPWriter creates smtp writer. func NewSMTPWriter() LoggerInterface { return &SMTPWriter{Level: TRACE} } -// init smtp writer with json config. +// Init smtp writer with json config. // config like: // { // "Username":"example@gmail.com", @@ -45,41 +45,43 @@ func (sw *SMTPWriter) Init(jsonconfig string) error { return json.Unmarshal([]byte(jsonconfig), sw) } -// write message in smtp writer. +// WriteMsg writes message in smtp writer. // it will send an email with subject and only this message. -func (s *SMTPWriter) WriteMsg(msg string, skip, level int) error { - if level < s.Level { +func (sw *SMTPWriter) WriteMsg(msg string, skip, level int) error { + if level < sw.Level { return nil } - hp := strings.Split(s.Host, ":") + hp := strings.Split(sw.Host, ":") // Set up authentication information. auth := smtp.PlainAuth( "", - s.Username, - s.Password, + sw.Username, + sw.Password, hp[0], ) // Connect to the server, authenticate, set the sender and recipient, // and send the email all in one step. - content_type := "Content-Type: text/plain" + "; charset=UTF-8" - mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.Username + "<" + s.Username + - ">\r\nSubject: " + s.Subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg) + contentType := "Content-Type: text/plain" + "; charset=UTF-8" + mailmsg := []byte("To: " + strings.Join(sw.RecipientAddresses, ";") + "\r\nFrom: " + sw.Username + "<" + sw.Username + + ">\r\nSubject: " + sw.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg) return smtp.SendMail( - s.Host, + sw.Host, auth, - s.Username, - s.RecipientAddresses, + sw.Username, + sw.RecipientAddresses, mailmsg, ) } -func (_ *SMTPWriter) Flush() { +// Flush when log should be flushed +func (sw *SMTPWriter) Flush() { } -func (_ *SMTPWriter) Destroy() { +// Destroy when writer is destroy +func (sw *SMTPWriter) Destroy() { } func init() { From 638dd24cec6f2951ecd4550165b858138c4c3f40 Mon Sep 17 00:00:00 2001 From: Andrey Nering Date: Sat, 26 Nov 2016 10:08:31 -0200 Subject: [PATCH 052/135] Fix HTTP headers for issue attachment download - Download filename was wrong for files other than images. Example: It was `download` instead of `file.pdf` - PDF was downloading instead of showing on browser --- cmd/web.go | 6 +----- routers/repo/download.go | 16 +++++++++------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/cmd/web.go b/cmd/web.go index 3d0c977798..f5553cdf00 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -336,11 +336,7 @@ func runWeb(ctx *cli.Context) error { } defer fr.Close() - ctx.Header().Set("Cache-Control", "public,max-age=86400") - ctx.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name)) - // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome. - // We must put the name in " manually. - if err = repo.ServeData(ctx, "\""+attach.Name+"\"", fr); err != nil { + if err = repo.ServeData(ctx, attach.Name, fr); err != nil { ctx.Handle(500, "ServeData", err) return } diff --git a/routers/repo/download.go b/routers/repo/download.go index 3adab315d4..aba0971a4a 100644 --- a/routers/repo/download.go +++ b/routers/repo/download.go @@ -5,8 +5,8 @@ package repo import ( + "fmt" "io" - "path" "code.gitea.io/git" @@ -22,14 +22,16 @@ func ServeData(ctx *context.Context, name string, reader io.Reader) error { buf = buf[:n] } - if !base.IsTextFile(buf) { - if !base.IsImageFile(buf) { - ctx.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+path.Base(ctx.Repo.TreePath)+"\"") - ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary") - } - } else if !ctx.QueryBool("render") { + ctx.Resp.Header().Set("Cache-Control", "public,max-age=86400") + + if base.IsTextFile(buf) || ctx.QueryBool("render") { ctx.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8") + } else if base.IsImageFile(buf) || base.IsPDFFile(buf) { + ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name)) + } else { + ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name)) } + ctx.Resp.Write(buf) _, err := io.Copy(ctx.Resp, reader) return err From d647d02c2f9816effd50b2eea45aa65fb1b4047c Mon Sep 17 00:00:00 2001 From: Andrey Nering Date: Sat, 26 Nov 2016 11:26:03 -0200 Subject: [PATCH 053/135] Fix Chrome not liking commas --- routers/repo/download.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/routers/repo/download.go b/routers/repo/download.go index aba0971a4a..85e9fc64c9 100644 --- a/routers/repo/download.go +++ b/routers/repo/download.go @@ -7,6 +7,7 @@ package repo import ( "fmt" "io" + "strings" "code.gitea.io/git" @@ -24,6 +25,9 @@ func ServeData(ctx *context.Context, name string, reader io.Reader) error { ctx.Resp.Header().Set("Cache-Control", "public,max-age=86400") + // Google Chrome dislike commas in filenames, so let's change it to a space + name = strings.Replace(name, ",", " ", -1) + if base.IsTextFile(buf) || ctx.QueryBool("render") { ctx.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8") } else if base.IsImageFile(buf) || base.IsPDFFile(buf) { From 4cb21115dc5e2cdb3ad7b28ffcb0ebe486ff4ee8 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Sat, 19 Nov 2016 21:40:13 -0500 Subject: [PATCH 054/135] Update locales and add Swedish Signed-off-by: Andrey Nering --- README.md | 2 +- conf/app.ini | 6 +- conf/locale/locale_cs-CZ.ini | 146 ++--- conf/locale/locale_de-DE.ini | 26 +- conf/locale/locale_es-ES.ini | 120 ++-- conf/locale/locale_fr-FR.ini | 28 +- conf/locale/locale_it-IT.ini | 44 +- conf/locale/locale_ja-JP.ini | 44 +- conf/locale/locale_lv-LV.ini | 146 ++--- conf/locale/locale_nl-NL.ini | 30 +- conf/locale/locale_pl-PL.ini | 24 +- conf/locale/locale_pt-BR.ini | 644 +++++++++--------- conf/locale/locale_ru-RU.ini | 42 +- conf/locale/locale_sv-SE.ini | 1200 ++++++++++++++++++++++++++++++++++ conf/locale/locale_tr-TR.ini | 12 +- conf/locale/locale_zh-TW.ini | 54 +- 16 files changed, 1885 insertions(+), 683 deletions(-) create mode 100644 conf/locale/locale_sv-SE.ini diff --git a/README.md b/README.md index 5ee2aec120..414d7e23f0 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ The goal of this project is to make the easiest, fastest, and most painless way - Mail service - Administration panel - Supports MySQL, PostgreSQL, SQLite3 and [TiDB](https://github.com/pingcap/tidb) (experimental) -- Multi-language support ([19 languages](https://crowdin.com/project/gogs)) +- Multi-language support ([20 languages](https://crowdin.com/project/gogs)) ## System Requirements diff --git a/conf/app.ini b/conf/app.ini index 0533d0326f..dfc8ae20fc 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -400,8 +400,8 @@ DEFAULT_INTERVAL = 8 MAX_RESPONSE_ITEMS = 50 [i18n] -LANGS = en-US,zh-CN,zh-HK,zh-TW,de-DE,fr-FR,nl-NL,lv-LV,ru-RU,ja-JP,es-ES,pt-BR,pl-PL,bg-BG,it-IT,fi-FI,tr-TR,cs-CZ,sr-SP -NAMES = English,简体中文,繁體中文(香港),繁體中文(台湾),Deutsch,Français,Nederlands,Latviešu,Русский,日本語,Español,Português do Brasil,Polski,български,Italiano,Suomalainen,Türkçe,čeština,Српски +LANGS = en-US,zh-CN,zh-HK,zh-TW,de-DE,fr-FR,nl-NL,lv-LV,ru-RU,ja-JP,es-ES,pt-BR,pl-PL,bg-BG,it-IT,fi-FI,tr-TR,cs-CZ,sr-SP,sv-SE +NAMES = English,简体中文,繁體中文(香港),繁體中文(台湾),Deutsch,Français,Nederlands,Latviešu,Русский,日本語,Español,Português do Brasil,Polski,български,Italiano,Suomalainen,Türkçe,čeština,Српски,Svenska ; Used for datetimepicker [i18n.datelang] @@ -423,6 +423,8 @@ it-IT = it fi-FI = fi tr-TR = tr cs-CZ = cs-CZ +sr-SP = sr +sv-SE = sv ; Extension mapping to highlight class ; e.g. .toml=ini diff --git a/conf/locale/locale_cs-CZ.ini b/conf/locale/locale_cs-CZ.ini index 542cb744c8..e150a66f7c 100644 --- a/conf/locale/locale_cs-CZ.ini +++ b/conf/locale/locale_cs-CZ.ini @@ -126,7 +126,7 @@ uname_holder=Uživatelské jméno nebo e-mailová adresa password_holder=Heslo switch_dashboard_context=Přepnout kontext přehledu my_repos=Mé repositáře -show_more_repos=Show more repositories... +show_more_repos=Zobrazit více repositářů... collaborative_repos=Společné repositáře my_orgs=Mé organizace my_mirrors=Má zrcadla @@ -151,7 +151,7 @@ forget_password=Zapomněli jste heslo? sign_up_now=Potřebujete účet? Zaregistrujte se. confirmation_mail_sent_prompt=Nový potvrzovací e-mail byl zaslán na %s, prosíme, zkontrolujte si vaši doručenou poštu během následující %d hodin pro dokončení registračního procesu. active_your_account=Aktivujte si váš účet -prohibit_login=Login Prohibited +prohibit_login=Přihlášení zakázáno prohibit_login_desc=Vašemu účtu je zakázáno se přihlásit, kontaktujte prosím správce webu. resent_limit_prompt=Omlouváme se, ale před chvílí jste požádal o aktivační e-mail. Prosíme, počkejte 3 minuty a pak to zkuste znovu. has_unconfirmed_mail=Zdravím, %s, máte nepotvrzenou e-mailovou adresu (%s). Pokud jste nedostali e-mail pro potvrzení nebo potřebujete zaslat nový, klikněte prosím na tlačítku níže. @@ -190,11 +190,11 @@ AuthName=Název ověření AdminEmail=E-mailová adresa správce NewBranchName=Název nové větve -CommitSummary=Commit summary -CommitMessage=Commit message -CommitChoice=Commit choice +CommitSummary=Shrnutí revize +CommitMessage=Zpráva revize +CommitChoice=Výběr revize TreeName=Cesta k souboru -Content=Content +Content=Obsah require_error=` nemůže být prázdný.` alpha_dash_error=` musí být pouze písmena, číslice či znaky - a _ .` @@ -232,7 +232,7 @@ org_still_own_repo=Tato organizace stále vlastní repositáře, musíte je nejd target_branch_not_exist=Cílová větev neexistuje. [user] -change_avatar=Change your avatar +change_avatar=Změnit vaši uživatelskou ikonu join_on=Připojil se dne repositories=Repositáře activity=Veřejná aktivita @@ -248,7 +248,7 @@ form.name_pattern_not_allowed=Vzor uživatelského jména '%s' není povolen. [settings] profile=Profil password=Heslo -avatar=Avatar +avatar=Uživatelská ikona ssh_keys=Klíče SSH social=Sociální účty applications=Aplikace @@ -269,7 +269,7 @@ change_username_prompt=Tato změna ovlivní vztah odkazů k vašemu účtu. continue=Pokračovat cancel=Zrušit -lookup_avatar_by_mail=Vyhledávat Avatar podle emailu +lookup_avatar_by_mail=Vyhledávat uživatelskou ikonu podle emailu federated_avatar_lookup=Federated Avatar Lookup enable_custom_avatar=Povolit uživatelskou ikonu uživatele choose_new_avatar=Vybrat novou ikonu uživatele @@ -357,7 +357,7 @@ fork_from=Rozštěpit z fork_visiblity_helper=Nemůžete změnit viditelnost repositáře rozštěpení. repo_desc=Popis repo_lang=Jazyk -repo_gitignore_helper=Select .gitignore templates +repo_gitignore_helper=Vyberte šablony .gitignore license=Licence license_helper=Vyberte licenční soubor readme=Soubor README @@ -365,12 +365,12 @@ readme_helper=Vyberte šablonu souboru README auto_init=Inicializovat tento repositář s vybranými soubory a šablonou create_repo=Vytvořit repositář default_branch=Výchozí větev -mirror_prune=Prune +mirror_prune=Vyčistit mirror_prune_desc=Remove any remote-tracking references that no longer exist on the remote mirror_interval=Odstup zrcadlení (hodina) mirror_address=Adresa zrcadla mirror_address_desc=Prosím, přidejte do adresy potřebné přihlašovací údaje. -mirror_last_synced=Last Synced +mirror_last_synced=Naposledy synchronizováno watchers=Sledující stargazers=Sledující forks=Rozštěpení @@ -427,33 +427,33 @@ file_view_raw=Zobrazit v surovém stavu file_permalink=Trvalý odkaz file_too_large=Tento soubor je příliš velký pro zobrazení -editor.new_file=New file -editor.upload_file=Upload file -editor.edit_file=Edit file -editor.preview_changes=Preview Changes +editor.new_file=Nový soubor +editor.upload_file=Nahrát soubor +editor.edit_file=Upravit soubor +editor.preview_changes=Náhled změn editor.cannot_edit_non_text_files=Netextové soubory není možné upravovat -editor.edit_this_file=Edit this file -editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file -editor.fork_before_edit=You must fork this repository before editing the file +editor.edit_this_file=Upravit tento soubor +editor.must_be_on_a_branch=Musíte mít zvolenu větev pro úpravu či návrh změn tohoto souboru +editor.fork_before_edit=Musíte provést rozvětvení repositáře před úpravou souboru editor.delete_this_file=Odstranit tento soubor editor.must_have_write_access=Musíte mít přístup pro zápis pro dělání či navrhování změn tohoto souboru editor.file_delete_success=Soubor '%s' byl úspěšně odstraněn! -editor.name_your_file=Name your file... +editor.name_your_file=Pojmenujte váš soubor... editor.filename_help=To add directory, just type it and press /. To remove a directory, go to the beginning of the field and press backspace. editor.or=nebo -editor.cancel_lower=cancel -editor.commit_changes=Commit Changes -editor.add_tmpl=Add '%s/' -editor.add=Add '%s' +editor.cancel_lower=zrušit +editor.commit_changes=Uložit změny revize +editor.add_tmpl=Přidat '%s/' +editor.add=Přidat '%s' editor.update=Aktualizovat "%s" -editor.delete=Delete '%s' -editor.commit_message_desc=Add an optional extended description... -editor.commit_directly_to_this_branch=Commit directly to the %s branch. -editor.create_new_branch=Create a new branch for this commit and start a pull request. +editor.delete=Smazat '%s' +editor.commit_message_desc=Přidat dobrovolný rozšířený popis... +editor.commit_directly_to_this_branch=Uložte změny revize přímo do větve %s. +editor.create_new_branch=Vytvořit novou větev pro tuto revizi a spustit požadavek na stažení. editor.new_branch_name_desc=Nový název větve... editor.cancel=Zrušit -editor.filename_cannot_be_empty=Filename cannot be empty. -editor.branch_already_exists=Branch '%s' already exists in this repository. +editor.filename_cannot_be_empty=Název souboru nemůže být prázdný. +editor.branch_already_exists=Repositář větev '%s' již obsahuje. editor.directory_is_a_file=Entry '%s' in the parent path is a file not a directory in this repository. editor.filename_is_a_directory=The filename '%s' is an existing directory in this repository. editor.file_editing_no_longer_exists=The file '%s' you are editing no longer exists in the repository. @@ -461,9 +461,9 @@ editor.file_changed_while_editing=Obsah souboru se změnil od začátku úprav. editor.file_already_exists=A file with name '%s' already exists in this repository. editor.no_changes_to_show=There are no changes to show. editor.fail_to_update_file=Failed to update/create file '%s' with error: %v -editor.add_subdir=Add subdirectory... -editor.unable_to_upload_files=Failed to upload files to '%s' with error: %v -editor.upload_files_to_dir=Upload files to '%s' +editor.add_subdir=Přidat podadresář... +editor.unable_to_upload_files=Nepodařilo se nahrát soubor '%s'. Chyba: %v +editor.upload_files_to_dir=Nahrát soubory do '%s' commits.commits=Revize commits.search=Hledání revizí @@ -490,11 +490,11 @@ issues.create=Vytvořit úkol issues.new_label=Nový štítek issues.new_label_placeholder=Název štítku... issues.create_label=Vytvořit štítek -issues.label_templates.title=Load a predefined set of labels -issues.label_templates.info=There aren’t any labels yet. You can click on the "New Label" button above to create one or use a predefined set below. -issues.label_templates.helper=Select a label set -issues.label_templates.use=Use this label set -issues.label_templates.fail_to_load_file=Failed to load label template file '%s': %v +issues.label_templates.title=Nahrát předdefinovanou sadu značek +issues.label_templates.info=Nejsou zadány žádné značky. Pro vytvoření nové klikněte na tlačítko Nová značka nebo použijte předdefinovanou sadu. +issues.label_templates.helper=Vyberte sadu značek +issues.label_templates.use=Použít tuto sadu značek +issues.label_templates.fail_to_load_file=Nepodařilo se nahrát soubor šablony značek '%s': %v issues.open_tab=%d otevřených issues.close_tab=%d zavřených issues.filter_label=Štítek @@ -522,8 +522,8 @@ issues.next=Další issues.open_title=otevřený issues.closed_title=zavřený issues.num_comments=%d komentářů -issues.commented_at=`commented %s` -issues.delete_comment_confirm=Are you sure you want to delete this comment? +issues.commented_at=`okomentoval %s` +issues.delete_comment_confirm=Jste si jist, že chcete smazat tento komentář? issues.no_content=Není zde žádný obsah. issues.close_issue=Zavřít issues.close_comment_issue=Okomentovat a zavřít @@ -536,7 +536,7 @@ issues.commit_ref_at=`odkázal na tento úkol z revize Sign in to join this conversation. +issues.sign_in_require_desc=Přihlašte se pro zapojení do konverzace. issues.edit=Upravit issues.cancel=Zrušit issues.save=Uložit @@ -551,8 +551,8 @@ issues.label_deletion=Smazání štítku issues.label_deletion_desc=Smazání tohoto štítku jej smaže také ze všech návazných úkolech. Chcete pokračovat? issues.label_deletion_success=Štítek byl úspěšně smazán! issues.num_participants=%d účastníků -issues.attachment.open_tab=`Click to see "%s" in a new tab` -issues.attachment.download=`Click to download "%s"` +issues.attachment.open_tab=`Klikněte pro zobrazení "%s" v nové záložce` +issues.attachment.download=`Klikněte pro stažení "%s"` pulls.new=Nový požadavek na natažení pulls.compare_changes=Porovnat změny @@ -625,32 +625,32 @@ wiki.last_updated=Naposledy aktualizováno: %s settings=Nastavení settings.options=Možnosti settings.collaboration=Spolupráce -settings.collaboration.admin=Admin -settings.collaboration.write=Write -settings.collaboration.read=Read -settings.collaboration.undefined=Undefined +settings.collaboration.admin=Správce +settings.collaboration.write=Zápis +settings.collaboration.read=Čtení +settings.collaboration.undefined=Neurčeno settings.hooks=Webové háčky settings.githooks=Háčky Gitu settings.basic_settings=Základní nastavení -settings.mirror_settings=Mirror Settings -settings.sync_mirror=Sync Now -settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute. +settings.mirror_settings=Nastavení zrcadla +settings.sync_mirror=Provést synchronizaci +settings.mirror_sync_in_progress=Synchronizace zrcadel probíhá, prosím načtěte znovu stránku přibližně za minutu. settings.site=Oficiální stránky settings.update_settings=Změnit nastavení settings.change_reponame_prompt=Tato změna ovlivní vztah odkazů k repositáři. settings.advanced_settings=Pokročilá nastavení -settings.wiki_desc=Enable wiki system -settings.use_internal_wiki=Use builtin wiki +settings.wiki_desc=Povolit systém Wiki +settings.use_internal_wiki=Použít vestavěný systém Wiki settings.use_external_wiki=Používat externí Wiki settings.external_wiki_url=URL externí Wiki settings.external_wiki_url_desc=Návštěvníci budou při kliknutí na záložku přesměrování na tuto URL. -settings.issues_desc=Enable issue tracker -settings.use_internal_issue_tracker=Use builtin lightweight issue tracker +settings.issues_desc=Povolit systém úkolů +settings.use_internal_issue_tracker=Povolit věstavěný odlehčený systém úkolů settings.use_external_issue_tracker=Použít externí systém úkolů settings.tracker_url_format=Formát URL externího systému úkolů -settings.tracker_issue_style=External Issue Tracker Naming Style: -settings.tracker_issue_style.numeric=Numeric -settings.tracker_issue_style.alphanumeric=Alphanumeric +settings.tracker_issue_style=Styl pojmenování externího systému úkolů: +settings.tracker_issue_style.numeric=Číselný +settings.tracker_issue_style.alphanumeric=Alfanumerický settings.tracker_url_format_desc=Můžete použít zástupné výrazy {user} {repo} {index} pro uživatelské jméno, název repositáře a index úkolu. settings.pulls_desc=Povolit požadavky na stažení, aby veřejné příspěvky mohly být akceptovány settings.danger_zone=Nebezpečná zóna @@ -720,7 +720,7 @@ settings.event_send_everything=Potřebuji vše. settings.event_choose=Nech mne vybrat, co potřebuji. settings.event_create=Vytvořit settings.event_create_desc=Větev nebo značka byla vytvořena -settings.event_pull_request=Pull Request +settings.event_pull_request=Požadavek na stažení settings.event_pull_request_desc=Pull request opened, closed, reopened, edited, assigned, unassigned, label updated, label cleared, or synchronized. settings.event_push=Nahrát settings.event_push_desc=Nahrání pomocí Gitu do repositáře @@ -760,7 +760,7 @@ diff.stats_desc= %d změnil soubory, kde provedl %d př diff.bin=binární diff.view_file=Zobrazit soubor diff.file_suppressed=File diff suppressed because it is too large -diff.too_many_files=Some files were not shown because too many files changed in this diff +diff.too_many_files=Některé soubory nejsou zobrazny, neboť je v této revizi změněno mnoho souborů release.releases=Vydání release.new_release=Nové vydání @@ -791,7 +791,7 @@ release.deletion=Smazání vydání release.deletion_desc=Smazáním tohoto vydání se také smaže odpovídající značka. Chcete pokračovat? release.deletion_success=Vydání bylo úspěšně smazáno! release.tag_name_already_exist=Vydání s touto značkou již existuje. -release.tag_name_invalid=Tag name is not valid. +release.tag_name_invalid=Název štítku není platný. release.downloads=Soubory ke stažení [org] @@ -959,7 +959,7 @@ users.edit_account=Upravit účet users.max_repo_creation=Limit počtu vytvořených repositářů users.max_repo_creation_desc=(Nastavte na -1 pro použití výchozího systémového limitu) users.is_activated=Tento účet je aktivován -users.prohibit_login=This account is prohibited to login +users.prohibit_login=Tento účet má zakázáno přihlášení users.is_admin=Tento účet je správce users.allow_git_hook=Tento účet má právo vytváře háčky Gitu users.allow_import_local=Tento účet má právo importovat místní repositáře @@ -990,7 +990,7 @@ auths.enabled=Povolený auths.updated=Upravený auths.auth_type=Typ ověření auths.auth_name=Název ověření -auths.security_protocol=Security Protocol +auths.security_protocol=Protokol zabezpečení auths.domain=Doména auths.host=Server auths.port=Port @@ -1115,17 +1115,17 @@ config.picture_service=Služba ikon uživatelů config.disable_gravatar=Zakázat službu Gravatar config.enable_federated_avatar=Enable Federated Avatars -config.git_config=Git Configuration -config.git_disable_diff_highlight=Disable Diff Syntax Highlight -config.git_max_diff_lines=Max Diff Lines (for a single file) -config.git_max_diff_line_characters=Max Diff Characters (for a single line) -config.git_max_diff_files=Max Diff Files (to be shown) -config.git_gc_args=GC Arguments -config.git_migrate_timeout=Migration Timeout -config.git_mirror_timeout=Mirror Update Timeout -config.git_clone_timeout=Clone Operation Timeout -config.git_pull_timeout=Pull Operation Timeout -config.git_gc_timeout=GC Operation Timeout +config.git_config=Konfigurace Gitu +config.git_disable_diff_highlight=Zakázat zvýraznění syntaxe v rozdílovém zobrazení +config.git_max_diff_lines=Maximální počet rozdílových řádků jednoho souboru +config.git_max_diff_line_characters=Maximální počet zobrazených rozdílových znaků +config.git_max_diff_files=Maximální počet zobrazených rozdílových souborů +config.git_gc_args=Parametry GC +config.git_migrate_timeout=Časový limit migrace +config.git_mirror_timeout=Časový limit aktualizace zrcadla +config.git_clone_timeout=Časový limit operace naklonování +config.git_pull_timeout=Časový limit operace stažení +config.git_gc_timeout=Časový limit operace GC config.log_config=Nastavení logů config.log_mode=Způsob logování diff --git a/conf/locale/locale_de-DE.ini b/conf/locale/locale_de-DE.ini index 8366996723..c255060c79 100644 --- a/conf/locale/locale_de-DE.ini +++ b/conf/locale/locale_de-DE.ini @@ -432,31 +432,31 @@ editor.upload_file=Datei hochladen editor.edit_file=Datei bearbeiten editor.preview_changes=Vorschau der Änderungen editor.cannot_edit_non_text_files=Nicht-Text Dateien können nicht bearbeitet werden -editor.edit_this_file=Diese Datei bearbeiten -editor.must_be_on_a_branch=Du musst dich in einer Branch befinden um Änderungen an dieser Datei vorzuschlagen oder vorzunehmen -editor.fork_before_edit=Um die Datei zu bearbeiten müssen Sie das Repository forken -editor.delete_this_file=Diese Datei löschen -editor.must_have_write_access=Du musst Schreibzugriff haben um Änderungen an dieser Datei vorzuschlagen oder vorzunehmen +editor.edit_this_file=Datei bearbeiten +editor.must_be_on_a_branch=Sie müssen sich in einem Branch befinden, um Änderungen an dieser Datei vorzuschlagen oder vorzunehmen +editor.fork_before_edit=Um die Datei zu bearbeiten, müssen Sie das Repository forken +editor.delete_this_file=Datei löschen +editor.must_have_write_access=Du musst Schreibzugriff haben, um Änderungen an dieser Datei vorzuschlagen oder vorzunehmen editor.file_delete_success=Die Datei '%s' wurde erfolgreich gelöscht! editor.name_your_file=Dateinamen eingeben... editor.filename_help=Um einen Ordner hinzuzufügen, gib den Namen ein und drücke /. Um einen Ordner zu entfernen, gehe zum Anfang des Feldes und drücke auf die Rücktaste. editor.or=oder editor.cancel_lower=abbrechen -editor.commit_changes=Änderungen im Commit +editor.commit_changes=Änderungen einchecken editor.add_tmpl=Hinzufügen von '%s/' editor.add='%s' hinzufügen editor.update='%s' ändern editor.delete='%s' löschen -editor.commit_message_desc=Eine optionale, erweiterte Commit Beschreibung... -editor.commit_directly_to_this_branch=Änderungen direkt dem Branch %s hinzufügen. -editor.create_new_branch=Erstellen Sie einen neuen Branch für diesen Commit und starten Sie einen Pull Request. +editor.commit_message_desc=Eine ausführlichere Beschreibung kann hinzugefügt werden... +editor.commit_directly_to_this_branch=Direkt in den %s Branch einchecken. +editor.create_new_branch=Einen neuen Branch für diesen Commit erstellen und einen Pull Request starten. editor.new_branch_name_desc=Neuer Branch Name... editor.cancel=Abbrechen editor.filename_cannot_be_empty=Der Dateiname darf nicht leer sein. editor.branch_already_exists=Branch '%s' existiert bereits in diesem Repository. editor.directory_is_a_file='%s' im übergeordneten Verzeichnis ist eine Datei und kein Verzeichnis. editor.filename_is_a_directory=Die Datei '%s' existiert bereits als Verzeichnis in diesem Repository. -editor.file_editing_no_longer_exists=Die Datei '%s' welche Sie bearbeiten existiert in diesem Repository nicht mehr. +editor.file_editing_no_longer_exists=Die Datei '%s', welche Sie bearbeiten, existiert in diesem Repository nicht mehr. editor.file_changed_while_editing=Seit dem Start der Bearbeitung hat sich die Datei geändert. Hier klicken um die Änderungen zu sehen, oder nochmals Commit drücken um die Änderungen zu überschreiben. editor.file_already_exists=Eine Datei mit dem Namen '%s' existiert bereits in diesem Repository. editor.no_changes_to_show=Keine Änderungen vorhanden. @@ -536,7 +536,7 @@ issues.commit_ref_at=`hat dieses Issue %[2]s aus issues.poster=Ersteller issues.collaborator=Mitarbeiter issues.owner=Besitzer -issues.sign_in_require_desc=Anmelden um an der Diskussion teilzunehmen. +issues.sign_in_require_desc=Anmelden, um an der Diskussion teilzunehmen. issues.edit=Bearbeiten issues.cancel=Abbrechen issues.save=Speichern @@ -720,8 +720,8 @@ settings.event_send_everything=Ich brauche alles. settings.event_choose=Lass mich auswählen, was ich brauche. settings.event_create=Erstellen settings.event_create_desc=Branch/Tag erstellt -settings.event_pull_request=Pull Request -settings.event_pull_request_desc=Pull-Request geöffnet, geschlossen, wieder geöffnet, bearbeitet, nicht zugewiesen, Label aktualisiert, Label gelöscht oder nicht synchronisiert. +settings.event_pull_request=Pull-Request +settings.event_pull_request_desc=Pull-Request geöffnet, geschlossen, wieder geöffnet, bearbeitet, zugewiesen, nicht zugewiesen, Label aktualisiert, Label gelöscht oder synchronisiert. settings.event_push=Push settings.event_push_desc=Git push auf ein Repository settings.active=Aktiv diff --git a/conf/locale/locale_es-ES.ini b/conf/locale/locale_es-ES.ini index 150a737378..56a3a88aa2 100644 --- a/conf/locale/locale_es-ES.ini +++ b/conf/locale/locale_es-ES.ini @@ -25,7 +25,7 @@ captcha=Captcha repository=Repositorio organization=Organización -mirror=Mirror +mirror=Réplica new_repo=Nuevo repositorio new_migrate=Nueva migración new_mirror=Nueva réplica @@ -190,11 +190,11 @@ AuthName=Nombre de autorización AdminEmail=Correo electrónico del administrador NewBranchName=Nuevo nombre de rama -CommitSummary=Commit summary -CommitMessage=Commit message -CommitChoice=Commit choice -TreeName=File path -Content=Content +CommitSummary=Resumen del commit +CommitMessage=Mensaje de commit +CommitChoice=Hacer commit de la elección +TreeName=Ruta del archivo +Content=Contenido require_error=` no puede estar vacío.` alpha_dash_error=` los caracteres deben ser Alfanumericos o dash(-_).` @@ -370,7 +370,7 @@ mirror_prune_desc=Remover referencias remotas que no existan remotamente mirror_interval=Intervalo de la réplica (en horas) mirror_address=Dirección de la réplica mirror_address_desc=Por favor, incluya las credenciales de usuario necesarias en la dirección. -mirror_last_synced=Last Synced +mirror_last_synced=Última sincronización watchers=Seguidores stargazers=Fans forks=Forks @@ -428,45 +428,45 @@ file_permalink=Permalink file_too_large=Este archivo es demasiado grande para ser mostrado editor.new_file=Nuevo archivo -editor.upload_file=Upload file -editor.edit_file=Edit file -editor.preview_changes=Preview Changes -editor.cannot_edit_non_text_files=Cannot edit non-text files -editor.edit_this_file=Edit this file -editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file -editor.fork_before_edit=You must fork this repository before editing the file -editor.delete_this_file=Delete this file -editor.must_have_write_access=You must have write access to make or propose changes to this file -editor.file_delete_success=File '%s' has been deleted successfully! -editor.name_your_file=Name your file... -editor.filename_help=To add directory, just type it and press /. To remove a directory, go to the beginning of the field and press backspace. -editor.or=or -editor.cancel_lower=cancel -editor.commit_changes=Commit Changes -editor.add_tmpl=Add '%s/' -editor.add=Add '%s' -editor.update=Update '%s' -editor.delete=Delete '%s' -editor.commit_message_desc=Add an optional extended description... -editor.commit_directly_to_this_branch=Commit directly to the %s branch. -editor.create_new_branch=Create a new branch for this commit and start a pull request. -editor.new_branch_name_desc=New branch name... -editor.cancel=Cancel -editor.filename_cannot_be_empty=Filename cannot be empty. -editor.branch_already_exists=Branch '%s' already exists in this repository. -editor.directory_is_a_file=Entry '%s' in the parent path is a file not a directory in this repository. -editor.filename_is_a_directory=The filename '%s' is an existing directory in this repository. -editor.file_editing_no_longer_exists=The file '%s' you are editing no longer exists in the repository. -editor.file_changed_while_editing=File content has been changed since you started editing. Click here to see what have been changed or press commit again to overwrite those changes. -editor.file_already_exists=A file with name '%s' already exists in this repository. -editor.no_changes_to_show=There are no changes to show. -editor.fail_to_update_file=Failed to update/create file '%s' with error: %v -editor.add_subdir=Add subdirectory... -editor.unable_to_upload_files=Failed to upload files to '%s' with error: %v -editor.upload_files_to_dir=Upload files to '%s' +editor.upload_file=Subir archivo +editor.edit_file=Editar archivo +editor.preview_changes=Vista previa de los cambios +editor.cannot_edit_non_text_files=Sólo puede editar archivos de texto +editor.edit_this_file=Editar este archivo +editor.must_be_on_a_branch=Debes estar en una rama para hacer o proponer cambios en este archivo +editor.fork_before_edit=Debes hacer un fork de este repositorio antes de editar el archivo +editor.delete_this_file=Eliminar este archivo +editor.must_have_write_access=Debes tener permisos de escritura para hacer o proponer cambios a este archivo +editor.file_delete_success=¡El archivo '%s' ha sido eliminado con éxito! +editor.name_your_file=Nombre de archivo... +editor.filename_help=Para añadir un directorio, simplemente escribelo y presiona /. Para eliminar un directorio, ve al principio del campo y presiona retroceso. +editor.or=o +editor.cancel_lower=cancelar +editor.commit_changes=Hacer commit de los cambios +editor.add_tmpl=Añadir '%s' +editor.add=Añadir '%s' +editor.update=Actualizar '%s' +editor.delete=Eliminar '%s' +editor.commit_message_desc=Añadir una descripción extendida opcional... +editor.commit_directly_to_this_branch=Hacer commit directamente en la rama %s. +editor.create_new_branch=Crear una nueva rama para este commit y hacer un pull request. +editor.new_branch_name_desc=Nombre de la rama nueva... +editor.cancel=Cancelar +editor.filename_cannot_be_empty=El nombre del archivo no puede estar vacío. +editor.branch_already_exists=La rama '%s' ya existe en este repositorio. +editor.directory_is_a_file=La entrada '%s' en el directorio padre es un archivo no un directorio en este repositorio. +editor.filename_is_a_directory=El nombre del fichero '%s' es un directorio existente en este repositorio. +editor.file_editing_no_longer_exists=El archivo '%s' que estás editando ya no existe en este repositorio. +editor.file_changed_while_editing=El contenido del archivo ha sido modificado desde que empezó a editarlo. Clic aquí para ver qué ha sido modificado o presiona confirmar de nuevo para sobrescribir estos cambios. +editor.file_already_exists=Ya existe un archivo con nombre '%s' en este repositorio. +editor.no_changes_to_show=No existen cambios para mostrar. +editor.fail_to_update_file=Error al actualizar/crear el archivo '%s', error: %v +editor.add_subdir=Añadir subdirectorio... +editor.unable_to_upload_files=Error al subir archivos a '%s', error: %v +editor.upload_files_to_dir=Subir archivos a '%s' commits.commits=Commits -commits.search=Buscar Commits +commits.search=Buscar commits commits.find=Buscar commits.author=Autor commits.message=Mensaje @@ -490,11 +490,11 @@ issues.create=Crear incidencia issues.new_label=Nueva Etiqueta issues.new_label_placeholder=Nombre etiqueta... issues.create_label=Crear etiqueta -issues.label_templates.title=Load a predefined set of labels -issues.label_templates.info=There aren’t any labels yet. You can click on the "New Label" button above to create one or use a predefined set below. -issues.label_templates.helper=Select a label set -issues.label_templates.use=Use this label set -issues.label_templates.fail_to_load_file=Failed to load label template file '%s': %v +issues.label_templates.title=Carga un conjunto predefinido de etiquetas +issues.label_templates.info=Tdavía no hay ninguna etiqueta. Puede hacer clic en el botón "Nueva etiqueta" para crear una o utilizar un conjunto predefinido abajo. +issues.label_templates.helper=Seleccionar un conjunto de etiquetas +issues.label_templates.use=Usar este conjunto de etiquetas +issues.label_templates.fail_to_load_file=Error al cargar el archivo de plantilla de etiqueta '%s': %v issues.open_tab=%d abiertas issues.close_tab=%d cerradas issues.filter_label=Etiqueta @@ -536,7 +536,7 @@ issues.commit_ref_at=`mencionada esta incidencia en un commit Sign in to join this conversation. +issues.sign_in_require_desc= Inicie sesión para unirse a esta conversación. issues.edit=Editar issues.cancel=Cancelar issues.save=Guardar @@ -551,8 +551,8 @@ issues.label_deletion=Borrado de Etiqueta issues.label_deletion_desc=Al borrar la etiqueta su información será eliminada de todas las incidencias relacionadas. Desea continuar? issues.label_deletion_success=Etiqueta borrada con éxito! issues.num_participants=%d participantes -issues.attachment.open_tab=`Click to see "%s" in a new tab` -issues.attachment.download=`Click to download "%s"` +issues.attachment.open_tab='Haga clic para ver "%s" en una pestaña nueva' +issues.attachment.download=`Haga clic para descargar "%s"` pulls.new=Nuevo Pull Request pulls.compare_changes=Comparar cambios @@ -570,8 +570,8 @@ pulls.tab_conversation=Conversación pulls.tab_commits=Commits pulls.tab_files=Archivos modificados pulls.reopen_to_merge=Por favor reabra este Pull Request para proceder con la operación de fusionado. -pulls.merged=Fuisionado -pulls.has_merged=¡Este pull request se ha completado con éxito! +pulls.merged=Fusionado +pulls.has_merged=¡Este Pull Request se ha completado con éxito! pulls.data_broken=Los datos de este pull request ya no están disponibles porque se ha eliminado la información del fork. pulls.is_checking=Se está procediendo a la búsqueda de conflictos, por favor actualice la página en unos momentos. pulls.can_auto_merge_desc=Este Pull Request puede ser fusionado automáticamente. @@ -632,9 +632,9 @@ settings.collaboration.undefined=Indefinido settings.hooks=Webhooks settings.githooks=Git Hooks settings.basic_settings=Configuración Básica -settings.mirror_settings=Mirror Settings -settings.sync_mirror=Sync Now -settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute. +settings.mirror_settings=Configuración de réplica +settings.sync_mirror=Sincronizar ahora +settings.mirror_sync_in_progress=Sincronización de réplica en curso, por favor actualice la página en unos minutos. settings.site=Sitio oficial settings.update_settings=Actualizar configuración settings.change_reponame_prompt=Este cambio afectará a los enlaces al repositorio. @@ -721,7 +721,7 @@ settings.event_choose=Déjeme elegir lo que necesito. settings.event_create=Crear settings.event_create_desc=Rama o etiqueta creada settings.event_pull_request=Pull Request -settings.event_pull_request_desc=Pull request opened, closed, reopened, edited, assigned, unassigned, label updated, label cleared, or synchronized. +settings.event_pull_request_desc=Pull request, abierta, cerrada, reabierta, editada, asignada, desasignada, con etiqueta actualizada, con etiqueta eliminada, o sincronizada. settings.event_push=Push settings.event_push_desc=Git push a un repositorio settings.active=Activo @@ -1122,7 +1122,7 @@ config.git_max_diff_line_characters=Carácteres de Diff máximos (para una sola config.git_max_diff_files=Máximo de archivos de Diff (que se mostrarán) config.git_gc_args=Argumentos de GC config.git_migrate_timeout=Tiempo de espera de migración -config.git_mirror_timeout=Tiempo de espera de actualización de espejos +config.git_mirror_timeout=Tiempo de espera de actualización de réplicas config.git_clone_timeout=Tiempo de espera de operación de clones config.git_pull_timeout=Tiempo de espera de operación de pull config.git_gc_timeout=Tiempo de espera de operación de GC @@ -1188,7 +1188,7 @@ hours=%[2]s %[1]d horas days=%[2]s %[1]d días weeks=%[2]s %[1]d semanas months=%[2]s %[1]d meses -years=%s %d años +years=%[2]s %[1]d años raw_seconds=segundos raw_minutes=minutos diff --git a/conf/locale/locale_fr-FR.ini b/conf/locale/locale_fr-FR.ini index 31f35cfa50..e1f542aae1 100644 --- a/conf/locale/locale_fr-FR.ini +++ b/conf/locale/locale_fr-FR.ini @@ -115,16 +115,16 @@ test_git_failed=Le test de la commande "git" a échoué : %v sqlite3_not_available=Votre version publiée ne prend pas en charge SQLite3. Veuillez télécharger la version binaire officielle à cette adresse %s. invalid_db_setting=Paramètres de base de données incorrects : %v invalid_repo_path=Chemin vers la racine du dépôt invalide : %v -run_user_not_match=L'utilisateur entré n'est pas l'utilisateur actuel : %s -> %s +run_user_not_match=L'utilisateur d'exécution saisi n'est pas l'utilisateur d'exécution actuel : %s -> %s save_config_failed=La sauvegarde de la configuration a échoué : %v invalid_admin_setting=Paramètres du compte administrateur invalides : %v install_success=Bienvenue ! Nous sommes heureux que vous ayez choisi Gitea, amusez-vous et prenez soin de vous. -invalid_log_root_path=Le chemin principal des fichiers logs est invalide: %v +invalid_log_root_path=L'emplacement racine des fichiers logs est invalide : %v [home] uname_holder=Nom d'utilisateur ou e-mail password_holder=Mot de passe -switch_dashboard_context=Basculer le Contexte du Tableau de Bord +switch_dashboard_context=Basculer le contexte du tableau de bord my_repos=Mes dépôts show_more_repos=Afficher plus de dépôts... collaborative_repos=Dépôts collaboratifs @@ -144,7 +144,7 @@ create_new_account=Créer un nouveau compte register_hepler_msg=Déjà enregistré ? Connectez-vous ! social_register_hepler_msg=Déjà enregistré ? Associez-le ! disable_register_prompt=Désolé, les enregistrements ont été désactivés. Veuillez contacter l'administrateur du site. -disable_register_mail=Désolé, la Confirmation par Mail des Enregistrements a été désactivée. +disable_register_mail=Désolé, la confirmation par e-mail des enregistrements a été désactivée. remember_me=Se souvenir de moi forgot_password=Mot de passe oublié forget_password=Mot de passe oublié ? @@ -162,13 +162,13 @@ reset_password=Réinitialiser le mot de passe invalid_code=Désolé, votre code de confirmation est invalide ou a expiré. reset_password_helper=Cliquez ici pour réinitialiser votre mot de passe password_too_short=Le mot de passe doit contenir 6 caractères minimum. -non_local_account=Les comptes non-locaux ne peuvent pas changer leur mot de passe via Gitea. +non_local_account=Les comptes non locaux ne peuvent pas changer leur mot de passe via Gitea. [mail] activate_account=Veuillez activer votre compte activate_email=Veuillez vérifier votre adresse e-mail reset_password=Réinitialiser votre mot de passe -register_success=Succès de l'enregistrement, Bienvenue +register_success=Inscription réussie, bienvenue register_notify=Bienvenue à bord [modal] @@ -179,13 +179,13 @@ modify=Modifier [form] UserName=Nom d'utilisateur RepoName=Nom du dépôt -Email=Adresse E-mail +Email=Adresse e-mail Password=Mot de passe Retype=Confirmez le mot de passe SSHTitle=Nom de la clé SSH HttpsUrl=URL HTTPS -PayloadUrl=URL des Données Utiles -TeamName=Nom d'équipe +PayloadUrl=URL des données utiles +TeamName=Nom de l'équipe AuthName=Nom d'autorisation AdminEmail=E-mail de l'administrateur @@ -196,9 +196,9 @@ CommitChoice=Choix de commit TreeName=Chemin du fichier Content=Contenu -require_error=` Ne peut être vide ` -alpha_dash_error=` doivent être des caractères alpha, numeriques ou console (-_) valides ` -alpha_dash_dot_error=` doivent être des caractères alpha, numeriques, console (-_) valides ou des points ` +require_error=` ne peut pas être vide.` +alpha_dash_error=` doivent être des caractères alpha, numériques ou tirets (-_) valides.` +alpha_dash_dot_error=` doivent être des caractères alpha, numériques, tirets (-_) valides ou des points.` size_error=` doit être à la taille de %s.` min_size_error=` %s caractères minimum ` max_size_error=` %s caractères maximum ` @@ -699,7 +699,7 @@ settings.webhook.test_delivery_desc=Envoyer un faux push pour tester la configur settings.webhook.test_delivery_success=Le webhook de test a été ajouté à la file d'attente de livraison. L'affichage dans l'historique de livraison peut prendre quelques secondes. settings.webhook.request=Requête settings.webhook.response=Réponse -settings.webhook.headers=Entêtes  +settings.webhook.headers=Entêtes settings.webhook.payload=Payload settings.webhook.body=Corps settings.githooks_desc=Les Hooks Git sont alimentés par Git lui même. Les Hooks compatibles sont modifiables dans la liste ci-dessous pour effectuer des opérations personnalisées. @@ -773,7 +773,7 @@ release.source_code=Code source release.new_subheader=Publier une version pour itérer sur le produit. release.edit_subheader=Un changelog détaillé peut aider les utilisateurs à comprendre ce qui a été amélioré. release.tag_name=Nom du tag -release.target=Cible  +release.target=Cible release.tag_helper=Choisissez un tag existant ou créez-en un nouveau à publier. release.title=Titre release.content=Contenu diff --git a/conf/locale/locale_it-IT.ini b/conf/locale/locale_it-IT.ini index 50705a9625..f6acda87d4 100644 --- a/conf/locale/locale_it-IT.ini +++ b/conf/locale/locale_it-IT.ini @@ -126,7 +126,7 @@ uname_holder=Nome Utente o E-mail password_holder=Password switch_dashboard_context=Cambia Dashboard Context my_repos=I miei Repository -show_more_repos=Show more repositories... +show_more_repos=Visualizza altre repositories... collaborative_repos=Repository Condivisi my_orgs=Le mie Organizzazioni my_mirrors=I miei Mirror @@ -151,8 +151,8 @@ forget_password=Password dimenticata? sign_up_now=Bisogno di un account? Iscriviti ora. confirmation_mail_sent_prompt=Una nuova email di conferma è stata inviata a %s, verifica la tua casella di posta entro le prossime %d ore per completare la registrazione. active_your_account=Attiva il tuo Account -prohibit_login=Login Prohibited -prohibit_login_desc=Your account is prohibited to login, please contact site admin. +prohibit_login=Accesso Vietato +prohibit_login_desc=Il tuo account è impossibilitato al login, contatta l'amministratore del sito. resent_limit_prompt=Siamo spiacenti, si stanno inviando e-mail di attivazione troppo spesso. Si prega di attendere 3 minuti. has_unconfirmed_mail=Ciao %s, hai un indirizzo di posta elettronica non confermato (%s). Se non hai ricevuto una e-mail di conferma o vuoi riceverla nuovamente, fare clic sul pulsante qui sotto. resend_mail=Clicca qui per inviare nuovamente l'e-mail di attivazione @@ -162,7 +162,7 @@ reset_password=Reimposta la tua Password invalid_code=Siamo spiacenti, il codice di conferma è scaduto o non valido. reset_password_helper=Clicca qui per reimpostare la password password_too_short=La lunghezza della password non può essere meno 6 caratteri. -non_local_account=Non-local accounts cannot change passwords through Gitea. +non_local_account=Gli account non locali non possono modificare le password tramite Gitea. [mail] activate_account=Per favore attiva il tuo account @@ -189,12 +189,12 @@ TeamName=Nome Team AuthName=Nome autorizzazione AdminEmail=Email dell'Admin -NewBranchName=New branch name -CommitSummary=Commit summary -CommitMessage=Commit message -CommitChoice=Commit choice -TreeName=File path -Content=Content +NewBranchName=Nuovo nome del branch +CommitSummary=Riepilogo dei commit +CommitMessage=Messaggio di commit +CommitChoice=Scelta di commit +TreeName=Percorso del file +Content=Contenuto require_error=` non può essere vuoto.` alpha_dash_error=` ammessi solo caratteri alfanumerici o trattini(-_).` @@ -232,7 +232,7 @@ org_still_own_repo=Questa organizzazione ha ancora la proprietà del repository, target_branch_not_exist=Il ramo (branch) di destinazione non esiste. [user] -change_avatar=Change your avatar +change_avatar=Cambia il tuo avatar join_on=Si è unito il repositories=Repository activity=Attività pubblica @@ -269,7 +269,7 @@ change_username_prompt=Questa modifica influenzerà il modo in cui i link si rif continue=Continua cancel=Annulla -lookup_avatar_by_mail=Lookup Avatar by mail +lookup_avatar_by_mail=Ricerca Avatar per mail federated_avatar_lookup=Federated Avatar Lookup enable_custom_avatar=Abilita avatar personalizzato choose_new_avatar=Scegli un nuovo avatar @@ -357,7 +357,7 @@ fork_from=Forka da fork_visiblity_helper=Non puoi cambiare la visibilità di un repository forkato. repo_desc=Descrizione repo_lang=Lingua -repo_gitignore_helper=Select .gitignore templates +repo_gitignore_helper=Seleziona i templates di .gitignore license=Licenza license_helper=Selezionare un file di licenza readme=Readme @@ -365,7 +365,7 @@ readme_helper=Seleziona un template per il readme auto_init=Inizializzare questo repository con i file e il modello selezionati create_repo=Crea Repository default_branch=Ramo (Branch) predefinito -mirror_prune=Prune +mirror_prune=Rimuovi mirror_prune_desc=Remove any remote-tracking references that no longer exist on the remote mirror_interval=Intervallo Mirror (in ore) mirror_address=Indirizzo del mirror @@ -425,14 +425,14 @@ file_raw=Originale file_history=Cronologia file_view_raw=Vedi originale file_permalink=Permalink -file_too_large=This file is too large to be shown - -editor.new_file=New file -editor.upload_file=Upload file -editor.edit_file=Edit file -editor.preview_changes=Preview Changes -editor.cannot_edit_non_text_files=Cannot edit non-text files -editor.edit_this_file=Edit this file +file_too_large=Questo file è troppo grande per essere mostrato + +editor.new_file=Nuovo file +editor.upload_file=Carica File +editor.edit_file=Modifica file +editor.preview_changes=Anteprima modifiche +editor.cannot_edit_non_text_files=Non è possibile modificare i file non di testo +editor.edit_this_file=Modifica questo file editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file editor.fork_before_edit=You must fork this repository before editing the file editor.delete_this_file=Delete this file diff --git a/conf/locale/locale_ja-JP.ini b/conf/locale/locale_ja-JP.ini index 27816f2036..d5a1a70788 100644 --- a/conf/locale/locale_ja-JP.ini +++ b/conf/locale/locale_ja-JP.ini @@ -194,7 +194,7 @@ CommitSummary=Commit summary CommitMessage=Commit message CommitChoice=Commit choice TreeName=File path -Content=Content +Content=コンテンツ require_error=空にできません alpha_dash_error=アルファベット、数字、ハイフン"-"、アンダースコア"_"のいずれかの必要があります @@ -248,7 +248,7 @@ form.name_pattern_not_allowed=ユーザ名のパターン '%s' は許可され [settings] profile=プロフィール password=パスワード -avatar=Avatar +avatar=アバター ssh_keys=SSH キー social=SNSアカウント applications=アプリケーション @@ -269,7 +269,7 @@ change_username_prompt=この変更はリンクをアカウントに関連付け continue=続行 cancel=キャンセル -lookup_avatar_by_mail=Lookup Avatar by mail +lookup_avatar_by_mail=メールからアバターを取得 federated_avatar_lookup=Federated Avatar Lookup enable_custom_avatar=カスタムのアバターを有効にする choose_new_avatar=新しいアバターを選択 @@ -370,7 +370,7 @@ mirror_prune_desc=Remove any remote-tracking references that no longer exist on mirror_interval=ミラー 間隔(時) mirror_address=ミラー アドレス mirror_address_desc=Please include necessary user credentials in the address. -mirror_last_synced=Last Synced +mirror_last_synced=最終同期 watchers=ウォッチャー stargazers=Stargazers forks=フォーク @@ -429,29 +429,29 @@ file_too_large=このファイルは大きすぎるため、表示できませ editor.new_file=New file editor.upload_file=Upload file -editor.edit_file=Edit file +editor.edit_file=ファイルを編集 editor.preview_changes=Preview Changes editor.cannot_edit_non_text_files=Cannot edit non-text files -editor.edit_this_file=Edit this file +editor.edit_this_file=このファイルを編集 editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file editor.fork_before_edit=You must fork this repository before editing the file -editor.delete_this_file=Delete this file +editor.delete_this_file=このファイルを削除 editor.must_have_write_access=You must have write access to make or propose changes to this file editor.file_delete_success=File '%s' has been deleted successfully! editor.name_your_file=Name your file... editor.filename_help=To add directory, just type it and press /. To remove a directory, go to the beginning of the field and press backspace. editor.or=or -editor.cancel_lower=cancel -editor.commit_changes=Commit Changes +editor.cancel_lower=キャンセル +editor.commit_changes=変更をコミット editor.add_tmpl=Add '%s/' -editor.add=Add '%s' -editor.update=Update '%s' -editor.delete=Delete '%s' +editor.add='%s' を追加 +editor.update='%s' を更新 +editor.delete='%s' を削除 editor.commit_message_desc=Add an optional extended description... editor.commit_directly_to_this_branch=Commit directly to the %s branch. editor.create_new_branch=Create a new branch for this commit and start a pull request. editor.new_branch_name_desc=New branch name... -editor.cancel=Cancel +editor.cancel=キャンセル editor.filename_cannot_be_empty=Filename cannot be empty. editor.branch_already_exists=Branch '%s' already exists in this repository. editor.directory_is_a_file=Entry '%s' in the parent path is a file not a directory in this repository. @@ -616,7 +616,7 @@ wiki.save_page=ページを保存 wiki.last_commit_info=%s このページを編集 %s wiki.edit_page_button=編集 wiki.new_page_button=新規ページ -wiki.delete_page_button=Delete Page +wiki.delete_page_button=ページの削除 wiki.delete_page_notice_1=This will delete the page "%s". Please be certain. wiki.page_already_exists=既に同じ名前のWiki ページが存在します。 wiki.pages=ページ @@ -625,15 +625,15 @@ wiki.last_updated=最終更新 %s settings=設定 settings.options=オプション settings.collaboration=コラボレーション -settings.collaboration.admin=Admin -settings.collaboration.write=Write -settings.collaboration.read=Read +settings.collaboration.admin=管理 +settings.collaboration.write=書込 +settings.collaboration.read=読込 settings.collaboration.undefined=Undefined settings.hooks=Webhooks settings.githooks=Git のフック settings.basic_settings=基本設定 settings.mirror_settings=Mirror Settings -settings.sync_mirror=Sync Now +settings.sync_mirror=今すぐ同期 settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute. settings.site=公式サイト settings.update_settings=設定の更新 @@ -649,7 +649,7 @@ settings.use_internal_issue_tracker=Use builtin lightweight issue tracker settings.use_external_issue_tracker=外部課題トラッキングシステムを使用 settings.tracker_url_format=外部課題トラッキングツール URLのフォーマット settings.tracker_issue_style=External Issue Tracker Naming Style: -settings.tracker_issue_style.numeric=Numeric +settings.tracker_issue_style.numeric=数値 settings.tracker_issue_style.alphanumeric=Alphanumeric settings.tracker_url_format_desc=You can use placeholder {user} {repo} {index} for user name, repository name and issue index. settings.pulls_desc=Enable pull requests to accept public contributions @@ -665,10 +665,10 @@ settings.transfer_desc=リポジトリをあなたが管理者権限を持って settings.transfer_notices_1=-新しい所有者が個人ユーザーの場合、あなたがアクセスできなくなります。 settings.transfer_notices_2=- You will conserve access if new owner is an organization and if you're one of the owners. settings.transfer_form_title=操作を確認するために、以下の情報を入力してください。 -settings.wiki_delete=Erase Wiki Data -settings.wiki_delete_desc=Once you erase wiki data there is no going back. Please be certain. +settings.wiki_delete=Wikiのデータ消去 +settings.wiki_delete_desc=Wikiのデータを消去すると元に戻すことは出来ません。よく確認してください。 settings.wiki_delete_notices_1=- This will delete and disable the wiki for %s -settings.wiki_deletion_success=Repository wiki data have been erased successfully. +settings.wiki_deletion_success=Wikiのデータ消去が完了しました。 settings.delete=このリポジトリを削除 settings.delete_desc=リポジトリを削除すると元に戻せません。確実に確認してください。 settings.delete_notices_1=-この操作は元に戻せません 。 diff --git a/conf/locale/locale_lv-LV.ini b/conf/locale/locale_lv-LV.ini index e291c91529..86e78e04b2 100644 --- a/conf/locale/locale_lv-LV.ini +++ b/conf/locale/locale_lv-LV.ini @@ -6,7 +6,7 @@ explore=Izpētīt help=Palīdzība sign_in=Pierakstīties sign_out=Izrakstīties -sign_up=Pieteikties +sign_up=Reģistrēties register=Reģistrēties website=Mājas lapa version=Versija @@ -96,8 +96,8 @@ offline_mode=Iespējot bezsaistes režīmu offline_mode_popup=Atspējot CDN arī produkcijas režīmā, visi resursu faili tiks piegādāti no servera. disable_gravatar=Atspējot Gravatar pakalpojumu disable_gravatar_popup=Atspējot Gravatar un citus avotus, visus avatarus augšupielādēts lietotāji vai izmantos noklusēto attēlu. -federated_avatar_lookup=Enable Federated Avatars Lookup -federated_avatar_lookup_popup=Enable federated avatars lookup to use federated open source service based on libravatar. +federated_avatar_lookup=Iespējot apvienoto profila bilžu meklētāju +federated_avatar_lookup_popup=Iespējot apvienoto profila bilžu meklētāju, lai izmantotu atvērtā koda apvienoto servisu balstītu uz libravatar. disable_registration=Atspējot lietotāju reģistrāciju disable_registration_popup=Atspējot lietotāju reģistrāciju, tikai administrators varēs izveidot jaunus lietotāju kontus. enable_captcha=Iespējot drošības kodu @@ -189,12 +189,12 @@ TeamName=Komandas nosaukums AuthName=Autorizācijas nosaukums AdminEmail=Admin e-pasta adrese -NewBranchName=New branch name -CommitSummary=Commit summary -CommitMessage=Commit message -CommitChoice=Commit choice -TreeName=File path -Content=Content +NewBranchName=Jauna atzara nosaukums +CommitSummary=Revīzijas kopsavilkums +CommitMessage=Revīzijas ziņojums +CommitChoice=Revīzijas izvēle +TreeName=Faila ceļš +Content=Saturs require_error=` nedrīkst būt tukšs.` alpha_dash_error=` drīkst saturēt tikai latīņu alfabēta burtus, ciparus vai domuzīmes (-_).` @@ -269,8 +269,8 @@ change_username_prompt=Šī izmaiņa ietekmēs saites, kas norāda uz Jūsu kont continue=Turpināt cancel=Atcelt -lookup_avatar_by_mail=Lookup Avatar by mail -federated_avatar_lookup=Federated Avatar Lookup +lookup_avatar_by_mail=Meklēt profila bildes pēc e-pasta +federated_avatar_lookup=Apvienotais profila bilžu meklētājs enable_custom_avatar=Iespējot maināmu profila attēlu choose_new_avatar=Izvēlēties jaunu profila attēlu update_avatar=Saglabāt profila bildi @@ -357,7 +357,7 @@ fork_from=Atdalīt no fork_visiblity_helper=Atdalītam repozitorijam nav iespējams nomainīt tā redzamību repo_desc=Apraksts repo_lang=Valoda -repo_gitignore_helper=Select .gitignore templates +repo_gitignore_helper=Izvēlieties .gitignore sagatavi license=Licence license_helper=Izvēlieties licences failu readme=LasiMani @@ -370,7 +370,7 @@ mirror_prune_desc=Izdzēst visas ārējās atsauces, kas ārējā repozitorijā mirror_interval=Spoguļošanas intervāls (stundās) mirror_address=Spoguļa adrese mirror_address_desc=Lūdzu iekļaujiet adresē nepieciešamo lietotājvārdu/paroli. -mirror_last_synced=Last Synced +mirror_last_synced=Pēdējo reizi sinhronizēts watchers=Novērotāji stargazers=Zvaigžņdevēji forks=Atdalītie repozitoriji @@ -427,43 +427,43 @@ file_view_raw=Rādīt neapstrādātu file_permalink=Patstāvīgā saite file_too_large=Šis fails ir par lielu, lai to parādītu -editor.new_file=New file -editor.upload_file=Upload file -editor.edit_file=Edit file -editor.preview_changes=Preview Changes -editor.cannot_edit_non_text_files=Cannot edit non-text files -editor.edit_this_file=Edit this file -editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file -editor.fork_before_edit=You must fork this repository before editing the file -editor.delete_this_file=Delete this file -editor.must_have_write_access=You must have write access to make or propose changes to this file -editor.file_delete_success=File '%s' has been deleted successfully! -editor.name_your_file=Name your file... -editor.filename_help=To add directory, just type it and press /. To remove a directory, go to the beginning of the field and press backspace. -editor.or=or -editor.cancel_lower=cancel -editor.commit_changes=Commit Changes -editor.add_tmpl=Add '%s/' -editor.add=Add '%s' -editor.update=Update '%s' -editor.delete=Delete '%s' -editor.commit_message_desc=Add an optional extended description... -editor.commit_directly_to_this_branch=Commit directly to the %s branch. -editor.create_new_branch=Create a new branch for this commit and start a pull request. -editor.new_branch_name_desc=New branch name... -editor.cancel=Cancel -editor.filename_cannot_be_empty=Filename cannot be empty. -editor.branch_already_exists=Branch '%s' already exists in this repository. -editor.directory_is_a_file=Entry '%s' in the parent path is a file not a directory in this repository. -editor.filename_is_a_directory=The filename '%s' is an existing directory in this repository. -editor.file_editing_no_longer_exists=The file '%s' you are editing no longer exists in the repository. -editor.file_changed_while_editing=File content has been changed since you started editing. Click here to see what have been changed or press commit again to overwrite those changes. -editor.file_already_exists=A file with name '%s' already exists in this repository. -editor.no_changes_to_show=There are no changes to show. -editor.fail_to_update_file=Failed to update/create file '%s' with error: %v -editor.add_subdir=Add subdirectory... -editor.unable_to_upload_files=Failed to upload files to '%s' with error: %v -editor.upload_files_to_dir=Upload files to '%s' +editor.new_file=Jauns fails +editor.upload_file=Augšupielādēt failu +editor.edit_file=Labot failu +editor.preview_changes=Priekšskatīt izmaiņas +editor.cannot_edit_non_text_files=Nevar rediģēt failus, kas nav teksta faili +editor.edit_this_file=Rediģēt šo failu +editor.must_be_on_a_branch=Ir jābūt izvēlētam atzaram, lai varētu veikt vai piedāvāt izmaiņas šim failam +editor.fork_before_edit=Lai varētu labot failu ir nepieciešams atdalīt repozitoriju +editor.delete_this_file=Dzēst šo failu +editor.must_have_write_access=Jums ir jābūt rakstīšanas tiesībām, lai varētu veikt vai piedāvāt izmaiņas šim failam +editor.file_delete_success=Fails '%s' ir veiksmīgi izdzēsts! +editor.name_your_file=Ievadiet faila nosaukumu... +editor.filename_help=Lai pievienotu direktoriju, ierakstiet tās nosaukumu un nospiediet /. Lai noņemtu direktoriju, ielieciet kursoru pirms faila nosaukuma un nospiediet atpakaļatkāpes taustiņu. +editor.or=vai +editor.cancel_lower=atcelt +editor.commit_changes=Pabeigt revīziju +editor.add_tmpl=Pievienot '%s/' +editor.add=Pievienot '%s' +editor.update=Atjaunināt '%s' +editor.delete=Dzēst '%s' +editor.commit_message_desc=Pievienot neobligātu paplašinātu aprakstu... +editor.commit_directly_to_this_branch=Apstiprināt revīzijas izmaiņas atzarā %s. +editor.create_new_branch=Izveidot jaunu atzaru un izmaiņu pieprasījumu šai revīzijai. +editor.new_branch_name_desc=Jaunā atzara nosaukums... +editor.cancel=Atcelt +editor.filename_cannot_be_empty=Nav ievadīts faila nosaukums. +editor.branch_already_exists=Atzars '%s' šajā repozitorijā jau eksistē. +editor.directory_is_a_file=Ieraksts '%s' vecāka ceļā ir fails nevis direktorija šajā repozitorijā. +editor.filename_is_a_directory=Faila nosaukums '%s' sakrīt ar direktorijas nosaukumu šajā repozitorijā. +editor.file_editing_no_longer_exists=Fails '%s', ko labojat, vairs neeksistē repozitorijā. +editor.file_changed_while_editing=Faila saturs ir mainījies kopš brīža, kad sākāt to labot. Nospiediet šeit, lai redzētu kas ir mainījies vai nospiediet atkārtoti pabeigt revīziju, lai pārrakstītu izmaiņas. +editor.file_already_exists=Fails ar nosaukumu '%s' repozitorijā jau eksistē. +editor.no_changes_to_show=Nav izmaiņu, ko rādīt. +editor.fail_to_update_file=Neizdevās izmainīt/izveidot failu '%s', kļūda: %v +editor.add_subdir=Pievienot apakšdirektoriju... +editor.unable_to_upload_files=Neizdevās augšupielādēt failus uz direktoriju '%s', kļūda: %v +editor.upload_files_to_dir=Augšupielādēt failus uz direktoriju '%s' commits.commits=Revīzijas commits.search=Meklēt revīzijas @@ -490,11 +490,11 @@ issues.create=Pieteikt problēmu issues.new_label=Jauna etiķete issues.new_label_placeholder=Etiķetes nosaukums... issues.create_label=Izveidot etiķeti -issues.label_templates.title=Load a predefined set of labels -issues.label_templates.info=There aren’t any labels yet. You can click on the "New Label" button above to create one or use a predefined set below. -issues.label_templates.helper=Select a label set -issues.label_templates.use=Use this label set -issues.label_templates.fail_to_load_file=Failed to load label template file '%s': %v +issues.label_templates.title=Ielādēt sākotnēji noteikto etiķešu kopu +issues.label_templates.info=Nav definēta neviena etiķete. Nospiediet pogu "Izveidot etiķeti", lai to izveidotu vai izmantojiet zemāk piedāvātās etiķetes. +issues.label_templates.helper=Izvēlieties etiķešu kopu +issues.label_templates.use=Izmantot šo etiķešu kopu +issues.label_templates.fail_to_load_file=Neizdevās ielādēt etiķetes sagataves failu '%s': %v issues.open_tab=%d atvērti issues.close_tab=%d aizvērti issues.filter_label=Etiķete @@ -536,7 +536,7 @@ issues.commit_ref_at=`pieminēja šo problēmu revīzijā Sign in to join this conversation. +issues.sign_in_require_desc=Pierakstieties, lai pievienotos šai sarunai. issues.edit=Labot issues.cancel=Atcelt issues.save=Saglabāt @@ -551,8 +551,8 @@ issues.label_deletion=Etiķetes dzēšana issues.label_deletion_desc=Dzēšot šo etiķeti, tā tiks noņemta no visām saistītajām problēmām. Vai vēlaties turpināt? issues.label_deletion_success=Etiķete tika veiksmīgi izdzēsta! issues.num_participants=%d dalībnieki -issues.attachment.open_tab=`Click to see "%s" in a new tab` -issues.attachment.download=`Click to download "%s"` +issues.attachment.open_tab=`Noklikšķiniet, lai apskatītos "%s" jaunā logā` +issues.attachment.download=`Noklikšķiniet, lai lejupielādētu "%s"` pulls.new=Jauns izmaiņu pieprasījums pulls.compare_changes=Salīdzināt izmaiņas @@ -632,9 +632,9 @@ settings.collaboration.undefined=Nedefinētas settings.hooks=Tīmekļa āķi settings.githooks=Git āķi settings.basic_settings=Pamatiestatījumi -settings.mirror_settings=Mirror Settings -settings.sync_mirror=Sync Now -settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute. +settings.mirror_settings=Spoguļa iestatījumi +settings.sync_mirror=Sinhronizēt tagad +settings.mirror_sync_in_progress=Notiek spoguļa sinhronizācija, uzgaidiet aptuveni minūti un atjaunojiet lapu. settings.site=Oficiālā mājas lapa settings.update_settings=Mainīt iestatījumus settings.change_reponame_prompt=Šī izmaiņa ietekmēs saites, kas ir saistītas ar šo repozitoriju. @@ -644,8 +644,8 @@ settings.use_internal_wiki=Izmantot iebūvēto vikivietni settings.use_external_wiki=Izmantot ārējo vikivietni settings.external_wiki_url=Ārējās Vikivietnes adrese settings.external_wiki_url_desc=Apmeklētāji tiks novirzīti uz adresi, kad viņi uzklikšķinās uz cilnes. -settings.issues_desc=Enable issue tracker -settings.use_internal_issue_tracker=Use builtin lightweight issue tracker +settings.issues_desc=Iespējot problēmu sekotāju +settings.use_internal_issue_tracker=Izmantot iebūvētu vieglu problēmu sekotāju settings.use_external_issue_tracker=Izmantot ārējo problēmu sekotāju settings.tracker_url_format=Ārējā problēmu sekotāja adreses formāts settings.tracker_issue_style=Ārējā problēmu reģistra nosaukumu stils: @@ -720,8 +720,8 @@ settings.event_send_everything=Vēlos saņemt visu. settings.event_choose=Atzīmēt, ko vēlos saņemt. settings.event_create=Izveidot settings.event_create_desc=Atzara vai taga izveidošana -settings.event_pull_request=Pull Request -settings.event_pull_request_desc=Pull request opened, closed, reopened, edited, assigned, unassigned, label updated, label cleared, or synchronized. +settings.event_pull_request=Izmaiņu pieprasījums +settings.event_pull_request_desc=Atvērts, aizvērts, atkāroti atvērts, labots, piešķirts vai noņemts izmaiņu pieprasījums, vai mainīta etiķete, vai veikta sinhronizācija. settings.event_push=Izmaiņu nosūtīšana settings.event_push_desc=Git izmaiņu nosūtīšana uz repozitoriju settings.active=Aktīvs @@ -1113,18 +1113,18 @@ config.cookie_life_time=Sīkdatņu glabāšanas ilgums config.picture_config=Attēlu konfigurācija config.picture_service=Lokāli attēli config.disable_gravatar=Atspējot Gravatar -config.enable_federated_avatar=Enable Federated Avatars +config.enable_federated_avatar=Iespējot apvienotās profila bildes config.git_config=Git konfigurācija -config.git_disable_diff_highlight=Disable Diff Syntax Highlight -config.git_max_diff_lines=Max Diff Lines (for a single file) -config.git_max_diff_line_characters=Max Diff Characters (for a single line) -config.git_max_diff_files=Max Diff Files (to be shown) +config.git_disable_diff_highlight=Atspējot salīdzināšanas sintakses iekrāsošanu +config.git_max_diff_lines=Maksimālais salīdzināmo rindu skaits vienam failam +config.git_max_diff_line_characters=Maksimālais salīdzināmo simbolu skaits vienai rindai +config.git_max_diff_files=Maksimālais salīdzināmo failu skaits, ko attēlot config.git_gc_args=GC argumenti config.git_migrate_timeout=Migrācijas noilgums -config.git_mirror_timeout=Mirror Update Timeout -config.git_clone_timeout=Clone Operation Timeout -config.git_pull_timeout=Pull Operation Timeout +config.git_mirror_timeout=Spoguļa atjaunošanas noilgums +config.git_clone_timeout=Klonēšanas darbības noilgums +config.git_pull_timeout=Izmaiņu saņemšanas darbības noilgums config.git_gc_timeout=GC darbības noilgums config.log_config=Žurnalizēšanas konfigurācija diff --git a/conf/locale/locale_nl-NL.ini b/conf/locale/locale_nl-NL.ini index 37fbd355b7..840fdb1549 100644 --- a/conf/locale/locale_nl-NL.ini +++ b/conf/locale/locale_nl-NL.ini @@ -193,8 +193,8 @@ NewBranchName=New branch name CommitSummary=Commit summary CommitMessage=Commit message CommitChoice=Commit choice -TreeName=File path -Content=Content +TreeName=Bestandspad +Content=Inhoud require_error=kan niet leeg zijn. alpha_dash_error=moet een valide alfanumeriek of dash(-_) karakter zijn. @@ -232,7 +232,7 @@ org_still_own_repo=De organisatie heeft nog eigendomen op repositories. U moet d target_branch_not_exist=Doel branch bestaat niet [user] -change_avatar=Change your avatar +change_avatar=Wijzig je profielfoto join_on=Aangemeld op repositories=repositories activity=Openbare activiteit @@ -248,7 +248,7 @@ form.name_pattern_not_allowed=Het gebruikersnaam patroon '%s' is niet toegestaan [settings] profile=Profiel password=Wachtwoord -avatar=Avatar +avatar=Profielfoto ssh_keys=SSH-sleutels social=Sociale netwerk-accounts applications=Toepassingen @@ -269,7 +269,7 @@ change_username_prompt=Deze verandering zal de weg links hebben betrekking op uw continue=Doorgaan cancel=Annuleren -lookup_avatar_by_mail=Lookup Avatar by mail +lookup_avatar_by_mail=Zoek profielfoto per email federated_avatar_lookup=Federated Avatar Lookup enable_custom_avatar=Aangepaste avatar inschakelen choose_new_avatar=Kies een nieuwe avatar @@ -370,7 +370,7 @@ mirror_prune_desc=Remove any remote-tracking references that no longer exist on mirror_interval=Mirror interval(uur) mirror_address=Kopie-adres mirror_address_desc=Gelieve noodzakelijke gebruikersgegevens in de adresbalk. -mirror_last_synced=Last Synced +mirror_last_synced=Laatste synchronisatie watchers=Volgers stargazers=Stargazers forks=Forks @@ -427,15 +427,15 @@ file_view_raw=Weergave ruwe file_permalink=Permalink file_too_large=This file is too large to be shown -editor.new_file=New file -editor.upload_file=Upload file -editor.edit_file=Edit file -editor.preview_changes=Preview Changes -editor.cannot_edit_non_text_files=Cannot edit non-text files -editor.edit_this_file=Edit this file -editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file -editor.fork_before_edit=You must fork this repository before editing the file -editor.delete_this_file=Delete this file +editor.new_file=Nieuw bestand +editor.upload_file=Bestand uploaden +editor.edit_file=Bewerk bestand +editor.preview_changes=Wijzigingen nagaan +editor.cannot_edit_non_text_files=Kan niet-tekstbestanden niet bewerken +editor.edit_this_file=Bestand aanpassen +editor.must_be_on_a_branch=Je moet in een branch zijn om aanpassingen te maken of voor te stellen +editor.fork_before_edit=Je moet deze repository eerst vorken om dit bestand aan te kunnen passen +editor.delete_this_file=Verwijder dit bestand editor.must_have_write_access=You must have write access to make or propose changes to this file editor.file_delete_success=File '%s' has been deleted successfully! editor.name_your_file=Name your file... diff --git a/conf/locale/locale_pl-PL.ini b/conf/locale/locale_pl-PL.ini index a994148331..9823f0cccd 100644 --- a/conf/locale/locale_pl-PL.ini +++ b/conf/locale/locale_pl-PL.ini @@ -189,11 +189,11 @@ TeamName=Nazwa zespołu AuthName=Nazwa autoryzacji AdminEmail=E-mail administratora -NewBranchName=New branch name +NewBranchName=Nazwa nowej gałęzi CommitSummary=Commit summary CommitMessage=Commit message CommitChoice=Commit choice -TreeName=File path +TreeName=Ścieżka pliku Content=Content require_error=` nie może być puste.` @@ -434,7 +434,7 @@ editor.preview_changes=Preview Changes editor.cannot_edit_non_text_files=Cannot edit non-text files editor.edit_this_file=Edit this file editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file -editor.fork_before_edit=You must fork this repository before editing the file +editor.fork_before_edit=Musisz sforkować to repozytorium przed edycją tego pliku editor.delete_this_file=Delete this file editor.must_have_write_access=You must have write access to make or propose changes to this file editor.file_delete_success=File '%s' has been deleted successfully! @@ -493,7 +493,7 @@ issues.create_label=Utwórz etykietę issues.label_templates.title=Load a predefined set of labels issues.label_templates.info=There aren’t any labels yet. You can click on the "New Label" button above to create one or use a predefined set below. issues.label_templates.helper=Select a label set -issues.label_templates.use=Use this label set +issues.label_templates.use=Użyj ten zestaw etykiet issues.label_templates.fail_to_load_file=Failed to load label template file '%s': %v issues.open_tab=Otwarte %d issues.close_tab=Zamknięte %d @@ -536,7 +536,7 @@ issues.commit_ref_at=`wspomina ten problem w commicie Sign in to join this conversation. +issues.sign_in_require_desc= Zaloguj się, aby dołączyć do tej rozmowy. issues.edit=Edytuj issues.cancel=Anuluj issues.save=Zapisz @@ -551,8 +551,8 @@ issues.label_deletion=Usunięcie etykiety issues.label_deletion_desc=Usunięcie tej etykiety spowoduje usuniecie jej ze wszystkich powiązanych problemów. Czy na pewno chcesz kontynuować? issues.label_deletion_success=Etykieta została usunięta pomyślnie! issues.num_participants=%d uczestników -issues.attachment.open_tab=`Click to see "%s" in a new tab` -issues.attachment.download=`Click to download "%s"` +issues.attachment.open_tab=`Kliknij, aby zobaczyć "%s" w nowej karcie` +issues.attachment.download=`Kliknij, aby pobrać "%s"` pulls.new=Nowy pull request pulls.compare_changes=Porównaj zmiany @@ -633,14 +633,14 @@ settings.hooks=Webhooki settings.githooks=Hooki Git settings.basic_settings=Ustawienia podstawowe settings.mirror_settings=Mirror Settings -settings.sync_mirror=Sync Now +settings.sync_mirror=Synchronizuj teraz settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute. settings.site=Oficjalna Strona settings.update_settings=Aktualizuj ustawienia settings.change_reponame_prompt=Zmiana nazwy repozytorium wpłynie na linki do niego. settings.advanced_settings=Ustawienia zaawansowane -settings.wiki_desc=Enable wiki system -settings.use_internal_wiki=Use builtin wiki +settings.wiki_desc=Włącz system wiki +settings.use_internal_wiki=Użyj wbudowanego wiki settings.use_external_wiki=Użyj zewnętrznego Wiki settings.external_wiki_url=Adres URL zewnętrznego Wiki settings.external_wiki_url_desc=Odwiedzający zostaną przekierowani do adresu URL po kliknięciu zakładki. @@ -1115,13 +1115,13 @@ config.picture_service=Serwis obrazów config.disable_gravatar=Wyłącz Gravatara config.enable_federated_avatar=Enable Federated Avatars -config.git_config=Git Configuration +config.git_config=Konfiguracja Git config.git_disable_diff_highlight=Disable Diff Syntax Highlight config.git_max_diff_lines=Max Diff Lines (for a single file) config.git_max_diff_line_characters=Max Diff Characters (for a single line) config.git_max_diff_files=Max Diff Files (to be shown) config.git_gc_args=GC Arguments -config.git_migrate_timeout=Migration Timeout +config.git_migrate_timeout=Limit czasu migracji config.git_mirror_timeout=Mirror Update Timeout config.git_clone_timeout=Clone Operation Timeout config.git_pull_timeout=Pull Operation Timeout diff --git a/conf/locale/locale_pt-BR.ini b/conf/locale/locale_pt-BR.ini index c428a0295a..fdb68c5749 100644 --- a/conf/locale/locale_pt-BR.ini +++ b/conf/locale/locale_pt-BR.ini @@ -1,7 +1,7 @@ -app_desc=Um serviço de Git auto-hospedado e amigável escrito em Go +app_desc=Um serviço de Git hospedável e amigável escrito em Go -home=Página Inicial -dashboard=Página Inicial +home=Página inicial +dashboard=Painel explore=Explorar help=Ajuda sign_in=Entrar @@ -15,7 +15,7 @@ template=Template language=Idioma create_new=Criar... user_profile_and_more=Perfil do usuário e configurações -signed_in_as=Você é +signed_in_as=Logado como username=Usuário email=E-mail @@ -26,20 +26,20 @@ captcha=Captcha repository=Repositório organization=Organização mirror=Espelho -new_repo=Novo Repositório -new_migrate=Nova Migração -new_mirror=Novo espelho -new_fork=Novo Fork de Repositório -new_org=Nova Organização -manage_org=Gerenciar Organizações -admin_panel=Painel do Administrador -account_settings=Configurações da Conta +new_repo=Novo repositório +new_migrate=Nova migração +new_mirror=Novo mirror +new_fork=Novo fork de repositório +new_org=Nova organização +manage_org=Gerenciar organizações +admin_panel=Painel do administrador +account_settings=Configurações da conta settings=Configurações your_profile=Seu perfil your_settings=Suas configurações activities=Atividades -pull_requests=Pull Requests +pull_requests=Pull requests issues=Problemas cancel=Cancelar @@ -49,8 +49,8 @@ install=Instalação title=Etapas de instalação para primeira execução docker_helper=Se você está rodando o Gitea dentro do Docker, por favor leia os Guias cuidadosamente antes de mudar qualquer coisa nesta página! requite_db_desc=Gitea requer MySQL, PostgreSQL, SQLite3 ou TiDB. -db_title=Configurações de Banco de Dados -db_type=Tipo do Banco de Dados +db_title=Configurações de banco de dados +db_type=Tipo de banco de dados host=Host user=Usuário password=Senha @@ -67,18 +67,18 @@ err_empty_admin_password=A senha de administrador não pode ser vazia. general_title=Configurações gerais do Gitea app_name=Nome do aplicativo app_name_helper=Coloque o nome da sua organização aqui! -repo_path=Caminho da raíz do repositório +repo_path=Caminho raíz do repositório repo_path_helper=Todos os repositórios remotos do Git serão salvos neste diretório. run_user=Usuário da execução run_user_helper=O usuário deve ter acesso ao caminho raiz do repositório e executar o Gitea domain=Domínio -domain_helper=Isto afeta URLs para clonagem via SSH. +domain_helper=Isto afeta URLs para o clone via SSH. ssh_port=Porta SSH ssh_port_helper=Número da porta que seu servidor SSH está usando, deixe vazio para desativar o recurso SSH. http_port=Porta HTTP http_port_helper=Número da porta em que a aplicação irá executar. app_url=URL do aplicativo -app_url_helper=Isto afeta a URL de clonagem via HTTP/HTTPs e também o e-mail. +app_url_helper=Isto afeta a URL de clone via HTTP/HTTPs e também o e-mail. log_root_path=Caminho do log log_root_path_helper=Pasta dos arquivos de log. @@ -122,14 +122,14 @@ install_success=Bem-vindo! Estamos contentes que você escolheu o Gitea, divirta invalid_log_root_path=Pasta raíz do log é inválida: %v [home] -uname_holder=Nome de Usuário ou E-mail +uname_holder=Nome de usuário ou e-mail password_holder=Senha -switch_dashboard_context=Trocar Contexto do Painel de Controle -my_repos=Meus Repositórios +switch_dashboard_context=Trocar contexto do painel de controle +my_repos=Meus repositórios show_more_repos=Mostrar mais repositórios... -collaborative_repos=Repositórios Colaborativos -my_orgs=Minhas Organizações -my_mirrors=Meus Espelhos +collaborative_repos=Repositórios colaborativos +my_orgs=Minhas organizações +my_mirrors=Meus mirrors view_home=Ver %s issues.in_your_repos=Em seus repositórios @@ -140,17 +140,17 @@ users=Usuários search=Pesquisar [auth] -create_new_account=Criar Nova Conta +create_new_account=Criar nova conta register_hepler_msg=Já tem uma conta? Entre agora! social_register_hepler_msg=Já tem uma conta? Junte-se agora! disable_register_prompt=Desculpe, novos registros estão desabilitados. Por favor entre em contato com o administrador do site. disable_register_mail=Desculpe, a confirmação de registro por e-mail foi desabilitada. -remember_me=Lembrar de Mim -forgot_password=Esqueci a Senha +remember_me=Lembrar de mim +forgot_password=Esqueci a senha forget_password=Esqueceu a senha? sign_up_now=Precisa de uma conta? Cadastre-se agora. confirmation_mail_sent_prompt=Um novo e-mail de confirmação foi enviado para %s, por favor, verifique sua caixa de entrada nas próximas %d horas para completar seu registro. -active_your_account=Ativar Sua Conta +active_your_account=Ativar sua conta prohibit_login=Login proibido prohibit_login_desc=Sua conta foi proibida de efetuar login, por favor contate o administrador do site. resent_limit_prompt=Desculpe, você está enviando um e-mail de ativação com muita frequência. Por favor, aguarde 3 minutos. @@ -158,11 +158,11 @@ has_unconfirmed_mail=Oi %s, você possui um endereço de e-mail não confirmado resend_mail=Clique aqui para reenviar seu e-mail de ativação email_not_associate=Este endereço de e-mail não é associado à nenhuma conta. send_reset_mail=Clique aqui para (re)enviar seu e-mail de redefinição da senha -reset_password=Redefinir Sua Senha +reset_password=Redefinir sua senha invalid_code=Desculpe, seu código de confirmação expirou ou não é válido. reset_password_helper=Clique aqui para redefinir sua senha password_too_short=O comprimento da senha não pode ser menor que 6. -non_local_account=Não é possível mudar a senha de contas não-locais pelo Gitea. +non_local_account=Não é possível mudar a senha de contas remotas pelo Gitea. [mail] activate_account=Por favor, ative sua conta @@ -187,17 +187,17 @@ HttpsUrl=URL HTTPS PayloadUrl=URL de carga TeamName=Nome da equipe AuthName=Nome de autorização -AdminEmail=E-mail do Administrador +AdminEmail=E-mail do administrador -NewBranchName=Novo nome do ramo -CommitSummary=Resumo da submissão -CommitMessage=Mensagem de submissão -CommitChoice=Commit choice +NewBranchName=Novo nome do branch +CommitSummary=Resumo dos commits +CommitMessage=Mensagem do commit +CommitChoice=Escolha de commit TreeName=Caminho do arquivo Content=Conteúdo require_error=` não pode estar vazio.` -alpha_dash_error=` devem ser caracteres alfanuméricos ou hífen (-) ou sublinhado (_).` +alpha_dash_error=` devem ser caracteres alfanuméricos, hífen (-) ou sublinhado (_).` alpha_dash_dot_error=` devem ser caracteres alfanuméricos ou hífen (-) ou sublinhado (_).` size_error=`deve ser do tamanho %s.` min_size_error=` deve conter pelo menos %s caracteres.` @@ -209,17 +209,17 @@ unknown_error=Erro desconhecido: captcha_incorrect=O captcha não correspondeu. password_not_match=Senha e confirmação da senha não são as mesmas. -username_been_taken=Nome de usuário já foi tomado. -repo_name_been_taken=Nome do repositório já foi tomado. +username_been_taken=O nome de usuário já existe. +repo_name_been_taken=Nome do repositório já existe. org_name_been_taken=Nome da organização já foi tomado. -team_name_been_taken=Nome da equipe já foi tomado. +team_name_been_taken=Nome da equipe já existe. email_been_used=Endereço de e-mail já foi usado. username_password_incorrect=Usuário ou senha incorretos. enterred_invalid_repo_name=Por favor certifique-se que informou o nome do repositório corretamente. enterred_invalid_owner_name=Por favor, verifique se o nome do proprietário está correto. enterred_invalid_password=Por favor, verifique se a senha que você digitou está correta. user_not_exist=O usuário informado não existe. -last_org_owner=O usuário a ser removido é o último membro na equipe de proprietários. Deve haver um outro proprietário. +last_org_owner=O usuário a ser removido é o último membro na equipe de proprietários. É obrigatório ter pelo menos um proprietário. invalid_ssh_key=Desculpe, não conseguimos verificar a sua chave SSH: %s unable_verify_ssh_key=Gitea não pode verificar sua chave SSH, mas assumimos que é válida, por favor, verifique a chave pessoalmente. @@ -235,9 +235,9 @@ target_branch_not_exist=O branch de destino não existe. change_avatar=Mude seu avatar join_on=Inscreveu-se em repositories=Repositórios -activity=Atividade Pública +activity=Atividade pública followers=Seguidores -starred=Favorito +starred=Repositórios favoritos following=Seguindo follow=Seguir unfollow=Deixar de seguir @@ -250,43 +250,43 @@ profile=Perfil password=Senha avatar=Avatar ssh_keys=Chaves SSH -social=Contas Sociais +social=Contas sociais applications=Aplicativos orgs=Organizações -delete=Deletar Conta +delete=Deletar conta uid=Uid -public_profile=Perfil Público +public_profile=Perfil público profile_desc=Seu endereço de E-mail é publico e será usado para qualquer notificação relacionada à conta, e qualquer operação na web feita através do site. -password_username_disabled=Usuários do tipo não-local não são permitidos de mudarem seu nome de usuário. +password_username_disabled=Usuários remotos não tem permissão para mudarem seu nome de usuário. full_name=Nome Completo website=Site location=Localização -update_profile=Atualizar o Perfil +update_profile=Atualizar o perfil update_profile_success=O seu perfil foi atualizado com sucesso. -change_username=Nome de Usuário Alterado +change_username=Nome de usuário alterado change_username_prompt=Essa alteração afetará os links para a sua conta. continue=Continuar cancel=Cancelar lookup_avatar_by_mail=Busca de avatar por e-mail federated_avatar_lookup=Busca de avatar federativo -enable_custom_avatar=Habilitar Avatar Customizado +enable_custom_avatar=Habilitar avatar customizado choose_new_avatar=Escolha um novo avatar -update_avatar=Atualizar configuração de Avatar -delete_current_avatar=Excluir o Avatar atual +update_avatar=Atualizar configuração de avatar +delete_current_avatar=Excluir o avatar atual uploaded_avatar_not_a_image=O arquivo enviado não é uma imagem. update_avatar_success=Sua configuração de avatar foi atualizada com sucesso. change_password=Mudança de senha old_password=Senha Atual -new_password=Nova Senha +new_password=Nova senha retype_new_password=Digite novamente a nova senha password_incorrect=A senha atual não está correta. change_password_success=A senha está alterada com sucesso. Você pode agora entrar com a senha nova. -password_change_disabled=Usuários do tipo não-local não são permitidos de mudarem sua senha. +password_change_disabled=Usuários remotos não tem permissão para mudar sua senha. -emails=Endereços de E-mail +emails=Endereços de e-mail manage_emails=Gerenciar endereços de e-mail email_desc=Seu endereço de e-mail principal será usado para notificações e outras operações. primary=Principal @@ -298,7 +298,7 @@ email_deletion_success=O E-mail foi excluído com sucesso! add_new_email=Adicionar novo endereço de e-mail add_email=Adicionar e-mail add_email_confirmation_sent=Um novo e-mail de confirmação foi enviado para '%s'. Por favor, verifique sua Caixa de Entrada dentro das próximas %d horas, para concluir o processo de confirmação. -add_email_success=Seu novo endereço de E-mail foi adicionado com sucesso. +add_email_success=Seu novo endereço de e-mail foi adicionado com sucesso. manage_ssh_keys=Gerenciar Chaves SSH add_key=Adicionar chave @@ -312,7 +312,7 @@ key_content=Conteúdo add_key_success=A nova chave pública '%s' foi adicionada com sucesso! delete_key=Deletar ssh_key_deletion=Exclusão da chave de SSH -ssh_key_deletion_desc=Ao Excluir esta chave de SSH será removido todos os acessos para sua conta. Você deseja continuar? +ssh_key_deletion_desc=Ao excluir esta chave de SSH será removido todos os acessos para sua conta. Você deseja continuar? ssh_key_deletion_success=A chave de SSH foi excluída com sucesso! add_on=Adicionado em last_used=Última vez usado em @@ -320,41 +320,41 @@ no_activity=Nenhuma atividade recente key_state_desc=Usada a pelo menos 7 dias token_state_desc=Este token é usado em pelo menos 7 dias -manage_social=Gerenciar Contas Sociais Associadas +manage_social=Gerenciar contas sociais associadas social_desc=Esta é uma lista de contas sociais. Remova qualquer ligação que você não reconheça. unbind=Desvincular unbind_success=A conta social foi desvinculada. -manage_access_token=Gerenciar Tokens de Acesso Pessoal -generate_new_token=Gerar novo Token +manage_access_token=Gerenciar tokens de acesso pessoal +generate_new_token=Gerar novo token tokens_desc=Tokens gerados por você que podem ser usados para acessar a API do Gitea. new_token_desc=Por enquanto, todo token terá acesso completo à sua conta. -token_name=Nome do Token -generate_token=Gerar Token +token_name=Nome do token +generate_token=Gerar token generate_token_succees=Novo token de acesso gerado com sucesso! Certifique-se de copiar seu novo token de acesso pessoal agora. Você não poderá vê-lo novamente! delete_token=Excluir -access_token_deletion=Exclusão do Token de acesso pessoal +access_token_deletion=Exclusão do token de acesso pessoal access_token_deletion_desc=Ao Excluir este token de acesso pessoal será removido todos os acessos do aplicativo. Você deseja continuar? delete_token_success=O Token de acesso pessoal foi removido com sucesso! Não se esqueça de atualizar seus aplicativos também. -delete_account=Deletar Sua Conta +delete_account=Deletar sua conta delete_prompt=A operação deletará sua conta permanentemente, e NÃO PODERÁ ser desfeita! -confirm_delete_account=Confirmar Deleção -delete_account_title=Deleção da Conta -delete_account_desc=Esta conta será deletada permanentemente, você quer continuar? +confirm_delete_account=Confirmar exclusão +delete_account_title=Exclusão da conta +delete_account_desc=Esta conta será excluída permanentemente, você quer continuar? [repo] owner=Dono -repo_name=Nome do Repositório +repo_name=Nome do repositório repo_name_helper=Nomes de repositórios bons são pequenos, memorizáveis e únicos. visibility=Visibilidade visiblity_helper=Este é um repositório privado -visiblity_helper_forced=O adminstrador forçou todos os novos repositórios para serem Privados +visiblity_helper_forced=O adminstrador forçou todos os novos repositórios para serem privados visiblity_fork_helper=(A alteração desse valor irá afetar todos os forks) -clone_helper=Precisa de ajuda com a clonagem? Visite a Ajuda! -fork_repo=Fork o Repositório +clone_helper=Precisa de ajuda com o clone? Visite a Ajuda! +fork_repo=Fork do repositório fork_from=Fork de -fork_visiblity_helper=Não é possível alterar a visibilidade de um repositório forkado. +fork_visiblity_helper=Não é possível alterar a visibilidade de um repositório fork. repo_desc=Descrição repo_lang=Linguagem repo_gitignore_helper=Selecionar templates de .gitignore @@ -363,12 +363,12 @@ license_helper=Selecione um arquivo de licença readme=Leia-me readme_helper=Selecione um modelo de leia-me auto_init=Inicializar este repositório com os arquivos selecionados e modelo -create_repo=Criar Repositório +create_repo=Criar repositório default_branch=Branch padrão mirror_prune=Varrer mirror_prune_desc=Remova quaisquer referências que não existem mais no remote -mirror_interval=Intervalo de Espelho (hora) -mirror_address=Endereço do espelho +mirror_interval=Intervalo de mirror (hora) +mirror_address=Endereço do mirror mirror_address_desc=Por favor, inclua as credenciais do usuário necessários no endereço. mirror_last_synced=Última sincronização watchers=Observadores @@ -379,31 +379,31 @@ form.reach_limit_of_creation=O proprietário atingiu o limite máximo de criaç form.name_reserved=O nome de repositório '%s' não pode ser usado. form.name_pattern_not_allowed=Não é permitido usar o padrão '%s' para o nome de repositório. -need_auth=Precisa de Autorização -migrate_type=Tipo de Migração -migrate_type_helper=Este repositório será um espelho -migrate_repo=Migrar Repositório -migrate.clone_address=Endereço de Clone +need_auth=Precisa de autorização +migrate_type=Tipo de migração +migrate_type_helper=Este repositório será um mirror +migrate_repo=Migrar repositório +migrate.clone_address=Endereço de clone migrate.clone_address_desc=Isto pode ser uma URL de HTTP/HTTPS/GIT ou um caminho de diretório local. migrate.permission_denied=Você não pode importar repositórios locais. migrate.invalid_local_path=Caminho local inválido, não existe ou não é um diretório. migrate.failed=Migração falhou: %v -mirror_from=espelho de -forked_from=forkado de +mirror_from=mirror de +forked_from=fork de fork_from_self=Você não pode criar fork de um repositório que já é seu! copy_link=Copiar copy_link_success=Copiado! copy_link_error=Pressione ⌘-C ou Ctrl-C para copiar copied=Copiado com sucesso -unwatch=Deixar de Observar +unwatch=Deixar de observar watch=Observar unstar=Remover favorito star=Favorito fork=Fork -no_desc=Nenhuma Descrição -quick_guide=Guia Rápido +no_desc=Nenhuma descrição +quick_guide=Guia rápido clone_this_repo=Clonar este repositório create_new_repo_command=Criar um novo repositório na linha de comando push_exist_repo=Push um repositório existente na linha de comando @@ -411,19 +411,19 @@ repo_is_empty=Este repositório está vazio, por favor volte mais tarde! code=Código branch=Branch -tree=Árvore +tree=Tree filter_branch_and_tag=Filtrar branch ou tag branches=Branches tags=Tags -issues=Problemas +issues=Issues pulls=Pull Requests labels=Etiquetas -milestones=Marcos +milestones=Milestones commits=Commits releases=Versões -file_raw=Cru +file_raw=Raw file_history=Histórico -file_view_raw=Ver cru +file_view_raw=Ver raw file_permalink=Link permanente file_too_large=Este arquivo é muito grande para ser exibido @@ -431,38 +431,38 @@ editor.new_file=Novo arquivo editor.upload_file=Enviar arquivo editor.edit_file=Editar arquivo editor.preview_changes=Visualizar alterações -editor.cannot_edit_non_text_files=Impossível editar arquivos que não são texto +editor.cannot_edit_non_text_files=Impossível editar arquivos que não são do tipo texto plano editor.edit_this_file=Editar este arquivo -editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file -editor.fork_before_edit=You must fork this repository before editing the file +editor.must_be_on_a_branch=Você deve estar em um branch para propor mudanças neste arquivo +editor.fork_before_edit=Você deve fazer fork deste repositório antes de editar o arquivo editor.delete_this_file=Excluir este arquivo -editor.must_have_write_access=You must have write access to make or propose changes to this file -editor.file_delete_success=File '%s' has been deleted successfully! +editor.must_have_write_access=Você deve ter permissão de escrita para fazer ou propor mudanças neste arquivo +editor.file_delete_success=Arquivo '%s' deletado com sucesso! editor.name_your_file=Nomeie seu arquivo... -editor.filename_help=To add directory, just type it and press /. To remove a directory, go to the beginning of the field and press backspace. +editor.filename_help=Para adicionar uma pasta, apenas digite o nome e pressione /. Para remover uma pasta, vá para o começo do campo e pressione backspace. editor.or=ou editor.cancel_lower=cancelar -editor.commit_changes=Commit Changes +editor.commit_changes=Efetivar mudanças editor.add_tmpl=Adicionar '%s/' editor.add=Adicionar '%s' editor.update=Atualizar '%s' editor.delete=Excluir '%s' editor.commit_message_desc=Adicione uma descrição estendida opcional... -editor.commit_directly_to_this_branch=Commit directly to the %s branch. -editor.create_new_branch=Create a new branch for this commit and start a pull request. +editor.commit_directly_to_this_branch=Efetive diretamente no branch %s. +editor.create_new_branch=Crie um novo branch para este commit e crie um pull request. editor.new_branch_name_desc=Novo nome do ramo... editor.cancel=Cancelar editor.filename_cannot_be_empty=Nome do arquivo não pode ser vazio. -editor.branch_already_exists=Branch '%s' already exists in this repository. -editor.directory_is_a_file=Entry '%s' in the parent path is a file not a directory in this repository. -editor.filename_is_a_directory=The filename '%s' is an existing directory in this repository. -editor.file_editing_no_longer_exists=The file '%s' you are editing no longer exists in the repository. -editor.file_changed_while_editing=File content has been changed since you started editing. Click here to see what have been changed or press commit again to overwrite those changes. -editor.file_already_exists=A file with name '%s' already exists in this repository. +editor.branch_already_exists=Branch '%s' já existe neste repositório. +editor.directory_is_a_file=Entrada '%s' no caminho pai é um arquivo e não uma pasta neste repositório. +editor.filename_is_a_directory=O arquivo '%s' é uma pasta existente neste repositório. +editor.file_editing_no_longer_exists=O arquivo '%s' que você está editando não existe mais neste repositório. +editor.file_changed_while_editing=O conteúdo do arquivo mudou desde que você começou a editar. Clique aqui para ver o que mudou ou pressione efetivar novamente para sobrescrever esses mudanças. +editor.file_already_exists=Um arquivo com nome '%s' já existe neste repositório. editor.no_changes_to_show=Nenhuma alteração a mostrar. -editor.fail_to_update_file=Failed to update/create file '%s' with error: %v +editor.fail_to_update_file=Houve erro ao criar ou atualizar arquivo '%s': %v editor.add_subdir=Adicionar o subdiretório... -editor.unable_to_upload_files=Failed to upload files to '%s' with error: %v +editor.unable_to_upload_files=Houve erro ao fazer upload de arquivos para '%s': %v editor.upload_files_to_dir=Enviar arquivos para '%s' commits.commits=Commits @@ -472,59 +472,59 @@ commits.author=Autor commits.message=Mensagem commits.date=Data commits.older=Mais Antigo -commits.newer=Mais Novo +commits.newer=Mais recente -issues.new=Novo problema +issues.new=Novo issue issues.new.labels=Etiquetas issues.new.no_label=Sem etiqueta -issues.new.clear_labels=Limpar -issues.new.milestone=Marco -issues.new.no_milestone=Sem marco -issues.new.clear_milestone=Limpar -issues.new.open_milestone=Marcos abertos -issues.new.closed_milestone=Marcos fechados +issues.new.clear_labels=Limpar etiquetas +issues.new.milestone=Milestone +issues.new.no_milestone=Sem milestone +issues.new.clear_milestone=Limpar milestone +issues.new.open_milestone=Milestone abertos +issues.new.closed_milestone=Milestone fechados issues.new.assignee=Responsável -issues.new.clear_assignee=Limpar +issues.new.clear_assignee=Limpar responsável issues.new.no_assignee=Não atribuída -issues.create=Salvar +issues.create=Criar issue issues.new_label=Nova etiqueta issues.new_label_placeholder=Nome da etiqueta... -issues.create_label=Salvar -issues.label_templates.title=Load a predefined set of labels -issues.label_templates.info=There aren’t any labels yet. You can click on the "New Label" button above to create one or use a predefined set below. -issues.label_templates.helper=Select a label set -issues.label_templates.use=Use this label set -issues.label_templates.fail_to_load_file=Failed to load label template file '%s': %v +issues.create_label=Criar etiqueta +issues.label_templates.title=Carregue um conjunto de etiquetas pré-definidas +issues.label_templates.info=Não existem etiquetas ainda. Você pode clicar em "Nova etiqueta" acima para criar uma ou usar um conjunto pré-definido abaixo. +issues.label_templates.helper=Selecione um conjunto de etiquetas +issues.label_templates.use=Usar este conjunto de etiquetas +issues.label_templates.fail_to_load_file=Houve erro ao carregar arquivo de template '%s': %v issues.open_tab=%d aberto -issues.close_tab=%d fechados +issues.close_tab=%d fechado issues.filter_label=Etiqueta issues.filter_label_no_select=Nenhuma etiqueta selecionada -issues.filter_milestone=Marco -issues.filter_milestone_no_select=Nenhum marco selecionado +issues.filter_milestone=Milestone +issues.filter_milestone_no_select=Nenhum milestone selecionado issues.filter_assignee=Atribuído issues.filter_assginee_no_select=Sem atribuição issues.filter_type=Tipo -issues.filter_type.all_issues=Todos os problemas +issues.filter_type.all_issues=Todos os issues issues.filter_type.assigned_to_you=Atribuídos a você issues.filter_type.created_by_you=Criado por você issues.filter_type.mentioning_you=Mencionando você issues.filter_sort=Ordenação -issues.filter_sort.latest=Mais novos +issues.filter_sort.latest=Mais recentes issues.filter_sort.oldest=Mais antigos issues.filter_sort.recentupdate=Mais recentemente atualizados issues.filter_sort.leastupdate=Menos recentemente atualizados issues.filter_sort.mostcomment=Mais comentados issues.filter_sort.leastcomment=Menos comentados issues.opened_by=%[1]s foi aberto por %[3]s -issues.opened_by_fake=aberto %[1]s por %[2]s -issues.previous=Página anterior -issues.next=Próxima página -issues.open_title=aberto -issues.closed_title=fechado +issues.opened_by_fake=%[1]s foi aberto por %[2]s +issues.previous=Anterior +issues.next=Próximo +issues.open_title=Aberto +issues.closed_title=Fechado issues.num_comments=%d comentários issues.commented_at=`comentado %s` issues.delete_comment_confirm=Tem certeza que deseja deletar este comentário? -issues.no_content=Nenhum conteúdo textual. +issues.no_content=Ainda não há conteúdo. issues.close_issue=Fechar issues.close_comment_issue=Comentar e fechar issues.reopen_issue=Reabrir @@ -534,9 +534,9 @@ issues.closed_at=`fechado em %[2]s` issues.reopened_at=`reaberto em %[2]s` issues.commit_ref_at=`citou este problema em um commit %[2]s` issues.poster=Autor -issues.collaborator=Colaboradores +issues.collaborator=Colaborador issues.owner=Proprietário -issues.sign_in_require_desc=Sign in to join this conversation. +issues.sign_in_require_desc=Faça login para participar desta conversação. issues.edit=Editar issues.cancel=Cancelar issues.save=Salvar @@ -551,8 +551,8 @@ issues.label_deletion=Exclusão de etiqueta issues.label_deletion_desc=Excluir uma etiqueta a retirará de todos os problemas que ela estiver marcando. Quer mesmo continuar? issues.label_deletion_success=A etiqueta foi excluída com sucesso! issues.num_participants=%d participantes -issues.attachment.open_tab=`Click to see "%s" in a new tab` -issues.attachment.download=`Click to download "%s"` +issues.attachment.open_tab=`Clique para ver "%s" em uma nova aba` +issues.attachment.download=`Clique para baixar "%s"` pulls.new=Novo Pull Request pulls.compare_changes=Comparar mudanças @@ -569,18 +569,18 @@ pulls.merged_title_desc=mesclou %[1]d commits de %[2]s em %[3 pulls.tab_conversation=Conversação pulls.tab_commits=Commits pulls.tab_files=Arquivos alterados -pulls.reopen_to_merge=Por favor reabra esse pull request para executar a operação de mescla. +pulls.reopen_to_merge=Por favor reabra este Pull Request para executar a operação de merge. pulls.merged=Merge realizado -pulls.has_merged=Este pull request foi mesclado com sucesso! -pulls.data_broken=Dados deste pull request foram quebrados devido à deleção de informação do fork. +pulls.has_merged=O merge deste Pull Request foi aplicado com sucesso! +pulls.data_broken=Dados deste Pull Request foram quebrados devido à remoção de informação do fork. pulls.is_checking=A verificação do conflito ainda está em progresso, por favor recarregue a página em instantes. -pulls.can_auto_merge_desc=Este pull request pode ser mesclado automaticamente. -pulls.cannot_auto_merge_desc=Este pull request não pode ser mesclado automaticamente pois há conflitos. -pulls.cannot_auto_merge_helper=Por favor, mescle manualmente para resolver os conflitos. -pulls.merge_pull_request=Merge Pull Request -pulls.open_unmerged_pull_exists=`Você não pode executar a operação de reabrir porque já existe uma solicitação de pull aberta (#%d) do mesmo repositório com as mesmas informações de merge e está esperando pelo merge.` +pulls.can_auto_merge_desc=O merge deste Pull Pequest pode ser aplicado automaticamente. +pulls.cannot_auto_merge_desc=O merge deste Pull Request não pode ser aplicado automaticamente pois há conflitos. +pulls.cannot_auto_merge_helper=Por favor, aplique o merge manualmente para resolver os conflitos. +pulls.merge_pull_request=Solicitação de merge de Pull Request +pulls.open_unmerged_pull_exists=`Você não pode executar a operação de reabrir porque já existe um Pull request aberto (#%d) do mesmo repositório com as mesmas informações de merge e está esperando pelo merge.` -milestones.new=Novo marco +milestones.new=Novo milestone milestones.open_tab=%d abertos milestones.close_tab=%d fechados milestones.closed=Fechado %s @@ -588,21 +588,21 @@ milestones.no_due_date=Sem prazo milestones.open=Reabrir milestones.close=Fechar milestones.new_subheader=Crie marcos para gerenciar seus problemas. -milestones.create=Salvar marco +milestones.create=Criar milestone milestones.title=Título milestones.desc=Descrição milestones.due_date=Prazo (opcional) milestones.clear=Limpar milestones.invalid_due_date_format=Formato inválido. O valor de data deve ser algo como 'aaaa-mm-dd'. milestones.create_success=O marco '%s' foi configurado com sucesso! -milestones.edit=Edição de marco -milestones.edit_subheader=Descreva bem a proposta do marco, assim as pessoas não ficarão confusas. +milestones.edit=Editar milestone +milestones.edit_subheader=Descreva bem a proposta do milestone, assim as pessoas não ficarão confusas. milestones.cancel=Cancelar -milestones.modify=Salvar alterações -milestones.edit_success=O marco '%s' foi alterado com sucesso! -milestones.deletion=Exclusão de marco -milestones.deletion_desc=Excluir este marco removerá a informação dele em todos os problemas aos quais estiver associado. Você quer mesmo continuar? -milestones.deletion_success=Marco excluído com sucesso! +milestones.modify=Modificar milestone +milestones.edit_success=O milestone '%s' foi alterado com sucesso! +milestones.deletion=Exclusão de milestone +milestones.deletion_desc=Excluir este milestone irá remover toda sua informação em todos as issues que estiver associado. Você quer mesmo continuar? +milestones.deletion_success=Milestone excluído com sucesso! wiki=Wiki wiki.welcome=Bem-vindo ao wiki! @@ -616,7 +616,7 @@ wiki.save_page=Salvar página wiki.last_commit_info=%s editou esta página %s wiki.edit_page_button=Editar wiki.new_page_button=Nova página -wiki.delete_page_button=Excluir Página +wiki.delete_page_button=Excluir página wiki.delete_page_notice_1=Isto irá apagar a página "%s". Por favor, certifique-se. wiki.page_already_exists=já existe uma página de wiki com o mesmo nome. wiki.pages=Páginas @@ -631,19 +631,19 @@ settings.collaboration.read=Leitura settings.collaboration.undefined=Indefinido settings.hooks=Webhooks settings.githooks=Hooks do Git -settings.basic_settings=Configurações Básicas -settings.mirror_settings=Mirror Settings -settings.sync_mirror=Sync Now -settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute. -settings.site=Site Oficial +settings.basic_settings=Configurações básicas +settings.mirror_settings=Opções de mirror +settings.sync_mirror=Sincronizar agora +settings.mirror_sync_in_progress=A sincronização do mirror está em andamento, por favor atualize a página em aproximadamente um minuto. +settings.site=Site oficial settings.update_settings=Atualizar configurações -settings.change_reponame_prompt=Este mudanças vai afetar os links para este repositório. +settings.change_reponame_prompt=Esta mudança irá afetar os links para este repositório. settings.advanced_settings=Configurações avançadas settings.wiki_desc=Habilitar sistema de wiki settings.use_internal_wiki=Usar wiki nativa settings.use_external_wiki=Usar wiki externa settings.external_wiki_url=URL externa da wiki -settings.external_wiki_url_desc=Os visitantes serão redirecionados para a URL quando clicarem na aba. +settings.external_wiki_url_desc=Os visitantes serão redirecionados para a URL ao clicar na aba. settings.issues_desc=Habilitar issue tracker settings.use_internal_issue_tracker=Usar o issue tracker nativo settings.use_external_issue_tracker=Usar issue tracker externo @@ -652,8 +652,8 @@ settings.tracker_issue_style=Estilo de nome de issue tracker externo: settings.tracker_issue_style.numeric=Numérico settings.tracker_issue_style.alphanumeric=Alfanumérico settings.tracker_url_format_desc=Você pode usar o espaço reservado {user} {repo} {index} para o nome do usuário, índice de nome e a questão do repositório. -settings.pulls_desc=Habilitar pull requests para aceitar contribuições públicas -settings.danger_zone=Zona de Perigo +settings.pulls_desc=Habilitar Pull Requests para aceitar contribuições públicas +settings.danger_zone=Zona de perigo settings.new_owner_has_same_repo=O novo dono já tem um repositório com o mesmo nome. Por favor, escolha outro nome. settings.convert=Converter para repositório tradicional settings.convert_desc=Você pode converter este espelho em um repositório tradicional. Esta ação não pode ser revertida. @@ -662,29 +662,29 @@ settings.convert_confirm=Confirmar conversão settings.convert_succeed=Repositório espelho convertido para tradicional com sucesso. settings.transfer=Transferir Propriedade settings.transfer_desc=Transferir este repositório para outro usuário ou para uma organização onde você tem direitos de administrador. -settings.transfer_notices_1=- Você vai perder acesso se o novo dono for um usuário individual. -settings.transfer_notices_2=- Você vai continuar tendo acesso se o novo dono é uma organização e você é um dos membros. +settings.transfer_notices_1=- Você irá perder o acesso se o novo dono for um usuário individual. +settings.transfer_notices_2=- Você irá continuar tendo acesso se o novo dono é uma organização e você é um dos membros. settings.transfer_form_title=Informe a seguinte informação para confirmar a sua operação: settings.wiki_delete=Apagar dados do Wiki settings.wiki_delete_desc=Uma vez que você apague os dados da wiki, não há volta. Por favor, certifique-se. settings.wiki_delete_notices_1=- Isso irá excluir e desativar o wiki para %s settings.wiki_deletion_success=Dados de wiki do repositório foram deletados com sucesso. -settings.delete=Deletar Este Repositório -settings.delete_desc=Uma vez que você deleta um repositório, não tem volta. Por favor, tenha certeza. +settings.delete=Deletar este repositório +settings.delete_desc=Uma vez que você remova um repositório, não tem volta. Por favor, tenha certeza. settings.delete_notices_1=-Esta operação NÃO PODERÁ ser desfeita. -settings.delete_notices_2=- Esta operação irá apagar permanentemente o tudo deste repositório, incluindo os dados do Git, problemas, comentários e acessos dos colaboradores. +settings.delete_notices_2=- Esta operação irá apagar permanentemente o tudo deste repositório, incluindo os dados do Git, Issues, comentários e acessos dos colaboradores. settings.delete_notices_fork_1=-Todos os forks se tornarão independentes após a exclusão. settings.deletion_success=Repositório excluído com sucesso! settings.update_settings_success=As opções do repositório foram atualizadas com sucesso. -settings.transfer_owner=Novo Dono -settings.make_transfer=Fazer Transferência +settings.transfer_owner=Novo dono +settings.make_transfer=Fazer transferência settings.transfer_succeed=A posse do repositório foi transferido com sucesso. -settings.confirm_delete=Confirmar Deleção -settings.add_collaborator=Adicionar um Novo Colaborador +settings.confirm_delete=Confirmar exclusão +settings.add_collaborator=Adicionar um novo colaborador settings.add_collaborator_success=O novo colaborador foi adicionado. -settings.delete_collaborator=Deletar +settings.delete_collaborator=Excluir settings.collaborator_deletion=Exclusão de colaborador -settings.collaborator_deletion_desc=Este usuário não terá mais acesso de colaboração neste repositório após a deleção. Você quer continuar? +settings.collaborator_deletion_desc=Este usuário não terá mais acesso de colaboração neste repositório após a exclusão. Você quer continuar? settings.remove_collaborator_success=O colaborador foi removido. settings.search_user_placeholder=Pesquisar usuário... settings.org_not_allowed_to_be_collaborator=Organização não tem permissão para ser adicionada como um colaborador. @@ -695,21 +695,21 @@ settings.webhook_deletion=Deletar Webhook settings.webhook_deletion_desc=Deletar este Webhook vai remover sua informação e todo o histórico de entrega. Deseja continuar? settings.webhook_deletion_success=Webhook deletado com sucesso! settings.webhook.test_delivery=Entrega de teste -settings.webhook.test_delivery_desc=Enviar uma entrega de evento de push falso para testar suas configurações de webhook -settings.webhook.test_delivery_success=O teste webhook foi adicionado para a fila de entrega. Pode demorar alguns segundos antes de ser exibido no histórico de entrega. +settings.webhook.test_delivery_desc=Enviar uma entrega de evento de Push falso para testar suas configurações de webhook +settings.webhook.test_delivery_success=O Webhook de teste foi adicionado para a fila de entrega. Pode demorar alguns segundos antes de ser exibido no histórico de entrega. settings.webhook.request=Solicitação settings.webhook.response=Resposta settings.webhook.headers=Cabeçalhos settings.webhook.payload=Payload -settings.webhook.body=Texto +settings.webhook.body=Corpo settings.githooks_desc=Hooks do Git são ofertados pelo próprio Git, você pode editar arquivos de hooks suportados na lista abaixo para aplicar operações personalizadas. settings.githook_edit_desc=Se o hook não estiver ativo, o conteúdo de exemplo será apresentado. Deixar o conteúdo em branco irá desativar esse hook. settings.githook_name=Nome do Hook settings.githook_content=Conteúdo do Hook settings.update_githook=Atualizar Hook settings.add_webhook_desc=Enviaremos uma solicitação POST para o URL abaixo com detalhes de quaisquer eventos inscritos. Você pode também especificar qual formato de dados você gostaria de receber (JSON, x-www-form-urlencoded, etc). Mais informação pode ser encontrada em Webhooks Guide. -settings.payload_url=URL de carga -settings.content_type=Tipo de Conteúdo +settings.payload_url=URL de Payload +settings.content_type=Tipo de conteúdo settings.secret=Secreto settings.slack_username=Nome de usuário settings.slack_icon_url=URL do ícone @@ -721,10 +721,10 @@ settings.event_choose=Deixe-me escolher o que eu preciso. settings.event_create=Criar settings.event_create_desc=Branch ou Tag criado settings.event_pull_request=Pull Request -settings.event_pull_request_desc=Pull request opened, closed, reopened, edited, assigned, unassigned, label updated, label cleared, or synchronized. +settings.event_pull_request_desc=Pull request aberto, fechado, reaberto, atribuído, desatribuído, teve etiqueta atualizada ou limpada ou foi sincronizado. settings.event_push=Push settings.event_push_desc=Git push para o repositório -settings.active=Ativar +settings.active=Ativo settings.active_helper=Enviaremos detalhes do evento quando este hook for acionado. settings.add_hook_success=Novos hooks de web foram adicionados. settings.update_webhook=Atualizar Webhook @@ -738,18 +738,18 @@ settings.slack_domain=Domínio settings.slack_channel=Canal settings.deploy_keys=Chaves de Deploy settings.add_deploy_key=Nova chave -settings.deploy_key_desc=Chave de deploy só tem acesso somente leitura. Não é igual as chaves SSH de conta pessoal. -settings.no_deploy_keys=Você ainda não adicionou chaves para implantação de software. +settings.deploy_key_desc=Chave de Deploy só tem acesso somente leitura. Não é igual as chaves SSH de conta pessoal. +settings.no_deploy_keys=Você ainda não adicionou nenhuma chave de Deploy. settings.title=Título settings.deploy_key_content=Conteúdo da chave -settings.key_been_used=Uma chave de implantação com esse mesmo conteúdo já está em uso. -settings.key_name_used=Uma chave de implantação já existe com esse com mesmo nome. -settings.add_key_success=A nova chave de implantação '%s' foi adicionada com sucesso! -settings.deploy_key_deletion=Exclusão de chave de deploy -settings.deploy_key_deletion_desc=Excluir esta chave de implantação removerá permissões de acesso a este repositório. Quer mesmo continuar? -settings.deploy_key_deletion_success=Chave de implantação excluída com sucesso! - -diff.browse_source=Ver Código Fonte +settings.key_been_used=Uma chave de Deploy com esse mesmo conteúdo já está em uso. +settings.key_name_used=Uma chave de Deploy já existe com esse com mesmo nome. +settings.add_key_success=A nova chave de Deploy '%s' foi adicionada com sucesso! +settings.deploy_key_deletion=Exclusão de chave de Deploy +settings.deploy_key_deletion_desc=Excluir esta chave de Deploy removerá permissões de acesso a este repositório. Quer mesmo continuar? +settings.deploy_key_deletion_success=Chave de Deploy excluída com sucesso! + +diff.browse_source=Ver código fonte diff.parent=pai diff.commit=commit diff.data_not_available=Dados de Diff não disponíveis. @@ -758,14 +758,14 @@ diff.show_split_view=Visão dividida diff.show_unified_view=Visão unificada diff.stats_desc= %d arquivos alterados com %d adições e %d exclusões diff.bin=BIN -diff.view_file=Ver Arquivo +diff.view_file=Ver arquivo diff.file_suppressed=Diferenças do arquivo suprimidas por serem muito extensas diff.too_many_files=Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff release.releases=Versões -release.new_release=Nova Versão +release.new_release=Nova versão release.draft=Rascunho -release.prerelease=Versão Prévia +release.prerelease=Versão prévia release.stable=Estável release.edit=editar release.ahead=%d commits para %s depois desta versão @@ -783,31 +783,31 @@ release.loading=Carregando... release.prerelease_desc=Esta é uma versão prévia release.prerelease_helper=Vou salientar que esta versão é identificada como não pronta para produção. release.cancel=Cancelar -release.publish=Publicar Versão -release.save_draft=Salvar Rascunho -release.edit_release=Editar Versão -release.delete_release=Deletar esta versão -release.deletion=Deleção de versão -release.deletion_desc=Deletar esta versão vai deletar a tag do git correspondente. Você deseja continuar? -release.deletion_success=A versão foi deletada com sucesso! -release.tag_name_already_exist=Já existiu versão com esse nome de tag. +release.publish=Publicar versão +release.save_draft=Salvar rascunho +release.edit_release=Editar versão +release.delete_release=Excluir esta versão +release.deletion=Exclusão de versão +release.deletion_desc=Excluir esta versão vai remover a tag do git correspondente. Você deseja continuar? +release.deletion_success=A versão foi removida com sucesso! +release.tag_name_already_exist=Já existe uma versão com esse nome de tag. release.tag_name_invalid=Nome de tag não é válido. release.downloads=Downloads [org] -org_name_holder=Nome da Organização +org_name_holder=Nome da organização org_full_name_holder=Nome completo da organização org_name_helper=Nomes de grandes organizações são curtos e memoráveis. -create_org=Criar Organização +create_org=Criar organização repo_updated=Atualizado people=Pessoas -invite_someone=Convidar Alguém +invite_someone=Convidar alguém teams=Equipes lower_members=membros lower_repositories=repositórios -create_new_team=Criar Nova Equipe +create_new_team=Criar nova equipe org_desc=Descrição -team_name=Nome da Equipe +team_name=Nome da equipe team_desc=Descrição team_name_helper=Você usará este nome para mencionar esta equipe em conversas. team_desc_helper=Do que trata essa equipe? @@ -818,19 +818,19 @@ form.name_pattern_not_allowed=Não é permitido usar o padrão '%s' para o nome settings=Configurações settings.options=Opções -settings.full_name=Nome Completo +settings.full_name=Nome completo settings.website=Site settings.location=Localização settings.update_settings=Atualizar Configurações settings.update_setting_success=Configuração da organização atualizada com sucesso. settings.change_orgname_prompt=Esta mudança vai afetar os links para esta organização. settings.update_avatar_success=A configuração de avatar da organização foi atualizado com sucesso. -settings.delete=Deletar Organização -settings.delete_account=Deletar Esta Organização -settings.delete_prompt=A operação deletará esta organização permanentemente, e NÃO PODERÁ ser desfeita! -settings.confirm_delete_account=Confirmar Deleção -settings.delete_org_title=Deleção da Organização -settings.delete_org_desc=Esta organização será deletada permanentemente, você quer continuar? +settings.delete=Excluir organização +settings.delete_account=Excluir esta organização +settings.delete_prompt=A operação irá excluir esta organização permanentemente, e NÃO PODERÁ ser desfeita! +settings.confirm_delete_account=Confirmar exclusão +settings.delete_org_title=Exclusão da organização +settings.delete_org_desc=Esta organização será excluída permanentemente, você quer continuar? settings.hooks_desc=Adicionar Webhooks que serão acionados para todos os repositórios dessa organização. members.membership_visibility=Visibilidade da associação: @@ -844,32 +844,32 @@ members.member=Membro members.remove=Remover members.leave=Sair members.invite_desc=Adicionar novo membro em %s: -members.invite_now=Convidar Agora +members.invite_now=Convidar agora teams.join=Juntar-se teams.leave=Deixar -teams.read_access=Acesso de Leitura +teams.read_access=Acesso de leitura teams.read_access_helper=Esta equipe poderá ver e clonar os repositórios dela. -teams.write_access=Acesso de Escrita +teams.write_access=Acesso de escrita teams.write_access_helper=Esta equipa será capaz de ler os seus repositórios, bem como fazer push para eles. -teams.admin_access=Acesso do Administrador +teams.admin_access=Acesso do administrador teams.admin_access_helper=Esta equipe será capaz de fazer push/pull em seus repositórios, bem como adicionar-lhes outros colaboradores. teams.no_desc=Esta equipe não tem descrição teams.settings=Configurações teams.owners_permission_desc=Donos tem acesso total a todos repositórios e também direitos de administrador para a organização. -teams.members=Membros da Equipe -teams.update_settings=Atualizar Configurações -teams.delete_team=Deletar Esta Equipe -teams.add_team_member=Adicionar Membro da Equipe -teams.delete_team_title=Deleção da Equipe -teams.delete_team_desc=Este equipe será deletada, você quer continuar? Membros desta equipe poderão perder acesso a alguns repositórios. -teams.delete_team_success=A equipe dada foi deletada com sucesso. +teams.members=Membros da equipe +teams.update_settings=Atualizar configurações +teams.delete_team=Excluir esta equipe +teams.add_team_member=Adicionar membro na equipe +teams.delete_team_title=Exclusão da equipe +teams.delete_team_desc=Este equipe será excluída, você quer continuar? Membros desta equipe poderão perder acesso a alguns repositórios. +teams.delete_team_success=A equipe dada foi excluída com sucesso. teams.read_permission_desc=Essa equipe concede acesso para Leitura: membros podem ver e clonar os repositórios da equipe. teams.write_permission_desc=Esta equipe concede acesso para escrita: Membros podem ler e fazer push para os repositórios da equipe. teams.admin_permission_desc=Esta equipe concede acesso de Administrador: Membros podem ler, fazer push e adicionar outros colaboradores para os repositórios da equipe. -teams.repositories=Repositórios da Equipe +teams.repositories=Repositórios da equipe teams.search_repo_placeholder=Pesquisar repositório... -teams.add_team_repository=Adicionar Repositório da Equipe +teams.add_team_repository=Adicionar repositório da equipe teams.remove_repo=Remover teams.add_nonexistent_repo=O repositório que você está tentando adicionar não existe, por favor, crie-o primeiro. @@ -888,9 +888,9 @@ total=Total: %d dashboard.statistic=Estatística dashboard.operations=Operações -dashboard.system_status=Status do Monitor de Sistema +dashboard.system_status=Status do monitor de sistema dashboard.statistic_info=O banco de dados do Gitea contém %d usuários, %d organizações, %d chaves públicas, %d repositórios, %d observadores, %d estrelas, %d ações, %d acessos, %d questões, %d comentários, %d contas sociais, %d seguidores, %d espelhos, %d versões, %d origens de login, %d Hooks da Web, %d milestones, %d labels, %d tarefas hook, %d equipes, %d tarefas de atualização, %d anexos. -dashboard.operation_name=Nome da Operação +dashboard.operation_name=Nome da operação dashboard.operation_switch=Trocar dashboard.operation_run=Executar dashboard.clean_unbind_oauth=Limpar OAuthes não acoplados @@ -910,38 +910,38 @@ dashboard.resync_all_update_hooks_success=Os hooks de atualização de todos os dashboard.reinit_missing_repos=Reinicializar todos os registros de repositório que perderam os arquivos do Git dashboard.reinit_missing_repos_success=Todos os repositórios que perderam arquivos do Git foram reinicializados com sucesso. -dashboard.server_uptime=Servidor Ligado +dashboard.server_uptime=Uptime do Servidor dashboard.current_goroutine=Goroutines Atuais -dashboard.current_memory_usage=Uso de Memória Atual -dashboard.total_memory_allocated=Total de Memória Alocada -dashboard.memory_obtained=Memória Obtida -dashboard.pointer_lookup_times=Nº de Consultas a Ponteiros -dashboard.memory_allocate_times=Nº de Alocações de Memória -dashboard.memory_free_times=Nº de Liberações de Memória -dashboard.current_heap_usage=Uso Atual da Heap -dashboard.heap_memory_obtained=Memória de Heap Obtida -dashboard.heap_memory_idle=Memória da Heap Ociosa -dashboard.heap_memory_in_use=Memória da Heap em Uso -dashboard.heap_memory_released=Memória da Heap Liberada -dashboard.heap_objects=Objetos na Heap -dashboard.bootstrap_stack_usage=Uso de Pilha Bootstrap -dashboard.stack_memory_obtained=Memória de Pilha Obtida -dashboard.mspan_structures_usage=Uso de Estruturas de MSpan -dashboard.mspan_structures_obtained=Estruturas de MSpan Obtidas -dashboard.mcache_structures_usage=Uso de Estruturas de MCache -dashboard.mcache_structures_obtained=Estruturas de MCache Obtidas -dashboard.profiling_bucket_hash_table_obtained=Perfil Obtido da Bucket Hash Table -dashboard.gc_metadata_obtained=Metadados do GC Obtidos -dashboard.other_system_allocation_obtained=Outra Alocação de Sistema Obtida -dashboard.next_gc_recycle=Próxima Reciclagem do GC -dashboard.last_gc_time=Desde da Última Vez do GC -dashboard.total_gc_time=Pausa Total do GC -dashboard.total_gc_pause=Pausa Total do GC -dashboard.last_gc_pause=Última Pausa do GC -dashboard.gc_times=Nº Execuções do GC - -users.user_manage_panel=Painel de Gerenciamento do Usuário -users.new_account=Criar Nova Conta +dashboard.current_memory_usage=Uso de memória atual +dashboard.total_memory_allocated=Total de memória alocada +dashboard.memory_obtained=Memória obtida +dashboard.pointer_lookup_times=Nº de consultas a ponteiros +dashboard.memory_allocate_times=Nº de alocações de memória +dashboard.memory_free_times=Nº de liberações de memória +dashboard.current_heap_usage=Uso atual da heap +dashboard.heap_memory_obtained=Memória de heap obtida +dashboard.heap_memory_idle=Memória da heap ociosa +dashboard.heap_memory_in_use=Memória da heap em uso +dashboard.heap_memory_released=Memória da heap liberada +dashboard.heap_objects=Objetos na heap +dashboard.bootstrap_stack_usage=Uso de pilha bootstrap +dashboard.stack_memory_obtained=Memória de pilha obtida +dashboard.mspan_structures_usage=Uso de estruturas de MSpan +dashboard.mspan_structures_obtained=Estruturas de MSpan obtidas +dashboard.mcache_structures_usage=Uso de estruturas de MCache +dashboard.mcache_structures_obtained=Estruturas de MCache obtidas +dashboard.profiling_bucket_hash_table_obtained=Perfil obtido da Bucket Hash Table +dashboard.gc_metadata_obtained=Metadados do GC obtidos +dashboard.other_system_allocation_obtained=Outra alocação de sistema obtida +dashboard.next_gc_recycle=Próxima reciclagem do GC +dashboard.last_gc_time=Desde da ultima vez do GC +dashboard.total_gc_time=Pausa total do GC +dashboard.total_gc_pause=Pausa total do GC +dashboard.last_gc_pause=Última pausa do GC +dashboard.gc_times=Nº de execuções do GC + +users.user_manage_panel=Painel de gerenciamento do usuário +users.new_account=Criar nova conta users.name=Nome users.activated=Ativado users.admin=Administrador @@ -955,7 +955,7 @@ users.local=Local users.auth_login_name=Nome de login da autenticação users.password_helper=Deixe em branco para não mudar. users.update_profile_success=O perfil da conta foi atualizado com sucesso. -users.edit_account=Editar Conta +users.edit_account=Editar conta users.max_repo_creation=Limite máximo de criação de repositórios users.max_repo_creation_desc=(Use "-1" para utilizar o limite padrão) users.is_activated=Esta conta está ativada @@ -963,24 +963,24 @@ users.prohibit_login=Esta conta está proibida de efetuar login users.is_admin=Esta conta tem permissões de administrador users.allow_git_hook=Esta conta tem permissões para criar hooks do Git users.allow_import_local=Esta conta tem permissões para importar repositórios locais -users.update_profile=Atualizar Perfil da Conta -users.delete_account=Deletar Esta Conta +users.update_profile=Atualizar perfil da conta +users.delete_account=Excluir esta conta users.still_own_repo=Sua conta ainda é proprietária do repositório, você tem que excluir ou transferi-lo primeiro. users.still_has_org=Sua conta ainda faz parte da organização, você deve sair ou excluí-la primeiro. -users.deletion_success=Conta deletada com sucesso! +users.deletion_success=Conta excluída com sucesso! -orgs.org_manage_panel=Painel de Gerenciamento da Organização +orgs.org_manage_panel=Painel de gerenciamento da organização orgs.name=Nome orgs.teams=Equipes orgs.members=Membros -repos.repo_manage_panel=Painel de Gerenciamento do Repositório +repos.repo_manage_panel=Painel de gerenciamento do repositório repos.owner=Dono repos.name=Nome repos.private=Privado repos.watches=Observadores repos.stars=Favoritos -repos.issues=Problemas +repos.issues=Issues auths.auth_manage_panel=Painel de gerenciamento da autenticação auths.new=Adicionar nova fonte @@ -1025,24 +1025,24 @@ auths.update_success=A configuração da autenticação foi atualizada com suces auths.update=Atualizar a configuração da autenticação auths.delete=Excluir esta autenticação auths.delete_auth_title=Exclusão da autenticação -auths.delete_auth_desc=Esta autenticação esta prestes a ser deletada, deseja continuar? -auths.still_in_used=Esta autenticação ainda é usada por alguns usuários. Por favor delete ou converta esses usuários para outro tipo de login primeiro. -auths.deletion_success=Autenticação deletada com sucesso! - -config.server_config=Configuração do Servidor -config.app_name=Nome do Aplicativo -config.app_ver=Versão do Aplicativo -config.app_url=URL do Aplicativo +auths.delete_auth_desc=Esta autenticação esta prestes a ser excluída, deseja continuar? +auths.still_in_used=Esta autenticação ainda é usada por alguns usuários. Por favor remova ou converta esses usuários para outro tipo de login primeiro. +auths.deletion_success=Autenticação excluída com sucesso! + +config.server_config=Configuração do servidor +config.app_name=Nome do aplicativo +config.app_ver=Versão do aplicativo +config.app_url=URL do aplicativo config.domain=Domínio config.offline_mode=Modo Offline -config.disable_router_log=Desabilitar o Log do Roteador -config.run_user=Usuário de Execução -config.run_mode=Modo de Execução -config.repo_root_path=Caminho Raiz do Repositório -config.static_file_root_path=Caminho Raiz para Arquivo Estático -config.log_file_root_path=Caminho Raiz para Arquivo de Log -config.script_type=Tipo de Script -config.reverse_auth_user=Usuário de Autenticação Reversa +config.disable_router_log=Desabilitar o Log do router +config.run_user=Usuário de execução +config.run_mode=Modo de execução +config.repo_root_path=Caminho raiz do repositório +config.static_file_root_path=Caminho raiz para arquivo estático +config.log_file_root_path=Caminho raiz para arquivo de log +config.script_type=Tipo de script +config.reverse_auth_user=Usuário de autenticação reversa config.ssh_config=Configuração de SSH config.ssh_enabled=Habilitado @@ -1056,7 +1056,7 @@ config.ssh_keygen_path=Caminho do keygen ('ssh-keygen') config.ssh_minimum_key_size_check=Verificar tamanho mínimo da chave config.ssh_minimum_key_sizes=Tamanhos mínimos da chave -config.db_config=Configuração do Banco de Dados +config.db_config=Configuração do banco de dados config.db_type=Tipo config.db_host=Host config.db_name=Nome @@ -1066,23 +1066,23 @@ config.db_ssl_mode_helper=(apenas para "postgres") config.db_path=Caminho config.db_path_helper=(para "sqlite3" e "tidb") -config.service_config=Configuração do Serviço -config.register_email_confirm=Requerer Confirmação de E-mail -config.disable_register=Desabilitar Registro -config.show_registration_button=Mostrar Botão de Registo -config.require_sign_in_view=Requerer Entrar no Gitea para Ver -config.mail_notify=Notificação de Correio +config.service_config=Configuração do serviço +config.register_email_confirm=Requerer confirmação de e-mail +config.disable_register=Desabilitar registro +config.show_registration_button=Mostrar botão de registo +config.require_sign_in_view=Requerer entrar no Gitea para visualizar +config.mail_notify=Notificação de e-mail config.disable_key_size_check=Desativar verificação de tamanho mínimo da chave -config.enable_captcha=Habilitar o Captcha +config.enable_captcha=Habilitar o captcha config.active_code_lives=Ativar Code Lives -config.reset_password_code_lives=Redefinir Senha de Code Lives +config.reset_password_code_lives=Redefinir senha de Code Lives config.webhook_config=Configuração de Hook da Web config.queue_length=Tamanho da fila -config.deliver_timeout=Intervalo de Entrega -config.skip_tls_verify=Pular Verificar TLS +config.deliver_timeout=Intervalo de entrega +config.skip_tls_verify=Pular verificação de TLS -config.mailer_config=Configuração de Correio +config.mailer_config=Configuração de envio de e-mail config.mailer_enabled=Habilitado config.mailer_disable_helo=Desabilitar HELO config.mailer_name=Nome @@ -1095,23 +1095,23 @@ config.test_mail_sent=O email de teste foi enviado para '%s'. config.oauth_config=Configuração do OAuth config.oauth_enabled=Habilitado -config.cache_config=Configuração de Cache -config.cache_adapter=Adaptador de Cache -config.cache_interval=Intervalo de Cache -config.cache_conn=Conexão de Cache +config.cache_config=Configuração de cache +config.cache_adapter=Adaptador de cache +config.cache_interval=Intervalo de cache +config.cache_conn=Conexão de cache -config.session_config=Configuração da Sessão -config.session_provider=Provedor da Sessão -config.provider_config=Configuração do Provedor -config.cookie_name=Nome do Cookie -config.enable_set_cookie=Habilitar Uso de Cookie +config.session_config=Configuração da sessão +config.session_provider=Provedor da sessão +config.provider_config=Configuração do provedor +config.cookie_name=Nome do cookie +config.enable_set_cookie=Habilitar uso de cookie config.gc_interval_time=Tempo de Intervalo do GC -config.session_life_time=Tempo de Vida da Sessão +config.session_life_time=Tempo de vida da sessão config.https_only=Apenas HTTPS -config.cookie_life_time=Tempo de Vida do Cookie +config.cookie_life_time=Tempo de vida do cookie -config.picture_config=Configuração da Imagem -config.picture_service=Serviço de Imagens +config.picture_config=Configuração da imagem +config.picture_service=Serviço de imagens config.disable_gravatar=Desativar Gravatar config.enable_federated_avatar=Habilitar avatares federativos @@ -1120,28 +1120,28 @@ config.git_disable_diff_highlight=Habilitar realce de mudanças no diff config.git_max_diff_lines=Máximo de linhas mostradas no diff (para um único arquivo) config.git_max_diff_line_characters=Máximo de caracteres mostrados no diff (para uma única linha) config.git_max_diff_files=Máximo de arquivos a serem mostrados no diff -config.git_gc_args=Argumentos do coletor de lixo +config.git_gc_args=Argumentos do GC config.git_migrate_timeout=Timeout de migração -config.git_mirror_timeout=Timeout para sincronização de espelho +config.git_mirror_timeout=Timeout para sincronização de mirror config.git_clone_timeout=Timeout para operação de clone config.git_pull_timeout=Timeout para operação de pull -config.git_gc_timeout=Timeout para execução do coletor de lixo +config.git_gc_timeout=Timeout para execução do GC -config.log_config=Configuração de Log -config.log_mode=Modo do Log +config.log_config=Configuração de log +config.log_mode=Modo do log -monitor.cron=Tarefas Cron +monitor.cron=Tarefas cron monitor.name=Nome monitor.schedule=Cronograma -monitor.next=Próxima Vez -monitor.previous=Última Vez -monitor.execute_times=Nº de Execuções -monitor.process=Processos em Execução +monitor.next=Próxima vez +monitor.previous=Última vez +monitor.execute_times=Nº de execuções +monitor.process=Processos em execução monitor.desc=Descrição -monitor.start=Hora de Início -monitor.execute_time=Tempo de Execução +monitor.start=Hora de início +monitor.execute_time=Tempo de execução -notices.system_notice_list=Sistema de Notificações +notices.system_notice_list=Sistema de notificações notices.view_detail_header=Ver detalhe do anúncio notices.actions=Ações notices.select_all=Selecionar tudo diff --git a/conf/locale/locale_ru-RU.ini b/conf/locale/locale_ru-RU.ini index 7161c058ea..536ef54403 100644 --- a/conf/locale/locale_ru-RU.ini +++ b/conf/locale/locale_ru-RU.ini @@ -96,7 +96,7 @@ offline_mode=Включение офлайн режима offline_mode_popup=Отключить CDN даже в производственном режиме, все файлы ресурсов будут раздаваться локально. disable_gravatar=Отключить службу Gravatar disable_gravatar_popup=Отключить Gravatar и пользовательские источники, все аватары по-умолчанию загружаются пользователями. -federated_avatar_lookup=Enable Federated Avatars Lookup +federated_avatar_lookup=Включить поиск внешних Аватаров federated_avatar_lookup_popup=Enable federated avatars lookup to use federated open source service based on libravatar. disable_registration=Отключить самостоятельную регистрацию disable_registration_popup=Запретить пользователям самостоятельную регистрацию, только администратор может создавать аккаунты. @@ -269,8 +269,8 @@ change_username_prompt=Это изменение может повлечь за continue=Далее cancel=Отмена -lookup_avatar_by_mail=Lookup Avatar by mail -federated_avatar_lookup=Federated Avatar Lookup +lookup_avatar_by_mail=Найти Аватар по адресу эл. почты +federated_avatar_lookup=Найти внешний Аватар enable_custom_avatar=Включить собственный аватар choose_new_avatar=Выбрать новый аватар update_avatar=Обновить настройку аватара @@ -431,14 +431,14 @@ editor.new_file=Новый файл editor.upload_file=Загрузить файл editor.edit_file=Редактировать файл editor.preview_changes=Просмотр изменений -editor.cannot_edit_non_text_files=Cannot edit non-text files +editor.cannot_edit_non_text_files=Возможно редактировать только текстовые файлы editor.edit_this_file=Отредактируйте этот файл editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file editor.fork_before_edit=Создайте ветку репозитория перед редактированием файла editor.delete_this_file=Удалить файл -editor.must_have_write_access=You must have write access to make or propose changes to this file +editor.must_have_write_access=Вам необходимо иметь доступ на запись, чтобы вносить или предлагать правки этого файла editor.file_delete_success=File '%s' has been deleted successfully! -editor.name_your_file=Name your file... +editor.name_your_file=Назовите свой файл... editor.filename_help=To add directory, just type it and press /. To remove a directory, go to the beginning of the field and press backspace. editor.or=или editor.cancel_lower=отмена @@ -453,16 +453,16 @@ editor.create_new_branch=Create a new branch for this commit an editor.new_branch_name_desc=Новое название ветки... editor.cancel=Отмена editor.filename_cannot_be_empty=Имя файла не может быть пустым. -editor.branch_already_exists=Branch '%s' already exists in this repository. +editor.branch_already_exists=Ветка «%s» уже существует в этом репозитории. editor.directory_is_a_file=Entry '%s' in the parent path is a file not a directory in this repository. editor.filename_is_a_directory=The filename '%s' is an existing directory in this repository. editor.file_editing_no_longer_exists=The file '%s' you are editing no longer exists in the repository. editor.file_changed_while_editing=File content has been changed since you started editing. Click here to see what have been changed or press commit again to overwrite those changes. -editor.file_already_exists=A file with name '%s' already exists in this repository. +editor.file_already_exists=Файл с именем «%s» уже существует в этом репозитории. editor.no_changes_to_show=Нет изменений. -editor.fail_to_update_file=Failed to update/create file '%s' with error: %v +editor.fail_to_update_file=Не удалось обновить/создать файл «%s» из-за ошибки: %v editor.add_subdir=Добавьте подкаталог... -editor.unable_to_upload_files=Failed to upload files to '%s' with error: %v +editor.unable_to_upload_files=Не удалось загрузить файлы в «%s» из-за ошибки: %v editor.upload_files_to_dir=Загрузить файлы '%s' commits.commits=Коммиты @@ -490,7 +490,7 @@ issues.create=Добавить задачу issues.new_label=Новая метка issues.new_label_placeholder=Имя метки... issues.create_label=Добавить метку -issues.label_templates.title=Load a predefined set of labels +issues.label_templates.title=Загрузить набор предопределённых меток issues.label_templates.info=There aren’t any labels yet. You can click on the "New Label" button above to create one or use a predefined set below. issues.label_templates.helper=Выберите метку issues.label_templates.use=Использовать ярлык @@ -536,7 +536,7 @@ issues.commit_ref_at=`упомянул эту задачу в коммите Sign in to join this conversation. +issues.sign_in_require_desc=Войдите, чтобы присоединиться к обсуждению. issues.edit=Изменить issues.cancel=Отмена issues.save=Сохранить @@ -551,8 +551,8 @@ issues.label_deletion=Удаление метки issues.label_deletion_desc=Удаление ярлыка затронет все связанные задачи. Продолжить? issues.label_deletion_success=Метка была удалена успешно! issues.num_participants=%d участников -issues.attachment.open_tab=`Click to see "%s" in a new tab` -issues.attachment.download=`Click to download "%s"` +issues.attachment.open_tab=`Нажмите, чтобы увидеть "%s" в новой вкладке` +issues.attachment.download=`Нажмите, чтобы скачать "%s"` pulls.new=Новый запрос на слияние pulls.compare_changes=Сравнить изменения @@ -634,7 +634,7 @@ settings.githooks=Git хуки settings.basic_settings=Основные параметры settings.mirror_settings=Настройки Зеркала settings.sync_mirror=Синхронизировать -settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute. +settings.mirror_sync_in_progress=Выполняется синхронизация Зеркала, пожалуйста, обновите эту страницу через минуту. settings.site=Официальный сайт settings.update_settings=Обновить настройки settings.change_reponame_prompt=Это изменение повлияет на отношения ссылок к этому репозиторию. @@ -675,7 +675,7 @@ settings.delete_notices_1=- Эта операция НЕ МОЖЕТRiktninjerna nogrant innan du ändrar någonting på denna sida! +requite_db_desc=Gogs kräver MySQL, PostgreSQL, SQLite3 eller TiDB. +db_title=Databasinställningar +db_type=Databastyp +host=Server +user=Användare +password=Lösenord +db_name=Databasens namn +db_helper=Se till att i MySQL använda INNODB med teckenuppsättningen utf8_general_ci. +ssl_mode=SSL-läge +path=Filväg +sqlite_helper=Sökvägen för SQLite3 eller TiDB databas.
Vänligen använd den absoluta sökvägen när du kör som en tjänst. +err_empty_db_path=SQLite3 eller TiDB databassökvägen får inte vara tom. +err_invalid_tidb_name=TiDB databasnamn tillåter inte tecknen "." och "-". +no_admin_and_disable_registration=Du kan inte inaktivera registrering utan att skapa ett administratörskonto. +err_empty_admin_password=Administratörslösenordet får ej vara tomt. + +general_title=Allmänna inställningar för Gogs +app_name=Applikationsnamn +app_name_helper=Skriv ditt organisationsnamn här stort och tydligt! +repo_path=Rotsökväg för utvecklingskatalog +repo_path_helper=Alla fjärr Git repos kommer bli sparade till denna mappen. +run_user=Exekverande Användare +run_user_helper=Denna användaren måste ha till gång till Huvudsökvägen för Repos och köra Gogs. +domain=Domän +domain_helper=Detta påverkar SSH klonings webbadresser. +ssh_port=SSH-port +ssh_port_helper=Portnumret som din SSH-server brukar, lämna tomt för att inaktivera SSH-funktionaliteten. +http_port=HTTP Port +http_port_helper=Portnumret vilket applikationen kommer lyssnar på. +app_url=Applikationsadressen +app_url_helper=Detta påverkar HTTP/HTTPS kloningsadressen och på platser i e-post. +log_root_path=Loggsökväg +log_root_path_helper=Katalog till vilken loggfiler skrivs. + +optional_title=Övriga inställningar +email_title=E-post tjänstens inställningar +smtp_host=SMTP-server +smtp_from=Från +smtp_from_helper=Epostaddress att skicka email ifrån, enligt RFC 5322. Den kan vara skriven i formatet 'email@example.com' alternativt '"Namn" '. +mailer_user=Avsändares e-post +mailer_password=Avsändares lösenord +register_confirm=Aktivera registreringsbekräftelse +mail_notify=Aktivera e-postavisering +server_service_title=Serverns och andra Tjänsters inställningar +offline_mode=Aktivera Nedkopplat Läge +offline_mode_popup=Inaktivera CDN även i produktionsläge, alla resursfiler kommer att distribureras lokalt. +disable_gravatar=Inaktivera Gravatar-tjänsten +disable_gravatar_popup=Inaktivera Gravatar och externa källor, alla avatarer är uppladdade av användaren alternativt standard. +federated_avatar_lookup=Aktivera förenad uppslagning av avatarer +federated_avatar_lookup_popup=Använd libravatar vid förenad uppslagning av avatarer. +disable_registration=Stäng av självregistrering +disable_registration_popup=Stäng av självregistrering av användare, endast administratören kan skapa konton. +enable_captcha=Aktivera Captcha +enable_captcha_popup=Kräv captcha för användarregistrering. +require_sign_in_view=Kräv inloggning för att visa sidor +require_sign_in_view_popup=Bara inloggade användare kan besöka sidorna, besökare kommer enbart kunna se inloggings/registreringssidor. +admin_setting_desc=Du behöver inte skapa ett administratörskonto just nu, kontot som har ID = 1 kommer automatiskt att bli administratör. +admin_title=Admin-konto inställningar +admin_name=Användarnamn +admin_password=Lösenord +confirm_password=Bekräfta lösenord +admin_email=Administratörs Epost +install_gogs=Installera Gogs +test_git_failed=Misslyckades att testa 'git' kommando: %v +sqlite3_not_available=Din release stödjer ej SQLite3, ladda vänligen ner den officiella binären via %s, inte gobuild varianten. +invalid_db_setting=Databas inställningen är inkorrekt: %v +invalid_repo_path=Utvecklingskatalogens rotsökväg är ogiltig: %v +run_user_not_match=Köranvändaren är inte aktuell användare: %s -> %s +save_config_failed=Konfigurationssparningen misslyckades: %v +invalid_admin_setting=Inställningarna för administratörskontot är felaktiga: %v +install_success=Välkommen! Vi är glada att du väljer Gogs, ha kul och ta hand om dig. +invalid_log_root_path=Ogiltig rotsökväg för loggfiler: %v + +[home] +uname_holder=Användarnamn eller e-post +password_holder=Lösenord +switch_dashboard_context=Växla Visad Instrumentpanel +my_repos=Mina utvecklingskataloger +show_more_repos=Visa fler förråd... +collaborative_repos=Kollaborativa Utvecklingskataloger +my_orgs=Mina organisationer +my_mirrors=Mina speglar +view_home=Visa %s + +issues.in_your_repos=I dina utvecklingskataloger + +[explore] +repos=Utvecklingskataloger +users=Användare +search=Sök + +[auth] +create_new_account=Skapa nytt konto +register_hepler_msg=Har du redan ett konto? Logga in nu! +social_register_hepler_msg=Har du redan ett konto? Anslut det nu! +disable_register_prompt=Tyvärr är användarregistreringen inaktiverad. Vänligen kontakta din administratör. +disable_register_mail=Tyvärr så är registreringsbekräftelemailutskick inaktiverat. +remember_me=Kom ihåg mig +forgot_password=Glömt lösenord +forget_password=Glömt lösenordet? +sign_up_now=Behöver du ett konto? Registrera dig nu. +confirmation_mail_sent_prompt=Ett nytt bekräftelsemail has skickats till %s, vänligen kolla din inkorg inom dom kommande %d timmarna för att slutföra registreringsprocessen. +active_your_account=Aktivera ditt konto +prohibit_login=Inloggning förhindrad +prohibit_login_desc=Ditt konto är förhindrat från att logga in. Vänligen kontakta webbplatsadministratören. +resent_limit_prompt=Tyvärr, du har nyligen begärt ett aktiveringsmail. Vänligen vänta 3 minuter och försök sedan igen. +has_unconfirmed_mail=Hej %s, du har en obekräftad epostaddress (%s). Om du inte har fått ett bekräftelsemail eller behöver ett nytt, klicka på knappen nedan. +resend_mail=Klicka här för att skicka ditt aktiveringsmejl igen +email_not_associate=Denna e-postadress är inte knutet till något konto. +send_reset_mail=Klicka här för att skicka e-post med lösenordsåterställning (igen) +reset_password=Återställ ditt lösenord +invalid_code=Tyvärr, din bekräftelsekod har antingen upphört att gälla eller är ogiltig. +reset_password_helper=Klicka här för att återställa ditt lösenord +password_too_short=Lösenordet får ej vara kortare än 6 tecken. +non_local_account=Icke-lokala konton får inte ändra lösenord genom Gogs. + +[mail] +activate_account=Vänligen aktivera ditt konto +activate_email=Verifiera din epostaddress +reset_password=Återställ ditt lösenord +register_success=Registreringen slutförd, välkommen +register_notify=Välkommen ombord + +[modal] +yes=Ja +no=Nej +modify=Ändra + +[form] +UserName=Användarnamn +RepoName=Utvecklingskatalogens namn +Email=E-postadress +Password=Lösenord +Retype=Skriv in lösenordet igen +SSHTitle=SSH-nyckelnamn +HttpsUrl=HTTPS-URL +PayloadUrl=Payload-URL +TeamName=Gruppnamn +AuthName=Auktoriseringsnamn +AdminEmail=Administratörs Epost + +NewBranchName=Nytt grennamn +CommitSummary=Sammanfattning av incheckning +CommitMessage=Incheckningsmeddelande +CommitChoice=Incheckningsval +TreeName=Filsökväg +Content=Innehåll + +require_error=får inte vara tomt +alpha_dash_error=` får bara innehålla bokstäver, nummer och bindestreck (-_).` +alpha_dash_dot_error=` får bara innehålla bokstäver, nummer, bindestreck (-_) och punkt` +size_error=` måste vara av storleken %s` +min_size_error=` måste innehålla minst %s tecken.` +max_size_error=` får inte innehålla mer än %s tecken.` +email_error=` är inte en giltlig epostaddress.` +url_error=Den givna URL-adressen är inte valid +include_error=` måste innehålla texten '%s'.` +unknown_error=Okänt fel: +captcha_incorrect=Captcha stämmer inte överens. +password_not_match=Givna lösenord stämmer inte överens med varandra. + +username_been_taken=Användarnamnet finns redan. +repo_name_been_taken=Namnet på utvecklingskatalogen har redan används. +org_name_been_taken=Organisationsnamnet har redan används. +team_name_been_taken=Team namn är redan använt. +email_been_used=E-postadressen har redan använts. +username_password_incorrect=Användarnamnet eller lösenordet är inte korrekt. +enterred_invalid_repo_name=Se till att utvecklingskatalogen som du angav är rätt. +enterred_invalid_owner_name=Kontrollera att ägarnamnet som du angav är rätt. +enterred_invalid_password=Se till att den som lösenord du angett är rätt. +user_not_exist=Angiven användare saknas. +last_org_owner=Att ta bort den sista användaren i ägare-teamet är inte tillåtet då det måste finnas minst en användare i ägare-teamet. + +invalid_ssh_key=Tyvärr, Din SSH-nyckel: %s kan inte verifieras +unable_verify_ssh_key=Gogs kan inte verifiera din SSH-nyckel, men Gogs antar att den är giltigt, vänligen dubbelkolla din SSH-nyckel. +auth_failed=Autentisering misslyckades: %v + +still_own_repo=Ditt konto har fortfarande ägandeskap över minst en utvecklingskatalog, måste du ta bort eller överföra dem först. +still_has_org=Ditt konto har fortfarande medlemskap i en organisation, du måste lämna den eller ta bort dina medlemskap först. +org_still_own_repo=Denna organisation har fortfarande ägandeskap över en eller flera utvecklingskataloger, du måste ta bort eller överföra dem först. + +target_branch_not_exist=Målgrenen finns inte. + +[user] +change_avatar=Byt din avatar +join_on=Gick med +repositories=Utvecklingskataloger +activity=Offentlig Aktivitet +followers=Följare +starred=Stjärnmärkta +following=Följer +follow=Följ +unfollow=Sluta följa + +form.name_reserved=Användarnamnet "%s" är reserverad. +form.name_pattern_not_allowed=Användarnamnet '%s' är inte tillåtet. + +[settings] +profile=Profil +password=Lösenord +avatar=Avatar +ssh_keys=SSH-nycklar +social=Sociala konton +applications=Applikationer +orgs=Organisationer +delete=Radera konto +uid=Uid + +public_profile=Offentlig profil +profile_desc=Din epostaddress är offentlig och kommer att användas för alla kontorelaterade notifieringar och alla webbaserade åtgärder gjorda på sidan. +password_username_disabled=Icke-lokala användare är inte tillåtna att ändra sitt användarnamn. +full_name=Fullständigt namn +website=Webbplats +location=Plats +update_profile=Uppdatera profil +update_profile_success=Din profil har uppdaterats. +change_username=Användarnamn ändrat +change_username_prompt=Denna ändring kommer att påverka hur länkar refererar till ditt konto. +continue=Fortsätt +cancel=Avbryt + +lookup_avatar_by_mail=Hämta avatar utifrån e-postadress +federated_avatar_lookup=Förenad uppslagning av avatar +enable_custom_avatar=Aktivera Egen Avatar +choose_new_avatar=Välj ny avatar +update_avatar=Uppdatera Avatarinställningar +delete_current_avatar=Tag bort aktuell avatar +uploaded_avatar_not_a_image=Den uppladdade filen är inte en bild. +update_avatar_success=Dina avatarinställningar har uppdaterats. + +change_password=Ändra lösenord +old_password=Nuvarande lösenord +new_password=Nytt lösenord +retype_new_password=Skriv ditt nya lösenord igen +password_incorrect=Nuvarande lösenord är felaktigt. +change_password_success=Lösenordet ändrades. Du kan nu logga in med ditt nya lösenord. +password_change_disabled=Icke-lokala användare är inte tillåtna att ändra sina lösenord. + +emails=E-postadresser +manage_emails=Hantera e-postadresser +email_desc=Din primära e-postadress kommer att användas för notifieringar och andra åtgärder. +primary=Primär +primary_email=Ställ in som primär +delete_email=Radera +email_deletion=Borttagning Av Epostaddress +email_deletion_desc=Borttagning av denna epostaddress kommer att ta bort relaterad information. Vill du fortsätta? +email_deletion_success=Epostaddressen har tagits bort! +add_new_email=Lägg till ny e-postadress +add_email=Lägga till e-post +add_email_confirmation_sent=Ett nytt bekräftelsemail har skickats till '%s', kontrollera vänligen din inbox inom dom närmsta %d timmarna för att slutföra bekräftelsen. +add_email_success=Din nya epostaddress har lagts till. + +manage_ssh_keys=Hantera SSH-nycklar +add_key=Lägg till nyckel +ssh_desc=Detta är en lista över SSH-nycklar som hör till ditt konto. Ta bort alla nycklar som du inte känner igen. +ssh_helper=Vet du inte hur? Kolla in Github's guide för att skapa din egen SSH-nycklar eller lösa vanliga problem som kan uppstå med SSH. +add_new_key=Lägg till SSH-nyckel +ssh_key_been_used=Innehåll i publik nyckel har använts. +ssh_key_name_used=Offentlig nyckel med samma namn har redan existerat. +key_name=Nyckelnamn +key_content=Innehåll +add_key_success=Ny SSH-nyckel "%s" har lagts till! +delete_key=Ta bort +ssh_key_deletion=SSH-nyckel radering +ssh_key_deletion_desc=Borttagning av denna SSH-nyckel kommer att ta bort all relaterad åtkomst för ditt konto. Vill du fortsätta? +ssh_key_deletion_success=SSH-nyckeln har tagits bort! +add_on=Tillagd +last_used=Användes senast +no_activity=Ingen nylig aktivitet +key_state_desc=Denna nyckel har använts inom dom senaste 7 dagarna +token_state_desc=Denna token har används inom dom senaste 7 dagarna + +manage_social=Hantera länkade sociala konton +social_desc=Detta är en lista över länkade sociala konton. Ta bort alla länkningar som du inte känner igen. +unbind=Ta bort länkning +unbind_success=Socialt konto är inte längre länkat. + +manage_access_token=Hantera personliga åtkomst-tokens +generate_new_token=Generera Nya Tokens +tokens_desc=Tokens som du har genererat kan användas för åtkomst av Gogs APIer. +new_token_desc=Varje token har full tillgång till ditt konto. +token_name=Tokennamn +generate_token=Generera Token +generate_token_succees=Din åtkomst-token har genererats! Se till att kopiera den nu, eftersom du inte kommer att kunna se den igen senare! +delete_token=Radera +access_token_deletion=Borttagning Av Personlig Åtkomsttoken +access_token_deletion_desc=Borttagning av denna personliga åtkomsttoken kommer att ta bort all relaterad åtkomst för applikationer. Vill du fortsätta? +delete_token_success=Personlig åtkomsttoken har tagits bort! Glöm inte bort att uppdatera din applikation också. + +delete_account=Radera ditt konto +delete_prompt=Åtgärden kommer at ta bort ditt konto permanent, och kan INTE ångras! +confirm_delete_account=Bekräfta Borttagelsen +delete_account_title=Kontoborttagning +delete_account_desc=Detta konto kommer att tas bort permanent, vill du fortsätta? + +[repo] +owner=Ägare +repo_name=Utvecklingskatalogens namn +repo_name_helper=Ett bra utvecklingskatalogsnamn består vanligtvis av korta, minnesvärda och unika nyckelord. +visibility=Synligt för +visiblity_helper=Denna utvecklingskatalog är Privat +visiblity_helper_forced=Administratören har tvingat alla nya utvecklingskataloger att vara Privata +visiblity_fork_helper=(Ändring av detta värde kommer att påverka alla forks) +clone_helper=Behöver du hjälp med kloning? Gå till Hjälp! +fork_repo=Forka Repo +fork_from=Forka Från +fork_visiblity_helper=Du kan inte ändra offentligheten på ett forkat repo. +repo_desc=Beskrivning +repo_lang=Språk +repo_gitignore_helper=Välj .gitignore-mallar +license=Licens +license_helper=Välj en licensfil +readme=Readme +readme_helper=Välj en readme-mall +auto_init=Initiera detta repo med valda filer och mall +create_repo=Skapa utvecklingskatalog +default_branch=Standardgren +mirror_prune=Rensa +mirror_prune_desc=Tag bort fjärrspårande referenser som inte längre finns på fjärren +mirror_interval=Speglingsintervall (timmar) +mirror_address=Speglingsaddress +mirror_address_desc=Vänligen inkludera nödvändiga användaruppgifter i adressen. +mirror_last_synced=Senast synkad +watchers=Observerare +stargazers=Stjärnmärkare +forks=Forks + +form.reach_limit_of_creation=Ägaren har nått maxgränsen av %d skapade repon. +form.name_reserved=Namnet '%s' på utvecklingskatalogen är reserverat. +form.name_pattern_not_allowed=Reponamnet '%s' är inte tillåtet. + +need_auth=Tillstånd Krävs +migrate_type=Migreringstyp +migrate_type_helper=Detta repo kommer att vara en spegling +migrate_repo=Migrera Repot +migrate.clone_address=Kloningsaddress +migrate.clone_address_desc=Detta kan vara en HTTP/HTTPS/GIT-URL eller en lokal sökväg på servern. +migrate.permission_denied=Du får inte importera lokala repon. +migrate.invalid_local_path=Ogiltig lokal sökväg, den finns inte eller är inte en katalog. +migrate.failed=Migrering misslyckades: %v + +mirror_from=spegling av +forked_from=forkad från +fork_from_self=Du kan inte forka ett repo som du redan äger! +copy_link=Kopiera +copy_link_success=Kopierad! +copy_link_error=Tryck på ⌘-C eller Ctrl-C för att kopiera +copied=Kopierade OK +unwatch=Avsluta bevakning +watch=Bevaka +unstar=Ta bort stjärnmärkning +star=Stjärnmärk +fork=Fork + +no_desc=Ingen beskrivning +quick_guide=Snabbguide +clone_this_repo=Klona detta repo +create_new_repo_command=Skapa ett nytt repo på kommandoraden +push_exist_repo=Knuffa ett existerande repo från kommandoraden +repo_is_empty=Detta repo är tomt, vänligen kom tillbaka senare! + +code=Kod +branch=Gren +tree=Träd +filter_branch_and_tag=Filtrera gren eller tagg +branches=Grenar +tags=Taggar +issues=Ärenden +pulls=Pull-förfrågningar +labels=Etiketter +milestones=Milstenar +commits=Incheckningar +releases=Släpp +file_raw=Rå +file_history=Historik +file_view_raw=Visa i råformat +file_permalink=Permalänk +file_too_large=Denna fil är för stor för att visas + +editor.new_file=Ny fil +editor.upload_file=Ladda upp fil +editor.edit_file=Redigera fil +editor.preview_changes=Förhandsgranska ändringar +editor.cannot_edit_non_text_files=Endast textfiler kan redigeras +editor.edit_this_file=Redigera denna fil +editor.must_be_on_a_branch=Du måste vara på en gren för att genomföra eller föreslå ändringar i denna fil +editor.fork_before_edit=Du måste förgrena detta förråd innan du kan redigera filen +editor.delete_this_file=Tag bort denna fil +editor.must_have_write_access=Du måste ha skrivrättigheter för att genomföra eller föreslå ändringar i denna fil +editor.file_delete_success=Filen '%s' har tagits bort! +editor.name_your_file=Namnge din fil... +editor.filename_help=För att lägga till en katalog, skriv dess namn och tryck /. För att ta bort en katalog, gå till början av fältet och tryck på backsteg. +editor.or=eller +editor.cancel_lower=avbryt +editor.commit_changes=Checka in ändringar +editor.add_tmpl=Lägg till '%s/' +editor.add=Lägg till '%s' +editor.update=Uppdatera '%s' +editor.delete=Tag bort '%s' +editor.commit_message_desc=Lägg till en valfri utökad beskrivning... +editor.commit_directly_to_this_branch=Checka in direkt till grenen %s. +editor.create_new_branch=Skapa en ny gren för denna incheckning och påbörja en hämtningsbegäran. +editor.new_branch_name_desc=Nytt grennamn... +editor.cancel=Avbryt +editor.filename_cannot_be_empty=Filnamnet får inte vara tomt. +editor.branch_already_exists=Grenen '%s' finns redan i förrådet. +editor.directory_is_a_file=Komponenten '%s' i föräldrasökvägen är en fil, inte en katalog i detta förråd. +editor.filename_is_a_directory=Filnmanet '%s' är en existerande katalog i detta förråd. +editor.file_editing_no_longer_exists=Filen '%s' som du redigerar finns inte lägre i förrådet. +editor.file_changed_while_editing=Filinnhållet har ändrats sedan du började redigera. Klicka här för att se vad som ändrats eller tryck checka in igen för att skriva över dessa ändringar. +editor.file_already_exists=En fil med namnet '%s' finns redan i förrådet. +editor.no_changes_to_show=Det finns inga ändringar att visa. +editor.fail_to_update_file=Uppdateringen/skapandet av filen '%s' misslyckades med felet: %v +editor.add_subdir=Lägg till underkatalog... +editor.unable_to_upload_files=Uppladdning av filen '%s' misslyckades med felet: %v +editor.upload_files_to_dir=Ladda upp filer till '%s' + +commits.commits=Incheckningar +commits.search=Sök bland incheckningar +commits.find=Sök +commits.author=Upphovsman +commits.message=Meddelande +commits.date=Datum +commits.older=Äldre +commits.newer=Nyare + +issues.new=Nytt Ärende +issues.new.labels=Etiketter +issues.new.no_label=Ingen Etikett +issues.new.clear_labels=Rensa etiketter +issues.new.milestone=Milsten +issues.new.no_milestone=Ingen Milsten +issues.new.clear_milestone=Rensa milstenar +issues.new.open_milestone=Öppna Milstenar +issues.new.closed_milestone=Stängda Milstenar +issues.new.assignee=Förvärvare +issues.new.clear_assignee=Rensa förvärvare +issues.new.no_assignee=Ingen förvärvare +issues.create=Skapa Ärende +issues.new_label=Ny etikett +issues.new_label_placeholder=Etikettnamn... +issues.create_label=Skapa Etikett +issues.label_templates.title=Ladda en fördefinierad uppsättning etiketter +issues.label_templates.info=Det finns inga etiketter än. Du kan klicka på knappen "Ny etikett" ovan för att skapa en, eller använda en fördefinierad uppsättning nedan. +issues.label_templates.helper=Markera en uppsättning etiketter +issues.label_templates.use=Använd denna etikettuppsättning +issues.label_templates.fail_to_load_file=Laddning av etikettmallen '%s' misslyckades: %v +issues.open_tab=%d Öppna +issues.close_tab=%d Stängda +issues.filter_label=Etikett +issues.filter_label_no_select=Ingen etikett vald +issues.filter_milestone=Milsten +issues.filter_milestone_no_select=Ingen milsten vald +issues.filter_assignee=Förvärvare +issues.filter_assginee_no_select=Ingen förvärvare vald +issues.filter_type=Typ +issues.filter_type.all_issues=Alla ärenden +issues.filter_type.assigned_to_you=Tilldelad dig +issues.filter_type.created_by_you=Skapade av dig +issues.filter_type.mentioning_you=Nämner dig +issues.filter_sort=Sortera +issues.filter_sort.latest=Nyaste +issues.filter_sort.oldest=Äldsta +issues.filter_sort.recentupdate=Nyligen uppdaterade +issues.filter_sort.leastupdate=Äldst uppdaterad +issues.filter_sort.mostcomment=Mest kommenterade +issues.filter_sort.leastcomment=Minst kommenterade +issues.opened_by=öppnade %[1]s av %[3]s +issues.opened_by_fake=öppnade %[1]s av %[2]s +issues.previous=Föregående +issues.next=Nästa +issues.open_title=Öppen +issues.closed_title=Stängd +issues.num_comments=%d kommentarer +issues.commented_at=`kommenterad %s` +issues.delete_comment_confirm=Är du säker på att du vill ta bort den här kommentaren? +issues.no_content=Det finns inget innehåll än. +issues.close_issue=Stäng +issues.close_comment_issue=Kommentera och stäng +issues.reopen_issue=Återöppna +issues.reopen_comment_issue=Kommentera och återöppna +issues.create_comment=Kommentera +issues.closed_at=`stängde %[2]s` +issues.reopened_at=`återöppnade %[2]s` +issues.commit_ref_at=`refererade till detta ärende från en incheckning %[2]s` +issues.poster=Skapare +issues.collaborator=Deltagare +issues.owner=Ägare +issues.sign_in_require_desc=Logga in för att delta i denna konversation. +issues.edit=Redigera +issues.cancel=Avbryt +issues.save=Spara +issues.label_title=Etikettsnamn +issues.label_color=Etikettsfärg +issues.label_count=%d etiketter +issues.label_open_issues=%d öppna ärenden +issues.label_edit=Redigera +issues.label_delete=Radera +issues.label_modify=Etikettsändring +issues.label_deletion=Etikettsborttagning +issues.label_deletion_desc=Borttagning av denna etikett kommer att ta bort information från alla relaterade ärenden. Vill du fortsätta? +issues.label_deletion_success=Etiketten har tagits bort! +issues.num_participants=%d Deltagare +issues.attachment.open_tab=`Klicka för att se "%s" i en ny flik` +issues.attachment.download=`Klicka för att hämta "%s"` + +pulls.new=Ny Pull-Förfrågan +pulls.compare_changes=Jämför Ändringar +pulls.compare_changes_desc=Jämför två grenar och skapa en pullförfrågan över ändringarna. +pulls.compare_base=bas +pulls.compare_compare=jämför +pulls.filter_branch=Filtrera gren +pulls.no_results=Inga resultat hittades. +pulls.nothing_to_compare=Det finns inget att jämföra eftersom bas och huvudgrenar är lika. +pulls.has_pull_request=`Det finns redan en pullförfrågan mellan detta två mål: %[2]s#%[3]s^ +pulls.create=Skapa Pullförfrågan +pulls.title_desc=vill sammanfoga %[1]d incheckningar från s[2]s in i %[3]s +pulls.merged_title_desc=sammanfogade %[1]d incheckningar från %[2]s in i %[3]s %[4]s +pulls.tab_conversation=Konversation +pulls.tab_commits=Incheckningar +pulls.tab_files=Ändrade filer +pulls.reopen_to_merge=Vänligen öppna denna Pull-förfrågan igen för att utföra sammanfogningen. +pulls.merged=Sammanfogat +pulls.has_merged=Denna pull-förfrågan har blivit sammanfogad! +pulls.data_broken=Data för denna pull-förfrågan har gått sönder på grund av borttagning av fork-information. +pulls.is_checking=Konfliktkontroll är fortfarande pågågående, vänligen uppdatera sidan om ett tag. +pulls.can_auto_merge_desc=Denna pull-förfrågan kan sammanfogas automatiskt. +pulls.cannot_auto_merge_desc=Denna pull-förfrågan kan inte sammanfogas automatiskt eftersom det finns konflikter. +pulls.cannot_auto_merge_helper=Vänligen sammanfoga manuellt för att lösa konflikter. +pulls.merge_pull_request=Sammanfoga Pull-förfrågan +pulls.open_unmerged_pull_exists=`Du kan inte utföra återöppningsoperationen eftersom det finns redan en öppen pull-förfrågan (#%d) från samma repo med samma sammanfogningsinformation som väntar på sammanfogning.` + +milestones.new=Ny milstolpe +milestones.open_tab=%d Öppna +milestones.close_tab=%d Stängda +milestones.closed=Stängt %s +milestones.no_due_date=Inget förfallodatum +milestones.open=Öppna +milestones.close=Stäng +milestones.new_subheader=Skapa milstolpar för att organisera dina ärenden. +milestones.create=Skapa Milstolpe +milestones.title=Titel +milestones.desc=Beskrivning +milestones.due_date=Förfallodatum (valfritt) +milestones.clear=Rensa +milestones.invalid_due_date_format=Datumformatet är ogiltig, måste vara "åååå-mm-dd". +milestones.create_success=Milstolpe "%s" har skapats! +milestones.edit=Redigera milstolpe +milestones.edit_subheader=Använda en bättre beskrivning för milstolpar så folk inte blir förvirrade. +milestones.cancel=Avbryt +milestones.modify=Ändra milstolpe +milestones.edit_success=Ändringar av milstolpen "%s" har sparats! +milestones.deletion=Milstolpsborttagning +milestones.deletion_desc=Borttagning av denna milstope kommer att ta bort information från alla relaterade ärenden. Vill du fortsätta? +milestones.deletion_success=Milstolpe har tagits bort! + +wiki=Wiki +wiki.welcome=Välkommen till Wiki! +wiki.welcome_desc=Wiki är den plats där du vill att dokumentera projektet tillsammans och göra det bättre. +wiki.create_first_page=Skapa den första sidan +wiki.page=Sida +wiki.filter_page=Filtrera sida +wiki.new_page=Skapa ny sida +wiki.default_commit_message=Skriva en anteckning om den här uppdateringen (valfritt). +wiki.save_page=Spara sidan +wiki.last_commit_info=%s redigerade denna sida %s +wiki.edit_page_button=Redigera +wiki.new_page_button=Ny Sida +wiki.delete_page_button=Tag bort sida +wiki.delete_page_notice_1=Sidan "%s" kommer tas bort. Se till att du är säker. +wiki.page_already_exists=Wiki-sida med samma namn finns redan. +wiki.pages=Sidor +wiki.last_updated=Senast uppdaterad %s + +settings=Inställningar +settings.options=Alternativ +settings.collaboration=Samarbete +settings.collaboration.admin=Adminstrera +settings.collaboration.write=Skriva +settings.collaboration.read=Läsa +settings.collaboration.undefined=Odefinierad +settings.hooks=Webbhookar +settings.githooks=Githookar +settings.basic_settings=Basinställningar +settings.mirror_settings=Inställningar för spegling +settings.sync_mirror=Synkronisera nu +settings.mirror_sync_in_progress=Spegningssynkronisering pågår, vänligen ladda om sidan om cirka en minut. +settings.site=Officiell webbplats +settings.update_settings=Uppdatera inställningar +settings.change_reponame_prompt=Denna ändring kommer att påverka hur länkar relaterar till detta repo. +settings.advanced_settings=Advancerade Inställningar +settings.wiki_desc=Aktivera wikisystem +settings.use_internal_wiki=Använd inbyggd wiki +settings.use_external_wiki=Använd extern wiki +settings.external_wiki_url=Extern Wiki-URL +settings.external_wiki_url_desc=Besökare kommer att bli omdirigerade till denna URL när dom klickar på fliken. +settings.issues_desc=Aktivera ärendehantering +settings.use_internal_issue_tracker=Använd enkel inbyggd ärendehantering +settings.use_external_issue_tracker=Använd extern ärendehanterare +settings.tracker_url_format=URL-Format För Extern Ärendehanterare +settings.tracker_issue_style=Namngivningsstil hos det externa ärendehanteringsystemet: +settings.tracker_issue_style.numeric=Numerisk +settings.tracker_issue_style.alphanumeric=Alfanumerisk +settings.tracker_url_format_desc=Du kan använda platshållaren {user} {repo} {index} för användarnamn, reponamn, och ärendenummer. +settings.pulls_desc=Aktivera pullförfrågningar för att ta emot publika bidrag +settings.danger_zone=Högrisksområde +settings.new_owner_has_same_repo=Den nya ägaren har redan ett repo med det namnet. Vänligen välj ett annat namn. +settings.convert=Konvertera Till Vanligt Repo +settings.convert_desc=Du kan konvertera denna spegling till ett vanligt förråd. Detta kan inte ångras. +settings.convert_notices_1=- Denna operation konverterar denna förrådsspegning till ett vanligt förråd och kan inte ångras. +settings.convert_confirm=Bekräfta Konvertering +settings.convert_succeed=Förrådet har konverterats till ett vanligt förråd. +settings.transfer=Överför Ägarskap +settings.transfer_desc=Överför detta repo till en annan användare, eller till en organisation där du har administratörsrättigheter. +settings.transfer_notices_1=- Du förlorar åtkomst om den nya ägaren är en enskild användare. +settings.transfer_notices_2=- Du kommer bevara tillgång om den nya ägaren är en organisation, och om du är en av ägarna. +settings.transfer_form_title=Ange följande information för att bekräfta åtgärden: +settings.wiki_delete=Tag bort wikidata +settings.wiki_delete_desc=När du väl tagit bort wikidatan finns det ingen återvända. Se till att du är säker. +settings.wiki_delete_notices_1=- Detta tar bort och avaktiverar wikin för %s +settings.wiki_deletion_success=Förrådets wikidata har tagits bort. +settings.delete=Ta Bort Detta Repo +settings.delete_desc=När du har tagit bort ett repo så finns det ingen återvändo. Var säker på vad du gör. +settings.delete_notices_1=- Denna åtgärd kan INTE ångras. +settings.delete_notices_2=- Denna åtgärd kommer permanent ta bort hela repot, includerat git-datan, ärenden, kommentarer, och åtkomst för deltagare. +settings.delete_notices_fork_1=- Alla förgreningar kommer bli oberoende efter borttagning. +settings.deletion_success=Repot har tagits bort! +settings.update_settings_success=Repo-inställningar har uppdaterats. +settings.transfer_owner=Ny Ägare +settings.make_transfer=Överför +settings.transfer_succeed=Repo-ägarskapet har blivit överfört. +settings.confirm_delete=Bekräfta Borttagelsen +settings.add_collaborator=Lätt Till Ny Kollaboratör +settings.add_collaborator_success=Ny kollaboratör har blivit tillagd. +settings.delete_collaborator=Tag bort +settings.collaborator_deletion=Borttagning av deltagare +settings.collaborator_deletion_desc=Denna användare kommer förlora sin åtkomst till förrådet. Vill du fortsätta? +settings.remove_collaborator_success=Deltagare har tagits bort. +settings.search_user_placeholder=Sök användare... +settings.org_not_allowed_to_be_collaborator=Organisationen kan inte läggas till som en deltagare. +settings.user_is_org_member=Änvändaren är en organisationsmedlem som inte kan bli tillagd som deltagare. +settings.add_webhook=Lägg Till Webbhook +settings.hooks_desc=Webbhookar påminner mycket om vanliga HTTP POST-händelseutlösare. När något inträffar i Gogs, kommer vi att meddela måldatorn som du anger. Läs mera i Webbhook Guide. +settings.webhook_deletion=Ta Bort Webbhook +settings.webhook_deletion_desc=Borttagning av denna webbhook kommer att ta bort all dess information och all leveranshistorik. Är du säker på att du vill fortsätta? +settings.webhook_deletion_success=Webbhook har tagits bort! +settings.webhook.test_delivery=Testa Leverans +settings.webhook.test_delivery_desc=Skicka en falsk pushhändelse för att testa dina webbhook-inställningar +settings.webhook.test_delivery_success=Testwebbhook har lagts till leveranskön. Det kan ta några sekunder innan den visas i leveranshistoriken. +settings.webhook.request=Begäran +settings.webhook.response=Svar +settings.webhook.headers=Huvuden +settings.webhook.payload=Nyttolast +settings.webhook.body=Innehåll +settings.githooks_desc=Git-krokar är en del av Git själv. För att utföra anpassade operationer kan du redigera filerna för de krokar som stöds i listan nedan. +settings.githook_edit_desc=Om kroken är inaktiv visas exempelinnehåll. Inaktivera denna krok genom att lämna innehållet tomt. +settings.githook_name=Kroknamn +settings.githook_content=Krokinnehåll +settings.update_githook=Uppdatera krok +settings.add_webhook_desc=Gogs kommer skicka POST-anrop till webbadressen du anger, tillsammans med information om händelsen som inträffade. Du kan också ange vilken sorts dataformat du vill få när kroken triggas (JSON, x-www-form-urlencoded, XML et.c.). Mer information finns i vår Webhooks Guide. +settings.payload_url=Adress till innehåll +settings.content_type=Typ av innehåll +settings.secret=Hemlighet +settings.slack_username=Användarnamn +settings.slack_icon_url=URL för ikon +settings.slack_color=Färg +settings.event_desc=När ska Webhooken köras? +settings.event_push_only=Endast push-eventet. +settings.event_send_everything=Jag behöver allt. +settings.event_choose=Låt mig välja. +settings.event_create=Skapa +settings.event_create_desc=Branch eller tagg skapad +settings.event_pull_request=Hämtningsbegäran +settings.event_pull_request_desc=Hämtningsbegäran öppnad, stängd, återöppnad, redigerad, tilldelad, otilldelad, etikett uppdaterad, etikett rensad eller synkroniserad. +settings.event_push=Pusha +settings.event_push_desc=Uppladdning till ett förråd +settings.active=Aktiv +settings.active_helper=Detaljer kring händelsen som triggade kroken kommer också levereras. +settings.add_hook_success=Ny webbkrok har lagts till. +settings.update_webhook=Uppdatera Webhook +settings.update_hook_success=Webbkrok har uppdaterats. +settings.delete_webhook=Tag bort webbkrok +settings.recent_deliveries=Färska leveranser +settings.hook_type=Kroktyp +settings.add_slack_hook_desc=Lägg till Slack-integration till ditt förråd. +settings.slack_token=Pollett +settings.slack_domain=Domän +settings.slack_channel=Kanal +settings.deploy_keys=Driftsättningsnycklar +settings.add_deploy_key=Lägg till driftsättningsnyckel +settings.deploy_key_desc=Driftsättningsnycklar har endast läsrättigheter. De är inte desamma som personliga SSH-kontonycklar. +settings.no_deploy_keys=Du har inte lagt till några driftsättningsnycklar. +settings.title=Titel +settings.deploy_key_content=Innehåll +settings.key_been_used=Driftsättningsnyckelns innehåll har använts. +settings.key_name_used=En driftsättningsnyckel med samma namn finns redan. +settings.add_key_success=Den nya driftsättningsnyckeln '%s' har lagts till! +settings.deploy_key_deletion=Ta bort distribueringsnyckel +settings.deploy_key_deletion_desc=Borttagning av detta distributionsnyckel kommer att ta bort all relaterad åtkomst till det här repot. Vill du fortsätta? +settings.deploy_key_deletion_success=Distributionsnyckeln har tagits bort! + +diff.browse_source=Bläddra i källkod +diff.parent=förälder +diff.commit=incheckning +diff.data_not_available=Diff-uppgifter Inte Tillgänglig. +diff.show_diff_stats=Visa Diff Statistik +diff.show_split_view=Delad Vy +diff.show_unified_view=Unifierad Vy +diff.stats_desc= %d ändrade filer med %d tillägg och %d borttagningar +diff.bin=BIN +diff.view_file=Visa fil +diff.file_suppressed=Filskillnaden har hållts tillbaka eftersom den är för stor +diff.too_many_files=Vissa filer visades inte eftersom för många filer har ändrats + +release.releases=Släpp +release.new_release=Nytt Släpp +release.draft=Utkast +release.prerelease=Försläpp +release.stable=Stabil +release.edit=redigera +release.ahead=%d ändringar mot %s sedan detta släpp +release.source_code=Källkod +release.new_subheader=Publicera släpp för att iterera produkten. +release.edit_subheader=Detaljerad ändringslogg kan hjälpa användarna att förstå vad har förbättrats. +release.tag_name=Taggnamn +release.target=Mål +release.tag_helper=Välj en befintlig tagg, eller skapa en ny tagg på publicera. +release.title=Titel +release.content=Innehåll +release.write=Skriv +release.preview=Förhandsgranska +release.loading=Laddar... +release.prerelease_desc=Detta är ett försläpp +release.prerelease_helper=Vi kommer att påpeka att detta släpp inte är produktionsredo. +release.cancel=Avbryt +release.publish=Publicera Släpp +release.save_draft=Spara Utkast +release.edit_release=Redigera Släpp +release.delete_release=Ta Bort Detta Släpp +release.deletion=Släppborttagning +release.deletion_desc=Borttagning av detta släpp kommer att ta bort motsvarande Git-tagg. Vill du fortsätta? +release.deletion_success=Släppet har tagits bort! +release.tag_name_already_exist=Ett släpp med denna tagg finns redan. +release.tag_name_invalid=Etikettnamnet är ogiltigt. +release.downloads=Nerladdningar + +[org] +org_name_holder=Organisationsnamn +org_full_name_holder=Organisationens Fullständiga Namn +org_name_helper=Bra organisation är korta och lättihågkommna. +create_org=Skapa organisation +repo_updated=Uppdaterad +people=Personer +invite_someone=Bjud In Någon +teams=Grupper +lower_members=medlemmar +lower_repositories=utvecklingskataloger +create_new_team=Skapa ny grupp +org_desc=Beskrivning +team_name=Gruppnamn +team_desc=Beskrivning +team_name_helper=Du kan använda detta namn för att nämna denna grupp i konversationer. +team_desc_helper=Vad handlar denna grupp om? +team_permission_desc=Vilka behörigheter ska denna grupp ha? + +form.name_reserved=Organisationsnamnet "%s" är reserverat. +form.name_pattern_not_allowed=Organisationsnamnet '%s' är inte tillåtet. + +settings=Inställningar +settings.options=Alternativ +settings.full_name=Fullständigt namn +settings.website=Webbplats +settings.location=Plats +settings.update_settings=Uppdatera inställningar +settings.update_setting_success=Organisationsinställningarna har uppdaterats. +settings.change_orgname_prompt=Denna förändring kommer att påverka hur länkar relaterar till organisationen. +settings.update_avatar_success=Organisationens avatar-inställningar har uppdaterats. +settings.delete=Tag bort organisation +settings.delete_account=Tag bort denna organisation +settings.delete_prompt=Organisationen kommer tas bort permanent, och det går INTE att ångra detta! +settings.confirm_delete_account=Bekräfta borttagning +settings.delete_org_title=Organisation borttagen +settings.delete_org_desc=Denna organisation kommer att tas bort permanent, vill du fortsätta? +settings.hooks_desc=Lägg till webbkrokar som triggas för alla förråd under denna organisation. + +members.membership_visibility=Synlighet för medlemskap: +members.public=Publik +members.public_helper=gör privat +members.private=Privat +members.private_helper=gör publik +members.member_role=Medlemsroll: +members.owner=Ägare +members.member=Medlem +members.remove=Ta bort +members.leave=Lämna +members.invite_desc=Lägg till en ny medlem i %s: +members.invite_now=Bjud in + +teams.join=Gå med +teams.leave=Gå ur +teams.read_access=Läsåtkomst +teams.read_access_helper=Detta team kommer att kunna visa och klona dess repon. +teams.write_access=Skrivåtkomst +teams.write_access_helper=Detta team kommer att kunna läsa alla repositories samt pusha till dessa. +teams.admin_access=Adminåtkomst +teams.admin_access_helper=Detta team kommer att kunna pusha/pulla till sina repositories, samt lägga till deltagare till dessa. +teams.no_desc=Detta team har ingen beskrivning +teams.settings=Inställningar +teams.owners_permission_desc=Ägare har full tillgång till alla förråd och har administratörsrättigheter för organisationen. +teams.members=Teammedlemmar +teams.update_settings=Uppdatera inställningar +teams.delete_team=Ta bort detta team +teams.add_team_member=Lägg till teammedlem +teams.delete_team_title=Borttagning av team +teams.delete_team_desc=Eftersom detta team tas bort kan medlemmar i teamet förlora sin tillgång till visa förråd. Vill du fortsätta? +teams.delete_team_success=Teamet togs bort. +teams.read_permission_desc=Medlemskap i detta team ger läsrättigheter: medlemmar kan visa och klona teamets förråd. +teams.write_permission_desc=Medlemskap i detta team ger skrivrättigheter: medlemmar kan läsa från och ladda upp till teamets förråd. +teams.admin_permission_desc=Medlemskap i detta team ger administratörsrättigheter: medlemmar kan läsa från, ladda upp till och lägga till deltagare till teamets förråd. +teams.repositories=Teamförråd +teams.search_repo_placeholder=Sök förråd... +teams.add_team_repository=Lägg till teamförråd +teams.remove_repo=Ta bort +teams.add_nonexistent_repo=Förrådet du försöka lägga till finns inte, vänligen skapa det först. + +[admin] +dashboard=Instrumentpanel +users=Användare +organizations=Organisationer +repositories=Utvecklingskataloger +authentication=Autentiseringar +config=Konfiguration +notices=Systemaviseringar +monitor=Övervakning +first_page=Första +last_page=Sista +total=Totalt: %d + +dashboard.statistic=Statistik +dashboard.operations=Operationer +dashboard.system_status=Systemstatus +dashboard.statistic_info=Gogs-databasen innehåller %d användare, %d organisationer, %d publika nyckar, %d förråd, %d vakter, %d stjärnor, %d handlingar, %d åtkomster, %d ärenden, %d kommentarer, %d sociala konton, %d följbegäran, %d speglingar, %d släpp, %d inloggningskällor, %d webbkrokar, %d milstolpar, %d etiketter, %d krokuppgifter, %d team, %d uppdateringsuppgifter, %d bilagor. +dashboard.operation_name=Operationsnamn +dashboard.operation_switch=Byt till +dashboard.operation_run=Kör +dashboard.clean_unbind_oauth=Rensa obundna OAuth-begäran +dashboard.clean_unbind_oauth_success=Alla obundna OAuth-begäran har tagit +dashboard.delete_inactivate_accounts=Ta bort alla inaktiva konton +dashboard.delete_inactivate_accounts_success=All inactivate accounts have been deleted successfully. +dashboard.delete_repo_archives=Delete all repositories archives +dashboard.delete_repo_archives_success=All repositories archives have been deleted successfully. +dashboard.delete_missing_repos=Delete all repository records that lost Git files +dashboard.delete_missing_repos_success=All repository records that lost Git files have been deleted successfully. +dashboard.git_gc_repos=Do garbage collection on repositories +dashboard.git_gc_repos_success=All repositories have done garbage collection successfully. +dashboard.resync_all_sshkeys=Rewrite '.ssh/authorized_keys' file (caution: non-Gogs keys will be lost) +dashboard.resync_all_sshkeys_success=All public keys have been rewritten successfully. +dashboard.resync_all_update_hooks=Rewrite all update hook of repositories (needed when custom config path is changed) +dashboard.resync_all_update_hooks_success=All repositories' update hook have been rewritten successfully. +dashboard.reinit_missing_repos=Reinitialize all repository records that lost Git files +dashboard.reinit_missing_repos_success=All repository records that lost Git files have been reinitialized successfully. + +dashboard.server_uptime=Serverns upptid +dashboard.current_goroutine=Current Goroutines +dashboard.current_memory_usage=Current Memory Usage +dashboard.total_memory_allocated=Total Memory Allocated +dashboard.memory_obtained=Memory Obtained +dashboard.pointer_lookup_times=Pointer Lookup Times +dashboard.memory_allocate_times=Memory Allocate Times +dashboard.memory_free_times=Memory Free Times +dashboard.current_heap_usage=Current Heap Usage +dashboard.heap_memory_obtained=Heap Memory Obtained +dashboard.heap_memory_idle=Heap Memory Idle +dashboard.heap_memory_in_use=Heap Memory In Use +dashboard.heap_memory_released=Heap Memory Released +dashboard.heap_objects=Heap Objects +dashboard.bootstrap_stack_usage=Bootstrap Stack Usage +dashboard.stack_memory_obtained=Stack Memory Obtained +dashboard.mspan_structures_usage=MSpan Structures Usage +dashboard.mspan_structures_obtained=MSpan Structures Obtained +dashboard.mcache_structures_usage=MCache Structures Usage +dashboard.mcache_structures_obtained=MCache Structures Obtained +dashboard.profiling_bucket_hash_table_obtained=Profiling Bucket Hash Table Obtained +dashboard.gc_metadata_obtained=GC Metadata Obtained +dashboard.other_system_allocation_obtained=Other System Allocation Obtained +dashboard.next_gc_recycle=Next GC Recycle +dashboard.last_gc_time=Tidpunkt för senaste skräpsamling +dashboard.total_gc_time=Total tid för pauser vid skräpsamling +dashboard.total_gc_pause=Total tid för pauser vid skräpsamling +dashboard.last_gc_pause=Senaste paus vid skräpsamling +dashboard.gc_times=Skräpsamlingstider + +users.user_manage_panel=Panel för hantering av användare +users.new_account=Skapa nytt konto +users.name=Namn +users.activated=Aktiverad +users.admin=Administratör +users.repos=Utvecklingskataloger +users.created=Skapad +users.send_register_notify=Skicka registreringsnotifikation till användare +users.new_success=Nytt konto '%s' har skapats. +users.edit=Redigera +users.auth_source=Autentiseringskälla +users.local=Lokal +users.auth_login_name=Användarnamn för autentisering +users.password_helper=Lämna det tomt för att låta det vara oförändrat. +users.update_profile_success=Kontoprofilen har uppdaterats. +users.edit_account=Redigera konto +users.max_repo_creation=Gräns för antal skapade förråd +users.max_repo_creation_desc=(Sätt till -1 för att använda den globala standardgränsen) +users.is_activated=Detta konto är aktivt +users.prohibit_login=Detta konto är förhindrat från att logga in +users.is_admin=Detta konto har administratörsrättigheter +users.allow_git_hook=Detta konto har tillåtelse att skapa Git-krokar +users.allow_import_local=Detta konto har tillåtelse att importera lokal förråd +users.update_profile=Uppdatera kontoprofil +users.delete_account=Tag bort detta konto +users.still_own_repo=Detta konto äger fortfarande åtminstone ett förråd, du måste ta bort eller överföra ägarskapen för dessa först. +users.still_has_org=Detta konto har fortfarande medlemskap i åtminstone en organisation, du måste lämna eller ta bort organisationerna först. +users.deletion_success=Kontot har tagits bort! + +orgs.org_manage_panel=Panel för hantering av organisation +orgs.name=Namn +orgs.teams=Team +orgs.members=Medlemmar + +repos.repo_manage_panel=Panel för hantering av förråd +repos.owner=Ägare +repos.name=Namn +repos.private=Privat +repos.watches=Vakter +repos.stars=Stjärnor +repos.issues=Ärenden + +auths.auth_manage_panel=Panel för hantering av autentisering +auths.new=Lägg till ny källa +auths.name=Namn +auths.type=Typ +auths.enabled=Aktiv +auths.updated=Uppdaterad +auths.auth_type=Autentiseringstyp +auths.auth_name=Autentiseringsnamn +auths.security_protocol=Säkerhetsprotokoll +auths.domain=Domän +auths.host=Värd +auths.port=Port +auths.bind_dn=Bind DN +auths.bind_password=Bind Password +auths.bind_password_helper=Warning: This password is stored in plain text. Do not use a high privileged account. +auths.user_base=User Search Base +auths.user_dn=User DN +auths.attribute_username=Username attribute +auths.attribute_username_placeholder=Leave empty to use sign-in form field value for user name. +auths.attribute_name=First name attribute +auths.attribute_surname=Surname attribute +auths.attribute_mail=Email attribute +auths.attributes_in_bind=Fetch attributes in Bind DN context +auths.filter=User Filter +auths.admin_filter=Admin Filter +auths.ms_ad_sa=Ms Ad SA +auths.smtp_auth=SMTP Authentication Type +auths.smtphost=SMTP Host +auths.smtpport=SMTP Port +auths.allowed_domains=Allowed Domains +auths.allowed_domains_helper=Leave it empty to not restrict any domains. Multiple domains should be separated by comma ','. +auths.enable_tls=Enable TLS Encryption +auths.skip_tls_verify=Skip TLS Verify +auths.pam_service_name=PAM Service Name +auths.enable_auto_register=Enable Auto Registration +auths.tips=Tips +auths.edit=Edit Authentication Setting +auths.activated=This authentication is activated +auths.new_success=New authentication '%s' has been added successfully. +auths.update_success=Authentication setting has been updated successfully. +auths.update=Update Authentication Setting +auths.delete=Delete This Authentication +auths.delete_auth_title=Authentication Deletion +auths.delete_auth_desc=This authentication is going to be deleted, do you want to continue? +auths.still_in_used=This authentication is still used by some users, please delete or convert these users to another login type first. +auths.deletion_success=Authentication has been deleted successfully! + +config.server_config=Server Configuration +config.app_name=Application Name +config.app_ver=Application Version +config.app_url=Application URL +config.domain=Domain +config.offline_mode=Offline Mode +config.disable_router_log=Disable Router Log +config.run_user=Run User +config.run_mode=Run Mode +config.repo_root_path=Rotsökväg för utvecklingskatalog +config.static_file_root_path=Static File Root Path +config.log_file_root_path=Log File Root Path +config.script_type=Script Type +config.reverse_auth_user=Reverse Authentication User + +config.ssh_config=SSH Configuration +config.ssh_enabled=Enabled +config.ssh_start_builtin_server=Start Builtin Server +config.ssh_domain=Domän +config.ssh_port=Port +config.ssh_listen_port=Lyssningsport +config.ssh_root_path=Rotsökväg +config.ssh_key_test_path=Testsökväg för nyckel +config.ssh_keygen_path=Sökväg för nyckelgenerator ('ssh-keygen') +config.ssh_minimum_key_size_check=Kontroll av minsta tillåtna nyckelstorlek +config.ssh_minimum_key_sizes=Minsta tillåtna nyckelstorlek + +config.db_config=Databaskonfiguration +config.db_type=Typ +config.db_host=Värd +config.db_name=Namn +config.db_user=Användare +config.db_ssl_mode=SSL-läge +config.db_ssl_mode_helper=(endast för "postgres") +config.db_path=Sökväg +config.db_path_helper=(för "sqlite3" och "tidb") + +config.service_config=Tjänstkonfiguration +config.register_email_confirm=Kräv bekräftelse via e-post +config.disable_register=Avaktivera registrering +config.show_registration_button=Visa registreringsknapp +config.require_sign_in_view=Kräv inloggningsvy +config.mail_notify=E-postavisering +config.disable_key_size_check=Avaktivera kontroll av minsta tillåtna nyckelstorlek +config.enable_captcha=Aktivera Captcha +config.active_code_lives=Aktivera livstid för koder +config.reset_password_code_lives=Livstid för koder för återställning av lösenord + +config.webhook_config=Webbkrokskonfiguration +config.queue_length=Kölängd +config.deliver_timeout=Tidsfrist för leverans +config.skip_tls_verify=Skippa verifikation av TLS + +config.mailer_config=Konfiguration för e-postutskick +config.mailer_enabled=Aktiverad +config.mailer_disable_helo=Avaktivera HELO +config.mailer_name=Namn +config.mailer_host=Server +config.mailer_user=Användare +config.send_test_mail=Skicka testmeddelande +config.test_mail_failed=Misslyckades skicka testmeddelande till '%s': %v +config.test_mail_sent=Testmeddelande har skickats till '%s'. + +config.oauth_config=OAuth-konfiguration +config.oauth_enabled=Aktiverad + +config.cache_config=Mellanlagringskonfiguration +config.cache_adapter=Mellanlagringsadapter +config.cache_interval=Mellanlagringsintervall +config.cache_conn=Mellanlagringsanslutning + +config.session_config=Sessionskonfiguration +config.session_provider=Sessionsleverantör +config.provider_config=Leverantörskonfiguration +config.cookie_name=Cookie-namn +config.enable_set_cookie=Aktivera sättning av kaka +config.gc_interval_time=Tidsintervall för skräpsamling +config.session_life_time=Livstid för session +config.https_only=Endast HTTPS +config.cookie_life_time=Livstid för kaka + +config.picture_config=Bildkonfiguration +config.picture_service=Bildtjänst +config.disable_gravatar=Disable Gravatar +config.enable_federated_avatar=Enable Federated Avatars + +config.git_config=Git Configuration +config.git_disable_diff_highlight=Disable Diff Syntax Highlight +config.git_max_diff_lines=Max Diff Lines (for a single file) +config.git_max_diff_line_characters=Max Diff Characters (for a single line) +config.git_max_diff_files=Max Diff Files (to be shown) +config.git_gc_args=GC Arguments +config.git_migrate_timeout=Migration Timeout +config.git_mirror_timeout=Mirror Update Timeout +config.git_clone_timeout=Clone Operation Timeout +config.git_pull_timeout=Pull Operation Timeout +config.git_gc_timeout=GC Operation Timeout + +config.log_config=Log Configuration +config.log_mode=Loggningsläge + +monitor.cron=Cron-jobb +monitor.name=Namn +monitor.schedule=Schemaläggning +monitor.next=Nästa tillfälle +monitor.previous=Föregående tillfälle +monitor.execute_times=Execute Times +monitor.process=Running Processes +monitor.desc=Beskrivning +monitor.start=Starttid +monitor.execute_time=Execution Time + +notices.system_notice_list=System Notices +notices.view_detail_header=View Notice Detail +notices.actions=Actions +notices.select_all=Select All +notices.deselect_all=Deselect All +notices.inverse_selection=Inverse Selection +notices.delete_selected=Delete Selected +notices.delete_all=Delete All Notices +notices.type=Typ +notices.type_1=Repository +notices.desc=Beskrivning +notices.op=Op. +notices.delete_success=System notices have been deleted successfully. + +[action] +create_repo=skapade utvecklingskatalog %s +rename_repo=renamed repository from %[1]s to %[3]s +commit_repo=pushed to %[3]s at %[4]s +create_issue=`opened issue %s#%[2]s` +close_issue=`closed issue %s#%[2]s` +reopen_issue=`reopened issue %s#%[2]s` +create_pull_request=`created pull request %s#%[2]s` +close_pull_request=`closed pull request %s#%[2]s` +reopen_pull_request=`reopened pull request %s#%[2]s` +comment_issue=`commented on issue %s#%[2]s` +merge_pull_request=`merged pull request %s#%[2]s` +transfer_repo=transfered repository %s to %s +push_tag=pushed tag %[2]s to %[3]s +compare_commits=View comparison for these %d commits + +[tool] +ago=sedan +from_now=från och med nu +now=nu +1s=1 sekund %s +1m=1 minut %s +1h=1 timme %s +1d=1 dag %s +1w=1 vecka %s +1mon=1 månad %s +1y=1 år %s +seconds=%d sekunder %s +minutes=%d minuter %s +hours=%d timmar %s +days=%d dagar %s +weeks=%d veckor %s +months=%d månader %s +years=%d år %s +raw_seconds=sekunder +raw_minutes=minuter + +[dropzone] +default_message=Drop files here or click to upload. +invalid_input_type=You can't upload files of this type. +file_too_big=File size ({{filesize}} MB) exceeds maximum size ({{maxFilesize}} MB). +remove_file=Remove file + diff --git a/conf/locale/locale_tr-TR.ini b/conf/locale/locale_tr-TR.ini index de7696bc45..64bb82db56 100644 --- a/conf/locale/locale_tr-TR.ini +++ b/conf/locale/locale_tr-TR.ini @@ -193,7 +193,7 @@ NewBranchName=New branch name CommitSummary=Commit summary CommitMessage=Commit message CommitChoice=Commit choice -TreeName=File path +TreeName=Dosya yolu Content=Content require_error=` boş olamaz.` @@ -429,9 +429,9 @@ file_too_large=Bu dosya sergilenmek için çok büyük editor.new_file=New file editor.upload_file=Upload file -editor.edit_file=Edit file +editor.edit_file=Dosya düzenle editor.preview_changes=Preview Changes -editor.cannot_edit_non_text_files=Cannot edit non-text files +editor.cannot_edit_non_text_files=Metin dışı dosyalar düzenlenemez editor.edit_this_file=Edit this file editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file editor.fork_before_edit=You must fork this repository before editing the file @@ -441,7 +441,7 @@ editor.file_delete_success=File '%s' has been deleted successfully! editor.name_your_file=Name your file... editor.filename_help=To add directory, just type it and press /. To remove a directory, go to the beginning of the field and press backspace. editor.or=or -editor.cancel_lower=cancel +editor.cancel_lower=iptal editor.commit_changes=Commit Changes editor.add_tmpl=Add '%s/' editor.add=Add '%s' @@ -451,7 +451,7 @@ editor.commit_message_desc=Add an optional extended description... editor.commit_directly_to_this_branch=Commit directly to the %s branch. editor.create_new_branch=Create a new branch for this commit and start a pull request. editor.new_branch_name_desc=New branch name... -editor.cancel=Cancel +editor.cancel=İptal editor.filename_cannot_be_empty=Filename cannot be empty. editor.branch_already_exists=Branch '%s' already exists in this repository. editor.directory_is_a_file=Entry '%s' in the parent path is a file not a directory in this repository. @@ -639,7 +639,7 @@ settings.site=Resmi Web Sitesi settings.update_settings=Ayarları Güncelle settings.change_reponame_prompt=Bu değişiklik, bağlantıların depoyla olan ilişkisini etkileyecektir. settings.advanced_settings=Gelişmiş Ayarlar -settings.wiki_desc=Enable wiki system +settings.wiki_desc=Viki sıstemini etkinleştir settings.use_internal_wiki=Use builtin wiki settings.use_external_wiki=Harici Wiki kullan settings.external_wiki_url=Harici Wiki bağlantısı diff --git a/conf/locale/locale_zh-TW.ini b/conf/locale/locale_zh-TW.ini index 7b9ea42c3f..d9bdf66a55 100644 --- a/conf/locale/locale_zh-TW.ini +++ b/conf/locale/locale_zh-TW.ini @@ -126,7 +126,7 @@ uname_holder=用戶名或郵箱 password_holder=密碼 switch_dashboard_context=切換控制面版用戶 my_repos=我的倉庫 -show_more_repos=Show more repositories... +show_more_repos=顯示更多倉庫... collaborative_repos=參與協作的倉庫 my_orgs=我的組織 my_mirrors=我的鏡像 @@ -151,7 +151,7 @@ forget_password=忘記密碼? sign_up_now=還沒帳戶?馬上註冊。 confirmation_mail_sent_prompt=一封新的確認郵件已經被發送至 %s,請檢查您的收件箱並在 %d 小時內完成確認註冊操作。 active_your_account=激活您的帳戶 -prohibit_login=Login Prohibited +prohibit_login=禁止登錄 prohibit_login_desc=Your account is prohibited to login, please contact site admin. resent_limit_prompt=對不起,您請求發送激活郵件過於頻繁,請等待 3 分鐘後再試! has_unconfirmed_mail=%s 您好,您有一封發送至( %s) 但未被確認的郵件。如果您未收到激活郵件,或需要重新發送,請單擊下方的按鈕。 @@ -189,12 +189,12 @@ TeamName=團隊名稱 AuthName=認證名稱 AdminEmail=管理員郵箱 -NewBranchName=New branch name +NewBranchName=新的分支名稱 CommitSummary=Commit summary -CommitMessage=Commit message +CommitMessage=提交訊息 CommitChoice=Commit choice -TreeName=File path -Content=Content +TreeName=檔案路徑 +Content=內容 require_error=不能為空。 alpha_dash_error=必須為英文字母、阿拉伯數字或橫線(-_)。 @@ -427,31 +427,31 @@ file_view_raw=查看原始文件 file_permalink=永久連結 file_too_large=This file is too large to be shown -editor.new_file=New file -editor.upload_file=Upload file -editor.edit_file=Edit file +editor.new_file=開新檔案 +editor.upload_file=上傳檔案 +editor.edit_file=編輯文件 editor.preview_changes=Preview Changes -editor.cannot_edit_non_text_files=Cannot edit non-text files -editor.edit_this_file=Edit this file +editor.cannot_edit_non_text_files=不能編輯非文字檔 +editor.edit_this_file=編輯此文件 editor.must_be_on_a_branch=You must be on a branch to make or propose changes to this file editor.fork_before_edit=You must fork this repository before editing the file -editor.delete_this_file=Delete this file +editor.delete_this_file=刪除此文件 editor.must_have_write_access=You must have write access to make or propose changes to this file editor.file_delete_success=File '%s' has been deleted successfully! editor.name_your_file=Name your file... editor.filename_help=To add directory, just type it and press /. To remove a directory, go to the beginning of the field and press backspace. -editor.or=or -editor.cancel_lower=cancel +editor.or=或 +editor.cancel_lower=取消 editor.commit_changes=Commit Changes editor.add_tmpl=Add '%s/' -editor.add=Add '%s' -editor.update=Update '%s' -editor.delete=Delete '%s' +editor.add=新增 '%s' +editor.update=更新 '%s' +editor.delete=刪除 '%s' editor.commit_message_desc=Add an optional extended description... editor.commit_directly_to_this_branch=Commit directly to the %s branch. editor.create_new_branch=Create a new branch for this commit and start a pull request. -editor.new_branch_name_desc=New branch name... -editor.cancel=Cancel +editor.new_branch_name_desc=新的分支名稱... +editor.cancel=取消 editor.filename_cannot_be_empty=Filename cannot be empty. editor.branch_already_exists=Branch '%s' already exists in this repository. editor.directory_is_a_file=Entry '%s' in the parent path is a file not a directory in this repository. @@ -459,9 +459,9 @@ editor.filename_is_a_directory=The filename '%s' is an existing directory in thi editor.file_editing_no_longer_exists=The file '%s' you are editing no longer exists in the repository. editor.file_changed_while_editing=File content has been changed since you started editing. Click here to see what have been changed or press commit again to overwrite those changes. editor.file_already_exists=A file with name '%s' already exists in this repository. -editor.no_changes_to_show=There are no changes to show. +editor.no_changes_to_show=沒有可以顯示的變更。 editor.fail_to_update_file=Failed to update/create file '%s' with error: %v -editor.add_subdir=Add subdirectory... +editor.add_subdir=新增子目錄... editor.unable_to_upload_files=Failed to upload files to '%s' with error: %v editor.upload_files_to_dir=Upload files to '%s' @@ -523,7 +523,7 @@ issues.open_title=開啟中 issues.closed_title=已關閉 issues.num_comments=%d 條評論 issues.commented_at=`commented %s` -issues.delete_comment_confirm=Are you sure you want to delete this comment? +issues.delete_comment_confirm=您確定要刪除該條評論嗎? issues.no_content=尚未有任何內容 issues.close_issue=關閉 issues.close_comment_issue=關閉及評論 @@ -551,8 +551,8 @@ issues.label_deletion=刪除標籤 issues.label_deletion_desc=刪除該標籤將會移除所有問題中相關的訊息。是否繼續? issues.label_deletion_success=標籤刪除成功! issues.num_participants=%d 參與者 -issues.attachment.open_tab=`Click to see "%s" in a new tab` -issues.attachment.download=`Click to download "%s"` +issues.attachment.open_tab=`在新的標籤頁中查看 '%s'` +issues.attachment.download=`點擊下載 '%s'` pulls.new=創建合併請求 pulls.compare_changes=對比文件變化 @@ -632,14 +632,14 @@ settings.collaboration.undefined=未定義 settings.hooks=管理 Web 鉤子 settings.githooks=管理 Git 鉤子 settings.basic_settings=基本設置 -settings.mirror_settings=Mirror Settings +settings.mirror_settings=鏡像設定 settings.sync_mirror=Sync Now settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute. settings.site=官方網站 settings.update_settings=更新倉庫設置 settings.change_reponame_prompt=該操作將會影響到所有與該倉庫有關的鏈接 settings.advanced_settings=高級設置 -settings.wiki_desc=Enable wiki system +settings.wiki_desc=啓用 Wiki 系統 settings.use_internal_wiki=Use builtin wiki settings.use_external_wiki=使用外部 wiki settings.external_wiki_url=外部 Wiki 連結 @@ -720,7 +720,7 @@ settings.event_send_everything=推送 所有 事件 settings.event_choose=讓我選擇我的需要 settings.event_create=創建 settings.event_create_desc=創建分支或標籤 -settings.event_pull_request=Pull Request +settings.event_pull_request=合併請求 settings.event_pull_request_desc=Pull request opened, closed, reopened, edited, assigned, unassigned, label updated, label cleared, or synchronized. settings.event_push=推送 settings.event_push_desc=Git 倉庫推送 From 5b998a6680258b6314430f71183e6eb85f1836d0 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 27 Nov 2016 14:03:59 +0800 Subject: [PATCH 055/135] golint fixed for modules/auth --- cmd/web.go | 2 +- models/login_source.go | 2 +- modules/auth/admin.go | 8 +++++-- modules/auth/auth.go | 9 ++++++-- modules/auth/auth_form.go | 2 ++ modules/auth/ldap/ldap.go | 5 ++-- modules/auth/org.go | 6 +++++ modules/auth/pam/pam.go | 3 ++- modules/auth/pam/pam_stub.go | 3 ++- modules/auth/repo_form.go | 44 ++++++++++++++++++++++++++++++++++-- modules/auth/user_form.go | 21 ++++++++++++++++- routers/admin/users.go | 2 +- routers/api/v1/repo/repo.go | 4 ++-- routers/install.go | 10 ++++---- routers/repo/pull.go | 2 +- routers/repo/repo.go | 4 ++-- 16 files changed, 103 insertions(+), 24 deletions(-) diff --git a/cmd/web.go b/cmd/web.go index 3d0c977798..7ece2140b3 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -280,7 +280,7 @@ func runWeb(ctx *cli.Context) error { m.Group("/users", func() { m.Get("", admin.Users) - m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost) + m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost) m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost) m.Post("/:userid/delete", admin.DeleteUser) }) diff --git a/models/login_source.go b/models/login_source.go index b570f415c7..7a5e6083a7 100644 --- a/models/login_source.go +++ b/models/login_source.go @@ -502,7 +502,7 @@ func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPC // LoginViaPAM queries if login/password is valid against the PAM, // and create a local user if success when enabled. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) { - if err := pam.PAMAuth(cfg.ServiceName, login, password); err != nil { + if err := pam.Auth(cfg.ServiceName, login, password); err != nil { if strings.Contains(err.Error(), "Authentication failure") { return nil, ErrUserNotExist{0, login, 0} } diff --git a/modules/auth/admin.go b/modules/auth/admin.go index 58d1a027fc..033dfe9388 100644 --- a/modules/auth/admin.go +++ b/modules/auth/admin.go @@ -10,7 +10,8 @@ import ( "github.com/go-macaron/binding" ) -type AdminCrateUserForm struct { +// AdminCreateUserForm form for admin to create user +type AdminCreateUserForm struct { LoginType string `binding:"Required"` LoginName string UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"` @@ -19,10 +20,12 @@ type AdminCrateUserForm struct { SendNotify bool } -func (f *AdminCrateUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { +// Validate validates form fields +func (f *AdminCreateUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// AdminEditUserForm form for admin to create user type AdminEditUserForm struct { LoginType string `binding:"Required"` LoginName string @@ -39,6 +42,7 @@ type AdminEditUserForm struct { ProhibitLogin bool } +// Validate validates form fields func (f *AdminEditUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/auth/auth.go b/modules/auth/auth.go index 2444a3ad1f..ed94d0a698 100644 --- a/modules/auth/auth.go +++ b/modules/auth/auth.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// IsAPIPath if URL is an api path func IsAPIPath(url string) bool { return strings.HasPrefix(url, "/api/") } @@ -110,9 +111,8 @@ func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool) // FIXME: should I create a system notice? log.Error(4, "CreateUser: %v", err) return nil, false - } else { - return u, false } + return u, false } } return u, false @@ -148,6 +148,7 @@ func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool) return u, false } +// Form form binding interface type Form interface { binding.Validator } @@ -190,18 +191,22 @@ func getRuleBody(field reflect.StructField, prefix string) string { return "" } +// GetSize get size int form tag func GetSize(field reflect.StructField) string { return getRuleBody(field, "Size(") } +// GetMinSize get minimal size in form tag func GetMinSize(field reflect.StructField) string { return getRuleBody(field, "MinSize(") } +// GetMaxSize get max size in form tag func GetMaxSize(field reflect.StructField) string { return getRuleBody(field, "MaxSize(") } +// GetInclude get include in form tag func GetInclude(field reflect.StructField) string { return getRuleBody(field, "Include(") } diff --git a/modules/auth/auth_form.go b/modules/auth/auth_form.go index 9454d85693..78ba2b8997 100644 --- a/modules/auth/auth_form.go +++ b/modules/auth/auth_form.go @@ -9,6 +9,7 @@ import ( "gopkg.in/macaron.v1" ) +// AuthenticationForm form for authentication type AuthenticationForm struct { ID int64 Type int `binding:"Range(2,5)"` @@ -37,6 +38,7 @@ type AuthenticationForm struct { PAMServiceName string } +// Validate validates fields func (f *AuthenticationForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/auth/ldap/ldap.go b/modules/auth/ldap/ldap.go index e2cbf18d98..0cabcb20a0 100644 --- a/modules/auth/ldap/ldap.go +++ b/modules/auth/ldap/ldap.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/log" ) +// SecurityProtocol protocol type type SecurityProtocol int // Note: new type must be added at the end of list to maintain compatibility. @@ -25,7 +26,7 @@ const ( SecurityProtocolStartTLS ) -// Basic LDAP authentication service +// Source Basic LDAP authentication service type Source struct { Name string // canonical name (ie. corporate.ad) Host string // LDAP host @@ -148,7 +149,7 @@ func bindUser(l *ldap.Conn, userDN, passwd string) error { return err } -// searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter +// SearchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) { l, err := dial(ls) if err != nil { diff --git a/modules/auth/org.go b/modules/auth/org.go index 53ef6245d9..e15cba0f9f 100644 --- a/modules/auth/org.go +++ b/modules/auth/org.go @@ -16,14 +16,17 @@ import ( // \_______ /__| \___ (____ /___| /__/_____ \(____ /__| |__|\____/|___| / // \/ /_____/ \/ \/ \/ \/ \/ +// CreateOrgForm form for creating organization type CreateOrgForm struct { OrgName string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"` } +// Validate valideates the fields func (f *CreateOrgForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// UpdateOrgSettingForm form for updating organization settings type UpdateOrgSettingForm struct { Name string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"` FullName string `binding:"MaxSize(100)"` @@ -33,6 +36,7 @@ type UpdateOrgSettingForm struct { MaxRepoCreation int } +// Validate valideates the fields func (f *UpdateOrgSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -44,12 +48,14 @@ func (f *UpdateOrgSettingForm) Validate(ctx *macaron.Context, errs binding.Error // |____| \___ >____ /__|_| / // \/ \/ \/ +// CreateTeamForm form for creating team type CreateTeamForm struct { TeamName string `binding:"Required;AlphaDashDot;MaxSize(30)"` Description string `binding:"MaxSize(255)"` Permission string } +// Validate valideates the fields func (f *CreateTeamForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/auth/pam/pam.go b/modules/auth/pam/pam.go index 7f326d42f5..6f0f7240ae 100644 --- a/modules/auth/pam/pam.go +++ b/modules/auth/pam/pam.go @@ -12,7 +12,8 @@ import ( "github.com/msteinert/pam" ) -func PAMAuth(serviceName, userName, passwd string) error { +// Auth pam auth service +func Auth(serviceName, userName, passwd string) error { t, err := pam.StartFunc(serviceName, userName, func(s pam.Style, msg string) (string, error) { switch s { case pam.PromptEchoOff: diff --git a/modules/auth/pam/pam_stub.go b/modules/auth/pam/pam_stub.go index 33ac751a34..ee2527dd89 100644 --- a/modules/auth/pam/pam_stub.go +++ b/modules/auth/pam/pam_stub.go @@ -10,6 +10,7 @@ import ( "errors" ) -func PAMAuth(serviceName, userName, passwd string) error { +// Auth not supported lack of pam tag +func Auth(serviceName, userName, passwd string) error { return errors.New("PAM not supported") } diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 94c99d8fb9..8a200c0206 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -21,8 +21,9 @@ import ( // |____|_ /_______ / |____| \_______ /_______ /|___| |____| \_______ /____|_ // ______| // \/ \/ \/ \/ \/ \/ \/ +// CreateRepoForm form for creating repository type CreateRepoForm struct { - Uid int64 `binding:"Required"` + UID int64 `binding:"Required"` RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` Private bool Description string `binding:"MaxSize(255)"` @@ -32,21 +33,24 @@ type CreateRepoForm struct { Readme string } +// Validate valideates the fields func (f *CreateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// MigrateRepoForm form for migrating repository type MigrateRepoForm struct { CloneAddr string `json:"clone_addr" binding:"Required"` AuthUsername string `json:"auth_username"` AuthPassword string `json:"auth_password"` - Uid int64 `json:"uid" binding:"Required"` + UID int64 `json:"uid" binding:"Required"` RepoName string `json:"repo_name" binding:"Required;AlphaDashDot;MaxSize(100)"` Mirror bool `json:"mirror"` Private bool `json:"private"` Description string `json:"description" binding:"MaxSize(255)"` } +// Validate valideates the fields func (f *MigrateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -79,6 +83,7 @@ func (f MigrateRepoForm) ParseRemoteAddr(user *models.User) (string, error) { return remoteAddr, nil } +// RepoSettingForm form for changing repository settings type RepoSettingForm struct { RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` Description string `binding:"MaxSize(255)"` @@ -101,6 +106,7 @@ type RepoSettingForm struct { EnablePulls bool } +// Validate valideates the fields func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -112,6 +118,7 @@ func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) bi // \__/\ / \___ >___ /___| /___| /\____/|__|_ \ // \/ \/ \/ \/ \/ \/ +// WebhookForm form for changing web hook type WebhookForm struct { Events string Create bool @@ -120,18 +127,22 @@ type WebhookForm struct { Active bool } +// PushOnly if the hook will be triggered when push func (f WebhookForm) PushOnly() bool { return f.Events == "push_only" } +// SendEverything if the hook will be triggered any event func (f WebhookForm) SendEverything() bool { return f.Events == "send_everything" } +// ChooseEvents if the hook will be triggered choose events func (f WebhookForm) ChooseEvents() bool { return f.Events == "choose_events" } +// NewWebhookForm form for creating web hook type NewWebhookForm struct { PayloadURL string `binding:"Required;Url"` ContentType int `binding:"Required"` @@ -139,10 +150,12 @@ type NewWebhookForm struct { WebhookForm } +// Validate valideates the fields func (f *NewWebhookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// NewSlackHookForm form for creating slack hook type NewSlackHookForm struct { PayloadURL string `binding:"Required;Url"` Channel string `binding:"Required"` @@ -152,6 +165,7 @@ type NewSlackHookForm struct { WebhookForm } +// Validate valideates the fields func (f *NewSlackHookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -163,6 +177,7 @@ func (f *NewSlackHookForm) Validate(ctx *macaron.Context, errs binding.Errors) b // |___/____ >____ >____/ \___ > // \/ \/ \/ +// CreateIssueForm form for creating issue type CreateIssueForm struct { Title string `binding:"Required;MaxSize(255)"` LabelIDs string `form:"label_ids"` @@ -172,16 +187,19 @@ type CreateIssueForm struct { Files []string } +// Validate valideates the fields func (f *CreateIssueForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// CreateCommentForm form for creating comment type CreateCommentForm struct { Content string Status string `binding:"OmitEmpty;In(reopen,close)"` Files []string } +// Validate valideates the fields func (f *CreateCommentForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -193,12 +211,14 @@ func (f *CreateCommentForm) Validate(ctx *macaron.Context, errs binding.Errors) // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ > // \/ \/ \/ \/ \/ +// CreateMilestoneForm form for creating milestone type CreateMilestoneForm struct { Title string `binding:"Required;MaxSize(50)"` Content string Deadline string } +// Validate valideates the fields func (f *CreateMilestoneForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -210,20 +230,24 @@ func (f *CreateMilestoneForm) Validate(ctx *macaron.Context, errs binding.Errors // |_______ (____ /___ /\___ >____/ // \/ \/ \/ \/ +// CreateLabelForm form for creating label type CreateLabelForm struct { ID int64 Title string `binding:"Required;MaxSize(50)" locale:"repo.issues.label_name"` Color string `binding:"Required;Size(7)" locale:"repo.issues.label_color"` } +// Validate valideates the fields func (f *CreateLabelForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// InitializeLabelsForm form for initializing labels type InitializeLabelsForm struct { TemplateName string `binding:"Required"` } +// Validate valideates the fields func (f *InitializeLabelsForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -235,6 +259,7 @@ func (f *InitializeLabelsForm) Validate(ctx *macaron.Context, errs binding.Error // |____|_ /\___ >____/\___ >____ /____ >\___ > // \/ \/ \/ \/ \/ \/ +// NewReleaseForm form for creating release type NewReleaseForm struct { TagName string `binding:"Required"` Target string `form:"tag_target" binding:"Required"` @@ -244,10 +269,12 @@ type NewReleaseForm struct { Prerelease bool } +// Validate valideates the fields func (f *NewReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// EditReleaseForm form for changing release type EditReleaseForm struct { Title string `form:"title" binding:"Required"` Content string `form:"content"` @@ -255,6 +282,7 @@ type EditReleaseForm struct { Prerelease bool `form:"prerelease"` } +// Validate valideates the fields func (f *EditReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -266,6 +294,7 @@ func (f *EditReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) bi // \__/\ / |__|__|_ \__| // \/ \/ +// NewWikiForm form for creating wiki type NewWikiForm struct { OldTitle string Title string `binding:"Required"` @@ -273,6 +302,7 @@ type NewWikiForm struct { Message string } +// Validate valideates the fields // FIXME: use code generation to generate this method. func (f *NewWikiForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) @@ -285,6 +315,7 @@ func (f *NewWikiForm) Validate(ctx *macaron.Context, errs binding.Errors) bindin // /_______ /\____ | |__||__| // \/ \/ +// EditRepoFileForm form for changing repository file type EditRepoFileForm struct { TreePath string `binding:"Required;MaxSize(500)"` Content string `binding:"Required"` @@ -295,14 +326,17 @@ type EditRepoFileForm struct { LastCommit string } +// Validate valideates the fields func (f *EditRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// EditPreviewDiffForm form for changing preview diff type EditPreviewDiffForm struct { Content string } +// Validate valideates the fields func (f *EditPreviewDiffForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -315,6 +349,7 @@ func (f *EditPreviewDiffForm) Validate(ctx *macaron.Context, errs binding.Errors // |__| \/ \/ // +// UploadRepoFileForm form for uploading repository file type UploadRepoFileForm struct { TreePath string `binding:"MaxSize(500)"` CommitSummary string `binding:"MaxSize(100)"` @@ -324,14 +359,17 @@ type UploadRepoFileForm struct { Files []string } +// Validate valideates the fields func (f *UploadRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// RemoveUploadFileForm form for removing uploaded file type RemoveUploadFileForm struct { File string `binding:"Required;MaxSize(50)"` } +// Validate valideates the fields func (f *RemoveUploadFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -343,6 +381,7 @@ func (f *RemoveUploadFileForm) Validate(ctx *macaron.Context, errs binding.Error // /_______ /\___ >____/\___ >__| \___ > // \/ \/ \/ \/ +// DeleteRepoFileForm form for deleting repository file type DeleteRepoFileForm struct { CommitSummary string `binding:"MaxSize(100)"` CommitMessage string @@ -350,6 +389,7 @@ type DeleteRepoFileForm struct { NewBranchName string `binding:"AlphaDashDot;MaxSize(100)"` } +// Validate valideates the fields func (f *DeleteRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/auth/user_form.go b/modules/auth/user_form.go index 09ef53db8f..0bdd7c1532 100644 --- a/modules/auth/user_form.go +++ b/modules/auth/user_form.go @@ -11,6 +11,7 @@ import ( "gopkg.in/macaron.v1" ) +// InstallForm form for installation page type InstallForm struct { DbType string `binding:"Required"` DbHost string @@ -26,7 +27,7 @@ type InstallForm struct { Domain string `binding:"Required"` SSHPort int HTTPPort string `binding:"Required"` - AppUrl string `binding:"Required"` + AppURL string `binding:"Required"` LogRootPath string `binding:"Required"` SMTPHost string @@ -49,6 +50,7 @@ type InstallForm struct { AdminEmail string `binding:"OmitEmpty;MinSize(3);MaxSize(254);Include(@)" locale:"install.admin_email"` } +// Validate valideates the fields func (f *InstallForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -60,6 +62,7 @@ func (f *InstallForm) Validate(ctx *macaron.Context, errs binding.Errors) bindin // \____|__ /______/ |____| \___|_ / // \/ \/ +// RegisterForm form for registering type RegisterForm struct { UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"` Email string `binding:"Required;Email;MaxSize(254)"` @@ -67,16 +70,19 @@ type RegisterForm struct { Retype string } +// Validate valideates the fields func (f *RegisterForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// SignInForm form for signing in type SignInForm struct { UserName string `binding:"Required;MaxSize(254)"` Password string `binding:"Required;MaxSize(255)"` Remember bool } +// Validate valideates the fields func (f *SignInForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -88,6 +94,7 @@ func (f *SignInForm) Validate(ctx *macaron.Context, errs binding.Errors) binding // /_______ //_______ / |____| |____| |___\____|__ /\______ /_______ / // \/ \/ \/ \/ \/ +// UpdateProfileForm form for updating profile type UpdateProfileForm struct { Name string `binding:"OmitEmpty;MaxSize(35)"` FullName string `binding:"MaxSize(100)"` @@ -96,15 +103,18 @@ type UpdateProfileForm struct { Location string `binding:"MaxSize(50)"` } +// Validate valideates the fields func (f *UpdateProfileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// Avatar types const ( AvatarLocal string = "local" AvatarByMail string = "bymail" ) +// AvatarForm form for changing avatar type AvatarForm struct { Source string Avatar *multipart.FileHeader @@ -112,41 +122,50 @@ type AvatarForm struct { Federavatar bool } +// Validate valideates the fields func (f *AvatarForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// AddEmailForm form for adding new email type AddEmailForm struct { Email string `binding:"Required;Email;MaxSize(254)"` } +// Validate valideates the fields func (f *AddEmailForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// ChangePasswordForm form for changing password type ChangePasswordForm struct { OldPassword string `form:"old_password" binding:"Required;MinSize(1);MaxSize(255)"` Password string `form:"password" binding:"Required;MaxSize(255)"` Retype string `form:"retype"` } +// Validate valideates the fields func (f *ChangePasswordForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// AddSSHKeyForm form for adding SSH key type AddSSHKeyForm struct { Title string `binding:"Required;MaxSize(50)"` Content string `binding:"Required"` } +// Validate valideates the fields func (f *AddSSHKeyForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// NewAccessTokenForm form for creating access token type NewAccessTokenForm struct { Name string `binding:"Required"` } +// Validate valideates the fields func (f *NewAccessTokenForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/routers/admin/users.go b/routers/admin/users.go index dd4d2f5786..7444d807b1 100644 --- a/routers/admin/users.go +++ b/routers/admin/users.go @@ -60,7 +60,7 @@ func NewUser(ctx *context.Context) { } // NewUserPost response for adding a new user -func NewUserPost(ctx *context.Context, form auth.AdminCrateUserForm) { +func NewUserPost(ctx *context.Context, form auth.AdminCreateUserForm) { ctx.Data["Title"] = ctx.Tr("admin.users.new_account") ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminUsers"] = true diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 6ae513db16..1fa0b14b40 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -177,8 +177,8 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { ctxUser := ctx.User // Not equal means context user is an organization, // or is another user/organization if current user is admin. - if form.Uid != ctxUser.ID { - org, err := models.GetUserByID(form.Uid) + if form.UID != ctxUser.ID { + org, err := models.GetUserByID(form.UID) if err != nil { if models.IsErrUserNotExist(err) { ctx.Error(422, "", err) diff --git a/routers/install.go b/routers/install.go index ab9c835507..595eecbf44 100644 --- a/routers/install.go +++ b/routers/install.go @@ -89,7 +89,7 @@ func Install(ctx *context.Context) { form.Domain = setting.Domain form.SSHPort = setting.SSH.Port form.HTTPPort = setting.HTTPPort - form.AppUrl = setting.AppUrl + form.AppURL = setting.AppUrl form.LogRootPath = setting.LogRootPath // E-mail service settings @@ -217,8 +217,8 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) { return } - if form.AppUrl[len(form.AppUrl)-1] != '/' { - form.AppUrl += "/" + if form.AppURL[len(form.AppURL)-1] != '/' { + form.AppURL += "/" } // Save settings. @@ -242,7 +242,7 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) { cfg.Section("").Key("RUN_USER").SetValue(form.RunUser) cfg.Section("server").Key("DOMAIN").SetValue(form.Domain) cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort) - cfg.Section("server").Key("ROOT_URL").SetValue(form.AppUrl) + cfg.Section("server").Key("ROOT_URL").SetValue(form.AppURL) if form.SSHPort == 0 { cfg.Section("server").Key("DISABLE_SSH").SetValue("true") @@ -328,5 +328,5 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) { log.Info("First-time run install finished!") ctx.Flash.Success(ctx.Tr("install.install_success")) - ctx.Redirect(form.AppUrl + "user/login") + ctx.Redirect(form.AppURL + "user/login") } diff --git a/routers/repo/pull.go b/routers/repo/pull.go index c8969b98f2..88a1f25492 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -94,7 +94,7 @@ func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { return } - ctxUser := checkContextUser(ctx, form.Uid) + ctxUser := checkContextUser(ctx, form.UID) if ctx.Written() { return } diff --git a/routers/repo/repo.go b/routers/repo/repo.go index c25f5c67cc..d41b66b381 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -112,7 +112,7 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["Licenses"] = models.Licenses ctx.Data["Readmes"] = models.Readmes - ctxUser := checkContextUser(ctx, form.Uid) + ctxUser := checkContextUser(ctx, form.UID) if ctx.Written() { return } @@ -167,7 +167,7 @@ func Migrate(ctx *context.Context) { func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_migrate") - ctxUser := checkContextUser(ctx, form.Uid) + ctxUser := checkContextUser(ctx, form.UID) if ctx.Written() { return } From 94da47271701401b6959bfd308d6c74fd30b22e2 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 27 Nov 2016 18:14:25 +0800 Subject: [PATCH 056/135] Golint fixed for modules/setting (#262) * golint fixed for modules/setting * typo fixed and renamed UNIXSOCKET to UnixSocket --- cmd/web.go | 18 ++++----- models/action.go | 6 +-- models/pull.go | 2 +- models/repo.go | 6 +-- models/user.go | 14 +++---- models/webhook_slack.go | 4 +- modules/base/tool.go | 2 +- modules/context/api.go | 8 ++-- modules/context/auth.go | 16 ++++---- modules/context/context.go | 2 +- modules/context/org.go | 2 +- modules/context/repo.go | 4 +- modules/markdown/markdown.go | 6 +-- modules/markdown/markdown_test.go | 6 +-- modules/setting/setting.go | 67 ++++++++++++++++++------------- modules/template/template.go | 6 +-- routers/admin/admin.go | 6 +-- routers/admin/auths.go | 8 ++-- routers/admin/notice.go | 2 +- routers/admin/repos.go | 2 +- routers/admin/users.go | 10 ++--- routers/api/v1/repo/key.go | 2 +- routers/api/v1/user/key.go | 2 +- routers/dev/template.go | 2 +- routers/home.go | 2 +- routers/install.go | 2 +- routers/org/members.go | 2 +- routers/org/org.go | 2 +- routers/org/setting.go | 4 +- routers/repo/commit.go | 12 +++--- routers/repo/editor.go | 2 +- routers/repo/issue.go | 6 +-- routers/repo/pull.go | 16 ++++---- routers/repo/repo.go | 4 +- routers/repo/setting.go | 12 +++--- routers/user/auth.go | 38 +++++++++--------- routers/user/home.go | 2 +- routers/user/setting.go | 38 +++++++++--------- 38 files changed, 178 insertions(+), 167 deletions(-) diff --git a/cmd/web.go b/cmd/web.go index 3d0c977798..3bb5ef3a9c 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -123,7 +123,7 @@ func newMacaron() *macaron.Macaron { m.Use(gzip.Gziper()) } if setting.Protocol == setting.FCGI { - m.SetURLPrefix(setting.AppSubUrl) + m.SetURLPrefix(setting.AppSubURL) } m.Use(macaron.Static( path.Join(setting.StaticRootPath, "public"), @@ -158,7 +158,7 @@ func newMacaron() *macaron.Macaron { localFiles[name] = bindata.MustAsset("conf/locale/" + name) } m.Use(i18n.I18n(i18n.Options{ - SubURL: setting.AppSubUrl, + SubURL: setting.AppSubURL, Files: localFiles, CustomDirectory: path.Join(setting.CustomPath, "conf/locale"), Langs: setting.Langs, @@ -172,7 +172,7 @@ func newMacaron() *macaron.Macaron { Interval: setting.CacheInterval, })) m.Use(captcha.Captchaer(captcha.Options{ - SubURL: setting.AppSubUrl, + SubURL: setting.AppSubURL, })) m.Use(session.Sessioner(setting.SessionConfig)) m.Use(csrf.Csrfer(csrf.Options{ @@ -180,7 +180,7 @@ func newMacaron() *macaron.Macaron { Cookie: setting.CSRFCookieName, SetCookie: true, Header: "X-Csrf-Token", - CookiePath: setting.AppSubUrl, + CookiePath: setting.AppSubURL, })) m.Use(toolbox.Toolboxer(m, toolbox.Options{ HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{ @@ -216,7 +216,7 @@ func runWeb(ctx *cli.Context) error { m.Get("/", ignSignIn, routers.Home) m.Group("/explore", func() { m.Get("", func(ctx *context.Context) { - ctx.Redirect(setting.AppSubUrl + "/explore/repos") + ctx.Redirect(setting.AppSubURL + "/explore/repos") }) m.Get("/repos", routers.ExploreRepos) m.Get("/users", routers.ExploreUsers) @@ -635,17 +635,17 @@ func runWeb(ctx *cli.Context) error { // Flag for port number in case first time run conflict. if ctx.IsSet("port") { - setting.AppUrl = strings.Replace(setting.AppUrl, setting.HTTPPort, ctx.String("port"), 1) + setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, ctx.String("port"), 1) setting.HTTPPort = ctx.String("port") } var listenAddr string - if setting.Protocol == setting.UNIX_SOCKET { + if setting.Protocol == setting.UnixSocket { listenAddr = fmt.Sprintf("%s", setting.HTTPAddr) } else { listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort) } - log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl) + log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL) var err error switch setting.Protocol { @@ -656,7 +656,7 @@ func runWeb(ctx *cli.Context) error { err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile) case setting.FCGI: err = fcgi.Serve(nil, m) - case setting.UNIX_SOCKET: + case setting.UnixSocket: os.Remove(listenAddr) var listener *net.UnixListener diff --git a/models/action.go b/models/action.go index 72d988955b..5312a1797f 100644 --- a/models/action.go +++ b/models/action.go @@ -152,8 +152,8 @@ func (a *Action) ShortRepoPath() string { // GetRepoLink returns relative link to action repository. func (a *Action) GetRepoLink() string { - if len(setting.AppSubUrl) > 0 { - return path.Join(setting.AppSubUrl, a.GetRepoPath()) + if len(setting.AppSubURL) > 0 { + return path.Join(setting.AppSubURL, a.GetRepoPath()) } return "/" + a.GetRepoPath() } @@ -546,7 +546,7 @@ func CommitRepoAction(opts CommitRepoActionOptions) error { Ref: opts.RefFullName, Before: opts.OldCommitID, After: opts.NewCommitID, - CompareURL: setting.AppUrl + opts.Commits.CompareURL, + CompareURL: setting.AppURL + opts.Commits.CompareURL, Commits: opts.Commits.ToAPIPayloadCommits(repo.HTMLURL()), Repo: apiRepo, Pusher: apiPusher, diff --git a/models/pull.go b/models/pull.go index d1ff974371..5d32c71766 100644 --- a/models/pull.go +++ b/models/pull.go @@ -317,7 +317,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error Ref: git.BRANCH_PREFIX + pr.BaseBranch, Before: pr.MergeBase, After: pr.MergedCommitID, - CompareURL: setting.AppUrl + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID), + CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID), Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()), Repo: pr.BaseRepo.APIFormat(nil), Pusher: pr.HeadRepo.MustOwner().APIFormat(), diff --git a/models/repo.go b/models/repo.go index b3e08a93e8..4f4477c9af 100644 --- a/models/repo.go +++ b/models/repo.go @@ -246,7 +246,7 @@ func (repo *Repository) FullName() string { } func (repo *Repository) HTMLURL() string { - return setting.AppUrl + repo.FullName() + return setting.AppURL + repo.FullName() } // Arguments that are allowed to be nil: permission @@ -412,7 +412,7 @@ func (repo *Repository) RelLink() string { } func (repo *Repository) Link() string { - return setting.AppSubUrl + "/" + repo.FullName() + return setting.AppSubURL + "/" + repo.FullName() } func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string { @@ -550,7 +550,7 @@ type CloneLink struct { // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name. func ComposeHTTPSCloneURL(owner, repo string) string { - return fmt.Sprintf("%s%s/%s.git", setting.AppUrl, owner, repo) + return fmt.Sprintf("%s%s/%s.git", setting.AppURL, owner, repo) } func (repo *Repository) cloneLink(isWiki bool) *CloneLink { diff --git a/models/user.go b/models/user.go index 6c0223e6ee..1e15b2a965 100644 --- a/models/user.go +++ b/models/user.go @@ -198,14 +198,14 @@ func (u *User) CanImportLocal() bool { // DashboardLink returns the user dashboard page link. func (u *User) DashboardLink() string { if u.IsOrganization() { - return setting.AppSubUrl + "/org/" + u.Name + "/dashboard/" + return setting.AppSubURL + "/org/" + u.Name + "/dashboard/" } - return setting.AppSubUrl + "/" + return setting.AppSubURL + "/" } // HomeLink returns the user or organization home page link. func (u *User) HomeLink() string { - return setting.AppSubUrl + "/" + u.Name + return setting.AppSubURL + "/" + u.Name } // GenerateEmailActivateCode generates an activate code based on user information and given e-mail. @@ -261,7 +261,7 @@ func (u *User) GenerateRandomAvatar() error { // which includes app sub-url as prefix. However, it is possible // to return full URL if user enables Gravatar-like service. func (u *User) RelAvatarLink() string { - defaultImgUrl := setting.AppSubUrl + "/img/avatar_default.png" + defaultImgUrl := setting.AppSubURL + "/img/avatar_default.png" if u.ID == -1 { return defaultImgUrl } @@ -271,7 +271,7 @@ func (u *User) RelAvatarLink() string { if !com.IsExist(u.CustomAvatarPath()) { return defaultImgUrl } - return setting.AppSubUrl + "/avatars/" + com.ToStr(u.ID) + return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID) case setting.DisableGravatar, setting.OfflineMode: if !com.IsExist(u.CustomAvatarPath()) { if err := u.GenerateRandomAvatar(); err != nil { @@ -279,7 +279,7 @@ func (u *User) RelAvatarLink() string { } } - return setting.AppSubUrl + "/avatars/" + com.ToStr(u.ID) + return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID) } return base.AvatarLink(u.AvatarEmail) } @@ -288,7 +288,7 @@ func (u *User) RelAvatarLink() string { func (u *User) AvatarLink() string { link := u.RelAvatarLink() if link[0] == '/' && link[1] != '/' { - return setting.AppUrl + strings.TrimPrefix(link, setting.AppSubUrl)[1:] + return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:] } return link } diff --git a/models/webhook_slack.go b/models/webhook_slack.go index f6b2a70f93..a872e7256c 100644 --- a/models/webhook_slack.go +++ b/models/webhook_slack.go @@ -142,7 +142,7 @@ func getSlackPushPayload(p *api.PushPayload, slack *SlackMeta) (*SlackPayload, e } func getSlackPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) (*SlackPayload, error) { - senderLink := SlackLinkFormatter(setting.AppUrl+p.Sender.UserName, p.Sender.UserName) + senderLink := SlackLinkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName) titleLink := SlackLinkFormatter(fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index), fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title)) var text, title, attachmentText string @@ -164,7 +164,7 @@ func getSlackPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) (*S attachmentText = SlackTextFormatter(p.PullRequest.Body) case api.HookIssueAssigned: text = fmt.Sprintf("[%s] Pull request assigned to %s: %s by %s", p.Repository.FullName, - SlackLinkFormatter(setting.AppUrl+p.PullRequest.Assignee.UserName, p.PullRequest.Assignee.UserName), + SlackLinkFormatter(setting.AppURL+p.PullRequest.Assignee.UserName, p.PullRequest.Assignee.UserName), titleLink, senderLink) case api.HookIssueUnassigned: text = fmt.Sprintf("[%s] Pull request unassigned: %s by %s", p.Repository.FullName, titleLink, senderLink) diff --git a/modules/base/tool.go b/modules/base/tool.go index db065afd8c..981f89b6a5 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -217,7 +217,7 @@ func AvatarLink(email string) string { return setting.GravatarSource + HashEmail(email) } - return setting.AppSubUrl + "/img/avatar_default.png" + return setting.AppSubURL + "/img/avatar_default.png" } // Seconds-based time units diff --git a/modules/context/api.go b/modules/context/api.go index 2823d696d2..7706e9c499 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -47,16 +47,16 @@ func (ctx *APIContext) SetLinkHeader(total, pageSize int) { page := paginater.New(total, pageSize, ctx.QueryInt("page"), 0) links := make([]string, 0, 4) if page.HasNext() { - links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppUrl, ctx.Req.URL.Path[1:], page.Next())) + links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"next\"", setting.AppURL, ctx.Req.URL.Path[1:], page.Next())) } if !page.IsLast() { - links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppUrl, ctx.Req.URL.Path[1:], page.TotalPages())) + links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"last\"", setting.AppURL, ctx.Req.URL.Path[1:], page.TotalPages())) } if !page.IsFirst() { - links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppUrl, ctx.Req.URL.Path[1:])) + links = append(links, fmt.Sprintf("<%s%s?page=1>; rel=\"first\"", setting.AppURL, ctx.Req.URL.Path[1:])) } if page.HasPrevious() { - links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppUrl, ctx.Req.URL.Path[1:], page.Previous())) + links = append(links, fmt.Sprintf("<%s%s?page=%d>; rel=\"prev\"", setting.AppURL, ctx.Req.URL.Path[1:], page.Previous())) } if len(links) > 0 { diff --git a/modules/context/auth.go b/modules/context/auth.go index 0e5ae93a87..372bcb187a 100644 --- a/modules/context/auth.go +++ b/modules/context/auth.go @@ -26,7 +26,7 @@ func Toggle(options *ToggleOptions) macaron.Handler { return func(ctx *Context) { // Cannot view any page before installation. if !setting.InstallLock { - ctx.Redirect(setting.AppSubUrl + "/install") + ctx.Redirect(setting.AppSubURL + "/install") return } @@ -38,14 +38,14 @@ func Toggle(options *ToggleOptions) macaron.Handler { } // Check non-logged users landing page. - if !ctx.IsSigned && ctx.Req.RequestURI == "/" && setting.LandingPageURL != setting.LANDING_PAGE_HOME { - ctx.Redirect(setting.AppSubUrl + string(setting.LandingPageURL)) + if !ctx.IsSigned && ctx.Req.RequestURI == "/" && setting.LandingPageURL != setting.LandingPageHome { + ctx.Redirect(setting.AppSubURL + string(setting.LandingPageURL)) return } // Redirect to dashboard if user tries to visit any non-login page. if options.SignOutRequired && ctx.IsSigned && ctx.Req.RequestURI != "/" { - ctx.Redirect(setting.AppSubUrl + "/") + ctx.Redirect(setting.AppSubURL + "/") return } @@ -66,8 +66,8 @@ func Toggle(options *ToggleOptions) macaron.Handler { return } - ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl) - ctx.Redirect(setting.AppSubUrl + "/user/login") + ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+ctx.Req.RequestURI), 0, setting.AppSubURL) + ctx.Redirect(setting.AppSubURL + "/user/login") return } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { ctx.Data["Title"] = ctx.Tr("auth.active_your_account") @@ -79,8 +79,8 @@ func Toggle(options *ToggleOptions) macaron.Handler { // Redirect to log in page if auto-signin info is provided and has not signed in. if !options.SignOutRequired && !ctx.IsSigned && !auth.IsAPIPath(ctx.Req.URL.Path) && len(ctx.GetCookie(setting.CookieUserName)) > 0 { - ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl) - ctx.Redirect(setting.AppSubUrl + "/user/login") + ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubURL+ctx.Req.RequestURI), 0, setting.AppSubURL) + ctx.Redirect(setting.AppSubURL + "/user/login") return } diff --git a/modules/context/context.go b/modules/context/context.go index 0535da995a..57a9195306 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -159,7 +159,7 @@ func Contexter() macaron.Handler { Org: &Organization{}, } // Compute current URL for real-time change language. - ctx.Data["Link"] = setting.AppSubUrl + strings.TrimSuffix(ctx.Req.URL.Path, "/") + ctx.Data["Link"] = setting.AppSubURL + strings.TrimSuffix(ctx.Req.URL.Path, "/") ctx.Data["PageStartTime"] = time.Now() diff --git a/modules/context/org.go b/modules/context/org.go index d31d9773a0..cfe9a26220 100644 --- a/modules/context/org.go +++ b/modules/context/org.go @@ -95,7 +95,7 @@ func HandleOrgAssignment(ctx *Context, args ...bool) { ctx.Data["IsOrganizationOwner"] = ctx.Org.IsOwner ctx.Data["IsOrganizationMember"] = ctx.Org.IsMember - ctx.Org.OrgLink = setting.AppSubUrl + "/org/" + org.Name + ctx.Org.OrgLink = setting.AppSubURL + "/org/" + org.Name ctx.Data["OrgLink"] = ctx.Org.OrgLink // Team. diff --git a/modules/context/repo.go b/modules/context/repo.go index 6135ac46ae..338a78cb93 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -117,7 +117,7 @@ func RetrieveBaseRepo(ctx *Context, repo *models.Repository) { // composeGoGetImport returns go-get-import meta content. func composeGoGetImport(owner, repo string) string { - return path.Join(setting.Domain, setting.AppSubUrl, owner, repo) + return path.Join(setting.Domain, setting.AppSubURL, owner, repo) } // earlyResponseForGoGetMeta responses appropriate go-get meta with status 200 @@ -331,7 +331,7 @@ func RepoAssignment(args ...bool) macaron.Handler { if ctx.Query("go-get") == "1" { ctx.Data["GoGetImport"] = composeGoGetImport(owner.Name, repo.Name) - prefix := setting.AppUrl + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName) + prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName) ctx.Data["GoDocDirectory"] = prefix + "{/dir}" ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}" } diff --git a/modules/markdown/markdown.go b/modules/markdown/markdown.go index e46f172d3e..6bf29db07a 100644 --- a/modules/markdown/markdown.go +++ b/modules/markdown/markdown.go @@ -135,7 +135,7 @@ func (r *Renderer) AutoLink(out *bytes.Buffer, link []byte, kind int) { // Since this method could only possibly serve one link at a time, // we do not need to find all. - if bytes.HasPrefix(link, []byte(setting.AppUrl)) { + if bytes.HasPrefix(link, []byte(setting.AppURL)) { m := CommitPattern.Find(link) if m != nil { m = bytes.TrimSpace(m) @@ -225,7 +225,7 @@ func cutoutVerbosePrefix(prefix string) string { if prefix[i] == '/' { count++ } - if count >= 3+setting.AppSubUrlDepth { + if count >= 3+setting.AppSubURLDepth { return prefix[:i] } } @@ -279,7 +279,7 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]strin for _, m := range ms { m = m[bytes.Index(m, []byte("@")):] rawBytes = bytes.Replace(rawBytes, m, - []byte(fmt.Sprintf(`%s`, setting.AppSubUrl, m[1:], m)), -1) + []byte(fmt.Sprintf(`%s`, setting.AppSubURL, m[1:], m)), -1) } rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas) diff --git a/modules/markdown/markdown_test.go b/modules/markdown/markdown_test.go index 3fc260bf1f..55496aa6af 100644 --- a/modules/markdown/markdown_test.go +++ b/modules/markdown/markdown_test.go @@ -16,7 +16,7 @@ func TestMarkdown(t *testing.T) { urlPrefix = "/prefix" metas map[string]string = nil ) - setting.AppSubUrlDepth = 0 + setting.AppSubURLDepth = 0 Convey("To the internal issue tracker", func() { Convey("It should not render anything when there are no mentions", func() { @@ -237,7 +237,7 @@ func TestMarkdown(t *testing.T) { }) Convey("Rendering an issue URL", t, func() { - setting.AppUrl = "http://localhost:3000/" + setting.AppURL = "http://localhost:3000/" htmlFlags := 0 htmlFlags |= blackfriday.HTML_SKIP_STYLE htmlFlags |= blackfriday.HTML_OMIT_CONTENTS @@ -279,7 +279,7 @@ func TestMarkdown(t *testing.T) { }) Convey("Rendering a commit URL", t, func() { - setting.AppUrl = "http://localhost:3000/" + setting.AppURL = "http://localhost:3000/" htmlFlags := 0 htmlFlags |= blackfriday.HTML_SKIP_STYLE htmlFlags |= blackfriday.HTML_OMIT_CONTENTS diff --git a/modules/setting/setting.go b/modules/setting/setting.go index baaa3f50a8..12025a27bf 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -18,10 +18,10 @@ import ( "time" "github.com/Unknwon/com" - _ "github.com/go-macaron/cache/memcache" + _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache _ "github.com/go-macaron/cache/redis" "github.com/go-macaron/session" - _ "github.com/go-macaron/session/redis" + _ "github.com/go-macaron/session/redis" // redis plugin for store session "gopkg.in/ini.v1" "strk.kbt.io/projects/go/libravatar" @@ -30,44 +30,51 @@ import ( "code.gitea.io/gitea/modules/user" ) +// Scheme describes protocol types type Scheme string +// enumerates all the scheme types const ( - HTTP Scheme = "http" - HTTPS Scheme = "https" - FCGI Scheme = "fcgi" - UNIX_SOCKET Scheme = "unix" + HTTP Scheme = "http" + HTTPS Scheme = "https" + FCGI Scheme = "fcgi" + UnixSocket Scheme = "unix" ) +// LandingPage describes the default page type LandingPage string +// enumerates all the landing page types const ( - LANDING_PAGE_HOME LandingPage = "/" - LANDING_PAGE_EXPLORE LandingPage = "/explore" + LandingPageHome LandingPage = "/" + LandingPageExplore LandingPage = "/explore" ) +// settings var ( - // Build information should only be set by -ldflags. + // BuildTime information should only be set by -ldflags. BuildTime string BuildGitHash string - // App settings + // AppVer settings AppVer string AppName string - AppUrl string - AppSubUrl string - AppSubUrlDepth int // Number of slashes + AppURL string + AppSubURL string + AppSubURLDepth int // Number of slashes AppPath string AppDataPath string // Server settings Protocol Scheme Domain string - HTTPAddr, HTTPPort string + HTTPAddr string + HTTPPort string LocalURL string OfflineMode bool DisableRouterLog bool - CertFile, KeyFile string + CertFile string + KeyFile string StaticRootPath string EnableGzip bool LandingPageURL LandingPage @@ -242,8 +249,9 @@ var ( } // I18n settings - Langs, Names []string - dateLangs map[string]string + Langs []string + Names []string + dateLangs map[string]string // Highlight settings are loaded in modules/template/hightlight.go @@ -386,20 +394,20 @@ please consider changing to GITEA_CUSTOM`) sec := Cfg.Section("server") AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service") - AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/") - if AppUrl[len(AppUrl)-1] != '/' { - AppUrl += "/" + AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/") + if AppURL[len(AppURL)-1] != '/' { + AppURL += "/" } // Check if has app suburl. - url, err := url.Parse(AppUrl) + url, err := url.Parse(AppURL) if err != nil { - log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppUrl, err) + log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err) } // Suburl should start with '/' and end without '/', such as '/{subpath}'. // This value is empty if site does not have sub-url. - AppSubUrl = strings.TrimSuffix(url.Path, "/") - AppSubUrlDepth = strings.Count(AppSubUrl, "/") + AppSubURL = strings.TrimSuffix(url.Path, "/") + AppSubURLDepth = strings.Count(AppSubURL, "/") Protocol = HTTP if sec.Key("PROTOCOL").String() == "https" { @@ -409,7 +417,7 @@ please consider changing to GITEA_CUSTOM`) } else if sec.Key("PROTOCOL").String() == "fcgi" { Protocol = FCGI } else if sec.Key("PROTOCOL").String() == "unix" { - Protocol = UNIX_SOCKET + Protocol = UnixSocket UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666") UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32) if err != nil || UnixSocketPermissionParsed > 0777 { @@ -429,9 +437,9 @@ please consider changing to GITEA_CUSTOM`) switch sec.Key("LANDING_PAGE").MustString("home") { case "explore": - LandingPageURL = LANDING_PAGE_EXPLORE + LandingPageURL = LandingPageExplore default: - LandingPageURL = LANDING_PAGE_HOME + LandingPageURL = LandingPageHome } SSH.RootPath = path.Join(homeDir, ".ssh") @@ -596,6 +604,7 @@ please consider changing to GITEA_CUSTOM`) HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt")) } +// Service settings var Service struct { ActiveCodeLives int ResetPwdCodeLives int @@ -719,7 +728,7 @@ func newSessionService() { []string{"memory", "file", "redis", "mysql"}) SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ") SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits") - SessionConfig.CookiePath = AppSubUrl + SessionConfig.CookiePath = AppSubURL SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool() SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400) SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400) @@ -744,6 +753,7 @@ type Mailer struct { } var ( + // MailService the global mailer MailService *Mailer ) @@ -810,6 +820,7 @@ func newWebhookService() { Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10) } +// NewServices initializes the services func NewServices() { newService() newLogService() diff --git a/modules/template/template.go b/modules/template/template.go index baf1a7ab92..65d78c2f6e 100644 --- a/modules/template/template.go +++ b/modules/template/template.go @@ -33,16 +33,16 @@ func NewFuncMap() []template.FuncMap { return strings.Title(runtime.Version()) }, "UseHTTPS": func() bool { - return strings.HasPrefix(setting.AppUrl, "https") + return strings.HasPrefix(setting.AppURL, "https") }, "AppName": func() string { return setting.AppName }, "AppSubUrl": func() string { - return setting.AppSubUrl + return setting.AppSubURL }, "AppUrl": func() string { - return setting.AppUrl + return setting.AppURL }, "AppVer": func() string { return setting.AppVer diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 655c6a30ba..00aca2d09f 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -164,7 +164,7 @@ func Dashboard(ctx *context.Context) { } else { ctx.Flash.Success(success) } - ctx.Redirect(setting.AppSubUrl + "/admin") + ctx.Redirect(setting.AppSubURL + "/admin") return } @@ -185,7 +185,7 @@ func SendTestMail(ctx *context.Context) { ctx.Flash.Info(ctx.Tr("admin.config.test_mail_sent", email)) } - ctx.Redirect(setting.AppSubUrl + "/admin/config") + ctx.Redirect(setting.AppSubURL + "/admin/config") } // Config show admin config page @@ -194,7 +194,7 @@ func Config(ctx *context.Context) { ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminConfig"] = true - ctx.Data["AppUrl"] = setting.AppUrl + ctx.Data["AppUrl"] = setting.AppURL ctx.Data["Domain"] = setting.Domain ctx.Data["OfflineMode"] = setting.OfflineMode ctx.Data["DisableRouterLog"] = setting.DisableRouterLog diff --git a/routers/admin/auths.go b/routers/admin/auths.go index 4a86e60b54..9e310b8c16 100644 --- a/routers/admin/auths.go +++ b/routers/admin/auths.go @@ -167,7 +167,7 @@ func NewAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { log.Trace("Authentication created by admin(%s): %s", ctx.User.Name, form.Name) ctx.Flash.Success(ctx.Tr("admin.auths.new_success", form.Name)) - ctx.Redirect(setting.AppSubUrl + "/admin/auths") + ctx.Redirect(setting.AppSubURL + "/admin/auths") } // EditAuthSource render editing auth source page @@ -236,7 +236,7 @@ func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) { log.Trace("Authentication changed by admin(%s): %s", ctx.User.Name, source.ID) ctx.Flash.Success(ctx.Tr("admin.auths.update_success")) - ctx.Redirect(setting.AppSubUrl + "/admin/auths/" + com.ToStr(form.ID)) + ctx.Redirect(setting.AppSubURL + "/admin/auths/" + com.ToStr(form.ID)) } // DeleteAuthSource response for deleting an auth source @@ -254,7 +254,7 @@ func DeleteAuthSource(ctx *context.Context) { ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err)) } ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/admin/auths/" + ctx.Params(":authid"), + "redirect": setting.AppSubURL + "/admin/auths/" + ctx.Params(":authid"), }) return } @@ -262,6 +262,6 @@ func DeleteAuthSource(ctx *context.Context) { ctx.Flash.Success(ctx.Tr("admin.auths.deletion_success")) ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/admin/auths", + "redirect": setting.AppSubURL + "/admin/auths", }) } diff --git a/routers/admin/notice.go b/routers/admin/notice.go index 4e4f0f1e94..2cf71ee070 100644 --- a/routers/admin/notice.go +++ b/routers/admin/notice.go @@ -72,5 +72,5 @@ func EmptyNotices(ctx *context.Context) { log.Trace("System notices deleted by admin (%s): [start: %d]", ctx.User.Name, 0) ctx.Flash.Success(ctx.Tr("admin.notices.delete_success")) - ctx.Redirect(setting.AppSubUrl + "/admin/notices") + ctx.Redirect(setting.AppSubURL + "/admin/notices") } diff --git a/routers/admin/repos.go b/routers/admin/repos.go index 287c294408..86a9ea9405 100644 --- a/routers/admin/repos.go +++ b/routers/admin/repos.go @@ -49,6 +49,6 @@ func DeleteRepo(ctx *context.Context) { ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success")) ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/admin/repos?page=" + ctx.Query("page"), + "redirect": setting.AppSubURL + "/admin/repos?page=" + ctx.Query("page"), }) } diff --git a/routers/admin/users.go b/routers/admin/users.go index dd4d2f5786..04e331d229 100644 --- a/routers/admin/users.go +++ b/routers/admin/users.go @@ -123,7 +123,7 @@ func NewUserPost(ctx *context.Context, form auth.AdminCrateUserForm) { } ctx.Flash.Success(ctx.Tr("admin.users.new_success", u.Name)) - ctx.Redirect(setting.AppSubUrl + "/admin/users/" + com.ToStr(u.ID)) + ctx.Redirect(setting.AppSubURL + "/admin/users/" + com.ToStr(u.ID)) } func prepareUserInfo(ctx *context.Context) *models.User { @@ -225,7 +225,7 @@ func EditUserPost(ctx *context.Context, form auth.AdminEditUserForm) { log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name) ctx.Flash.Success(ctx.Tr("admin.users.update_profile_success")) - ctx.Redirect(setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid")) + ctx.Redirect(setting.AppSubURL + "/admin/users/" + ctx.Params(":userid")) } // DeleteUser response for deleting a user @@ -241,12 +241,12 @@ func DeleteUser(ctx *context.Context) { case models.IsErrUserOwnRepos(err): ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo")) ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid"), + "redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"), }) case models.IsErrUserHasOrgs(err): ctx.Flash.Error(ctx.Tr("admin.users.still_has_org")) ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid"), + "redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"), }) default: ctx.Handle(500, "DeleteUser", err) @@ -257,6 +257,6 @@ func DeleteUser(ctx *context.Context) { ctx.Flash.Success(ctx.Tr("admin.users.deletion_success")) ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/admin/users", + "redirect": setting.AppSubURL + "/admin/users", }) } diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index 51f080a385..546cc40e61 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -16,7 +16,7 @@ import ( ) func composeDeployKeysAPILink(repoPath string) string { - return setting.AppUrl + "api/v1/repos/" + repoPath + "/keys/" + return setting.AppURL + "api/v1/repos/" + repoPath + "/keys/" } // ListDeployKeys list all the deploy keys of a repository diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index c743b5deab..39a045df32 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -34,7 +34,7 @@ func GetUserByParams(ctx *context.APIContext) *models.User { } func composePublicKeysAPILink() string { - return setting.AppUrl + "api/v1/user/keys/" + return setting.AppURL + "api/v1/user/keys/" } func listPublicKeys(ctx *context.APIContext, uid int64) { diff --git a/routers/dev/template.go b/routers/dev/template.go index 15ac1c8635..fae85a3968 100644 --- a/routers/dev/template.go +++ b/routers/dev/template.go @@ -16,7 +16,7 @@ func TemplatePreview(ctx *context.Context) { ctx.Data["User"] = models.User{Name: "Unknown"} ctx.Data["AppName"] = setting.AppName ctx.Data["AppVer"] = setting.AppVer - ctx.Data["AppUrl"] = setting.AppUrl + ctx.Data["AppUrl"] = setting.AppURL ctx.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374" ctx.Data["ActiveCodeLives"] = setting.Service.ActiveCodeLives / 60 ctx.Data["ResetPwdCodeLives"] = setting.Service.ResetPwdCodeLives / 60 diff --git a/routers/home.go b/routers/home.go index ee425a830e..a2faf65bcc 100644 --- a/routers/home.go +++ b/routers/home.go @@ -42,7 +42,7 @@ func Home(ctx *context.Context) { // Check auto-login. uname := ctx.GetCookie(setting.CookieUserName) if len(uname) != 0 { - ctx.Redirect(setting.AppSubUrl + "/user/login") + ctx.Redirect(setting.AppSubURL + "/user/login") return } diff --git a/routers/install.go b/routers/install.go index ab9c835507..ed8fae15f1 100644 --- a/routers/install.go +++ b/routers/install.go @@ -89,7 +89,7 @@ func Install(ctx *context.Context) { form.Domain = setting.Domain form.SSHPort = setting.SSH.Port form.HTTPPort = setting.HTTPPort - form.AppUrl = setting.AppUrl + form.AppUrl = setting.AppURL form.LogRootPath = setting.LogRootPath // E-mail service settings diff --git a/routers/org/members.go b/routers/org/members.go index e7f1960665..70e4161c00 100644 --- a/routers/org/members.go +++ b/routers/org/members.go @@ -91,7 +91,7 @@ func MembersAction(ctx *context.Context) { if ctx.Params(":action") != "leave" { ctx.Redirect(ctx.Org.OrgLink + "/members") } else { - ctx.Redirect(setting.AppSubUrl + "/") + ctx.Redirect(setting.AppSubURL + "/") } } diff --git a/routers/org/org.go b/routers/org/org.go index 1475c6e542..579a2917b4 100644 --- a/routers/org/org.go +++ b/routers/org/org.go @@ -55,5 +55,5 @@ func CreatePost(ctx *context.Context, form auth.CreateOrgForm) { } log.Trace("Organization created: %s", org.Name) - ctx.Redirect(setting.AppSubUrl + "/org/" + form.OrgName + "/dashboard") + ctx.Redirect(setting.AppSubURL + "/org/" + form.OrgName + "/dashboard") } diff --git a/routers/org/setting.go b/routers/org/setting.go index 4a7a891d47..4faed77d0d 100644 --- a/routers/org/setting.go +++ b/routers/org/setting.go @@ -64,7 +64,7 @@ func SettingsPost(ctx *context.Context, form auth.UpdateOrgSettingForm) { return } // reset ctx.org.OrgLink with new name - ctx.Org.OrgLink = setting.AppSubUrl + "/org/" + form.Name + ctx.Org.OrgLink = setting.AppSubURL + "/org/" + form.Name log.Trace("Organization name changed: %s -> %s", org.Name, form.Name) } // In case it's just a case change. @@ -134,7 +134,7 @@ func SettingsDelete(ctx *context.Context) { } } else { log.Trace("Organization deleted: %s", org.Name) - ctx.Redirect(setting.AppSubUrl + "/") + ctx.Redirect(setting.AppSubURL + "/") } return } diff --git a/routers/repo/commit.go b/routers/repo/commit.go index 7f41158633..ff90cdf465 100644 --- a/routers/repo/commit.go +++ b/routers/repo/commit.go @@ -194,11 +194,11 @@ func Diff(ctx *context.Context) { ctx.Data["Diff"] = diff ctx.Data["Parents"] = parents ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 - ctx.Data["SourcePath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "src", commitID) + ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", commitID) if commit.ParentCount() > 0 { - ctx.Data["BeforeSourcePath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "src", parents[0]) + ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", parents[0]) } - ctx.Data["RawPath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "raw", commitID) + ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", commitID) ctx.HTML(200, tplDiff) } @@ -257,8 +257,8 @@ func CompareDiff(ctx *context.Context) { ctx.Data["Commit"] = commit ctx.Data["Diff"] = diff ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 - ctx.Data["SourcePath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "src", afterCommitID) - ctx.Data["BeforeSourcePath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "src", beforeCommitID) - ctx.Data["RawPath"] = setting.AppSubUrl + "/" + path.Join(userName, repoName, "raw", afterCommitID) + ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", afterCommitID) + ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "src", beforeCommitID) + ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(userName, repoName, "raw", afterCommitID) ctx.HTML(200, tplDiff) } diff --git a/routers/repo/editor.go b/routers/repo/editor.go index 92a41f0147..f037b39b21 100644 --- a/routers/repo/editor.go +++ b/routers/repo/editor.go @@ -96,7 +96,7 @@ func editFile(ctx *context.Context, isNewFile bool) { ctx.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",") ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",") ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",") - ctx.Data["EditorconfigURLPrefix"] = fmt.Sprintf("%s/api/v1/repos/%s/editorconfig/", setting.AppSubUrl, ctx.Repo.Repository.FullName()) + ctx.Data["EditorconfigURLPrefix"] = fmt.Sprintf("%s/api/v1/repos/%s/editorconfig/", setting.AppSubURL, ctx.Repo.Repository.FullName()) ctx.HTML(200, tplEditFile) } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 62bfd3a569..e3c088d940 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -123,8 +123,8 @@ func Issues(ctx *context.Context) { // Must sign in to see issues about you. if viewType != "all" && !ctx.IsSigned { - ctx.SetCookie("redirect_to", "/"+url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl) - ctx.Redirect(setting.AppSubUrl + "/user/login") + ctx.SetCookie("redirect_to", "/"+url.QueryEscape(setting.AppSubURL+ctx.Req.RequestURI), 0, setting.AppSubURL) + ctx.Redirect(setting.AppSubURL + "/user/login") return } @@ -651,7 +651,7 @@ func ViewIssue(ctx *context.Context) { ctx.Data["NumParticipants"] = len(participants) ctx.Data["Issue"] = issue ctx.Data["IsIssueOwner"] = ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID)) - ctx.Data["SignInLink"] = setting.AppSubUrl + "/user/login?redirect_to=" + ctx.Data["Link"].(string) + ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string) ctx.HTML(200, tplIssueView) } diff --git a/routers/repo/pull.go b/routers/repo/pull.go index c8969b98f2..bc958bdda1 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -107,7 +107,7 @@ func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { repo, has := models.HasForkedRepo(ctxUser.ID, forkRepo.ID) if has { - ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + repo.Name) + ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name) return } @@ -136,7 +136,7 @@ func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { } log.Trace("Repository forked[%d]: %s/%s", forkRepo.ID, ctxUser.Name, repo.Name) - ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + repo.Name) + ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name) } func checkPullInfo(ctx *context.Context) *models.Issue { @@ -376,9 +376,9 @@ func ViewPullFiles(ctx *context.Context) { ctx.Data["Username"] = pull.HeadUserName ctx.Data["Reponame"] = pull.HeadRepo.Name ctx.Data["IsImageFile"] = commit.IsImageFile - ctx.Data["SourcePath"] = setting.AppSubUrl + "/" + path.Join(headTarget, "src", endCommitID) - ctx.Data["BeforeSourcePath"] = setting.AppSubUrl + "/" + path.Join(headTarget, "src", startCommitID) - ctx.Data["RawPath"] = setting.AppSubUrl + "/" + path.Join(headTarget, "raw", endCommitID) + ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID) + ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID) + ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID) ctx.Data["RequireHighlightJS"] = true ctx.HTML(200, tplPullFiles) @@ -581,9 +581,9 @@ func PrepareCompareDiff( ctx.Data["IsImageFile"] = headCommit.IsImageFile headTarget := path.Join(headUser.Name, repo.Name) - ctx.Data["SourcePath"] = setting.AppSubUrl + "/" + path.Join(headTarget, "src", headCommitID) - ctx.Data["BeforeSourcePath"] = setting.AppSubUrl + "/" + path.Join(headTarget, "src", prInfo.MergeBase) - ctx.Data["RawPath"] = setting.AppSubUrl + "/" + path.Join(headTarget, "raw", headCommitID) + ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", headCommitID) + ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", prInfo.MergeBase) + ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", headCommitID) return false } diff --git a/routers/repo/repo.go b/routers/repo/repo.go index c25f5c67cc..df1c3feb4c 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -134,7 +134,7 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) { }) if err == nil { log.Trace("Repository created [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) - ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + repo.Name) + ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name) return } @@ -208,7 +208,7 @@ func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) { }) if err == nil { log.Trace("Repository migrated [%d]: %s/%s", repo.ID, ctxUser.Name, form.RepoName) - ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + form.RepoName) + ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + form.RepoName) return } diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 2b8c5a2315..aaba5427fc 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -194,7 +194,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) { } log.Trace("Repository converted from mirror to regular: %s/%s", ctx.Repo.Owner.Name, repo.Name) ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed")) - ctx.Redirect(setting.AppSubUrl + "/" + ctx.Repo.Owner.Name + "/" + repo.Name) + ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name) case "transfer": if !ctx.Repo.IsOwner() { @@ -233,7 +233,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) { } log.Trace("Repository transfered: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner) ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed")) - ctx.Redirect(setting.AppSubUrl + "/" + newOwner + "/" + repo.Name) + ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name) case "delete": if !ctx.Repo.IsOwner() { @@ -314,7 +314,7 @@ func Collaboration(ctx *context.Context) { func CollaborationPost(ctx *context.Context) { name := strings.ToLower(ctx.Query("collaborator")) if len(name) == 0 || ctx.Repo.Owner.LowerName == name { - ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) + ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path) return } @@ -322,7 +322,7 @@ func CollaborationPost(ctx *context.Context) { if err != nil { if models.IsErrUserNotExist(err) { ctx.Flash.Error(ctx.Tr("form.user_not_exist")) - ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) + ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path) } else { ctx.Handle(500, "GetUserByName", err) } @@ -332,7 +332,7 @@ func CollaborationPost(ctx *context.Context) { // Organization is not allowed to be added as a collaborator. if u.IsOrganization() { ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator")) - ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) + ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path) return } @@ -353,7 +353,7 @@ func CollaborationPost(ctx *context.Context) { } ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success")) - ctx.Redirect(setting.AppSubUrl + ctx.Req.URL.Path) + ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path) } // ChangeCollaborationAccessMode response for changing access of a collaboration diff --git a/routers/user/auth.go b/routers/user/auth.go index ebee24365c..eecb5e051f 100644 --- a/routers/user/auth.go +++ b/routers/user/auth.go @@ -44,8 +44,8 @@ func AutoSignIn(ctx *context.Context) (bool, error) { defer func() { if !isSucceed { log.Trace("auto-login cookie cleared: %s", uname) - ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl) - ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl) + ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL) + ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL) } }() @@ -65,7 +65,7 @@ func AutoSignIn(ctx *context.Context) (bool, error) { isSucceed = true ctx.Session.Set("uid", u.ID) ctx.Session.Set("uname", u.Name) - ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubUrl) + ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL) return true, nil } @@ -82,17 +82,17 @@ func SignIn(ctx *context.Context) { redirectTo := ctx.Query("redirect_to") if len(redirectTo) > 0 { - ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubUrl) + ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL) } else { redirectTo, _ = url.QueryUnescape(ctx.GetCookie("redirect_to")) } if isSucceed { if len(redirectTo) > 0 { - ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl) + ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL) ctx.Redirect(redirectTo) } else { - ctx.Redirect(setting.AppSubUrl + "/") + ctx.Redirect(setting.AppSubURL + "/") } return } @@ -121,16 +121,16 @@ func SignInPost(ctx *context.Context, form auth.SignInForm) { if form.Remember { days := 86400 * setting.LogInRememberDays - ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubUrl) + ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL) ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd), - setting.CookieRememberName, u.Name, days, setting.AppSubUrl) + setting.CookieRememberName, u.Name, days, setting.AppSubURL) } ctx.Session.Set("uid", u.ID) ctx.Session.Set("uname", u.Name) // Clear whatever CSRF has right now, force to generate a new one - ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubUrl) + ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL) // Register last login u.SetLastLogin() @@ -140,12 +140,12 @@ func SignInPost(ctx *context.Context, form auth.SignInForm) { } if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 { - ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl) + ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL) ctx.Redirect(redirectTo) return } - ctx.Redirect(setting.AppSubUrl + "/") + ctx.Redirect(setting.AppSubURL + "/") } // SignOut sign out from login status @@ -155,10 +155,10 @@ func SignOut(ctx *context.Context) { ctx.Session.Delete("socialId") ctx.Session.Delete("socialName") ctx.Session.Delete("socialEmail") - ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl) - ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl) - ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubUrl) - ctx.Redirect(setting.AppSubUrl + "/") + ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL) + ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL) + ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL) + ctx.Redirect(setting.AppSubURL + "/") } // SignUp render the register page @@ -255,7 +255,7 @@ func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterFo return } - ctx.Redirect(setting.AppSubUrl + "/user/login") + ctx.Redirect(setting.AppSubURL + "/user/login") } // Activate render activate user page @@ -303,7 +303,7 @@ func Activate(ctx *context.Context) { ctx.Session.Set("uid", user.ID) ctx.Session.Set("uname", user.Name) - ctx.Redirect(setting.AppSubUrl + "/") + ctx.Redirect(setting.AppSubURL + "/") return } @@ -326,7 +326,7 @@ func ActivateEmail(ctx *context.Context) { ctx.Flash.Success(ctx.Tr("settings.add_email_success")) } - ctx.Redirect(setting.AppSubUrl + "/user/settings/email") + ctx.Redirect(setting.AppSubURL + "/user/settings/email") return } @@ -437,7 +437,7 @@ func ResetPasswdPost(ctx *context.Context) { } log.Trace("User password reset: %s", u.Name) - ctx.Redirect(setting.AppSubUrl + "/user/login") + ctx.Redirect(setting.AppSubURL + "/user/login") return } diff --git a/routers/user/home.go b/routers/user/home.go index e6b789e2f3..5745791e48 100644 --- a/routers/user/home.go +++ b/routers/user/home.go @@ -390,5 +390,5 @@ func Email2User(ctx *context.Context) { } return } - ctx.Redirect(setting.AppSubUrl + "/user/" + u.Name) + ctx.Redirect(setting.AppSubURL + "/user/" + u.Name) } diff --git a/routers/user/setting.go b/routers/user/setting.go index ae526162f3..018881e8b2 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -52,16 +52,16 @@ func handleUsernameChange(ctx *context.Context, newName string) { switch { case models.IsErrUserAlreadyExist(err): ctx.Flash.Error(ctx.Tr("newName_been_taken")) - ctx.Redirect(setting.AppSubUrl + "/user/settings") + ctx.Redirect(setting.AppSubURL + "/user/settings") case models.IsErrEmailAlreadyUsed(err): ctx.Flash.Error(ctx.Tr("form.email_been_used")) - ctx.Redirect(setting.AppSubUrl + "/user/settings") + ctx.Redirect(setting.AppSubURL + "/user/settings") case models.IsErrNameReserved(err): ctx.Flash.Error(ctx.Tr("user.newName_reserved")) - ctx.Redirect(setting.AppSubUrl + "/user/settings") + ctx.Redirect(setting.AppSubURL + "/user/settings") case models.IsErrNamePatternNotAllowed(err): ctx.Flash.Error(ctx.Tr("user.newName_pattern_not_allowed")) - ctx.Redirect(setting.AppSubUrl + "/user/settings") + ctx.Redirect(setting.AppSubURL + "/user/settings") default: ctx.Handle(500, "ChangeUserName", err) } @@ -101,7 +101,7 @@ func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) { log.Trace("User settings updated: %s", ctx.User.Name) ctx.Flash.Success(ctx.Tr("settings.update_profile_success")) - ctx.Redirect(setting.AppSubUrl + "/user/settings") + ctx.Redirect(setting.AppSubURL + "/user/settings") } // UpdateAvatarSetting update user's avatar @@ -162,7 +162,7 @@ func SettingsAvatarPost(ctx *context.Context, form auth.AvatarForm) { ctx.Flash.Success(ctx.Tr("settings.update_avatar_success")) } - ctx.Redirect(setting.AppSubUrl + "/user/settings/avatar") + ctx.Redirect(setting.AppSubURL + "/user/settings/avatar") } // SettingsDeleteAvatar render delete avatar page @@ -171,7 +171,7 @@ func SettingsDeleteAvatar(ctx *context.Context) { ctx.Flash.Error(err.Error()) } - ctx.Redirect(setting.AppSubUrl + "/user/settings/avatar") + ctx.Redirect(setting.AppSubURL + "/user/settings/avatar") } // SettingsPassword render change user's password page @@ -207,7 +207,7 @@ func SettingsPasswordPost(ctx *context.Context, form auth.ChangePasswordForm) { ctx.Flash.Success(ctx.Tr("settings.change_password_success")) } - ctx.Redirect(setting.AppSubUrl + "/user/settings/password") + ctx.Redirect(setting.AppSubURL + "/user/settings/password") } // SettingsEmails render user's emails page @@ -238,7 +238,7 @@ func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) { } log.Trace("Email made primary: %s", ctx.User.Name) - ctx.Redirect(setting.AppSubUrl + "/user/settings/email") + ctx.Redirect(setting.AppSubURL + "/user/settings/email") return } @@ -282,7 +282,7 @@ func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) { } log.Trace("Email address added: %s", email.Email) - ctx.Redirect(setting.AppSubUrl + "/user/settings/email") + ctx.Redirect(setting.AppSubURL + "/user/settings/email") } // DeleteEmail reponse for delete user's email @@ -295,7 +295,7 @@ func DeleteEmail(ctx *context.Context) { ctx.Flash.Success(ctx.Tr("settings.email_deletion_success")) ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/user/settings/email", + "redirect": setting.AppSubURL + "/user/settings/email", }) } @@ -337,7 +337,7 @@ func SettingsSSHKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) { ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key")) } else { ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error())) - ctx.Redirect(setting.AppSubUrl + "/user/settings/ssh") + ctx.Redirect(setting.AppSubURL + "/user/settings/ssh") return } } @@ -358,7 +358,7 @@ func SettingsSSHKeysPost(ctx *context.Context, form auth.AddSSHKeyForm) { } ctx.Flash.Success(ctx.Tr("settings.add_key_success", form.Title)) - ctx.Redirect(setting.AppSubUrl + "/user/settings/ssh") + ctx.Redirect(setting.AppSubURL + "/user/settings/ssh") } // DeleteSSHKey response for delete user's SSH key @@ -370,7 +370,7 @@ func DeleteSSHKey(ctx *context.Context) { } ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/user/settings/ssh", + "redirect": setting.AppSubURL + "/user/settings/ssh", }) } @@ -417,7 +417,7 @@ func SettingsApplicationsPost(ctx *context.Context, form auth.NewAccessTokenForm ctx.Flash.Success(ctx.Tr("settings.generate_token_succees")) ctx.Flash.Info(t.Sha1) - ctx.Redirect(setting.AppSubUrl + "/user/settings/applications") + ctx.Redirect(setting.AppSubURL + "/user/settings/applications") } // SettingsDeleteApplication response for delete user access token @@ -429,7 +429,7 @@ func SettingsDeleteApplication(ctx *context.Context) { } ctx.JSON(200, map[string]interface{}{ - "redirect": setting.AppSubUrl + "/user/settings/applications", + "redirect": setting.AppSubURL + "/user/settings/applications", }) } @@ -452,16 +452,16 @@ func SettingsDelete(ctx *context.Context) { switch { case models.IsErrUserOwnRepos(err): ctx.Flash.Error(ctx.Tr("form.still_own_repo")) - ctx.Redirect(setting.AppSubUrl + "/user/settings/delete") + ctx.Redirect(setting.AppSubURL + "/user/settings/delete") case models.IsErrUserHasOrgs(err): ctx.Flash.Error(ctx.Tr("form.still_has_org")) - ctx.Redirect(setting.AppSubUrl + "/user/settings/delete") + ctx.Redirect(setting.AppSubURL + "/user/settings/delete") default: ctx.Handle(500, "DeleteUser", err) } } else { log.Trace("Account deleted: %s", ctx.User.Name) - ctx.Redirect(setting.AppSubUrl + "/") + ctx.Redirect(setting.AppSubURL + "/") } return } From 9aaf2a6d9a33416ed55798a7eb60f78bd9195352 Mon Sep 17 00:00:00 2001 From: Mura Li Date: Sun, 27 Nov 2016 10:10:08 +0800 Subject: [PATCH 057/135] modules/process: add ExecDirEnv (next to ExecDir) Add a sibling to ExecDir which is capable of specifying environment variables, so that we can invoke `git` with GIT_INDEX_FILE, GIT_DIR, etc.. For #258 --- modules/process/manager.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/modules/process/manager.go b/modules/process/manager.go index 2748c14bb4..0d5416ec13 100644 --- a/modules/process/manager.go +++ b/modules/process/manager.go @@ -52,11 +52,11 @@ func Add(desc string, cmd *exec.Cmd) int64 { return pid } -// ExecDir runs a command in given path and waits for its completion +// ExecDirEnv runs a command in given path and environment variables, and waits for its completion // up to the given timeout (or DefaultTimeout if -1 is given). // Returns its complete stdout and stderr // outputs and an error, if any (including timeout) -func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) (string, string, error) { +func ExecDirEnv(timeout time.Duration, dir, desc string, env []string, cmdName string, args ...string) (string, string, error) { if timeout == -1 { timeout = DefaultTimeout } @@ -66,6 +66,7 @@ func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) ( cmd := exec.Command(cmdName, args...) cmd.Dir = dir + cmd.Env = env cmd.Stdout = bufOut cmd.Stderr = bufErr if err := cmd.Start(); err != nil { @@ -93,6 +94,11 @@ func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) ( return bufOut.String(), bufErr.String(), err } +// ExecDir works exactly like ExecDirEnv except no environment variable is provided. +func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) (string, string, error) { + return ExecDirEnv(timeout, dir, desc, nil, cmdName, args...) +} + // ExecTimeout runs a command and waits for its completion // up to the given timeout (or DefaultTimeout if -1 is given). // Returns its complete stdout and stderr From a4ece1f22391a3602631ada5cb89797e134c4e13 Mon Sep 17 00:00:00 2001 From: Bwko Date: Sun, 27 Nov 2016 12:59:12 +0100 Subject: [PATCH 058/135] Fixes typos --- conf/locale/locale_en-US.ini | 2 +- conf/locale/locale_sv-SE.ini | 2 +- models/org.go | 2 +- models/user.go | 2 +- models/user_mail.go | 12 ++++++------ routers/repo/setting.go | 2 +- routers/repo/webhook.go | 2 +- routers/user/home.go | 2 +- routers/user/setting.go | 2 +- 9 files changed, 14 insertions(+), 14 deletions(-) diff --git a/conf/locale/locale_en-US.ini b/conf/locale/locale_en-US.ini index b6e47594d1..d7b407cd27 100644 --- a/conf/locale/locale_en-US.ini +++ b/conf/locale/locale_en-US.ini @@ -1173,7 +1173,7 @@ close_pull_request = `closed pull request %s#%[2]s` reopen_pull_request = `reopened pull request %s#%[2]s` comment_issue = `commented on issue %s#%[2]s` merge_pull_request = `merged pull request %s#%[2]s` -transfer_repo = transfered repository %s to %s +transfer_repo = transferred repository %s to %s push_tag = pushed tag %[2]s to %[3]s compare_commits = View comparison for these %d commits diff --git a/conf/locale/locale_sv-SE.ini b/conf/locale/locale_sv-SE.ini index c37deb34db..67ed618661 100644 --- a/conf/locale/locale_sv-SE.ini +++ b/conf/locale/locale_sv-SE.ini @@ -1167,7 +1167,7 @@ close_pull_request=`closed pull request %s#%[2]s` reopen_pull_request=`reopened pull request %s#%[2]s` comment_issue=`commented on issue %s#%[2]s` merge_pull_request=`merged pull request %s#%[2]s` -transfer_repo=transfered repository %s to %s +transfer_repo=transferred repository %s to %s push_tag=pushed tag %[2]s to %[3]s compare_commits=View comparison for these %d commits diff --git a/models/org.go b/models/org.go index 1d2ff1300f..3b04ed578c 100644 --- a/models/org.go +++ b/models/org.go @@ -500,7 +500,7 @@ func (org *User) getUserTeams(e Engine, userID int64, cols ...string) ([]*Team, Find(&teams) } -// GetUserTeamIDs returns of all team IDs of the organization that user is memeber of. +// GetUserTeamIDs returns of all team IDs of the organization that user is member of. func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) { teams, err := org.getUserTeams(x, userID, "team.id") if err != nil { diff --git a/models/user.go b/models/user.go index 1e15b2a965..34bf685a7d 100644 --- a/models/user.go +++ b/models/user.go @@ -80,7 +80,7 @@ type User struct { // Remember visibility choice for convenience, true for private LastRepoVisibility bool - // Maximum repository creation limit, -1 means use gloabl default + // Maximum repository creation limit, -1 means use global default MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"` // Permissions diff --git a/models/user_mail.go b/models/user_mail.go index 3fc4f4ae89..69f87c2b37 100644 --- a/models/user_mail.go +++ b/models/user_mail.go @@ -81,12 +81,12 @@ func addEmailAddress(e Engine, email *EmailAddress) error { return err } -// AddEmailAddress adds an email adress to given user. +// AddEmailAddress adds an email address to given user. func AddEmailAddress(email *EmailAddress) error { return addEmailAddress(x, email) } -// AddEmailAddresses adds an email adress to given user. +// AddEmailAddresses adds an email address to given user. func AddEmailAddresses(emails []*EmailAddress) error { if len(emails) == 0 { return nil @@ -110,7 +110,7 @@ func AddEmailAddresses(emails []*EmailAddress) error { return nil } -// Activate activates the email adress to given user. +// Activate activates the email address to given user. func (email *EmailAddress) Activate() error { user, err := GetUserByID(email.UID) if err != nil { @@ -137,7 +137,7 @@ func (email *EmailAddress) Activate() error { return sess.Commit() } -// DeleteEmailAddress deletes an email adress of given user. +// DeleteEmailAddress deletes an email address of given user. func DeleteEmailAddress(email *EmailAddress) (err error) { if email.ID > 0 { _, err = x.Id(email.ID).Delete(new(EmailAddress)) @@ -149,7 +149,7 @@ func DeleteEmailAddress(email *EmailAddress) (err error) { return err } -// DeleteEmailAddresses deletes multiple email adresses +// DeleteEmailAddresses deletes multiple email addresses func DeleteEmailAddresses(emails []*EmailAddress) (err error) { for i := range emails { if err = DeleteEmailAddress(emails[i]); err != nil { @@ -160,7 +160,7 @@ func DeleteEmailAddresses(emails []*EmailAddress) (err error) { return nil } -// MakeEmailPrimary sets primary email adress of given user. +// MakeEmailPrimary sets primary email address of given user. func MakeEmailPrimary(email *EmailAddress) error { has, err := x.Get(email) if err != nil { diff --git a/routers/repo/setting.go b/routers/repo/setting.go index aaba5427fc..e29f0fcb1f 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -231,7 +231,7 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) { } return } - log.Trace("Repository transfered: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner) + log.Trace("Repository transferred: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner) ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed")) ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name) diff --git a/routers/repo/webhook.go b/routers/repo/webhook.go index 33ad834c95..5a4770cdf3 100644 --- a/routers/repo/webhook.go +++ b/routers/repo/webhook.go @@ -310,7 +310,7 @@ func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) { ctx.Redirect(fmt.Sprintf("%s/settings/hooks/%d", orCtx.Link, w.ID)) } -// SlackHooksEditPost reponse for editing slack hook +// SlackHooksEditPost response for editing slack hook func SlackHooksEditPost(ctx *context.Context, form auth.NewSlackHookForm) { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsHooks"] = true diff --git a/routers/user/home.go b/routers/user/home.go index 5745791e48..a08fae0727 100644 --- a/routers/user/home.go +++ b/routers/user/home.go @@ -313,7 +313,7 @@ func Issues(ctx *context.Context) { ctx.HTML(200, tplIssues) } -// ShowSSHKeys ouput all the ssh keys of user by uid +// ShowSSHKeys output all the ssh keys of user by uid func ShowSSHKeys(ctx *context.Context, uid int64) { keys, err := models.ListPublicKeys(uid) if err != nil { diff --git a/routers/user/setting.go b/routers/user/setting.go index 018881e8b2..1d405fba37 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -285,7 +285,7 @@ func SettingsEmailPost(ctx *context.Context, form auth.AddEmailForm) { ctx.Redirect(setting.AppSubURL + "/user/settings/email") } -// DeleteEmail reponse for delete user's email +// DeleteEmail response for delete user's email func DeleteEmail(ctx *context.Context) { if err := models.DeleteEmailAddress(&models.EmailAddress{ID: ctx.QueryInt64("id")}); err != nil { ctx.Handle(500, "DeleteEmail", err) From ec87a75c000d52bfc2a8dcfc7097c14fe872c376 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 27 Nov 2016 14:03:59 +0800 Subject: [PATCH 059/135] golint fixed for modules/auth --- cmd/web.go | 2 +- models/login_source.go | 2 +- modules/auth/admin.go | 8 +++++-- modules/auth/auth.go | 9 ++++++-- modules/auth/auth_form.go | 2 ++ modules/auth/ldap/ldap.go | 5 ++-- modules/auth/org.go | 6 +++++ modules/auth/pam/pam.go | 3 ++- modules/auth/pam/pam_stub.go | 3 ++- modules/auth/repo_form.go | 44 ++++++++++++++++++++++++++++++++++-- modules/auth/user_form.go | 21 ++++++++++++++++- routers/admin/users.go | 2 +- routers/api/v1/repo/repo.go | 4 ++-- routers/install.go | 10 ++++---- routers/repo/pull.go | 2 +- routers/repo/repo.go | 4 ++-- 16 files changed, 103 insertions(+), 24 deletions(-) diff --git a/cmd/web.go b/cmd/web.go index a962f9ca5a..2a69247f99 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -280,7 +280,7 @@ func runWeb(ctx *cli.Context) error { m.Group("/users", func() { m.Get("", admin.Users) - m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCrateUserForm{}), admin.NewUserPost) + m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost) m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost) m.Post("/:userid/delete", admin.DeleteUser) }) diff --git a/models/login_source.go b/models/login_source.go index b570f415c7..7a5e6083a7 100644 --- a/models/login_source.go +++ b/models/login_source.go @@ -502,7 +502,7 @@ func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPC // LoginViaPAM queries if login/password is valid against the PAM, // and create a local user if success when enabled. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) { - if err := pam.PAMAuth(cfg.ServiceName, login, password); err != nil { + if err := pam.Auth(cfg.ServiceName, login, password); err != nil { if strings.Contains(err.Error(), "Authentication failure") { return nil, ErrUserNotExist{0, login, 0} } diff --git a/modules/auth/admin.go b/modules/auth/admin.go index 58d1a027fc..033dfe9388 100644 --- a/modules/auth/admin.go +++ b/modules/auth/admin.go @@ -10,7 +10,8 @@ import ( "github.com/go-macaron/binding" ) -type AdminCrateUserForm struct { +// AdminCreateUserForm form for admin to create user +type AdminCreateUserForm struct { LoginType string `binding:"Required"` LoginName string UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"` @@ -19,10 +20,12 @@ type AdminCrateUserForm struct { SendNotify bool } -func (f *AdminCrateUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { +// Validate validates form fields +func (f *AdminCreateUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// AdminEditUserForm form for admin to create user type AdminEditUserForm struct { LoginType string `binding:"Required"` LoginName string @@ -39,6 +42,7 @@ type AdminEditUserForm struct { ProhibitLogin bool } +// Validate validates form fields func (f *AdminEditUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/auth/auth.go b/modules/auth/auth.go index 2444a3ad1f..ed94d0a698 100644 --- a/modules/auth/auth.go +++ b/modules/auth/auth.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// IsAPIPath if URL is an api path func IsAPIPath(url string) bool { return strings.HasPrefix(url, "/api/") } @@ -110,9 +111,8 @@ func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool) // FIXME: should I create a system notice? log.Error(4, "CreateUser: %v", err) return nil, false - } else { - return u, false } + return u, false } } return u, false @@ -148,6 +148,7 @@ func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool) return u, false } +// Form form binding interface type Form interface { binding.Validator } @@ -190,18 +191,22 @@ func getRuleBody(field reflect.StructField, prefix string) string { return "" } +// GetSize get size int form tag func GetSize(field reflect.StructField) string { return getRuleBody(field, "Size(") } +// GetMinSize get minimal size in form tag func GetMinSize(field reflect.StructField) string { return getRuleBody(field, "MinSize(") } +// GetMaxSize get max size in form tag func GetMaxSize(field reflect.StructField) string { return getRuleBody(field, "MaxSize(") } +// GetInclude get include in form tag func GetInclude(field reflect.StructField) string { return getRuleBody(field, "Include(") } diff --git a/modules/auth/auth_form.go b/modules/auth/auth_form.go index 9454d85693..78ba2b8997 100644 --- a/modules/auth/auth_form.go +++ b/modules/auth/auth_form.go @@ -9,6 +9,7 @@ import ( "gopkg.in/macaron.v1" ) +// AuthenticationForm form for authentication type AuthenticationForm struct { ID int64 Type int `binding:"Range(2,5)"` @@ -37,6 +38,7 @@ type AuthenticationForm struct { PAMServiceName string } +// Validate validates fields func (f *AuthenticationForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/auth/ldap/ldap.go b/modules/auth/ldap/ldap.go index e2cbf18d98..0cabcb20a0 100644 --- a/modules/auth/ldap/ldap.go +++ b/modules/auth/ldap/ldap.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/log" ) +// SecurityProtocol protocol type type SecurityProtocol int // Note: new type must be added at the end of list to maintain compatibility. @@ -25,7 +26,7 @@ const ( SecurityProtocolStartTLS ) -// Basic LDAP authentication service +// Source Basic LDAP authentication service type Source struct { Name string // canonical name (ie. corporate.ad) Host string // LDAP host @@ -148,7 +149,7 @@ func bindUser(l *ldap.Conn, userDN, passwd string) error { return err } -// searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter +// SearchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) { l, err := dial(ls) if err != nil { diff --git a/modules/auth/org.go b/modules/auth/org.go index 53ef6245d9..e15cba0f9f 100644 --- a/modules/auth/org.go +++ b/modules/auth/org.go @@ -16,14 +16,17 @@ import ( // \_______ /__| \___ (____ /___| /__/_____ \(____ /__| |__|\____/|___| / // \/ /_____/ \/ \/ \/ \/ \/ +// CreateOrgForm form for creating organization type CreateOrgForm struct { OrgName string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"` } +// Validate valideates the fields func (f *CreateOrgForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// UpdateOrgSettingForm form for updating organization settings type UpdateOrgSettingForm struct { Name string `binding:"Required;AlphaDashDot;MaxSize(35)" locale:"org.org_name_holder"` FullName string `binding:"MaxSize(100)"` @@ -33,6 +36,7 @@ type UpdateOrgSettingForm struct { MaxRepoCreation int } +// Validate valideates the fields func (f *UpdateOrgSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -44,12 +48,14 @@ func (f *UpdateOrgSettingForm) Validate(ctx *macaron.Context, errs binding.Error // |____| \___ >____ /__|_| / // \/ \/ \/ +// CreateTeamForm form for creating team type CreateTeamForm struct { TeamName string `binding:"Required;AlphaDashDot;MaxSize(30)"` Description string `binding:"MaxSize(255)"` Permission string } +// Validate valideates the fields func (f *CreateTeamForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/auth/pam/pam.go b/modules/auth/pam/pam.go index 7f326d42f5..6f0f7240ae 100644 --- a/modules/auth/pam/pam.go +++ b/modules/auth/pam/pam.go @@ -12,7 +12,8 @@ import ( "github.com/msteinert/pam" ) -func PAMAuth(serviceName, userName, passwd string) error { +// Auth pam auth service +func Auth(serviceName, userName, passwd string) error { t, err := pam.StartFunc(serviceName, userName, func(s pam.Style, msg string) (string, error) { switch s { case pam.PromptEchoOff: diff --git a/modules/auth/pam/pam_stub.go b/modules/auth/pam/pam_stub.go index 33ac751a34..ee2527dd89 100644 --- a/modules/auth/pam/pam_stub.go +++ b/modules/auth/pam/pam_stub.go @@ -10,6 +10,7 @@ import ( "errors" ) -func PAMAuth(serviceName, userName, passwd string) error { +// Auth not supported lack of pam tag +func Auth(serviceName, userName, passwd string) error { return errors.New("PAM not supported") } diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 94c99d8fb9..8a200c0206 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -21,8 +21,9 @@ import ( // |____|_ /_______ / |____| \_______ /_______ /|___| |____| \_______ /____|_ // ______| // \/ \/ \/ \/ \/ \/ \/ +// CreateRepoForm form for creating repository type CreateRepoForm struct { - Uid int64 `binding:"Required"` + UID int64 `binding:"Required"` RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` Private bool Description string `binding:"MaxSize(255)"` @@ -32,21 +33,24 @@ type CreateRepoForm struct { Readme string } +// Validate valideates the fields func (f *CreateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// MigrateRepoForm form for migrating repository type MigrateRepoForm struct { CloneAddr string `json:"clone_addr" binding:"Required"` AuthUsername string `json:"auth_username"` AuthPassword string `json:"auth_password"` - Uid int64 `json:"uid" binding:"Required"` + UID int64 `json:"uid" binding:"Required"` RepoName string `json:"repo_name" binding:"Required;AlphaDashDot;MaxSize(100)"` Mirror bool `json:"mirror"` Private bool `json:"private"` Description string `json:"description" binding:"MaxSize(255)"` } +// Validate valideates the fields func (f *MigrateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -79,6 +83,7 @@ func (f MigrateRepoForm) ParseRemoteAddr(user *models.User) (string, error) { return remoteAddr, nil } +// RepoSettingForm form for changing repository settings type RepoSettingForm struct { RepoName string `binding:"Required;AlphaDashDot;MaxSize(100)"` Description string `binding:"MaxSize(255)"` @@ -101,6 +106,7 @@ type RepoSettingForm struct { EnablePulls bool } +// Validate valideates the fields func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -112,6 +118,7 @@ func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) bi // \__/\ / \___ >___ /___| /___| /\____/|__|_ \ // \/ \/ \/ \/ \/ \/ +// WebhookForm form for changing web hook type WebhookForm struct { Events string Create bool @@ -120,18 +127,22 @@ type WebhookForm struct { Active bool } +// PushOnly if the hook will be triggered when push func (f WebhookForm) PushOnly() bool { return f.Events == "push_only" } +// SendEverything if the hook will be triggered any event func (f WebhookForm) SendEverything() bool { return f.Events == "send_everything" } +// ChooseEvents if the hook will be triggered choose events func (f WebhookForm) ChooseEvents() bool { return f.Events == "choose_events" } +// NewWebhookForm form for creating web hook type NewWebhookForm struct { PayloadURL string `binding:"Required;Url"` ContentType int `binding:"Required"` @@ -139,10 +150,12 @@ type NewWebhookForm struct { WebhookForm } +// Validate valideates the fields func (f *NewWebhookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// NewSlackHookForm form for creating slack hook type NewSlackHookForm struct { PayloadURL string `binding:"Required;Url"` Channel string `binding:"Required"` @@ -152,6 +165,7 @@ type NewSlackHookForm struct { WebhookForm } +// Validate valideates the fields func (f *NewSlackHookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -163,6 +177,7 @@ func (f *NewSlackHookForm) Validate(ctx *macaron.Context, errs binding.Errors) b // |___/____ >____ >____/ \___ > // \/ \/ \/ +// CreateIssueForm form for creating issue type CreateIssueForm struct { Title string `binding:"Required;MaxSize(255)"` LabelIDs string `form:"label_ids"` @@ -172,16 +187,19 @@ type CreateIssueForm struct { Files []string } +// Validate valideates the fields func (f *CreateIssueForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// CreateCommentForm form for creating comment type CreateCommentForm struct { Content string Status string `binding:"OmitEmpty;In(reopen,close)"` Files []string } +// Validate valideates the fields func (f *CreateCommentForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -193,12 +211,14 @@ func (f *CreateCommentForm) Validate(ctx *macaron.Context, errs binding.Errors) // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ > // \/ \/ \/ \/ \/ +// CreateMilestoneForm form for creating milestone type CreateMilestoneForm struct { Title string `binding:"Required;MaxSize(50)"` Content string Deadline string } +// Validate valideates the fields func (f *CreateMilestoneForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -210,20 +230,24 @@ func (f *CreateMilestoneForm) Validate(ctx *macaron.Context, errs binding.Errors // |_______ (____ /___ /\___ >____/ // \/ \/ \/ \/ +// CreateLabelForm form for creating label type CreateLabelForm struct { ID int64 Title string `binding:"Required;MaxSize(50)" locale:"repo.issues.label_name"` Color string `binding:"Required;Size(7)" locale:"repo.issues.label_color"` } +// Validate valideates the fields func (f *CreateLabelForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// InitializeLabelsForm form for initializing labels type InitializeLabelsForm struct { TemplateName string `binding:"Required"` } +// Validate valideates the fields func (f *InitializeLabelsForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -235,6 +259,7 @@ func (f *InitializeLabelsForm) Validate(ctx *macaron.Context, errs binding.Error // |____|_ /\___ >____/\___ >____ /____ >\___ > // \/ \/ \/ \/ \/ \/ +// NewReleaseForm form for creating release type NewReleaseForm struct { TagName string `binding:"Required"` Target string `form:"tag_target" binding:"Required"` @@ -244,10 +269,12 @@ type NewReleaseForm struct { Prerelease bool } +// Validate valideates the fields func (f *NewReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// EditReleaseForm form for changing release type EditReleaseForm struct { Title string `form:"title" binding:"Required"` Content string `form:"content"` @@ -255,6 +282,7 @@ type EditReleaseForm struct { Prerelease bool `form:"prerelease"` } +// Validate valideates the fields func (f *EditReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -266,6 +294,7 @@ func (f *EditReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) bi // \__/\ / |__|__|_ \__| // \/ \/ +// NewWikiForm form for creating wiki type NewWikiForm struct { OldTitle string Title string `binding:"Required"` @@ -273,6 +302,7 @@ type NewWikiForm struct { Message string } +// Validate valideates the fields // FIXME: use code generation to generate this method. func (f *NewWikiForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) @@ -285,6 +315,7 @@ func (f *NewWikiForm) Validate(ctx *macaron.Context, errs binding.Errors) bindin // /_______ /\____ | |__||__| // \/ \/ +// EditRepoFileForm form for changing repository file type EditRepoFileForm struct { TreePath string `binding:"Required;MaxSize(500)"` Content string `binding:"Required"` @@ -295,14 +326,17 @@ type EditRepoFileForm struct { LastCommit string } +// Validate valideates the fields func (f *EditRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// EditPreviewDiffForm form for changing preview diff type EditPreviewDiffForm struct { Content string } +// Validate valideates the fields func (f *EditPreviewDiffForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -315,6 +349,7 @@ func (f *EditPreviewDiffForm) Validate(ctx *macaron.Context, errs binding.Errors // |__| \/ \/ // +// UploadRepoFileForm form for uploading repository file type UploadRepoFileForm struct { TreePath string `binding:"MaxSize(500)"` CommitSummary string `binding:"MaxSize(100)"` @@ -324,14 +359,17 @@ type UploadRepoFileForm struct { Files []string } +// Validate valideates the fields func (f *UploadRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// RemoveUploadFileForm form for removing uploaded file type RemoveUploadFileForm struct { File string `binding:"Required;MaxSize(50)"` } +// Validate valideates the fields func (f *RemoveUploadFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -343,6 +381,7 @@ func (f *RemoveUploadFileForm) Validate(ctx *macaron.Context, errs binding.Error // /_______ /\___ >____/\___ >__| \___ > // \/ \/ \/ \/ +// DeleteRepoFileForm form for deleting repository file type DeleteRepoFileForm struct { CommitSummary string `binding:"MaxSize(100)"` CommitMessage string @@ -350,6 +389,7 @@ type DeleteRepoFileForm struct { NewBranchName string `binding:"AlphaDashDot;MaxSize(100)"` } +// Validate valideates the fields func (f *DeleteRepoFileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/auth/user_form.go b/modules/auth/user_form.go index 09ef53db8f..0bdd7c1532 100644 --- a/modules/auth/user_form.go +++ b/modules/auth/user_form.go @@ -11,6 +11,7 @@ import ( "gopkg.in/macaron.v1" ) +// InstallForm form for installation page type InstallForm struct { DbType string `binding:"Required"` DbHost string @@ -26,7 +27,7 @@ type InstallForm struct { Domain string `binding:"Required"` SSHPort int HTTPPort string `binding:"Required"` - AppUrl string `binding:"Required"` + AppURL string `binding:"Required"` LogRootPath string `binding:"Required"` SMTPHost string @@ -49,6 +50,7 @@ type InstallForm struct { AdminEmail string `binding:"OmitEmpty;MinSize(3);MaxSize(254);Include(@)" locale:"install.admin_email"` } +// Validate valideates the fields func (f *InstallForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -60,6 +62,7 @@ func (f *InstallForm) Validate(ctx *macaron.Context, errs binding.Errors) bindin // \____|__ /______/ |____| \___|_ / // \/ \/ +// RegisterForm form for registering type RegisterForm struct { UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"` Email string `binding:"Required;Email;MaxSize(254)"` @@ -67,16 +70,19 @@ type RegisterForm struct { Retype string } +// Validate valideates the fields func (f *RegisterForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// SignInForm form for signing in type SignInForm struct { UserName string `binding:"Required;MaxSize(254)"` Password string `binding:"Required;MaxSize(255)"` Remember bool } +// Validate valideates the fields func (f *SignInForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } @@ -88,6 +94,7 @@ func (f *SignInForm) Validate(ctx *macaron.Context, errs binding.Errors) binding // /_______ //_______ / |____| |____| |___\____|__ /\______ /_______ / // \/ \/ \/ \/ \/ +// UpdateProfileForm form for updating profile type UpdateProfileForm struct { Name string `binding:"OmitEmpty;MaxSize(35)"` FullName string `binding:"MaxSize(100)"` @@ -96,15 +103,18 @@ type UpdateProfileForm struct { Location string `binding:"MaxSize(50)"` } +// Validate valideates the fields func (f *UpdateProfileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// Avatar types const ( AvatarLocal string = "local" AvatarByMail string = "bymail" ) +// AvatarForm form for changing avatar type AvatarForm struct { Source string Avatar *multipart.FileHeader @@ -112,41 +122,50 @@ type AvatarForm struct { Federavatar bool } +// Validate valideates the fields func (f *AvatarForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// AddEmailForm form for adding new email type AddEmailForm struct { Email string `binding:"Required;Email;MaxSize(254)"` } +// Validate valideates the fields func (f *AddEmailForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// ChangePasswordForm form for changing password type ChangePasswordForm struct { OldPassword string `form:"old_password" binding:"Required;MinSize(1);MaxSize(255)"` Password string `form:"password" binding:"Required;MaxSize(255)"` Retype string `form:"retype"` } +// Validate valideates the fields func (f *ChangePasswordForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// AddSSHKeyForm form for adding SSH key type AddSSHKeyForm struct { Title string `binding:"Required;MaxSize(50)"` Content string `binding:"Required"` } +// Validate valideates the fields func (f *AddSSHKeyForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } +// NewAccessTokenForm form for creating access token type NewAccessTokenForm struct { Name string `binding:"Required"` } +// Validate valideates the fields func (f *NewAccessTokenForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/routers/admin/users.go b/routers/admin/users.go index 04e331d229..c95aba7729 100644 --- a/routers/admin/users.go +++ b/routers/admin/users.go @@ -60,7 +60,7 @@ func NewUser(ctx *context.Context) { } // NewUserPost response for adding a new user -func NewUserPost(ctx *context.Context, form auth.AdminCrateUserForm) { +func NewUserPost(ctx *context.Context, form auth.AdminCreateUserForm) { ctx.Data["Title"] = ctx.Tr("admin.users.new_account") ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminUsers"] = true diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 6ae513db16..1fa0b14b40 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -177,8 +177,8 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { ctxUser := ctx.User // Not equal means context user is an organization, // or is another user/organization if current user is admin. - if form.Uid != ctxUser.ID { - org, err := models.GetUserByID(form.Uid) + if form.UID != ctxUser.ID { + org, err := models.GetUserByID(form.UID) if err != nil { if models.IsErrUserNotExist(err) { ctx.Error(422, "", err) diff --git a/routers/install.go b/routers/install.go index ed8fae15f1..495aa9ab79 100644 --- a/routers/install.go +++ b/routers/install.go @@ -89,7 +89,7 @@ func Install(ctx *context.Context) { form.Domain = setting.Domain form.SSHPort = setting.SSH.Port form.HTTPPort = setting.HTTPPort - form.AppUrl = setting.AppURL + form.AppURL = setting.AppURL form.LogRootPath = setting.LogRootPath // E-mail service settings @@ -217,8 +217,8 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) { return } - if form.AppUrl[len(form.AppUrl)-1] != '/' { - form.AppUrl += "/" + if form.AppURL[len(form.AppURL)-1] != '/' { + form.AppURL += "/" } // Save settings. @@ -242,7 +242,7 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) { cfg.Section("").Key("RUN_USER").SetValue(form.RunUser) cfg.Section("server").Key("DOMAIN").SetValue(form.Domain) cfg.Section("server").Key("HTTP_PORT").SetValue(form.HTTPPort) - cfg.Section("server").Key("ROOT_URL").SetValue(form.AppUrl) + cfg.Section("server").Key("ROOT_URL").SetValue(form.AppURL) if form.SSHPort == 0 { cfg.Section("server").Key("DISABLE_SSH").SetValue("true") @@ -328,5 +328,5 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) { log.Info("First-time run install finished!") ctx.Flash.Success(ctx.Tr("install.install_success")) - ctx.Redirect(form.AppUrl + "user/login") + ctx.Redirect(form.AppURL + "user/login") } diff --git a/routers/repo/pull.go b/routers/repo/pull.go index bc958bdda1..389fcb0898 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -94,7 +94,7 @@ func ForkPost(ctx *context.Context, form auth.CreateRepoForm) { return } - ctxUser := checkContextUser(ctx, form.Uid) + ctxUser := checkContextUser(ctx, form.UID) if ctx.Written() { return } diff --git a/routers/repo/repo.go b/routers/repo/repo.go index df1c3feb4c..fa111d5e4a 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -112,7 +112,7 @@ func CreatePost(ctx *context.Context, form auth.CreateRepoForm) { ctx.Data["Licenses"] = models.Licenses ctx.Data["Readmes"] = models.Readmes - ctxUser := checkContextUser(ctx, form.Uid) + ctxUser := checkContextUser(ctx, form.UID) if ctx.Written() { return } @@ -167,7 +167,7 @@ func Migrate(ctx *context.Context) { func MigratePost(ctx *context.Context, form auth.MigrateRepoForm) { ctx.Data["Title"] = ctx.Tr("new_migrate") - ctxUser := checkContextUser(ctx, form.Uid) + ctxUser := checkContextUser(ctx, form.UID) if ctx.Written() { return } From 21846d16e517cf0b7f7bed5e595277aab025711f Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 28 Nov 2016 09:30:08 +0800 Subject: [PATCH 060/135] golint for models/org_team.go --- models/org.go | 10 +++--- models/org_team.go | 83 +++++++++++++++++++++++----------------------- 2 files changed, 47 insertions(+), 46 deletions(-) diff --git a/models/org.go b/models/org.go index 3b04ed578c..4a81814bae 100644 --- a/models/org.go +++ b/models/org.go @@ -41,7 +41,7 @@ func (org *User) GetTeam(name string) (*Team, error) { } func (org *User) getOwnerTeam(e Engine) (*Team, error) { - return org.getTeam(e, OWNER_TEAM) + return org.getTeam(e, ownerTeamName) } // GetOwnerTeam returns owner team of organization. @@ -52,7 +52,7 @@ func (org *User) GetOwnerTeam() (*Team, error) { func (org *User) getTeams(e Engine) error { return e. Where("org_id=?", org.ID). - OrderBy("CASE WHEN name LIKE '" + OWNER_TEAM + "' THEN '' ELSE name END"). + OrderBy("CASE WHEN name LIKE '" + ownerTeamName + "' THEN '' ELSE name END"). Find(&org.Teams) } @@ -140,8 +140,8 @@ func CreateOrganization(org, owner *User) (err error) { // Create default owner team. t := &Team{ OrgID: org.ID, - LowerName: strings.ToLower(OWNER_TEAM), - Name: OWNER_TEAM, + LowerName: strings.ToLower(ownerTeamName), + Name: ownerTeamName, Authorize: AccessModeOwner, NumMembers: 1, } @@ -150,7 +150,7 @@ func CreateOrganization(org, owner *User) (err error) { } if _, err = sess.Insert(&TeamUser{ - Uid: owner.ID, + UID: owner.ID, OrgID: org.ID, TeamID: t.ID, }); err != nil { diff --git a/models/org_team.go b/models/org_team.go index bc23660b16..8f1448ebdb 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -10,7 +10,7 @@ import ( "strings" ) -const OWNER_TEAM = "Owners" +const ownerTeamName = "Owners" // Team represents a organization team. type Team struct { @@ -28,12 +28,12 @@ type Team struct { // IsOwnerTeam returns true if team is owner team. func (t *Team) IsOwnerTeam() bool { - return t.Name == OWNER_TEAM + return t.Name == ownerTeamName } -// IsTeamMember returns true if given user is a member of team. -func (t *Team) IsMember(uid int64) bool { - return IsTeamMember(t.OrgID, t.ID, uid) +// IsMember returns true if given user is a member of team. +func (t *Team) IsMember(uID int64) bool { + return IsTeamMember(t.OrgID, t.ID, uID) } func (t *Team) getRepositories(e Engine) (err error) { @@ -72,13 +72,13 @@ func (t *Team) GetMembers() (err error) { // AddMember adds new membership of the team to the organization, // the user will have membership to the organization automatically when needed. -func (t *Team) AddMember(uid int64) error { - return AddTeamMember(t.OrgID, t.ID, uid) +func (t *Team) AddMember(uID int64) error { + return AddTeamMember(t.OrgID, t.ID, uID) } // RemoveMember removes member from team of organization. -func (t *Team) RemoveMember(uid int64) error { - return RemoveTeamMember(t.OrgID, t.ID, uid) +func (t *Team) RemoveMember(uID int64) error { + return RemoveTeamMember(t.OrgID, t.ID, uID) } func (t *Team) hasRepository(e Engine, repoID int64) bool { @@ -196,6 +196,7 @@ func (t *Team) RemoveRepository(repoID int64) error { return sess.Commit() } +// IsUsableTeamName tests if a name could be as team name func IsUsableTeamName(name string) (err error) { var reservedTeamNames = []string{"new"} @@ -256,9 +257,9 @@ func NewTeam(t *Team) (err error) { return sess.Commit() } -func getTeam(e Engine, orgId int64, name string) (*Team, error) { +func getTeam(e Engine, orgID int64, name string) (*Team, error) { t := &Team{ - OrgID: orgId, + OrgID: orgID, LowerName: strings.ToLower(name), } has, err := e.Get(t) @@ -271,13 +272,13 @@ func getTeam(e Engine, orgId int64, name string) (*Team, error) { } // GetTeam returns team by given team name and organization. -func GetTeam(orgId int64, name string) (*Team, error) { - return getTeam(x, orgId, name) +func GetTeam(orgID int64, name string) (*Team, error) { + return getTeam(x, orgID, name) } -func getTeamByID(e Engine, teamId int64) (*Team, error) { +func getTeamByID(e Engine, teamID int64) (*Team, error) { t := new(Team) - has, err := e.Id(teamId).Get(t) + has, err := e.Id(teamID).Get(t) if err != nil { return nil, err } else if !has { @@ -287,8 +288,8 @@ func getTeamByID(e Engine, teamId int64) (*Team, error) { } // GetTeamByID returns team by given ID. -func GetTeamByID(teamId int64) (*Team, error) { - return getTeamByID(x, teamId) +func GetTeamByID(teamID int64) (*Team, error) { + return getTeamByID(x, teamID) } // UpdateTeam updates information of team. @@ -397,21 +398,21 @@ type TeamUser struct { ID int64 `xorm:"pk autoincr"` OrgID int64 `xorm:"INDEX"` TeamID int64 `xorm:"UNIQUE(s)"` - Uid int64 `xorm:"UNIQUE(s)"` + UID int64 `xorm:"UNIQUE(s)"` } -func isTeamMember(e Engine, orgID, teamID, uid int64) bool { +func isTeamMember(e Engine, orgID, teamID, uID int64) bool { has, _ := e. Where("org_id=?", orgID). And("team_id=?", teamID). - And("uid=?", uid). + And("uid=?", uID). Get(new(TeamUser)) return has } // IsTeamMember returns true if given user is a member of team. -func IsTeamMember(orgID, teamID, uid int64) bool { - return isTeamMember(x, orgID, teamID, uid) +func IsTeamMember(orgID, teamID, uID int64) bool { + return isTeamMember(x, orgID, teamID, uID) } func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) { @@ -424,8 +425,8 @@ func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) { members := make([]*User, 0, len(teamUsers)) for i := range teamUsers { member := new(User) - if _, err = e.Id(teamUsers[i].Uid).Get(member); err != nil { - return nil, fmt.Errorf("get user '%d': %v", teamUsers[i].Uid, err) + if _, err = e.Id(teamUsers[i].UID).Get(member); err != nil { + return nil, fmt.Errorf("get user '%d': %v", teamUsers[i].UID, err) } members = append(members, member) } @@ -437,11 +438,11 @@ func GetTeamMembers(teamID int64) ([]*User, error) { return getTeamMembers(x, teamID) } -func getUserTeams(e Engine, orgId, uid int64) ([]*Team, error) { +func getUserTeams(e Engine, orgID, uID int64) ([]*Team, error) { tus := make([]*TeamUser, 0, 5) if err := e. - Where("uid=?", uid). - And("org_id=?", orgId). + Where("uid=?", uID). + And("org_id=?", orgID). Find(&tus); err != nil { return nil, err } @@ -461,18 +462,18 @@ func getUserTeams(e Engine, orgId, uid int64) ([]*Team, error) { } // GetUserTeams returns all teams that user belongs to in given organization. -func GetUserTeams(orgId, uid int64) ([]*Team, error) { - return getUserTeams(x, orgId, uid) +func GetUserTeams(orgID, uID int64) ([]*Team, error) { + return getUserTeams(x, orgID, uID) } // AddTeamMember adds new membership of given team to given organization, // the user will have membership to given organization automatically when needed. -func AddTeamMember(orgID, teamID, uid int64) error { - if IsTeamMember(orgID, teamID, uid) { +func AddTeamMember(orgID, teamID, uID int64) error { + if IsTeamMember(orgID, teamID, uID) { return nil } - if err := AddOrgUser(orgID, uid); err != nil { + if err := AddOrgUser(orgID, uID); err != nil { return err } @@ -494,7 +495,7 @@ func AddTeamMember(orgID, teamID, uid int64) error { } tu := &TeamUser{ - Uid: uid, + UID: uID, OrgID: orgID, TeamID: teamID, } @@ -514,7 +515,7 @@ func AddTeamMember(orgID, teamID, uid int64) error { // We make sure it exists before. ou := new(OrgUser) if _, err = sess. - Where("uid = ?", uid). + Where("uid = ?", uID). And("org_id = ?", orgID). Get(ou); err != nil { return err @@ -530,8 +531,8 @@ func AddTeamMember(orgID, teamID, uid int64) error { return sess.Commit() } -func removeTeamMember(e Engine, orgID, teamID, uid int64) error { - if !isTeamMember(e, orgID, teamID, uid) { +func removeTeamMember(e Engine, orgID, teamID, uID int64) error { + if !isTeamMember(e, orgID, teamID, uID) { return nil } @@ -543,7 +544,7 @@ func removeTeamMember(e Engine, orgID, teamID, uid int64) error { // Check if the user to delete is the last member in owner team. if t.IsOwnerTeam() && t.NumMembers == 1 { - return ErrLastOrgOwner{UID: uid} + return ErrLastOrgOwner{UID: uID} } t.NumMembers-- @@ -559,7 +560,7 @@ func removeTeamMember(e Engine, orgID, teamID, uid int64) error { } tu := &TeamUser{ - Uid: uid, + UID: uID, OrgID: orgID, TeamID: teamID, } @@ -582,7 +583,7 @@ func removeTeamMember(e Engine, orgID, teamID, uid int64) error { // This must exist. ou := new(OrgUser) _, err = e. - Where("uid = ?", uid). + Where("uid = ?", uID). And("org_id = ?", org.ID). Get(ou) if err != nil { @@ -602,13 +603,13 @@ func removeTeamMember(e Engine, orgID, teamID, uid int64) error { } // RemoveTeamMember removes member from given team of given organization. -func RemoveTeamMember(orgID, teamID, uid int64) error { +func RemoveTeamMember(orgID, teamID, uID int64) error { sess := x.NewSession() defer sessionRelease(sess) if err := sess.Begin(); err != nil { return err } - if err := removeTeamMember(sess, orgID, teamID, uid); err != nil { + if err := removeTeamMember(sess, orgID, teamID, uID); err != nil { return err } return sess.Commit() From bf8d90c5cc6bea9ec4eeb2e827d10cd247043fe0 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 28 Nov 2016 15:25:16 +0800 Subject: [PATCH 061/135] golint fixed for models/models.go (#284) --- models/models.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/models/models.go b/models/models.go index 0b02de54d4..bab04c661b 100644 --- a/models/models.go +++ b/models/models.go @@ -149,7 +149,7 @@ func getEngine() (*xorm.Engine, error) { } case "sqlite3": if !EnableSQLite3 { - return nil, errors.New("This binary version does not build support for SQLite3.") + return nil, errors.New("this binary version does not build support for SQLite3") } if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil { return nil, fmt.Errorf("Fail to create directories: %v", err) @@ -157,7 +157,7 @@ func getEngine() (*xorm.Engine, error) { connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc" case "tidb": if !EnableTiDB { - return nil, errors.New("This binary version does not build support for TiDB.") + return nil, errors.New("this binary version does not build support for TiDB") } if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil { return nil, fmt.Errorf("Fail to create directories: %v", err) @@ -218,7 +218,7 @@ func NewEngine() (err error) { } if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil { - return fmt.Errorf("sync database struct error: %v\n", err) + return fmt.Errorf("sync database struct error: %v", err) } return nil From f215d78157cd78b810145922e16606c8b0cfa82d Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 28 Nov 2016 16:33:08 +0800 Subject: [PATCH 062/135] rename all uID -> userID on models/org_team.go --- models/org_team.go | 52 +++++++++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/models/org_team.go b/models/org_team.go index 8f1448ebdb..237a6fcf0c 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -32,8 +32,8 @@ func (t *Team) IsOwnerTeam() bool { } // IsMember returns true if given user is a member of team. -func (t *Team) IsMember(uID int64) bool { - return IsTeamMember(t.OrgID, t.ID, uID) +func (t *Team) IsMember(userID int64) bool { + return IsTeamMember(t.OrgID, t.ID, userID) } func (t *Team) getRepositories(e Engine) (err error) { @@ -72,13 +72,13 @@ func (t *Team) GetMembers() (err error) { // AddMember adds new membership of the team to the organization, // the user will have membership to the organization automatically when needed. -func (t *Team) AddMember(uID int64) error { - return AddTeamMember(t.OrgID, t.ID, uID) +func (t *Team) AddMember(userID int64) error { + return AddTeamMember(t.OrgID, t.ID, userID) } // RemoveMember removes member from team of organization. -func (t *Team) RemoveMember(uID int64) error { - return RemoveTeamMember(t.OrgID, t.ID, uID) +func (t *Team) RemoveMember(userID int64) error { + return RemoveTeamMember(t.OrgID, t.ID, userID) } func (t *Team) hasRepository(e Engine, repoID int64) bool { @@ -401,18 +401,18 @@ type TeamUser struct { UID int64 `xorm:"UNIQUE(s)"` } -func isTeamMember(e Engine, orgID, teamID, uID int64) bool { +func isTeamMember(e Engine, orgID, teamID, userID int64) bool { has, _ := e. Where("org_id=?", orgID). And("team_id=?", teamID). - And("uid=?", uID). + And("uid=?", userID). Get(new(TeamUser)) return has } // IsTeamMember returns true if given user is a member of team. -func IsTeamMember(orgID, teamID, uID int64) bool { - return isTeamMember(x, orgID, teamID, uID) +func IsTeamMember(orgID, teamID, userID int64) bool { + return isTeamMember(x, orgID, teamID, userID) } func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) { @@ -438,10 +438,10 @@ func GetTeamMembers(teamID int64) ([]*User, error) { return getTeamMembers(x, teamID) } -func getUserTeams(e Engine, orgID, uID int64) ([]*Team, error) { +func getUserTeams(e Engine, orgID, userID int64) ([]*Team, error) { tus := make([]*TeamUser, 0, 5) if err := e. - Where("uid=?", uID). + Where("uid=?", userID). And("org_id=?", orgID). Find(&tus); err != nil { return nil, err @@ -462,18 +462,18 @@ func getUserTeams(e Engine, orgID, uID int64) ([]*Team, error) { } // GetUserTeams returns all teams that user belongs to in given organization. -func GetUserTeams(orgID, uID int64) ([]*Team, error) { - return getUserTeams(x, orgID, uID) +func GetUserTeams(orgID, userID int64) ([]*Team, error) { + return getUserTeams(x, orgID, userID) } // AddTeamMember adds new membership of given team to given organization, // the user will have membership to given organization automatically when needed. -func AddTeamMember(orgID, teamID, uID int64) error { - if IsTeamMember(orgID, teamID, uID) { +func AddTeamMember(orgID, teamID, userID int64) error { + if IsTeamMember(orgID, teamID, userID) { return nil } - if err := AddOrgUser(orgID, uID); err != nil { + if err := AddOrgUser(orgID, userID); err != nil { return err } @@ -495,7 +495,7 @@ func AddTeamMember(orgID, teamID, uID int64) error { } tu := &TeamUser{ - UID: uID, + UID: userID, OrgID: orgID, TeamID: teamID, } @@ -515,7 +515,7 @@ func AddTeamMember(orgID, teamID, uID int64) error { // We make sure it exists before. ou := new(OrgUser) if _, err = sess. - Where("uid = ?", uID). + Where("uid = ?", userID). And("org_id = ?", orgID). Get(ou); err != nil { return err @@ -531,8 +531,8 @@ func AddTeamMember(orgID, teamID, uID int64) error { return sess.Commit() } -func removeTeamMember(e Engine, orgID, teamID, uID int64) error { - if !isTeamMember(e, orgID, teamID, uID) { +func removeTeamMember(e Engine, orgID, teamID, userID int64) error { + if !isTeamMember(e, orgID, teamID, userID) { return nil } @@ -544,7 +544,7 @@ func removeTeamMember(e Engine, orgID, teamID, uID int64) error { // Check if the user to delete is the last member in owner team. if t.IsOwnerTeam() && t.NumMembers == 1 { - return ErrLastOrgOwner{UID: uID} + return ErrLastOrgOwner{UID: userID} } t.NumMembers-- @@ -560,7 +560,7 @@ func removeTeamMember(e Engine, orgID, teamID, uID int64) error { } tu := &TeamUser{ - UID: uID, + UID: userID, OrgID: orgID, TeamID: teamID, } @@ -583,7 +583,7 @@ func removeTeamMember(e Engine, orgID, teamID, uID int64) error { // This must exist. ou := new(OrgUser) _, err = e. - Where("uid = ?", uID). + Where("uid = ?", userID). And("org_id = ?", org.ID). Get(ou) if err != nil { @@ -603,13 +603,13 @@ func removeTeamMember(e Engine, orgID, teamID, uID int64) error { } // RemoveTeamMember removes member from given team of given organization. -func RemoveTeamMember(orgID, teamID, uID int64) error { +func RemoveTeamMember(orgID, teamID, userID int64) error { sess := x.NewSession() defer sessionRelease(sess) if err := sess.Begin(); err != nil { return err } - if err := removeTeamMember(sess, orgID, teamID, uID); err != nil { + if err := removeTeamMember(sess, orgID, teamID, userID); err != nil { return err } return sess.Commit() From 86aa8e413acc1dbcc7760cb220a6ee2126e926b6 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 14:13:18 +0100 Subject: [PATCH 063/135] Restructured docker building I have restructured the docker build process entirely, the binary gets built outside of the docker build command, now we are managing all dependencies with real Alpine packages and I have dropped features like socat or the cron daemon. Signed-off-by: Thomas Boerger --- .dockerignore | 24 ++----- Dockerfile | 59 +++++++++++----- Dockerfile.rpi | 62 +++++++++++------ docker/README.md | 111 ------------------------------- docker/build.sh | 36 ---------- docker/{ => etc}/nsswitch.conf | 1 - docker/etc/profile.d/gitea.sh | 2 + docker/etc/s6/.s6-svscan/finish | 2 + docker/etc/s6/gitea/finish | 2 + docker/etc/s6/gitea/run | 6 ++ docker/etc/s6/gitea/setup | 19 ++++++ docker/etc/s6/openssh/finish | 2 + docker/etc/s6/openssh/run | 6 ++ docker/etc/s6/openssh/setup | 29 ++++++++ docker/etc/s6/syslogd/finish | 2 + docker/etc/s6/syslogd/run | 6 ++ docker/etc/s6/syslogd/setup | 1 + docker/{ => etc/ssh}/sshd_config | 27 ++++++-- docker/etc/templates/app.ini | 24 +++++++ docker/s6/.s6-svscan/finish | 5 -- docker/s6/crond/down | 0 docker/s6/crond/run | 9 --- docker/s6/gogs/run | 8 --- docker/s6/gogs/setup | 23 ------- docker/s6/openssh/run | 7 -- docker/s6/openssh/setup | 23 ------- docker/s6/syslogd/run | 7 -- docker/start.sh | 65 ------------------ docker/usr/bin/entrypoint | 11 +++ 29 files changed, 223 insertions(+), 356 deletions(-) delete mode 100644 docker/README.md delete mode 100755 docker/build.sh rename docker/{ => etc}/nsswitch.conf (99%) create mode 100755 docker/etc/profile.d/gitea.sh create mode 100755 docker/etc/s6/.s6-svscan/finish create mode 100755 docker/etc/s6/gitea/finish create mode 100755 docker/etc/s6/gitea/run create mode 100755 docker/etc/s6/gitea/setup create mode 100755 docker/etc/s6/openssh/finish create mode 100755 docker/etc/s6/openssh/run create mode 100755 docker/etc/s6/openssh/setup create mode 100755 docker/etc/s6/syslogd/finish create mode 100755 docker/etc/s6/syslogd/run create mode 100755 docker/etc/s6/syslogd/setup rename docker/{ => etc/ssh}/sshd_config (58%) create mode 100644 docker/etc/templates/app.ini delete mode 100755 docker/s6/.s6-svscan/finish delete mode 100644 docker/s6/crond/down delete mode 100755 docker/s6/crond/run delete mode 100755 docker/s6/gogs/run delete mode 100755 docker/s6/gogs/setup delete mode 100755 docker/s6/openssh/run delete mode 100755 docker/s6/openssh/setup delete mode 100755 docker/s6/syslogd/run delete mode 100755 docker/start.sh create mode 100755 docker/usr/bin/entrypoint diff --git a/.dockerignore b/.dockerignore index b33dbf58a8..e3e379e3f7 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,19 +1,5 @@ -.git -.git/** -packager -packager/** -scripts -scripts/** -.github/ -.github/** -config.codekit -.dockerignore -*.yml -*.md -.bra.toml -.editorconfig -.gitignore -Dockerfile* -vendor -vendor/** -gogs +* +!docker +!bin +!public +!templates diff --git a/Dockerfile b/Dockerfile index aa6c834e20..df363e07fb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,22 +1,47 @@ -FROM alpine:3.3 -MAINTAINER jp@roemer.im +FROM alpine:edge +MAINTAINER Thomas Boerger -# Install system utils & Gogs runtime dependencies -ADD https://github.com/tianon/gosu/releases/download/1.9/gosu-amd64 /usr/sbin/gosu -RUN chmod +x /usr/sbin/gosu \ - && apk --no-cache --no-progress add ca-certificates bash git linux-pam s6 curl openssh socat tzdata - -ENV GITEA_CUSTOM /data/gogs +EXPOSE 22 3000 -COPY . /app/gogs/ -WORKDIR /app/gogs/ -RUN ./docker/build.sh +RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories && \ + apk -U add \ + gosu@testing \ + shadow \ + ca-certificates \ + sqlite \ + bash \ + git \ + linux-pam \ + s6 \ + curl \ + openssh \ + tzdata && \ + rm -rf \ + /var/cache/apk/* && \ + groupadd \ + -r \ + -g 1000 \ + git && \ + useradd \ + -r -M \ + -p '*' \ + -d /data/git \ + -s /bin/bash \ + -u 1000 \ + -g git \ + git -# Configure LibC Name Service -COPY docker/nsswitch.conf /etc/nsswitch.conf +ENV USER git +ENV GITEA_CUSTOM /data/gitea +ENV GODEBUG=netdns=go -# Configure Docker Container VOLUME ["/data"] -EXPOSE 22 3000 -ENTRYPOINT ["docker/start.sh"] -CMD ["/bin/s6-svscan", "/app/gogs/docker/s6/"] + +ENTRYPOINT ["/usr/bin/entrypoint"] +CMD ["/bin/s6-svscan", "/etc/s6"] + +COPY docker / + +COPY public /app/gitea/public +COPY templates /app/gitea/templates +COPY bin/gitea /app/gitea/gitea diff --git a/Dockerfile.rpi b/Dockerfile.rpi index 8e034fe204..6a168c3a5b 100644 --- a/Dockerfile.rpi +++ b/Dockerfile.rpi @@ -1,25 +1,47 @@ -FROM hypriot/rpi-alpine-scratch:v3.2 -MAINTAINER jp@roemer.im, raxetul@gmail.com +FROM hypriot/rpi-alpine-scratch:edge +MAINTAINER Thomas Boerger -# Install system utils & Gogs runtime dependencies -ADD https://github.com/tianon/gosu/releases/download/1.9/gosu-armhf /usr/sbin/gosu -RUN chmod +x /usr/sbin/gosu \ - && echo "http://dl-4.alpinelinux.org/alpine/v3.3/main/" | tee /etc/apk/repositories \ - && echo "http://dl-4.alpinelinux.org/alpine/v3.3/community/" | tee -a /etc/apk/repositories \ - && apk -U --no-progress upgrade && rm -f /var/cache/apk/APKINDEX.* \ - && apk --no-cache --no-progress add ca-certificates bash git linux-pam s6 curl openssh socat tzdata - -ENV GITEA_CUSTOM /data/gogs +EXPOSE 22 3000 -COPY . /app/gogs/ -WORKDIR /app/gogs/ -RUN ./docker/build.sh +RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories && \ + apk -U add \ + gosu@testing \ + shadow \ + ca-certificates \ + sqlite \ + bash \ + git \ + linux-pam \ + s6 \ + curl \ + openssh \ + tzdata && \ + rm -rf \ + /var/cache/apk/* && \ + groupadd \ + -r \ + -g 1000 \ + git && \ + useradd \ + -r -M \ + -p '*' \ + -d /data/git \ + -s /bin/bash \ + -u 1000 \ + -g git \ + git -# Configure LibC Name Service -COPY docker/nsswitch.conf /etc/nsswitch.conf +ENV USER git +ENV GITEA_CUSTOM /data/gitea +ENV GODEBUG=netdns=go -# Configure Docker Container VOLUME ["/data"] -EXPOSE 22 3000 -ENTRYPOINT ["docker/start.sh"] -CMD ["/bin/s6-svscan", "/app/gogs/docker/s6/"] + +ENTRYPOINT ["/usr/bin/entrypoint"] +CMD ["/bin/s6-svscan", "/etc/s6"] + +COPY docker / + +COPY public /app/gitea/public +COPY templates /app/gitea/templates +COPY bin/gitea /app/gitea/gitea diff --git a/docker/README.md b/docker/README.md deleted file mode 100644 index e6fa15dda3..0000000000 --- a/docker/README.md +++ /dev/null @@ -1,111 +0,0 @@ -# Docker for Gogs - -Visit [Docker Hub](https://hub.docker.com/r/gogs/) see all available images and tags. - -## Usage - -To keep your data out of Docker container, we do a volume (`/var/gogs` -> `/data`) here, and you can change it based on your situation. - -``` -# Pull image from Docker Hub. -$ docker pull gogs/gogs - -# Create local directory for volume. -$ mkdir -p /var/gogs - -# Use `docker run` for the first time. -$ docker run --name=gogs -p 10022:22 -p 10080:3000 -v /var/gogs:/data gogs/gogs - -# Use `docker start` if you have stopped it. -$ docker start gogs -``` - -Note: It is important to map the Gogs ssh service from the container to the host and set the appropriate SSH Port and URI settings when setting up Gogs for the first time. To access and clone Gogs Git repositories with the above configuration you would use: `git clone ssh://git@hostname:10022/username/myrepo.git` for example. - -Files will be store in local path `/var/gogs` in my case. - -Directory `/var/gogs` keeps Git repositories and Gogs data: - - /var/gogs - |-- git - | |-- gogs-repositories - |-- ssh - | |-- # ssh public/private keys for Gogs - |-- gogs - |-- conf - |-- data - |-- log - -### Volume with data container - -If you're more comfortable with mounting data to a data container, the commands you execute at the first time will look like as follows: - -``` -# Create data container -docker run --name=gogs-data --entrypoint /bin/true gogs/gogs - -# Use `docker run` for the first time. -docker run --name=gogs --volumes-from gogs-data -p 10022:22 -p 10080:3000 gogs/gogs -``` - -#### Using Docker 1.9 Volume command - -``` -# Create docker volume. -$ docker volume create --name gogs-data - -# Use `docker run` for the first time. -$ docker run --name=gogs -p 10022:22 -p 10080:3000 -v gogs-data:/data gogs/gogs -``` - -## Settings - -### Application - -Most of settings are obvious and easy to understand, but there are some settings can be confusing by running Gogs inside Docker: - -- **Repository Root Path**: keep it as default value `/home/git/gogs-repositories` because `start.sh` already made a symbolic link for you. -- **Run User**: keep it as default value `git` because `start.sh` already setup a user with name `git`. -- **Domain**: fill in with Docker container IP (e.g. `192.168.99.100`). But if you want to access your Gogs instance from a different physical machine, please fill in with the hostname or IP address of the Docker host machine. -- **SSH Port**: Use the exposed port from Docker container. For example, your SSH server listens on `22` inside Docker, but you expose it by `10022:22`, then use `10022` for this value. **Builtin SSH server is not recommended inside Docker Container** -- **HTTP Port**: Use port you want Gogs to listen on inside Docker container. For example, your Gogs listens on `3000` inside Docker, and you expose it by `10080:3000`, but you still use `3000` for this value. -- **Application URL**: Use combination of **Domain** and **exposed HTTP Port** values (e.g. `http://192.168.99.100:10080/`). - -Full documentation of application settings can be found [here](https://gogs.io/docs/advanced/configuration_cheat_sheet.html). - -### Container options - -This container have some options available via environment variables, these options are opt-in features that can help the administration of this container: - -- **SOCAT_LINK**: - - Possible value: - `true`, `false`, `1`, `0` - - Default: - `true` - - Action: - Bind linked docker container to localhost socket using socat. - Any exported port from a linked container will be binded to the matching port on localhost. - - Disclaimer: - As this option rely on the environment variable created by docker when a container is linked, this option should be deactivated in managed environment such as Rancher or Kubernetes (set to `0` or `false`) -- **RUN_CROND**: - - Possible value: - `true`, `false`, `1`, `0` - - Default: - `false` - - Action: - Request crond to be run inside the container. Its default configuration will periodically run all scripts from `/etc/periodic/${period}` but custom crontabs can be added to `/var/spool/cron/crontabs/`. - -## Upgrade - -:exclamation::exclamation::exclamation:**Make sure you have volumed data to somewhere outside Docker container**:exclamation::exclamation::exclamation: - -Steps to upgrade Gogs with Docker: - -- `docker pull gogs/gogs` -- `docker stop gogs` -- `docker rm gogs` -- Finally, create container as the first time and don't forget to do same volume and port mapping. - -## Known Issues - -- The docker container can not currently be build on Raspberry 1 (armv6l) as our base image `alpine` does not have a `go` package available for this platform. diff --git a/docker/build.sh b/docker/build.sh deleted file mode 100755 index 9965cef376..0000000000 --- a/docker/build.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/sh -set -x -set -e - -# Set temp environment vars -export GOPATH=/tmp/go -export PATH=${PATH}:${GOPATH}/bin -export GO15VENDOREXPERIMENT=1 - -# Install build deps -apk --no-cache --no-progress add --virtual build-deps build-base linux-pam-dev go - -# Install glide -git clone -b 0.10.2 https://github.com/Masterminds/glide ${GOPATH}/src/github.com/Masterminds/glide -cd ${GOPATH}/src/github.com/Masterminds/glide -make build -go install - - - -# Build Gogs -mkdir -p ${GOPATH}/src/github.com/gogits/ -ln -s /app/gogs/ ${GOPATH}/src/github.com/go-gitea/gitea -cd ${GOPATH}/src/github.com/go-gitea/gitea -glide install -make build TAGS="sqlite cert pam" - -# Cleanup GOPATH & vendoring dir -rm -r $GOPATH /app/gogs/vendor - -# Remove build deps -apk --no-progress del build-deps - -# Create git user for Gogs -adduser -H -D -g 'Gogs Git User' git -h /data/git -s /bin/bash && passwd -u git -echo "export GITEA_CUSTOM=${GITEA_CUSTOM}" >> /etc/profile diff --git a/docker/nsswitch.conf b/docker/etc/nsswitch.conf similarity index 99% rename from docker/nsswitch.conf rename to docker/etc/nsswitch.conf index 70eb1733f4..25fad995e6 100644 --- a/docker/nsswitch.conf +++ b/docker/etc/nsswitch.conf @@ -13,4 +13,3 @@ ethers: db files rpc: db files netgroup: nis - diff --git a/docker/etc/profile.d/gitea.sh b/docker/etc/profile.d/gitea.sh new file mode 100755 index 0000000000..41afd4cfb8 --- /dev/null +++ b/docker/etc/profile.d/gitea.sh @@ -0,0 +1,2 @@ +#!/bin/bash +export GITEA_CUSTOM=/data/gitea diff --git a/docker/etc/s6/.s6-svscan/finish b/docker/etc/s6/.s6-svscan/finish new file mode 100755 index 0000000000..06bd986563 --- /dev/null +++ b/docker/etc/s6/.s6-svscan/finish @@ -0,0 +1,2 @@ +#!/bin/bash +exit 0 diff --git a/docker/etc/s6/gitea/finish b/docker/etc/s6/gitea/finish new file mode 100755 index 0000000000..06bd986563 --- /dev/null +++ b/docker/etc/s6/gitea/finish @@ -0,0 +1,2 @@ +#!/bin/bash +exit 0 diff --git a/docker/etc/s6/gitea/run b/docker/etc/s6/gitea/run new file mode 100755 index 0000000000..246e74d27c --- /dev/null +++ b/docker/etc/s6/gitea/run @@ -0,0 +1,6 @@ +#!/bin/bash +[[ -f ./setup ]] && source ./setup + +pushd /app/gitea > /dev/null + exec gosu git /app/gitea/gitea web +popd diff --git a/docker/etc/s6/gitea/setup b/docker/etc/s6/gitea/setup new file mode 100755 index 0000000000..27ca49db30 --- /dev/null +++ b/docker/etc/s6/gitea/setup @@ -0,0 +1,19 @@ +#!/bin/bash + +if [ ! -d /data/git/.ssh ]; then + mkdir -p /data/git/.ssh + chmod 700 /data/git/.ssh +fi + +if [ ! -f /data/git/.ssh/environment ]; then + echo "GITEA_CUSTOM=/data/gitea" >| /data/git/.ssh/environment + chmod 600 /data/git/.ssh/environment +fi + +if [ ! -f /data/gitea/conf/app.ini ]; then + mkdir -p /data/gitea/conf + cp /etc/templates/app.ini /data/gitea/conf/app.ini +fi + +chown -R git:git /data/gitea /app/gitea /data/git +chmod 0755 /data/gitea /app/gitea /data/git diff --git a/docker/etc/s6/openssh/finish b/docker/etc/s6/openssh/finish new file mode 100755 index 0000000000..06bd986563 --- /dev/null +++ b/docker/etc/s6/openssh/finish @@ -0,0 +1,2 @@ +#!/bin/bash +exit 0 diff --git a/docker/etc/s6/openssh/run b/docker/etc/s6/openssh/run new file mode 100755 index 0000000000..b4c4cb4088 --- /dev/null +++ b/docker/etc/s6/openssh/run @@ -0,0 +1,6 @@ +#!/bin/bash +[[ -f ./setup ]] && source ./setup + +pushd /root > /dev/null + exec gosu root /usr/sbin/sshd -E /var/log/sshd.log -D +popd diff --git a/docker/etc/s6/openssh/setup b/docker/etc/s6/openssh/setup new file mode 100755 index 0000000000..b529431a15 --- /dev/null +++ b/docker/etc/s6/openssh/setup @@ -0,0 +1,29 @@ +#!/bin/bash + +if [ ! -d /data/ssh ]; then + mkdir -p /data/ssh +fi + +if [ ! -f /data/ssh/ssh_host_ed25519_key ]; then + echo "Generating /data/ssh/ssh_host_ed25519_key..." + ssh-keygen -t ed25519 -b 4096 -f /data/ssh/ssh_host_ed25519_key -N "" > /dev/null +fi + +if [ ! -f /data/ssh/ssh_host_rsa_key ]; then + echo "Generating /data/ssh/ssh_host_rsa_key..." + ssh-keygen -t rsa -b 2048 -f /data/ssh/ssh_host_rsa_key -N "" > /dev/null +fi + +if [ ! -f /data/ssh/ssh_host_dsa_key ]; then + echo "Generating /data/ssh/ssh_host_dsa_key..." + ssh-keygen -t dsa -f /data/ssh/ssh_host_dsa_key -N "" > /dev/null +fi + +if [ ! -f /data/ssh/ssh_host_ecdsa_key ]; then + echo "Generating /data/ssh/ssh_host_ecdsa_key..." + ssh-keygen -t ecdsa -b 256 -f /data/ssh/ssh_host_ecdsa_key -N "" > /dev/null +fi + +chown root:root /data/ssh/* +chmod 0700 /data/ssh +chmod 0600 /data/ssh/* diff --git a/docker/etc/s6/syslogd/finish b/docker/etc/s6/syslogd/finish new file mode 100755 index 0000000000..06bd986563 --- /dev/null +++ b/docker/etc/s6/syslogd/finish @@ -0,0 +1,2 @@ +#!/bin/bash +exit 0 diff --git a/docker/etc/s6/syslogd/run b/docker/etc/s6/syslogd/run new file mode 100755 index 0000000000..d876093047 --- /dev/null +++ b/docker/etc/s6/syslogd/run @@ -0,0 +1,6 @@ +#!/bin/bash +[[ -f ./setup ]] && source ./setup + +pushd /root > /dev/null + exec gosu root /sbin/syslogd -nS -O- +popd diff --git a/docker/etc/s6/syslogd/setup b/docker/etc/s6/syslogd/setup new file mode 100755 index 0000000000..a9bf588e2f --- /dev/null +++ b/docker/etc/s6/syslogd/setup @@ -0,0 +1 @@ +#!/bin/bash diff --git a/docker/sshd_config b/docker/etc/ssh/sshd_config similarity index 58% rename from docker/sshd_config rename to docker/etc/ssh/sshd_config index 30c4e23c08..991b5196a0 100644 --- a/docker/sshd_config +++ b/docker/etc/ssh/sshd_config @@ -1,16 +1,33 @@ Port 22 +Protocol 2 + AddressFamily any ListenAddress 0.0.0.0 ListenAddress :: -Protocol 2 + LogLevel INFO + +HostKey /data/ssh/ssh_host_ed25519_key HostKey /data/ssh/ssh_host_rsa_key HostKey /data/ssh/ssh_host_dsa_key HostKey /data/ssh/ssh_host_ecdsa_key -HostKey /data/ssh/ssh_host_ed25519_key + +AuthorizedKeysFile .ssh/authorized_keys + +UseDNS no +AllowAgentForwarding no +AllowTcpForwarding no +PrintMotd no +PrintLastLog no + +PermitUserEnvironment yes PermitRootLogin no -AuthorizedKeysFile .ssh/authorized_keys +ChallengeResponseAuthentication no PasswordAuthentication no -UsePrivilegeSeparation no -PermitUserEnvironment yes +PermitEmptyPasswords no + AllowUsers git + +Banner none +Subsystem sftp /usr/lib/ssh/sftp-server +UsePrivilegeSeparation no diff --git a/docker/etc/templates/app.ini b/docker/etc/templates/app.ini new file mode 100644 index 0000000000..0c4b9d6595 --- /dev/null +++ b/docker/etc/templates/app.ini @@ -0,0 +1,24 @@ +[repository] +ROOT = /data/git/repositories + +[repository.upload] +TEMP_PATH = /data/gitea/uploads + +[server] +APP_DATA_PATH = /data/gitea + +[database] +HOST = mysql:3306 +PATH = /data/gitea/gitea.db + +[session] +PROVIDER_CONFIG = /data/gitea/sessions + +[picture] +AVATAR_UPLOAD_PATH = /data/gitea/avatars + +[attachment] +PATH = /data/gitea/attachments + +[log] +ROOT_PATH = /data/gitea/log diff --git a/docker/s6/.s6-svscan/finish b/docker/s6/.s6-svscan/finish deleted file mode 100755 index 3fab7f42e5..0000000000 --- a/docker/s6/.s6-svscan/finish +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -# Cleanup SOCAT services and s6 event folder -rm -rf $(find /app/gogs/docker/s6/ -name 'event') -rm -rf /app/gogs/docker/s6/SOCAT_* diff --git a/docker/s6/crond/down b/docker/s6/crond/down deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docker/s6/crond/run b/docker/s6/crond/run deleted file mode 100755 index 9aa9fb9f27..0000000000 --- a/docker/s6/crond/run +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh -# Crontabs are located by default in /var/spool/cron/crontabs/ -# The default configuration is also calling all the scripts in /etc/periodic/${period} - -if test -f ./setup; then - source ./setup -fi - -exec gosu root /usr/sbin/crond -fS diff --git a/docker/s6/gogs/run b/docker/s6/gogs/run deleted file mode 100755 index 1aa70eb41d..0000000000 --- a/docker/s6/gogs/run +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/sh - -if test -f ./setup; then - source ./setup -fi - -export USER=git -exec gosu $USER /app/gogs/gogs web diff --git a/docker/s6/gogs/setup b/docker/s6/gogs/setup deleted file mode 100755 index 8435e25b6b..0000000000 --- a/docker/s6/gogs/setup +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/sh - -if ! test -d ~git/.ssh; then - mkdir -p ~git/.ssh - chmod 700 ~git/.ssh -fi - -if ! test -f ~git/.ssh/environment; then - echo "GITEA_CUSTOM=${GITEA_CUSTOM}" > ~git/.ssh/environment - chmod 600 ~git/.ssh/environment -fi - -cd /app/gogs - -# Link volumed data with app data -ln -sf /data/gogs/log ./log -ln -sf /data/gogs/data ./data - -# Backward Compatibility with Gogs Container v0.6.15 -ln -sf /data/git /home/git - -chown -R git:git /data /app/gogs ~git/ -chmod 0755 /data /data/gogs ~git/ diff --git a/docker/s6/openssh/run b/docker/s6/openssh/run deleted file mode 100755 index 99172aab69..0000000000 --- a/docker/s6/openssh/run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -if test -f ./setup; then - source ./setup -fi - -exec gosu root /usr/sbin/sshd -D -f /app/gogs/docker/sshd_config diff --git a/docker/s6/openssh/setup b/docker/s6/openssh/setup deleted file mode 100755 index 5333d3c06e..0000000000 --- a/docker/s6/openssh/setup +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/sh - -# Check if host keys are present, else create them -if ! test -f /data/ssh/ssh_host_rsa_key; then - ssh-keygen -q -f /data/ssh/ssh_host_rsa_key -N '' -t rsa -fi - -if ! test -f /data/ssh/ssh_host_dsa_key; then - ssh-keygen -q -f /data/ssh/ssh_host_dsa_key -N '' -t dsa -fi - -if ! test -f /data/ssh/ssh_host_ecdsa_key; then - ssh-keygen -q -f /data/ssh/ssh_host_ecdsa_key -N '' -t ecdsa -fi - -if ! test -f /data/ssh/ssh_host_ed25519_key; then - ssh-keygen -q -f /data/ssh/ssh_host_ed25519_key -N '' -t ed25519 -fi - -# Set correct right to ssh keys -chown -R root:root /data/ssh/* -chmod 0700 /data/ssh -chmod 0600 /data/ssh/* diff --git a/docker/s6/syslogd/run b/docker/s6/syslogd/run deleted file mode 100755 index f7bdbe36d6..0000000000 --- a/docker/s6/syslogd/run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -if test -f ./setup; then - source ./setup -fi - -exec gosu root /sbin/syslogd -nS -O- diff --git a/docker/start.sh b/docker/start.sh deleted file mode 100755 index a54c2a9bfd..0000000000 --- a/docker/start.sh +++ /dev/null @@ -1,65 +0,0 @@ -#!/bin/sh - -create_socat_links() { - # Bind linked docker container to localhost socket using socat - USED_PORT="3000:22" - while read NAME ADDR PORT; do - if test -z "$NAME$ADDR$PORT"; then - continue - elif echo $USED_PORT | grep -E "(^|:)$PORT($|:)" > /dev/null; then - echo "init:socat | Can't bind linked container ${NAME} to localhost, port ${PORT} already in use" 1>&2 - else - SERV_FOLDER=/app/gogs/docker/s6/SOCAT_${NAME}_${PORT} - mkdir -p ${SERV_FOLDER} - CMD="socat -ls TCP4-LISTEN:${PORT},fork,reuseaddr TCP4:${ADDR}:${PORT}" - echo -e "#!/bin/sh\nexec $CMD" > ${SERV_FOLDER}/run - chmod +x ${SERV_FOLDER}/run - USED_PORT="${USED_PORT}:${PORT}" - echo "init:socat | Linked container ${NAME} will be binded to localhost on port ${PORT}" 1>&2 - fi - done << EOT - $(env | sed -En 's|(.*)_PORT_([0-9]+)_TCP=tcp://(.*):([0-9]+)|\1 \3 \4|p') -EOT -} - -cleanup() { - # Cleanup SOCAT services and s6 event folder - # On start and on shutdown in case container has been killed - rm -rf $(find /app/gogs/docker/s6/ -name 'event') - rm -rf /app/gogs/docker/s6/SOCAT_* -} - -create_volume_subfolder() { - # Create VOLUME subfolder - for f in /data/gogs/data /data/gogs/conf /data/gogs/log /data/git /data/ssh; do - if ! test -d $f; then - mkdir -p $f - fi - done -} - -cleanup -create_volume_subfolder - -LINK=$(echo "$SOCAT_LINK" | tr '[:upper:]' '[:lower:]') -if [ "$LINK" = "false" -o "$LINK" = "0" ]; then - echo "init:socat | Will not try to create socat links as requested" 1>&2 -else - create_socat_links -fi - -CROND=$(echo "$RUN_CROND" | tr '[:upper:]' '[:lower:]') -if [ "$CROND" = "true" -o "$CROND" = "1" ]; then - echo "init:crond | Cron Daemon (crond) will be run as requested by s6" 1>&2 - rm -f /app/gogs/docker/s6/crond/down -else - # Tell s6 not to run the crond service - touch /app/gogs/docker/s6/crond/down -fi - -# Exec CMD or S6 by default if nothing present -if [ $# -gt 0 ];then - exec "$@" -else - exec /bin/s6-svscan /app/gogs/docker/s6/ -fi diff --git a/docker/usr/bin/entrypoint b/docker/usr/bin/entrypoint new file mode 100755 index 0000000000..a450d20607 --- /dev/null +++ b/docker/usr/bin/entrypoint @@ -0,0 +1,11 @@ +#!/bin/sh + +for FOLDER in /data/gitea/conf /data/gitea/log /data/git /data/ssh; do + mkdir -p ${FOLDER} +done + +if [ $# -gt 0 ]; then + exec "$@" +else + exec /bin/s6-svscan /etc/s6 +fi From 575dc69e3b3384310e50fff6da227c15f50b3826 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 14:15:14 +0100 Subject: [PATCH 064/135] Updated drone docker definitions In order to automatically build docker images I have re-enabled the docker building parts within our drone runs on every push to master and on every tag. Signed-off-by: Thomas Boerger --- .drone.yml | 28 ++++++++++++++-------------- .drone.yml.sig | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.drone.yml b/.drone.yml index ad99c6ea21..9b858b0731 100644 --- a/.drone.yml +++ b/.drone.yml @@ -50,21 +50,21 @@ pipeline: event: [ push, tag ] branch: [ master, refs/tags/* ] - # docker: - # image: plugins/docker - # repo: gitea/gitea - # tags: [ '${TAG}' ] - # when: - # event: [ tag ] - # branch: [ refs/tags/* ] + docker: + image: plugins/docker + repo: gitea/gitea + tags: [ '${TAG}' ] + when: + event: [ tag ] + branch: [ refs/tags/* ] - # docker: - # image: plugins/docker - # repo: gitea/gitea - # tags: [ 'latest' ] - # when: - # event: [ push ] - # branch: [ master ] + docker: + image: plugins/docker + repo: gitea/gitea + tags: [ 'latest' ] + when: + event: [ push ] + branch: [ master ] release: image: plugins/s3 diff --git a/.drone.yml.sig b/.drone.yml.sig index 998c0e19f3..8e29273f1b 100644 --- a/.drone.yml.sig +++ b/.drone.yml.sig @@ -1 +1 @@ -eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogICMgZG9ja2VyOgogICMgICBpbWFnZTogcGx1Z2lucy9kb2NrZXIKICAjICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAjICAgdGFnczogWyAnJHtUQUd9JyBdCiAgIyAgIHdoZW46CiAgIyAgICAgZXZlbnQ6IFsgdGFnIF0KICAjICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICAjIGRvY2tlcjoKICAjICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgIyAgIHJlcG86IGdpdGVhL2dpdGVhCiAgIyAgIHRhZ3M6IFsgJ2xhdGVzdCcgXQogICMgICB3aGVuOgogICMgICAgIGV2ZW50OiBbIHB1c2ggXQogICMgICAgIGJyYW5jaDogWyBtYXN0ZXIgXQoKICByZWxlYXNlOgogICAgaW1hZ2U6IHBsdWdpbnMvczMKICAgIHBhdGhfc3R5bGU6IHRydWUKICAgIHN0cmlwX3ByZWZpeDogZGlzdC9yZWxlYXNlLwogICAgc291cmNlOiBkaXN0L3JlbGVhc2UvKgogICAgdGFyZ2V0OiAvZ2l0ZWEvbWFzdGVyCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc3RyaXBfcHJlZml4OiBkaXN0L3JlbGVhc2UvCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8qCiAgICB0YXJnZXQ6IC9naXRlYS8kJFRBRwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZ2l0aHViOgogICAgaW1hZ2U6IHBsdWdpbnMvZ2l0aHViLXJlbGVhc2UKICAgIGZpbGVzOgogICAgICAtIGRpc3QvcmVsZWFzZS8qCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBnaXR0ZXI6CiAgICBpbWFnZTogcGx1Z2lucy9naXR0ZXIKCnNlcnZpY2VzOgogIG15c3FsOgogICAgaW1hZ2U6IG15c3FsOjUuNwogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gTVlTUUxfREFUQUJBU0U9dGVzdAogICAgICAtIE1ZU1FMX0FMTE9XX0VNUFRZX1BBU1NXT1JEPXllcwogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCgogIHBnc3FsOgogICAgaW1hZ2U6IHBvc3RncmVzOjkuNQogICAgZW52aXJvbm1lbnQ6CiAgICAgIC0gUE9TVEdSRVNfREI9dGVzdAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCBdCg.CJAqrylL68UPxR-wlKhIL9waJKRhw6isiol_f9Lx5ao \ No newline at end of file +eyJhbGciOiJIUzI1NiJ9.d29ya3NwYWNlOgogIGJhc2U6IC9zcnYvYXBwCiAgcGF0aDogc3JjL2NvZGUuZ2l0ZWEuaW8vZ2l0ZWEKCnBpcGVsaW5lOgogIHRlc3Q6CiAgICBpbWFnZTogd2ViaGlwcGllL2dvbGFuZzplZGdlCiAgICBwdWxsOiB0cnVlCiAgICBlbnZpcm9ubWVudDoKICAgICAgQ0dPX0VOQUJMRUQ6IDEKICAgICAgVEFHUzogY2VydCBzcWxpdGUgcGFtIG1pbml3aW5zdmMKICAgIGNvbW1hbmRzOgogICAgICAtIGFwayAtVSBhZGQgbGludXgtcGFtLWRldiBvcGVuc3NoLWNsaWVudAogICAgICAtIG1ha2UgY2xlYW4KICAgICAgLSBtYWtlIHZldAogICAgICAjIC0gbWFrZSBsaW50CiAgICAgIC0gbWFrZSB0ZXN0CiAgICAgIC0gbWFrZSBidWlsZAogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgcHVzaCwgdGFnLCBwdWxsX3JlcXVlc3QgXQoKICB0ZXN0LW15c3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtbXlzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICB0ZXN0LXBnc3FsOgogICAgaW1hZ2U6IHdlYmhpcHBpZS9nb2xhbmc6ZWRnZQogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgLSBtYWtlIHRlc3QtcGdzcWwKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQoKICBjb3ZlcmFnZToKICAgIGltYWdlOiBwbHVnaW5zL2NvdmVyYWdlCiAgICBzZXJ2ZXI6IGh0dHBzOi8vY292ZXJhZ2UuZ2l0ZWEuaW8KICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2gsIHRhZywgcHVsbF9yZXF1ZXN0IF0KCiAgdXBkYXRlcjoKICAgIGltYWdlOiBrYXJhbGFiZS94Z28tbGF0ZXN0OmxhdGVzdAogICAgcHVsbDogdHJ1ZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSBwdWJsaXNoCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoLCB0YWcgXQogICAgICBicmFuY2g6IFsgbWFzdGVyLCByZWZzL3RhZ3MvKiBdCgogIGRvY2tlcjoKICAgIGltYWdlOiBwbHVnaW5zL2RvY2tlcgogICAgcmVwbzogZ2l0ZWEvZ2l0ZWEKICAgIHRhZ3M6IFsgJyR7VEFHfScgXQogICAgd2hlbjoKICAgICAgZXZlbnQ6IFsgdGFnIF0KICAgICAgYnJhbmNoOiBbIHJlZnMvdGFncy8qIF0KCiAgZG9ja2VyOgogICAgaW1hZ2U6IHBsdWdpbnMvZG9ja2VyCiAgICByZXBvOiBnaXRlYS9naXRlYQogICAgdGFnczogWyAnbGF0ZXN0JyBdCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KICAgICAgYnJhbmNoOiBbIG1hc3RlciBdCgogIHJlbGVhc2U6CiAgICBpbWFnZTogcGx1Z2lucy9zMwogICAgcGF0aF9zdHlsZTogdHJ1ZQogICAgc3RyaXBfcHJlZml4OiBkaXN0L3JlbGVhc2UvCiAgICBzb3VyY2U6IGRpc3QvcmVsZWFzZS8qCiAgICB0YXJnZXQ6IC9naXRlYS9tYXN0ZXIKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHB1c2ggXQogICAgICBicmFuY2g6IFsgbWFzdGVyIF0KCiAgcmVsZWFzZToKICAgIGltYWdlOiBwbHVnaW5zL3MzCiAgICBwYXRoX3N0eWxlOiB0cnVlCiAgICBzdHJpcF9wcmVmaXg6IGRpc3QvcmVsZWFzZS8KICAgIHNvdXJjZTogZGlzdC9yZWxlYXNlLyoKICAgIHRhcmdldDogL2dpdGVhLyQkVEFHCiAgICB3aGVuOgogICAgICBldmVudDogWyB0YWcgXQogICAgICBicmFuY2g6IFsgcmVmcy90YWdzLyogXQoKICBnaXRodWI6CiAgICBpbWFnZTogcGx1Z2lucy9naXRodWItcmVsZWFzZQogICAgZmlsZXM6CiAgICAgIC0gZGlzdC9yZWxlYXNlLyoKICAgIHdoZW46CiAgICAgIGV2ZW50OiBbIHRhZyBdCiAgICAgIGJyYW5jaDogWyByZWZzL3RhZ3MvKiBdCgogIGdpdHRlcjoKICAgIGltYWdlOiBwbHVnaW5zL2dpdHRlcgoKc2VydmljZXM6CiAgbXlzcWw6CiAgICBpbWFnZTogbXlzcWw6NS43CiAgICBlbnZpcm9ubWVudDoKICAgICAgLSBNWVNRTF9EQVRBQkFTRT10ZXN0CiAgICAgIC0gTVlTUUxfQUxMT1dfRU1QVFlfUEFTU1dPUkQ9eWVzCiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0KCiAgcGdzcWw6CiAgICBpbWFnZTogcG9zdGdyZXM6OS41CiAgICBlbnZpcm9ubWVudDoKICAgICAgLSBQT1NUR1JFU19EQj10ZXN0CiAgICB3aGVuOgogICAgICBldmVudDogWyBwdXNoIF0K.W-dU1J1yWsWKPzQp5YvXtNAxoTa-vP_OkmBenzqR00c \ No newline at end of file From 3d2138812cf5cebc986762b3ce099e6b6f370825 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 14:27:59 +0100 Subject: [PATCH 065/135] Unified editorconfig accross all projects --- .editorconfig | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.editorconfig b/.editorconfig index 008b61ed63..12b242448b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,17 +11,17 @@ trim_trailing_whitespace = true indent_style = tab indent_size = 8 -[*.tmpl] -indent_style = tab -indent_size = 2 - -[Makefile] +[*.{tmpl,html}] indent_style = tab +indent_size = 4 [*.{less,yml}] indent_style = space -indent_size = 2 +indent_size = 4 [*.js] indent_style = space indent_size = 4 + +[Makefile] +indent_style = tab From 9628d4fb4405b1d6dfddd43ec8dd65c8dc163424 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 14:28:40 +0100 Subject: [PATCH 066/135] Unified GitHub templates accross all projects --- .github/ISSUE_TEMPLATE.md | 24 ------------------------ .github/PULL_REQUEST_TEMPLATE.md | 10 ---------- .github/issue_template.md | 19 +++++++++++++++++++ .github/pull_request_template.md | 7 +++++++ 4 files changed, 26 insertions(+), 34 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE.md delete mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/issue_template.md create mode 100644 .github/pull_request_template.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f5fb775bd9..0000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,24 +0,0 @@ - -1. Please speak English -2. Please ask questions or config/deploy problems - on our gitter channel: https://gitter.im/go-gitea/gitea - Here are bugs and feature requests only. -3. Please take a moment to search that an issue doesn't already exist. -4. Please give all relevant information below for bug reports; incomplete - details considered invalid report. - -**You MUST delete above content including this line before posting; -too lazy to take this action considered invalid report.** - -- Gitea version (or commit ref): -- Git version: -- Operating system: -- Database (use `[x]`): - - [ ] PostgreSQL - - [ ] MySQL - - [ ] SQLite -- Log gist: - -## Description - -... diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 380150422f..0000000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,10 +0,0 @@ -Please check the following: - -1. Make sure you are targeting the `master` branch. -2. Read contributing guidelines: - https://github.com/go-gitea/gitea/blob/master/CONTRIBUTING.md -3. Describe what your pull request does and which issue - you're targeting (if any) - -**You MUST delete above content including this line before posting; -too lazy to take this action considered invalid pull request.** diff --git a/.github/issue_template.md b/.github/issue_template.md new file mode 100644 index 0000000000..ec619ded50 --- /dev/null +++ b/.github/issue_template.md @@ -0,0 +1,19 @@ +1. Please speak English, this is the language everybody of us can speak and write. +2. Please ask questions or config/deploy problems on our Gitter channel: https://gitter.im/go-gitea/gitea +3. Please take a moment to search that an issue doesn't already exist. +4. Please give all relevant information below for bug reports, incomplete details will be handled as an invalid report. + +**You MUST delete the content above including this line before posting, otherwise your pull request will be invalid.** + +- Gitea version (or commit ref): +- Git version: +- Operating system: +- Database (use `[x]`): + - [ ] PostgreSQL + - [ ] MySQL + - [ ] SQLite +- Log gist: + +## Description + +... diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..702062490d --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,7 @@ +Please check the following: + +1. Make sure you are targeting the `master` branch, pull requests on release branches are only allowed for bug fixes. +2. Read contributing guidelines: https://github.com/go-gitea/gitea/blob/master/CONTRIBUTING.md +3. Describe what your pull request does and which issue you're targeting (if any) + +**You MUST delete the content above including this line before posting, otherwise your pull request will be invalid.** From 7b6cc9244d227c4df810ec6b3389d64eb3046121 Mon Sep 17 00:00:00 2001 From: Matthias Loibl Date: Mon, 28 Nov 2016 14:29:39 +0100 Subject: [PATCH 067/135] =?UTF-8?q?Update=20link=20on=20user=E2=80=99s=20p?= =?UTF-8?q?rofile=20avatar=20to=20avatar=20settings=20(#287)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- templates/user/profile.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/user/profile.tmpl b/templates/user/profile.tmpl index a7edd88c6d..59989f3830 100644 --- a/templates/user/profile.tmpl +++ b/templates/user/profile.tmpl @@ -5,7 +5,7 @@
{{if eq .SignedUserName .Owner.Name}} - + {{else}} From 9fc609ce1717682d85d191002d6f9e15b7c6bdaa Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 28 Nov 2016 21:33:09 +0800 Subject: [PATCH 068/135] golint fixed for models/issue_comment.go --- models/issue_comment.go | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/models/issue_comment.go b/models/issue_comment.go index c7aa7e2b13..f0fc22af34 100644 --- a/models/issue_comment.go +++ b/models/issue_comment.go @@ -21,6 +21,7 @@ import ( // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference. type CommentType int +// Enumerate all the comment types const ( // Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0) CommentTypeComment CommentType = iota @@ -37,8 +38,10 @@ const ( CommentTypePullRef ) +// CommentTag defines comment tag type type CommentTag int +// Enumerate all the comment tag types const ( CommentTagNone CommentTag = iota CommentTagPoster @@ -72,15 +75,19 @@ type Comment struct { ShowTag CommentTag `xorm:"-"` } +// BeforeInsert will be invoked by XORM before inserting a record +// representing this object. func (c *Comment) BeforeInsert() { c.CreatedUnix = time.Now().Unix() c.UpdatedUnix = c.CreatedUnix } +// BeforeUpdate is invoked from XORM before updating this object. func (c *Comment) BeforeUpdate() { c.UpdatedUnix = time.Now().Unix() } +// AfterSet is invoked from XORM after setting the value of a field of this object. func (c *Comment) AfterSet(colName string, _ xorm.Cell) { var err error switch colName { @@ -107,6 +114,7 @@ func (c *Comment) AfterSet(colName string, _ xorm.Cell) { } } +// AfterDelete is invoked from XORM after the object is deleted. func (c *Comment) AfterDelete() { _, err := DeleteAttachmentsByComment(c.ID, true) @@ -115,6 +123,7 @@ func (c *Comment) AfterDelete() { } } +// APIFormat converts a Comment to the api.Comment format func (c *Comment) APIFormat() *api.Comment { return &api.Comment{ ID: c.ID, @@ -137,21 +146,21 @@ func (c *Comment) EventTag() string { // MailParticipants sends new comment emails to repository watchers // and mentioned people. -func (cmt *Comment) MailParticipants(opType ActionType, issue *Issue) (err error) { - mentions := markdown.FindAllMentions(cmt.Content) - if err = UpdateIssueMentions(cmt.IssueID, mentions); err != nil { - return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err) +func (c *Comment) MailParticipants(opType ActionType, issue *Issue) (err error) { + mentions := markdown.FindAllMentions(c.Content) + if err = UpdateIssueMentions(c.IssueID, mentions); err != nil { + return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err) } switch opType { case ActionCommentIssue: - issue.Content = cmt.Content + issue.Content = c.Content case ActionCloseIssue: issue.Content = fmt.Sprintf("Closed #%d", issue.Index) case ActionReopenIssue: issue.Content = fmt.Sprintf("Reopened #%d", issue.Index) } - if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil { + if err = mailIssueCommentToParticipants(issue, c.Poster, mentions); err != nil { log.Error(4, "mailIssueCommentToParticipants: %v", err) } @@ -272,6 +281,7 @@ func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *I }) } +// CreateCommentOptions defines options for creating comment type CreateCommentOptions struct { Type CommentType Doer *User @@ -374,7 +384,7 @@ func GetCommentsByIssueID(issueID int64) ([]*Comment, error) { return getCommentsByIssueID(x, issueID) } -// GetCommentsByIssueID returns a list of comments of an issue since a given time point. +// GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) { return getCommentsByIssueIDSince(x, issueID, since) } From c2044e5b394ddfc2fe402c9f3936f9235e59519f Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 14:34:06 +0100 Subject: [PATCH 069/135] Dropped always outdated contributors file, link to it the graph on readme --- CONTRIBUTORS | 9 --------- README.md | 13 +++++++++---- 2 files changed, 9 insertions(+), 13 deletions(-) delete mode 100644 CONTRIBUTORS diff --git a/CONTRIBUTORS b/CONTRIBUTORS deleted file mode 100644 index 65db519453..0000000000 --- a/CONTRIBUTORS +++ /dev/null @@ -1,9 +0,0 @@ -Andrey Nering (@andreynering) -Kim Carlbäcker (@bkcsoft) -LefsFlare (@LefsFlarey) -Lunny Xiao (@lunny) -Rachid Zarouali (@xinity) -Rémy Boulanouar (@DblK) -Sandro Santilli (@strk) -Thibault Meyer (@0xbaadf00d) -Thomas Boerger (@tboerger) diff --git a/README.md b/README.md index 414d7e23f0..1fb4897859 100644 --- a/README.md +++ b/README.md @@ -122,11 +122,16 @@ How to install Gitea: - Thanks [DigitalOcean](https://www.digitalocean.com) for hosting home and demo sites. - Thanks [KeyCDN](https://www.keycdn.com/) and [QiNiu](http://www.qiniu.com/) for providing CDN service. -## Contributors -- See [Maintainer](https://github.com/orgs/go-gitea/people) -- See [Contributors](https://github.com/go-gitea/gitea/graphs/contributors) for full list of contributors. -- See [Translators](conf/locale/TRANSLATORS) for public list of translators. +## Contributing + +Fork -> Patch -> Push -> Pull Request + +## Authors + +* [Maintainers](https://github.com/orgs/go-gitea/people) +* [Contributors](https://github.com/go-gitea/gitea/graphs/contributors) +* [Translators](conf/locale/TRANSLATORS) ## License From caac5fb99d70e6c2ca551d9bcb36c54e724a91ad Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 14:35:04 +0100 Subject: [PATCH 070/135] Updated maintainers file to latest status --- MAINTAINERS | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 9a54274d77..3b18bcb599 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -1,4 +1,6 @@ -Andrey Nering (@andreynering) +Alexey Makhov (@makhov) +Andrey Nering (@andreynering) +Bwko (@Bwko) Kim Carlbäcker (@bkcsoft) LefsFlare (@LefsFlarey) Lunny Xiao (@lunny) @@ -6,5 +8,5 @@ Matthias Loibl (@metalmatze) Rachid Zarouali (@xinity) Rémy Boulanouar (@DblK) Sandro Santilli (@strk) -Thibault Meyer (@0xbaadf00d) +Thibault Meyer (@0xbaadf00d) Thomas Boerger (@tboerger) From 91d6c715ea3323cd4b06d21c1aae20364a47a2a0 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 14:35:55 +0100 Subject: [PATCH 071/135] Dropped new lines from contributing, some rewording and reformatting --- CONTRIBUTING.md | 156 ++++++++---------------------------------------- 1 file changed, 25 insertions(+), 131 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 752e02015f..fc0b240af2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,185 +2,79 @@ ## Introduction -This document explains how to contribute changes to the Gitea -project. It assumes you have followed the [installation -instructions](https://github.com/go-gitea/docs/tree/master/en-US/installation) - -Sensitive security-related issues should be reported to -[security@gitea.io](mailto:security@gitea.io). +This document explains how to contribute changes to the Gitea project. It assumes you have followed the [installation instructions](https://github.com/go-gitea/docs/tree/master/en-US/installation). Sensitive security-related issues should be reported to [security@gitea.io](mailto:security@gitea.io). ## Bug reports -Please search the issues on the issue tracker with a variety of keywords -to ensure your bug is not already reported. +Please search the issues on the issue tracker with a variety of keywords to ensure your bug is not already reported. -If unique, [open an issue](https://github.com/go-gitea/gitea/issues/new) -and answer the questions so we can understand and reproduce the -problematic behavior. +If unique, [open an issue](https://github.com/go-gitea/gitea/issues/new) and answer the questions so we can understand and reproduce the problematic behavior. -The burden is on you to convince us that it is actually a bug -in Gitea. This is easiest to do when you write clear, concise -instructions so we can reproduce the behavior (even if it seems -obvious). The more detailed and specific you are, the faster -we will be able to help you. Check out [How to Report Bugs -Effectively](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html). +The burden is on you to convince us that it is actually a bug in Gitea. This is easiest to do when you write clear, concise instructions so we can reproduce the behavior (even if it seems obvious). The more detailed and specific you are, the faster we will be able to help you. Check out [How to Report Bugs Effectively](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html). -Please be kind, remember that Gitea comes at no cost to you, and you're -getting free help. +Please be kind, remember that Gitea comes at no cost to you, and you're getting free help. ## Discuss your design -The project welcomes submissions but please let everyone know what -you're working on if you want to change or add something to the Gitea -repositories. +The project welcomes submissions but please let everyone know what you're working on if you want to change or add something to the Gitea repositories. -Before starting to write something new for the Gitea project, please -[file an issue](https://github.com/go-gitea/gitea/issues/new). -Significant changes must go through the [change proposal -process](https://github.com/go-gitea/proposals) before they can be -accepted. +Before starting to write something new for the Gitea project, please [file an issue](https://github.com/go-gitea/gitea/issues/new). Significant changes must go through the [change proposal process](https://github.com/go-gitea/proposals) before they can be accepted. -This process gives everyone a chance to validate the design, helps -prevent duplication of effort, and ensures that the idea fits inside -the goals for the project and tools. It also checks that the design is -sound before code is written; the code review tool is not the place for -high-level discussions. +This process gives everyone a chance to validate the design, helps prevent duplication of effort, and ensures that the idea fits inside the goals for the project and tools. It also checks that the design is sound before code is written; the code review tool is not the place for high-level discussions. ## Testing redux -Before sending code out for review, run all the tests for the whole -tree to make sure the changes don't break other usage and keep the -compatibility on upgrade: - -After running for a while, the command should print - -``` -ALL TESTS PASSED -``` -## Vendoring - -We keep a cached copy of dependencies within the `vendor/` directory, -managing updates via [govendor](http://github.com/kardianos/govendor). - -Pull requests should only include `vendor/` updates if they are -part of the same change, be it a bugfix or a feature addition. - -The `vendor/` update needs to be justified as part of the PR description, -and must be verified by the reviewers and/or merger to always reference -an existing upstream commit. +Before sending code out for review, run all the tests for the whole tree to make sure the changes don't break other usage and keep the compatibility on upgrade. To make sure you are running the test suite exactly like we do you should install the CLI for [Drone CI](https://github.com/drone/drone) as we are using the server for continous testing, follow [these instructions](http://readme.drone.io/0.5/install/cli/). After that you can simply call `drone exec` within you working directory and it will try to run the test suite locally. ## Code review -Changes to Gitea must be reviewed before they are accepted, no matter -who makes the change even if an owners or a maintainer. We use github's -pull request workflow to do that and use [lgtm](http://lgtm.co) to ensure -every PR is reviewed by at least 2 maintainers. - -Please try to make your pull request easy to review for us. Please read the -["How to get faster PR reviews"](https://github.com/kubernetes/kubernetes/blob/master/docs/devel/faster_reviews.md), -guide, it got useful tips for any project you may want to contribute. See some -of the points: - -- Make small pull requests. The smaller, the faster to review and the more - likely it will be merged soon. -- Don't make changes unrelated to your PR. Maybe there are typos on some - comments, maybe refactoring would welcome on a function... but if that is not - related to you PR, please make *another* PR for that. -- Split big pull requests in multiple. An incremental change will be faster to - review than a huge PR. +Changes to Gitea must be reviewed before they are accepted, no matter who makes the change even if an owner or a maintainer. We use GitHub's pull request workflow to do that and we also use [LGTM](http://lgtm.co) to ensure every PR is reviewed by at least 2 maintainers. ## Sign your work -The sign-off is a simple line at the end of the explanation for the -patch. Your signature certifies that you wrote the patch or otherwise -have the right to pass it on as an open-source patch. The rules are -pretty simple: If you can certify [DCO](DCO), then you just add a line -to every git commit message: +The sign-off is a simple line at the end of the explanation for the patch. Your signature certifies that you wrote the patch or otherwise have the right to pass it on as an open-source patch. The rules are pretty simple: If you can certify [DCO](DCO), then you just add a line to every git commit message: ``` Signed-off-by: Joe Smith ``` -Please use your real name, we really dislike pseudonyms or anonymous -contributions. We are in the opensource world without secrets. If you -set your `user.name` and `user.email` git configs, you can sign your -commit automatically with `git commit -s`. - -## Contributors - -Everyone who sent a PR to Gitea that gets accepted will -be as a contributor. Please send a PR to add your name to -[CONTRIBUTORS](CONTRIBUTORS). For the format, see the -[CONTRIBUTORS](CONTRIBUTORS). +Please use your real name, we really dislike pseudonyms or anonymous contributions. We are in the opensource world without secrets. If you set your `user.name` and `user.email` git configs, you can sign your commit automatically with `git commit -s`. ## Maintainers -To make sure every PR have been checked, we make a team maintainers. Any -PR MUST be reviewed and by at least two maintainers before it can -get merged. Maintainers should be a contributor of gitea(or gogs) and -contributed at least 4 accepted PRs. And a contributor should apply as a -maintainer in [gitter Gitea develop](https://gitter.im/go-gitea/develop). -And the owners or the team maintainer could invite the contributor. A -maintainer should spend some time on code reviews. If some maintainer -have no time to do that, he should apply to leave maintainers team and -we will give him an honor to be as a member of advisor team. Of course, -if an advisor have time to code view, welcome it back to maintainers team. -If some one have no time to code view and forget to leave the maintainers, -the owners have the power to move him from maintainers team to advisors -team. +To make sure every PR have been checked, we got team maintainers. Any PR MUST be reviewed and by at least two maintainers before it can get merged. Maintainers should be a contributor of Gitea (or Gogs) and contributed at least 4 accepted PRs. A contributor should apply as a maintainer in [Gitter development channel](https://gitter.im/go-gitea/develop). The owners or the team maintainers could invite the contributor. A maintainer should spend some time on code reviews. If some maintainer have no time to do that, he should apply to leave the maintainers team and we will give him an honor to be as a member of advisor team. Of course, if an advisor have time to code view, welcome it back to maintainers team. If someone have no time to code review and forget to leave the maintainers team, the owners have the power to move him from maintainers team to advisors team. ## Owners -Since Gitea is a pure community organization without any company -support, to keep the development healthly We will elect the owners every -year. Every time we will elect three owners. All the contributers could -vote for three owners, one is the main owner, the other two are assistant -owners. When the new owners have been elected, the old owners MUST move -the power to the new owners. If some owner don't obey these rules, -the other owners are allowed to revoke his owner status. +Since Gitea is a pure community organization without any company support, to keep the development healthly we will elect the owners every year. Every time we will elect three owners. All the contributers could vote for three owners, one is the main owner, the other two are assistant owners. When the new owners have been elected, the old owners MUST move the power to the new owners. If some owner don't obey these rules, the other owners are allowed to revoke his owner status. -After the election, the new owners should say he agrees with these -rules on the [CONTRIBUTING](CONTRIBUTING.md) on the [Gitter Gitea -Channel](https://gitter.im/go-gitea/gitea). Below is the word to speak +After the election, the new owners should say he agrees with these rules on the [CONTRIBUTING](CONTRIBUTING.md) on the [Gitter main channel](https://gitter.im/go-gitea/gitea). Below are the words to speak: ``` -I'm glad to be an owner of Gitea, -I agree with [CONTRIBUTING](CONTRIBUTING.md). -I will spend part of my time on gitea -and lead the development of gitea. +I'm glad to be an owner of Gitea, I agree with [CONTRIBUTING](CONTRIBUTING.md). I will spend part of my time on Gitea and lead the development of Gitea. ``` -For a honor to the owners, this document will add the history owners -below: - -2016-11-04 ~ 2017-12-31 +For a honor to the owners, this document will add the history owners below: -- lunny -- tboerger -- bkcsoft +* 2016-11-04 ~ 2017-12-31 + * [Lunny Xiao](https://github.com/lunny) + * [Thomas Boerger](https://github.com/tboerger) + * [Kim Carlbäcker](https://github.com/bkcsoft) ## Versions -Gitea has one master as a tip branch and have many version branch -such as v0.9. v0.9 is a release branch and we will tag v0.9.0 both for -binary download. If v0.9.0 have some bugs, we will accept PR on v0.9 -and publish v0.9.1 and merge bug PR to master. +Gitea has one master as a tip branch and have version branches such as `v0.9`. `v0.9` is a release branch and we will tag `v0.9.0` for binary download. If `v0.9.0` got some bug, we will accept pull requests on the `v0.9` branch and publish a `v0.9.1` tag, afterwards we will port the bug fix also to the master branch. -Branch master is a tip version, so if you wish a production usage, -please download the latest release tag version. All the branch will be -protected via github, All the PRs to all the branches should be review -by two maintainers and pass the automatic tests. +The `master` branch is a tip version, so if you wish a production usage, please download the latest release tag version. All the branches will be protected via github, all the PRs to all the branches should be review by two maintainers and pass the automatic tests. ## Copyright Code that you contribute should use the standard copyright header: ``` -// Copyright 2016 - 2017 The Gitea Authors. All rights reserved. +// Copyright 2016 The Gitea Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. ``` -Files in the repository are copyright the year they are added and the -year they are last changed. If the copyright author is changed, just -copy the head below the old one. +Files in the repository are copyright the year they are added and the year they are last changed. If the copyright author is changed, just copy the head below the old one. From b3abc2775f7b7d1815c7776eee26982f4c49a638 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 14:36:35 +0100 Subject: [PATCH 072/135] Dropped more or less useless files --- .gitattributes | 11 ----------- .mailmap | 2 -- 2 files changed, 13 deletions(-) delete mode 100644 .gitattributes delete mode 100644 .mailmap diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 09dfc210fc..0000000000 --- a/.gitattributes +++ /dev/null @@ -1,11 +0,0 @@ -public/conf/gitignore/* linguist-vendored -public/conf/license/* linguist-vendored -public/assets/* linguist-vendored -public/plugins/* linguist-vendored -public/plugins/* linguist-vendored -public/css/themes/* linguist-vendored -public/css/github.min.css linguist-vendored -public/css/semantic-2.2.1.min.css linguist-vendored -public/js/libs/* linguist-vendored -public/js/jquery-1.11.3.min.js linguist-vendored -public/js/semantic-2.2.1.min.js linguist-vendored \ No newline at end of file diff --git a/.mailmap b/.mailmap deleted file mode 100644 index 88ff1591a4..0000000000 --- a/.mailmap +++ /dev/null @@ -1,2 +0,0 @@ -Unknwon -Unknwon 无闻 From 1d0f811399439ae3952d2f80c11a6cb478655d35 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 28 Nov 2016 23:31:06 +0800 Subject: [PATCH 073/135] golint fixed for models/pull.go (#292) --- models/pull.go | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/models/pull.go b/models/pull.go index 5d32c71766..f2eb895960 100644 --- a/models/pull.go +++ b/models/pull.go @@ -21,17 +21,21 @@ import ( "github.com/go-xorm/xorm" ) -var PullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength) +var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength) +// PullRequestType defines pull request type type PullRequestType int +// Enumerate all the pull request types const ( PullRequestGitea PullRequestType = iota PullRequestGit ) +// PullRequestStatus defines pull request status type PullRequestStatus int +// Enumerate all the pull request status const ( PullRequestStatusConflict PullRequestStatus = iota PullRequestStatusChecking @@ -65,10 +69,12 @@ type PullRequest struct { MergedUnix int64 } +// BeforeUpdate is invoked from XORM before updating an object of this type. func (pr *PullRequest) BeforeUpdate() { pr.MergedUnix = pr.Merged.Unix() } +// AfterSet is invoked from XORM after setting the value of a field of this object. // Note: don't try to get Issue because will end up recursive querying. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) { switch colName { @@ -96,10 +102,12 @@ func (pr *PullRequest) loadAttributes(e Engine) (err error) { return nil } +// LoadAttributes loads pull request attributes from database func (pr *PullRequest) LoadAttributes() error { return pr.loadAttributes(x) } +// LoadIssue loads issue information from database func (pr *PullRequest) LoadIssue() (err error) { if pr.Issue != nil { return nil @@ -109,7 +117,7 @@ func (pr *PullRequest) LoadIssue() (err error) { return err } -// This method assumes following fields have been assigned with valid values: +// APIFormat assumes following fields have been assigned with valid values: // Required - Issue // Optional - Merger func (pr *PullRequest) APIFormat() *api.PullRequest { @@ -150,10 +158,12 @@ func (pr *PullRequest) getHeadRepo(e Engine) (err error) { return nil } +// GetHeadRepo loads the head repository func (pr *PullRequest) GetHeadRepo() error { return pr.getHeadRepo(x) } +// GetBaseRepo loads the target repository func (pr *PullRequest) GetBaseRepo() (err error) { if pr.BaseRepo != nil { return nil @@ -538,7 +548,7 @@ func (pr *PullRequest) Update() error { return err } -// Update updates specific fields of pull request. +// UpdateCols updates specific fields of pull request. func (pr *PullRequest) UpdateCols(cols ...string) error { _, err := x.Id(pr.ID).Cols(cols...).Update(pr) return err @@ -623,7 +633,7 @@ func (pr *PullRequest) PushToBaseRepo() (err error) { // AddToTaskQueue adds itself to pull request test task queue. func (pr *PullRequest) AddToTaskQueue() { - go PullRequestQueue.AddFunc(pr.ID, func() { + go pullRequestQueue.AddFunc(pr.ID, func() { pr.Status = PullRequestStatusChecking if err := pr.UpdateCols("status"); err != nil { log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err) @@ -631,6 +641,7 @@ func (pr *PullRequest) AddToTaskQueue() { }) } +// PullRequestList defines a list of pull requests type PullRequestList []*PullRequest func (prs PullRequestList) loadAttributes(e Engine) error { @@ -661,6 +672,7 @@ func (prs PullRequestList) loadAttributes(e Engine) error { return nil } +// LoadAttributes load all the prs attributes func (prs PullRequestList) LoadAttributes() error { return prs.loadAttributes(x) } @@ -730,6 +742,7 @@ func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool } } +// ChangeUsernameInPullRequests changes the name of head_user_name func ChangeUsernameInPullRequests(oldUserName, newUserName string) error { pr := PullRequest{ HeadUserName: strings.ToLower(newUserName), @@ -750,7 +763,7 @@ func (pr *PullRequest) checkAndUpdateStatus() { } // Make sure there is no waiting test to process before levaing the checking status. - if !PullRequestQueue.Exist(pr.ID) { + if !pullRequestQueue.Exist(pr.ID) { if err := pr.UpdateCols("status"); err != nil { log.Error(4, "Update[%d]: %v", pr.ID, err) } @@ -786,9 +799,9 @@ func TestPullRequests() { } // Start listening on new test requests. - for prID := range PullRequestQueue.Queue() { + for prID := range pullRequestQueue.Queue() { log.Trace("TestPullRequests[%v]: processing test task", prID) - PullRequestQueue.Remove(prID) + pullRequestQueue.Remove(prID) pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64()) if err != nil { @@ -803,6 +816,7 @@ func TestPullRequests() { } } +// InitTestPullRequests runs the task to test all the checking status pull requests func InitTestPullRequests() { go TestPullRequests() } From 27d66855eb642b22852b557cbb8ffd7781d73d4e Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 28 Nov 2016 23:44:17 +0800 Subject: [PATCH 074/135] golint fixed for models/migrations (#291) --- models/migrations/migrations.go | 62 ++++++++++++++++++++++++++------- models/migrations/v14.go | 2 ++ 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 957af42661..9c37da4a3a 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -25,8 +25,9 @@ import ( "code.gitea.io/gitea/modules/setting" ) -const _MIN_DB_VER = 4 +const minDBVersion = 4 +// Migration describes on migration from lower version to high version type Migration interface { Description() string Migrate(*xorm.Engine) error @@ -37,19 +38,22 @@ type migration struct { migrate func(*xorm.Engine) error } +// NewMigration creates a new migration func NewMigration(desc string, fn func(*xorm.Engine) error) Migration { return &migration{desc, fn} } +// Description returns the migration's description func (m *migration) Description() string { return m.description } +// Migrate executes the migration func (m *migration) Migrate(x *xorm.Engine) error { return m.migrate(x) } -// The version table. Should have only one row with id==1 +// Version describes the version table. Should have only one row with id==1 type Version struct { ID int64 `xorm:"pk autoincr"` Version int64 @@ -57,11 +61,11 @@ type Version struct { // This is a sequence of migrations. Add new migrations to the bottom of the list. // If you want to "retire" a migration, remove it from the top of the list and -// update _MIN_VER_DB accordingly +// update minDBVersion accordingly var migrations = []Migration{ // v0 -> v4: before 0.6.0 -> 0.7.33 NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0 - NewMigration("trim action compare URL prefix", trimCommitActionAppUrlPrefix), // V5 -> V6:v0.6.3 + NewMigration("trim action compare URL prefix", trimCommitActionAppURLPrefix), // V5 -> V6:v0.6.3 NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4 NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4 NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16 @@ -89,7 +93,7 @@ func Migrate(x *xorm.Engine) error { } else if !has { // If the version record does not exist we think // it is a fresh installation and we can skip all migrations. - currentVersion.Version = int64(_MIN_DB_VER + len(migrations)) + currentVersion.Version = int64(minDBVersion + len(migrations)) if _, err = x.InsertOne(currentVersion); err != nil { return fmt.Errorf("insert: %v", err) @@ -97,19 +101,19 @@ func Migrate(x *xorm.Engine) error { } v := currentVersion.Version - if _MIN_DB_VER > v { + if minDBVersion > v { log.Fatal(4, `Gogs no longer supports auto-migration from your previously installed version. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`) return nil } - if int(v-_MIN_DB_VER) > len(migrations) { + if int(v-minDBVersion) > len(migrations) { // User downgraded Gogs. - currentVersion.Version = int64(len(migrations) + _MIN_DB_VER) + currentVersion.Version = int64(len(migrations) + minDBVersion) _, err = x.Id(1).Update(currentVersion) return err } - for i, m := range migrations[v-_MIN_DB_VER:] { + for i, m := range migrations[v-minDBVersion:] { log.Info("Migration: %s", m.Description()) if err = m.Migrate(x); err != nil { return fmt.Errorf("do migrate: %v", err) @@ -144,7 +148,7 @@ func fixLocaleFileLoadPanic(_ *xorm.Engine) error { return nil } -func trimCommitActionAppUrlPrefix(x *xorm.Engine) error { +func trimCommitActionAppURLPrefix(x *xorm.Engine) error { type PushCommit struct { Sha1 string Message string @@ -155,7 +159,7 @@ func trimCommitActionAppUrlPrefix(x *xorm.Engine) error { type PushCommits struct { Len int Commits []*PushCommit - CompareUrl string + CompareURL string `json:"CompareUrl"` } type Action struct { @@ -186,11 +190,11 @@ func trimCommitActionAppUrlPrefix(x *xorm.Engine) error { return fmt.Errorf("unmarshal action content[%d]: %v", actID, err) } - infos := strings.Split(pushCommits.CompareUrl, "/") + infos := strings.Split(pushCommits.CompareURL, "/") if len(infos) <= 4 { continue } - pushCommits.CompareUrl = strings.Join(infos[len(infos)-4:], "/") + pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/") p, err := json.Marshal(pushCommits) if err != nil { @@ -463,27 +467,34 @@ func generateOrgRandsAndSalt(x *xorm.Engine) (err error) { return sess.Commit() } +// TAction defines the struct for migrating table action type TAction struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TAction) TableName() string { return "action" } +// TNotice defines the struct for migrating table notice type TNotice struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TNotice) TableName() string { return "notice" } +// TComment defines the struct for migrating table comment type TComment struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TComment) TableName() string { return "comment" } +// TIssue defines the struct for migrating table issue type TIssue struct { ID int64 `xorm:"pk autoincr"` DeadlineUnix int64 @@ -491,99 +502,124 @@ type TIssue struct { UpdatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TIssue) TableName() string { return "issue" } +// TMilestone defines the struct for migrating table milestone type TMilestone struct { ID int64 `xorm:"pk autoincr"` DeadlineUnix int64 ClosedDateUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TMilestone) TableName() string { return "milestone" } +// TAttachment defines the struct for migrating table attachment type TAttachment struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TAttachment) TableName() string { return "attachment" } +// TLoginSource defines the struct for migrating table login_source type TLoginSource struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 UpdatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TLoginSource) TableName() string { return "login_source" } +// TPull defines the struct for migrating table pull_request type TPull struct { ID int64 `xorm:"pk autoincr"` MergedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TPull) TableName() string { return "pull_request" } +// TRelease defines the struct for migrating table release type TRelease struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TRelease) TableName() string { return "release" } +// TRepo defines the struct for migrating table repository type TRepo struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 UpdatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TRepo) TableName() string { return "repository" } +// TMirror defines the struct for migrating table mirror type TMirror struct { ID int64 `xorm:"pk autoincr"` UpdatedUnix int64 NextUpdateUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TMirror) TableName() string { return "mirror" } +// TPublicKey defines the struct for migrating table public_key type TPublicKey struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 UpdatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TPublicKey) TableName() string { return "public_key" } +// TDeployKey defines the struct for migrating table deploy_key type TDeployKey struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 UpdatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TDeployKey) TableName() string { return "deploy_key" } +// TAccessToken defines the struct for migrating table access_token type TAccessToken struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 UpdatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TAccessToken) TableName() string { return "access_token" } +// TUser defines the struct for migrating table user type TUser struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 UpdatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TUser) TableName() string { return "user" } +// TWebhook defines the struct for migrating table webhook type TWebhook struct { ID int64 `xorm:"pk autoincr"` CreatedUnix int64 UpdatedUnix int64 } +// TableName will be invoked by XORM to customrize the table name func (t *TWebhook) TableName() string { return "webhook" } func convertDateToUnix(x *xorm.Engine) (err error) { diff --git a/models/migrations/v14.go b/models/migrations/v14.go index 0cdcf1005f..12ae6290b1 100644 --- a/models/migrations/v14.go +++ b/models/migrations/v14.go @@ -23,10 +23,12 @@ func setCommentUpdatedWithCreated(x *xorm.Engine) (err error) { return nil } +// UserV14 describes the added fields for migrating from v13 -> v14 type UserV14 struct { DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"` } +// TableName will be invoked by XORM to customrize the table name func (*UserV14) TableName() string { return "user" } From 8def53ffcce755db5c9ef7e160f202fe576fa586 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 16:57:42 +0100 Subject: [PATCH 075/135] Add a pragraph to the k8s PR guide to contributors guide --- CONTRIBUTING.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc0b240af2..11e0d73d4f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,6 +30,12 @@ Before sending code out for review, run all the tests for the whole tree to make Changes to Gitea must be reviewed before they are accepted, no matter who makes the change even if an owner or a maintainer. We use GitHub's pull request workflow to do that and we also use [LGTM](http://lgtm.co) to ensure every PR is reviewed by at least 2 maintainers. +Please try to make your pull request easy to review for us. Please read the "[How to get faster PR reviews](https://github.com/kubernetes/kubernetes/blob/master/docs/devel/faster_reviews.md)" guide, it got useful tips for any project you may want to contribute. See some of the points: + +* Make small pull requests. The smaller, the faster to review and the more likely it will be merged soon. +* Don't make changes unrelated to your PR. Maybe there are typos on some comments, maybe refactoring would welcome on a function... but if that is not related to you PR, please make *another* PR for that. +* Split big pull requests in multiple. An incremental change will be faster to review than a huge PR. + ## Sign your work The sign-off is a simple line at the end of the explanation for the patch. Your signature certifies that you wrote the patch or otherwise have the right to pass it on as an open-source patch. The rules are pretty simple: If you can certify [DCO](DCO), then you just add a line to every git commit message: From 65d0426b915472bd680788158d0c66bbbec9716e Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 17:16:13 +0100 Subject: [PATCH 076/135] Use su-exec instead of gosu, much smaller --- Dockerfile | 6 +++--- Dockerfile.rpi | 6 +++--- docker/etc/s6/gitea/run | 2 +- docker/etc/s6/openssh/run | 2 +- docker/etc/s6/syslogd/run | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Dockerfile b/Dockerfile index df363e07fb..fd25c88346 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,9 +3,9 @@ MAINTAINER Thomas Boerger EXPOSE 22 3000 -RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories && \ - apk -U add \ - gosu@testing \ +RUN apk update && \ + apk add \ + su-exec \ shadow \ ca-certificates \ sqlite \ diff --git a/Dockerfile.rpi b/Dockerfile.rpi index 6a168c3a5b..d237a63ba0 100644 --- a/Dockerfile.rpi +++ b/Dockerfile.rpi @@ -3,9 +3,9 @@ MAINTAINER Thomas Boerger EXPOSE 22 3000 -RUN echo "@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories && \ - apk -U add \ - gosu@testing \ +RUN apk update && \ + apk add \ + su-exec \ shadow \ ca-certificates \ sqlite \ diff --git a/docker/etc/s6/gitea/run b/docker/etc/s6/gitea/run index 246e74d27c..1fddb93708 100755 --- a/docker/etc/s6/gitea/run +++ b/docker/etc/s6/gitea/run @@ -2,5 +2,5 @@ [[ -f ./setup ]] && source ./setup pushd /app/gitea > /dev/null - exec gosu git /app/gitea/gitea web + exec su-exec git /app/gitea/gitea web popd diff --git a/docker/etc/s6/openssh/run b/docker/etc/s6/openssh/run index b4c4cb4088..46f422cce6 100755 --- a/docker/etc/s6/openssh/run +++ b/docker/etc/s6/openssh/run @@ -2,5 +2,5 @@ [[ -f ./setup ]] && source ./setup pushd /root > /dev/null - exec gosu root /usr/sbin/sshd -E /var/log/sshd.log -D + exec su-exec root /usr/sbin/sshd -E /var/log/sshd.log -D popd diff --git a/docker/etc/s6/syslogd/run b/docker/etc/s6/syslogd/run index d876093047..2c8d2cf1f2 100755 --- a/docker/etc/s6/syslogd/run +++ b/docker/etc/s6/syslogd/run @@ -2,5 +2,5 @@ [[ -f ./setup ]] && source ./setup pushd /root > /dev/null - exec gosu root /sbin/syslogd -nS -O- + exec su-exec root /sbin/syslogd -nS -O- popd From 972ce6b791244ca99959a725aed693628ae895ef Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 17:22:22 +0100 Subject: [PATCH 077/135] Replaced shadow with addgroup and adduser --- Dockerfile | 13 +++++-------- Dockerfile.rpi | 13 +++++-------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/Dockerfile b/Dockerfile index fd25c88346..c5aba1cfe9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,7 +6,6 @@ EXPOSE 22 3000 RUN apk update && \ apk add \ su-exec \ - shadow \ ca-certificates \ sqlite \ bash \ @@ -18,17 +17,15 @@ RUN apk update && \ tzdata && \ rm -rf \ /var/cache/apk/* && \ - groupadd \ - -r \ + addgroup \ -g 1000 \ git && \ - useradd \ - -r -M \ - -p '*' \ - -d /data/git \ + adduser \ + -S -H -D \ + -h /data/git \ -s /bin/bash \ -u 1000 \ - -g git \ + -G git \ git ENV USER git diff --git a/Dockerfile.rpi b/Dockerfile.rpi index d237a63ba0..c618c94f2a 100644 --- a/Dockerfile.rpi +++ b/Dockerfile.rpi @@ -6,7 +6,6 @@ EXPOSE 22 3000 RUN apk update && \ apk add \ su-exec \ - shadow \ ca-certificates \ sqlite \ bash \ @@ -18,17 +17,15 @@ RUN apk update && \ tzdata && \ rm -rf \ /var/cache/apk/* && \ - groupadd \ - -r \ + addgroup \ -g 1000 \ git && \ - useradd \ - -r -M \ - -p '*' \ - -d /data/git \ + adduser \ + -S -H -D \ + -h /data/git \ -s /bin/bash \ -u 1000 \ - -g git \ + -G git \ git ENV USER git From 4b0abdae9e989614066fa01297d08ca5a7565daa Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 17:23:22 +0100 Subject: [PATCH 078/135] Replaced edge with 3.4 for the alpine base image --- Dockerfile | 2 +- Dockerfile.rpi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index c5aba1cfe9..80dc194c1b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:edge +FROM alpine:3.4 MAINTAINER Thomas Boerger EXPOSE 22 3000 diff --git a/Dockerfile.rpi b/Dockerfile.rpi index c618c94f2a..e82428c1b5 100644 --- a/Dockerfile.rpi +++ b/Dockerfile.rpi @@ -1,4 +1,4 @@ -FROM hypriot/rpi-alpine-scratch:edge +FROM hypriot/rpi-alpine-scratch:v3.4 MAINTAINER Thomas Boerger EXPOSE 22 3000 From d7dea676fd3f370c327a747bf819832121c0dd98 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Mon, 28 Nov 2016 17:37:31 +0100 Subject: [PATCH 079/135] Added -S flag to addgroup command within Dockerfiles --- Dockerfile | 2 +- Dockerfile.rpi | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 80dc194c1b..bc6b72a208 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,7 +18,7 @@ RUN apk update && \ rm -rf \ /var/cache/apk/* && \ addgroup \ - -g 1000 \ + -S -g 1000 \ git && \ adduser \ -S -H -D \ diff --git a/Dockerfile.rpi b/Dockerfile.rpi index e82428c1b5..91d8c3da85 100644 --- a/Dockerfile.rpi +++ b/Dockerfile.rpi @@ -18,7 +18,7 @@ RUN apk update && \ rm -rf \ /var/cache/apk/* && \ addgroup \ - -g 1000 \ + -S -g 1000 \ git && \ adduser \ -S -H -D \ From 9963d61233f6ac62be6df80293cd006b209d21e4 Mon Sep 17 00:00:00 2001 From: Bwko Date: Mon, 28 Nov 2016 17:47:46 +0100 Subject: [PATCH 080/135] Lint models/user.go --- models/user.go | 64 ++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/models/user.go b/models/user.go index 34bf685a7d..63544b365f 100644 --- a/models/user.go +++ b/models/user.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" "image" + // Needed for jpeg support _ "image/jpeg" "image/png" "os" @@ -34,20 +35,35 @@ import ( "code.gitea.io/gitea/modules/setting" ) +// UserType defines the user type type UserType int const ( + // UserTypeIndividual defines an individual user UserTypeIndividual UserType = iota // Historic reason to make it starts at 0. + + // UserTypeOrganization defines an organization UserTypeOrganization ) var ( - ErrUserNotKeyOwner = errors.New("User does not the owner of public key") - ErrEmailNotExist = errors.New("E-mail does not exist") - ErrEmailNotActivated = errors.New("E-mail address has not been activated") - ErrUserNameIllegal = errors.New("User name contains illegal characters") + // ErrUserNotKeyOwner user does not own this key error + ErrUserNotKeyOwner = errors.New("User does not own this public key") + + // ErrEmailNotExist e-mail does not exist error + ErrEmailNotExist = errors.New("E-mail does not exist") + + // ErrEmailNotActivated e-mail address has not been activated error + ErrEmailNotActivated = errors.New("E-mail address has not been activated") + + // ErrUserNameIllegal user name contains illegal characters error + ErrUserNameIllegal = errors.New("User name contains illegal characters") + + // ErrLoginSourceNotActived login source is not actived error ErrLoginSourceNotActived = errors.New("Login source is not actived") - ErrUnsupportedLoginType = errors.New("Login source is unknown") + + // ErrUnsupportedLoginType login source is unknown error + ErrUnsupportedLoginType = errors.New("Login source is unknown") ) // User represents the object of individual and member of organization. @@ -112,11 +128,13 @@ type User struct { DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"` } +// BeforeInsert is invoked from XORM before inserting an object of this type. func (u *User) BeforeInsert() { u.CreatedUnix = time.Now().Unix() u.UpdatedUnix = u.CreatedUnix } +// BeforeUpdate is invoked from XORM before updating this object. func (u *User) BeforeUpdate() { if u.MaxRepoCreation < -1 { u.MaxRepoCreation = -1 @@ -124,16 +142,18 @@ func (u *User) BeforeUpdate() { u.UpdatedUnix = time.Now().Unix() } -// Set time to last login +// SetLastLogin set time to last login func (u *User) SetLastLogin() { u.LastLoginUnix = time.Now().Unix() } +// UpdateDiffViewStyle updates the users diff view style func (u *User) UpdateDiffViewStyle(style string) error { u.DiffViewStyle = style return UpdateUser(u) } +// AfterSet is invoked from XORM after setting the value of a field of this object. func (u *User) AfterSet(colName string, _ xorm.Cell) { switch colName { case "full_name": @@ -147,6 +167,7 @@ func (u *User) AfterSet(colName string, _ xorm.Cell) { } } +// APIFormat converts a User to api.User func (u *User) APIFormat() *api.User { return &api.User{ ID: u.ID, @@ -157,7 +178,7 @@ func (u *User) APIFormat() *api.User { } } -// returns true if user login type is LoginPlain. +// IsLocal returns true if user login type is LoginPlain. func (u *User) IsLocal() bool { return u.LoginType <= LoginPlain } @@ -168,6 +189,7 @@ func (u *User) HasForkedRepo(repoID int64) bool { return has } +// RepoCreationNum returns the number of repositories created by the user func (u *User) RepoCreationNum() int { if u.MaxRepoCreation <= -1 { return setting.Repository.MaxCreationLimit @@ -175,6 +197,7 @@ func (u *User) RepoCreationNum() int { return u.MaxRepoCreation } +// CanCreateRepo returns if user login can create a repository func (u *User) CanCreateRepo() bool { if u.MaxRepoCreation <= -1 { if setting.Repository.MaxCreationLimit <= -1 { @@ -261,15 +284,15 @@ func (u *User) GenerateRandomAvatar() error { // which includes app sub-url as prefix. However, it is possible // to return full URL if user enables Gravatar-like service. func (u *User) RelAvatarLink() string { - defaultImgUrl := setting.AppSubURL + "/img/avatar_default.png" + defaultImgURL := setting.AppSubURL + "/img/avatar_default.png" if u.ID == -1 { - return defaultImgUrl + return defaultImgURL } switch { case u.UseCustomAvatar: if !com.IsExist(u.CustomAvatarPath()) { - return defaultImgUrl + return defaultImgURL } return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID) case setting.DisableGravatar, setting.OfflineMode: @@ -293,7 +316,7 @@ func (u *User) AvatarLink() string { return link } -// User.GetFollwoers returns range of user's followers. +// GetFollowers returns range of user's followers. func (u *User) GetFollowers(page int) ([]*User, error) { users := make([]*User, 0, ItemsPerPage) sess := x. @@ -307,6 +330,7 @@ func (u *User) GetFollowers(page int) ([]*User, error) { return users, sess.Find(&users) } +// IsFollowing returns true if user is following followID. func (u *User) IsFollowing(followID int64) bool { return IsFollowing(u.ID, followID) } @@ -418,13 +442,13 @@ func (u *User) IsOrganization() bool { } // IsUserOrgOwner returns true if user is in the owner team of given organization. -func (u *User) IsUserOrgOwner(orgId int64) bool { - return IsOrganizationOwner(orgId, u.ID) +func (u *User) IsUserOrgOwner(orgID int64) bool { + return IsOrganizationOwner(orgID, u.ID) } // IsPublicMember returns true if user public his/her membership in give organization. -func (u *User) IsPublicMember(orgId int64) bool { - return IsPublicMembership(orgId, u.ID) +func (u *User) IsPublicMember(orgID int64) bool { + return IsPublicMembership(orgID, u.ID) } func (u *User) getOrganizationCount(e Engine) (int64, error) { @@ -444,7 +468,7 @@ func (u *User) GetRepositories(page, pageSize int) (err error) { return err } -// GetRepositories returns mirror repositories that user owns, including private repositories. +// GetMirrorRepositories returns mirror repositories that user owns, including private repositories. func (u *User) GetMirrorRepositories() ([]*Repository, error) { return GetUserMirrorRepositories(u.ID) } @@ -481,6 +505,7 @@ func (u *User) DisplayName() string { return u.Name } +// ShortName ellipses username to length func (u *User) ShortName(length int) string { return base.EllipsisString(u.Name, length) } @@ -542,6 +567,7 @@ func isUsableName(names, patterns []string, name string) error { return nil } +// IsUsableUsername returns an error when a username is reserved func IsUsableUsername(name string) error { return isUsableName(reservedUsernames, reservedUserPatterns, name) } @@ -630,7 +656,7 @@ func getVerifyUser(code string) (user *User) { return nil } -// verify active code when active account +// VerifyUserActiveCode verifies active code when active account func VerifyUserActiveCode(code string) (user *User) { minutes := setting.Service.ActiveCodeLives @@ -646,7 +672,7 @@ func VerifyUserActiveCode(code string) (user *User) { return nil } -// verify active code when active account +// VerifyActiveEmailCode verifies active email code when active account func VerifyActiveEmailCode(code, email string) *EmailAddress { minutes := setting.Service.ActiveCodeLives @@ -1063,6 +1089,7 @@ func GetUserByEmail(email string) (*User, error) { return nil, ErrUserNotExist{0, email, 0} } +// SearchUserOptions contains the options for searching type SearchUserOptions struct { Keyword string Type UserType @@ -1123,6 +1150,7 @@ type Follow struct { FollowID int64 `xorm:"UNIQUE(follow)"` } +// IsFollowing returns true if user is following followID. func IsFollowing(userID, followID int64) bool { has, _ := x.Get(&Follow{UserID: userID, FollowID: followID}) return has From a5aae1c145b0393012898f1e834b8854e8f98f9c Mon Sep 17 00:00:00 2001 From: Bwko Date: Mon, 28 Nov 2016 17:58:59 +0100 Subject: [PATCH 081/135] Lint models/repo_* --- models/repo_collaboration.go | 1 + models/repo_editor.go | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/models/repo_collaboration.go b/models/repo_collaboration.go index e5be729895..0561ad86be 100644 --- a/models/repo_collaboration.go +++ b/models/repo_collaboration.go @@ -16,6 +16,7 @@ type Collaboration struct { Mode AccessMode `xorm:"DEFAULT 2 NOT NULL"` } +// ModeI18nKey returns the collaboration mode I18n Key func (c *Collaboration) ModeI18nKey() string { switch c.Mode { case AccessModeRead: diff --git a/models/repo_editor.go b/models/repo_editor.go index ba34a999f0..0d821f9f8c 100644 --- a/models/repo_editor.go +++ b/models/repo_editor.go @@ -50,6 +50,7 @@ func discardLocalRepoBranchChanges(localPath, branch string) error { return nil } +// DiscardLocalRepoBranchChanges discards the local repository branch changes func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error { return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch) } @@ -66,10 +67,12 @@ func checkoutNewBranch(repoPath, localPath, oldBranch, newBranch string) error { return nil } +// CheckoutNewBranch checks out a new branch func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error { return checkoutNewBranch(repo.RepoPath(), repo.LocalCopyPath(), oldBranch, newBranch) } +// UpdateRepoFileOptions holds the repository file update options type UpdateRepoFileOptions struct { LastCommitID string OldBranch string @@ -223,6 +226,7 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff * // \/ \/ \/ \/ \/ \/ // +// DeleteRepoFileOptions holds the repository delete file options type DeleteRepoFileOptions struct { LastCommitID string OldBranch string @@ -231,6 +235,7 @@ type DeleteRepoFileOptions struct { Message string } +// DeleteRepoFile deletes a repository file func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) { repoWorkingPool.CheckIn(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) @@ -351,6 +356,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err return upload, nil } +// GetUploadByUUID returns the Upload by UUID func GetUploadByUUID(uuid string) (*Upload, error) { upload := &Upload{UUID: uuid} has, err := x.Get(upload) @@ -362,6 +368,7 @@ func GetUploadByUUID(uuid string) (*Upload, error) { return upload, nil } +// GetUploadsByUUIDs returns multiple uploads by UUIDS func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) { if len(uuids) == 0 { return []*Upload{}, nil @@ -372,6 +379,7 @@ func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) { return uploads, x.In("uuid", uuids).Find(&uploads) } +// DeleteUploads deletes multiple uploads func DeleteUploads(uploads ...*Upload) (err error) { if len(uploads) == 0 { return nil @@ -407,10 +415,12 @@ func DeleteUploads(uploads ...*Upload) (err error) { return sess.Commit() } +// DeleteUpload delete a upload func DeleteUpload(u *Upload) error { return DeleteUploads(u) } +// DeleteUploadByUUID deletes a upload by UUID func DeleteUploadByUUID(uuid string) error { upload, err := GetUploadByUUID(uuid) if err != nil { @@ -427,6 +437,7 @@ func DeleteUploadByUUID(uuid string) error { return nil } +// UploadRepoFileOptions contains the uploaded repository file options type UploadRepoFileOptions struct { LastCommitID string OldBranch string @@ -436,6 +447,7 @@ type UploadRepoFileOptions struct { Files []string // In UUID format. } +// UploadRepoFiles uploads files to a repository func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) { if len(opts.Files) == 0 { return nil From bad1bc65188d53c94f10258c5ed07065ca99cff5 Mon Sep 17 00:00:00 2001 From: Bwko Date: Mon, 28 Nov 2016 18:27:55 +0100 Subject: [PATCH 082/135] Lint models/repo.go --- models/repo.go | 90 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 73 insertions(+), 17 deletions(-) diff --git a/models/repo.go b/models/repo.go index 4f4477c9af..482c96055f 100644 --- a/models/repo.go +++ b/models/repo.go @@ -41,20 +41,40 @@ const ( var repoWorkingPool = sync.NewExclusivePool() var ( - ErrRepoFileNotExist = errors.New("Repository file does not exist") + // ErrRepoFileNotExist repository file does not exist error + ErrRepoFileNotExist = errors.New("Repository file does not exist") + + // ErrRepoFileNotLoaded repository file not loaded error ErrRepoFileNotLoaded = errors.New("Repository file not loaded") - ErrMirrorNotExist = errors.New("Mirror does not exist") - ErrInvalidReference = errors.New("Invalid reference specified") - ErrNameEmpty = errors.New("Name is empty") + + // ErrMirrorNotExist mirror does not exist error + ErrMirrorNotExist = errors.New("Mirror does not exist") + + // ErrInvalidReference invalid reference specified error + ErrInvalidReference = errors.New("Invalid reference specified") + + // ErrNameEmpty name is empty error + ErrNameEmpty = errors.New("Name is empty") ) var ( - Gitignores, Licenses, Readmes, LabelTemplates []string + // Gitignores contains the gitiginore files + Gitignores []string + + // Licenses contains the license files + Licenses []string + + // Readmes contains the readme files + Readmes []string + + // LabelTemplates contains the label template files + LabelTemplates []string - // Maximum items per page in forks, watchers and stars of a repo + // ItemsPerPage maximum items per page in forks, watchers and stars of a repo ItemsPerPage = 40 ) +// LoadRepoConfig loads the repository config func LoadRepoConfig() { // Load .gitignore and license files and readme templates. types := []string{"gitignore", "license", "readme", "label"} @@ -104,6 +124,7 @@ func LoadRepoConfig() { Licenses = sortedLicenses } +// NewRepoContext creates a new repository context func NewRepoContext() { zip.Verbose = false @@ -200,15 +221,18 @@ type Repository struct { UpdatedUnix int64 } +// BeforeInsert is invoked from XORM before inserting an object of this type. func (repo *Repository) BeforeInsert() { repo.CreatedUnix = time.Now().Unix() repo.UpdatedUnix = repo.CreatedUnix } +// BeforeUpdate is invoked from XORM before updating this object. func (repo *Repository) BeforeUpdate() { repo.UpdatedUnix = time.Now().Unix() } +// AfterSet is invoked from XORM after setting the value of a field of this object. func (repo *Repository) AfterSet(colName string, _ xorm.Cell) { switch colName { case "default_branch": @@ -241,14 +265,17 @@ func (repo *Repository) MustOwner() *User { return repo.mustOwner(x) } +// FullName returns the repository full name func (repo *Repository) FullName() string { return repo.MustOwner().Name + "/" + repo.Name } +// HTMLURL returns the repository HTML URL func (repo *Repository) HTMLURL() string { return setting.AppURL + repo.FullName() } +// APIFormat converts a Repository to api.Repository // Arguments that are allowed to be nil: permission func (repo *Repository) APIFormat(permission *api.Permission) *api.Repository { cloneLink := repo.CloneLink() @@ -284,6 +311,7 @@ func (repo *Repository) getOwner(e Engine) (err error) { return err } +// GetOwner returns the repository owner func (repo *Repository) GetOwner() error { return repo.getOwner(x) } @@ -381,11 +409,13 @@ func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int6 return GetRepoIssueStats(repo.ID, uid, filterMode, isPull) } +// GetMirror sets the repository mirror, returns an error upon failure func (repo *Repository) GetMirror() (err error) { repo.Mirror, err = GetMirrorByRepoID(repo.ID) return err } +// GetBaseRepo returns the base repository func (repo *Repository) GetBaseRepo() (err error) { if !repo.IsFork { return nil @@ -399,31 +429,38 @@ func (repo *Repository) repoPath(e Engine) string { return RepoPath(repo.mustOwner(e).Name, repo.Name) } +// RepoPath returns the repository path func (repo *Repository) RepoPath() string { return repo.repoPath(x) } +// GitConfigPath returns the repository git config path func (repo *Repository) GitConfigPath() string { return filepath.Join(repo.RepoPath(), "config") } +// RelLink returns the repository relative link func (repo *Repository) RelLink() string { return "/" + repo.FullName() } +// Link returns the repository link func (repo *Repository) Link() string { return setting.AppSubURL + "/" + repo.FullName() } +// ComposeCompareURL returns the repository comparison URL func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string { return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID) } +// HasAccess returns true when user has access to this repository func (repo *Repository) HasAccess(u *User) bool { has, _ := HasAccess(u, repo, AccessModeRead) return has } +// IsOwnedBy returns true when user owns this repository func (repo *Repository) IsOwnedBy(userID int64) bool { return repo.OwnerID == userID } @@ -438,7 +475,7 @@ func (repo *Repository) CanEnablePulls() bool { return !repo.IsMirror } -// AllowPulls returns true if repository meets the requirements of accepting pulls and has them enabled. +// AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled. func (repo *Repository) AllowsPulls() bool { return repo.CanEnablePulls() && repo.EnablePulls } @@ -448,6 +485,7 @@ func (repo *Repository) CanEnableEditor() bool { return !repo.IsMirror } +// NextIssueIndex returns the next issue index // FIXME: should have a mutex to prevent producing same index for two issues that are created // closely enough. func (repo *Repository) NextIssueIndex() int64 { @@ -455,22 +493,23 @@ func (repo *Repository) NextIssueIndex() int64 { } var ( - DescPattern = regexp.MustCompile(`https?://\S+`) + descPattern = regexp.MustCompile(`https?://\S+`) ) -// DescriptionHtml does special handles to description and return HTML string. -func (repo *Repository) DescriptionHtml() template.HTML { +// DescriptionHTML does special handles to description and return HTML string. +func (repo *Repository) DescriptionHTML() template.HTML { sanitize := func(s string) string { return fmt.Sprintf(`%[1]s`, s) } - return template.HTML(DescPattern.ReplaceAllStringFunc(markdown.Sanitizer.Sanitize(repo.Description), sanitize)) + return template.HTML(descPattern.ReplaceAllStringFunc(markdown.Sanitizer.Sanitize(repo.Description), sanitize)) } +// LocalCopyPath returns the local repository copy path func (repo *Repository) LocalCopyPath() string { return path.Join(setting.AppDataPath, "tmp/local-rpeo", com.ToStr(repo.ID)) } -// UpdateLocalCopy pulls latest changes of given branch from repoPath to localPath. +// UpdateLocalCopyBranch pulls latest changes of given branch from repoPath to localPath. // It creates a new clone if local copy does not exist. // This function checks out target branch by default, it is safe to assume subsequent // operations are operating against target branch when caller has confidence for no race condition. @@ -575,6 +614,7 @@ func (repo *Repository) CloneLink() (cl *CloneLink) { return repo.cloneLink(false) } +// MigrateRepoOptions contains the repository migrate options type MigrateRepoOptions struct { Name string Description string @@ -711,7 +751,7 @@ func createUpdateHook(repoPath string) error { fmt.Sprintf(tplUpdateHook, setting.ScriptType, "\""+setting.AppPath+"\"", setting.CustomConf)) } -// Finish migrating repository and/or wiki with things that don't need to be done for mirrors. +// CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) { repoPath := repo.RepoPath() if err := createUpdateHook(repoPath); err != nil { @@ -759,6 +799,7 @@ func initRepoCommit(tmpPath string, sig *git.Signature) (err error) { return nil } +// CreateRepoOptions contains the create repository options type CreateRepoOptions struct { Name string Description string @@ -897,6 +938,7 @@ var ( reservedRepoPatterns = []string{"*.git", "*.wiki"} ) +// IsUsableRepoName returns true when repository is usable func IsUsableRepoName(name string) error { return isUsableName(reservedRepoNames, reservedRepoPatterns, name) } @@ -1030,6 +1072,7 @@ func CountUserRepositories(userID int64, private bool) int64 { return countRepositories(userID, private) } +// Repositories returns all repositories func Repositories(page, pageSize int) (_ []*Repository, err error) { repos := make([]*Repository, 0, pageSize) return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos) @@ -1275,6 +1318,7 @@ func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err e return nil } +// UpdateRepository updates a repository func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) { sess := x.NewSession() defer sessionRelease(sess) @@ -1474,7 +1518,7 @@ func GetUserRepositories(userID int64, private bool, page, pageSize int) ([]*Rep return repos, sess.Find(&repos) } -// GetUserRepositories returns a list of mirror repositories of given user. +// GetUserMirrorRepositories returns a list of mirror repositories of given user. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) { repos := make([]*Repository, 0, 10) return repos, x. @@ -1502,6 +1546,7 @@ func GetRepositoryCount(u *User) (int64, error) { return getRepositoryCount(x, u) } +// SearchRepoOptions holds the search options type SearchRepoOptions struct { Keyword string OwnerID int64 @@ -1670,6 +1715,7 @@ func GitFsck() { } } +// GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository func GitGcRepos() error { args := append([]string{"gc"}, setting.Git.GCArgs...) return x. @@ -1712,6 +1758,7 @@ func repoStatsCheck(checker *repoChecker) { } } +// CheckRepoStats checks the repository stats func CheckRepoStats() { if taskStatusTable.IsRunning(checkRepos) { return @@ -1806,6 +1853,7 @@ func CheckRepoStats() { // ***** END: Repository.NumForks ***** } +// RepositoryList contains a list of repositories type RepositoryList []*Repository func (repos RepositoryList) loadAttributes(e Engine) error { @@ -1838,10 +1886,12 @@ func (repos RepositoryList) loadAttributes(e Engine) error { return nil } +// LoadAttributes loads the attributes for the given RepositoryList func (repos RepositoryList) LoadAttributes() error { return repos.loadAttributes(x) } +// MirrorRepositoryList contains the mirror repositories type MirrorRepositoryList []*Repository func (repos MirrorRepositoryList) loadAttributes(e Engine) error { @@ -1876,6 +1926,7 @@ func (repos MirrorRepositoryList) loadAttributes(e Engine) error { return nil } +// LoadAttributes loads the attributes for the given MirrorRepositoryList func (repos MirrorRepositoryList) LoadAttributes() error { return repos.loadAttributes(x) } @@ -1925,7 +1976,7 @@ func watchRepo(e Engine, userID, repoID int64, watch bool) (err error) { return err } -// Watch or unwatch repository. +// WatchRepo watch or unwatch repository. func WatchRepo(userID, repoID int64, watch bool) (err error) { return watchRepo(x, userID, repoID, watch) } @@ -1940,7 +1991,7 @@ func GetWatchers(repoID int64) ([]*Watch, error) { return getWatchers(x, repoID) } -// Repository.GetWatchers returns range of users watching given repository. +// GetWatchers returns range of users watching given repository. func (repo *Repository) GetWatchers(page int) ([]*User, error) { users := make([]*User, 0, ItemsPerPage) sess := x. @@ -1993,13 +2044,14 @@ func NotifyWatchers(act *Action) error { // /_______ /|__| (____ /__| // \/ \/ +// Star contains the star information type Star struct { ID int64 `xorm:"pk autoincr"` UID int64 `xorm:"UNIQUE(s)"` RepoID int64 `xorm:"UNIQUE(s)"` } -// Star or unstar repository. +// StarRepo star or unstar repository. func StarRepo(userID, repoID int64, star bool) (err error) { if star { if IsStaring(userID, repoID) { @@ -2031,6 +2083,7 @@ func IsStaring(userID, repoID int64) bool { return has } +// GetStargazers returns the users who gave stars to this repository func (repo *Repository) GetStargazers(page int) ([]*User, error) { users := make([]*User, 0, ItemsPerPage) sess := x. @@ -2060,6 +2113,7 @@ func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) { return repo, has } +// ForkRepository forks a repository func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) { repo := &Repository{ OwnerID: u.ID, @@ -2109,6 +2163,7 @@ func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Reposit return repo, sess.Commit() } +// GetForks returns all the forks of the repository func (repo *Repository) GetForks() ([]*Repository, error) { forks := make([]*Repository, 0, repo.NumForks) return forks, x.Find(&forks, &Repository{ForkID: repo.ID}) @@ -2122,6 +2177,7 @@ func (repo *Repository) GetForks() ([]*Repository, error) { // \/ \/ \/ \/ \/ // +// CreateNewBranch creates a new repository branch func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName string) (err error) { repoWorkingPool.CheckIn(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) From 36a4663393c30476bbc0fd1bb03e6a56d3aa4295 Mon Sep 17 00:00:00 2001 From: Michael Stroucken Date: Mon, 28 Nov 2016 20:03:45 -0500 Subject: [PATCH 083/135] Rebase branch onto go-gitea/gitea --- conf/locale/locale_de-DE.ini | 12 ++++++------ conf/locale/locale_en-US.ini | 2 +- conf/locale/locale_es-ES.ini | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/conf/locale/locale_de-DE.ini b/conf/locale/locale_de-DE.ini index c255060c79..f86bfc0261 100644 --- a/conf/locale/locale_de-DE.ini +++ b/conf/locale/locale_de-DE.ini @@ -76,7 +76,7 @@ domain_helper=Dies hat Auswirkung auf die SSH Klon-URLs. ssh_port=SSH Port ssh_port_helper=Der Port Ihres SSH-Servers. Leer lassen um SSH zu deaktivieren. http_port=HTTP Port -http_port_helper=Auf dieser Port Nummer wird Gitea erreichbar sein. +http_port_helper=Auf diesem Port wird Gitea erreichbar sein. app_url=Anwendungs-URL app_url_helper=Dies hat Auswirkung auf die HTTP/HTTPS Klon-URLs und den Inhalt der E-Mails. log_root_path=Logdateipfad @@ -593,7 +593,7 @@ milestones.title=Titel milestones.desc=Beschreibung milestones.due_date=Fälligkeitsdatum (optional) milestones.clear=Feld leeren -milestones.invalid_due_date_format=Format des Fälligkeitsdatums ist ungültig. Es muss das Format 'JJJJ-mm-dd' haben. +milestones.invalid_due_date_format=Format des Fälligkeitsdatums ist ungültig. Es muss das Format 'JJJJ-MM-TT' haben. milestones.create_success=Meilenstein '%s' wurde erfolgreich erstellt! milestones.edit=Meilenstein bearbeiten milestones.edit_subheader=Verwenden Sie eine aussagekräftige Beschreibung für Meilensteine, um Missverständnisse zu vermeiden. @@ -915,9 +915,9 @@ dashboard.current_goroutine=Aktuelle Goroutines dashboard.current_memory_usage=Aktuelle Speichernutzung dashboard.total_memory_allocated=Zugeteilter Gesamtspeicher dashboard.memory_obtained=Erhaltener Speicher -dashboard.pointer_lookup_times=Pointer Lookup Times -dashboard.memory_allocate_times=Memory Allocate Times -dashboard.memory_free_times=Memory Free Times +dashboard.pointer_lookup_times=Zeigerlookup-Dauern +dashboard.memory_allocate_times=Speicheranforderungsdauern +dashboard.memory_free_times=Speicherfreigabedauern dashboard.current_heap_usage=Aktuelle Heap-Auslastung dashboard.heap_memory_obtained=Erhaltener Heap-Memory dashboard.heap_memory_idle=Unbenutzter Heap-Memory @@ -938,7 +938,7 @@ dashboard.last_gc_time=Seit letztem GC-Zyklus dashboard.total_gc_time=Gesamte GC-Pause dashboard.total_gc_pause=Gesamte GC-Pause dashboard.last_gc_pause=Letzte GC-Pause -dashboard.gc_times=GC-Takt +dashboard.gc_times=GC-Dauern users.user_manage_panel=Benutzer users.new_account=Neues Konto erstellen diff --git a/conf/locale/locale_en-US.ini b/conf/locale/locale_en-US.ini index d7b407cd27..30a906a5b6 100644 --- a/conf/locale/locale_en-US.ini +++ b/conf/locale/locale_en-US.ini @@ -492,7 +492,7 @@ issues.new_label = New Label issues.new_label_placeholder = Label name... issues.create_label = Create Label issues.label_templates.title = Load a predefined set of labels -issues.label_templates.info = There aren’t any labels yet. You can click on the "New Label" button above to create one or use a predefined set below. +issues.label_templates.info = There aren't any labels yet. You can click on the "New Label" button above to create one or use a predefined set below. issues.label_templates.helper = Select a label set issues.label_templates.use = Use this label set issues.label_templates.fail_to_load_file = Failed to load label template file '%s': %v diff --git a/conf/locale/locale_es-ES.ini b/conf/locale/locale_es-ES.ini index 56a3a88aa2..3d5b0a12f2 100644 --- a/conf/locale/locale_es-ES.ini +++ b/conf/locale/locale_es-ES.ini @@ -491,7 +491,7 @@ issues.new_label=Nueva Etiqueta issues.new_label_placeholder=Nombre etiqueta... issues.create_label=Crear etiqueta issues.label_templates.title=Carga un conjunto predefinido de etiquetas -issues.label_templates.info=Tdavía no hay ninguna etiqueta. Puede hacer clic en el botón "Nueva etiqueta" para crear una o utilizar un conjunto predefinido abajo. +issues.label_templates.info=Todavía no hay ninguna etiqueta. Puede hacer clic en el botón "Nueva etiqueta" para crear una o utilizar un conjunto predefinido abajo. issues.label_templates.helper=Seleccionar un conjunto de etiquetas issues.label_templates.use=Usar este conjunto de etiquetas issues.label_templates.fail_to_load_file=Error al cargar el archivo de plantilla de etiqueta '%s': %v @@ -522,7 +522,7 @@ issues.next=Página Siguiente issues.open_title=Abierta issues.closed_title=Cerrada issues.num_comments=%d comentarios -issues.commented_at='comentado %s' +issues.commented_at=`comentado %s` issues.delete_comment_confirm=¿Seguro que deseas eliminar este comentario? issues.no_content=Aún no existe contenido. issues.close_issue=Cerrar From abf6c3a8e31711b8a22525cabb892b5fcdab4e86 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 29 Nov 2016 14:57:36 +0800 Subject: [PATCH 084/135] bug fixed caused by #295 (#299) --- templates/explore/repo_list.tmpl | 2 +- templates/repo/home.tmpl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/explore/repo_list.tmpl b/templates/explore/repo_list.tmpl index a4beb20143..2cf7202fdf 100644 --- a/templates/explore/repo_list.tmpl +++ b/templates/explore/repo_list.tmpl @@ -16,7 +16,7 @@ {{.NumForks}}
- {{if .DescriptionHtml}}

{{.DescriptionHtml}}

{{end}} + {{if .DescriptionHTML}}

{{.DescriptionHTML}}

{{end}}

{{$.i18n.Tr "org.repo_updated"}} {{TimeSince .Updated $.i18n.Lang}}

{{end}} diff --git a/templates/repo/home.tmpl b/templates/repo/home.tmpl index 52d93a213e..6e86518daa 100644 --- a/templates/repo/home.tmpl +++ b/templates/repo/home.tmpl @@ -4,7 +4,7 @@
{{template "base/alert" .}}

- {{if .Repository.DescriptionHtml}}{{.Repository.DescriptionHtml}}{{else}}{{.i18n.Tr "repo.no_desc"}}{{end}} + {{if .Repository.DescriptionHTML}}{{.Repository.DescriptionHTML}}{{else}}{{.i18n.Tr "repo.no_desc"}}{{end}} {{.Repository.Website}}