From b1ff386e2418ed6a7f183e756b13277d701278ef Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 19 Dec 2019 23:55:23 +0100 Subject: [PATCH 01/13] use numbers and not http.Status___ enum --- routers/api/v1/misc/markdown.go | 9 +++--- routers/api/v1/misc/markdown_test.go | 1 - routers/api/v1/misc/signing.go | 3 +- routers/api/v1/repo/blob.go | 7 ++--- routers/api/v1/repo/file.go | 31 ++++++++++----------- routers/api/v1/repo/hook_test.go | 3 +- routers/api/v1/repo/issue.go | 5 ++-- routers/api/v1/repo/pull.go | 15 +++++----- routers/api/v1/repo/repo.go | 37 ++++++++++++------------- routers/api/v1/repo/repo_test.go | 5 ++-- routers/api/v1/repo/tag.go | 9 +++--- routers/api/v1/repo/topic.go | 41 ++++++++++++++-------------- routers/api/v1/user/user.go | 7 ++--- routers/api/v1/utils/hook.go | 5 ++-- 14 files changed, 82 insertions(+), 96 deletions(-) diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index 23f0b168d084..3d099ae0c07c 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -5,7 +5,6 @@ package misc import ( - "net/http" "strings" "code.gitea.io/gitea/modules/context" @@ -65,20 +64,20 @@ func Markdown(ctx *context.APIContext, form api.MarkdownOption) { if form.Wiki { _, err := ctx.Write([]byte(markdown.RenderWiki(md, urlPrefix, meta))) if err != nil { - ctx.Error(http.StatusInternalServerError, "", err) + ctx.Error(500, "", err) return } } else { _, err := ctx.Write(markdown.Render(md, urlPrefix, meta)) if err != nil { - ctx.Error(http.StatusInternalServerError, "", err) + ctx.Error(500, "", err) return } } default: _, err := ctx.Write(markdown.RenderRaw([]byte(form.Text), "", false)) if err != nil { - ctx.Error(http.StatusInternalServerError, "", err) + ctx.Error(500, "", err) return } } @@ -112,7 +111,7 @@ func MarkdownRaw(ctx *context.APIContext) { } _, err = ctx.Write(markdown.RenderRaw(body, "", false)) if err != nil { - ctx.Error(http.StatusInternalServerError, "", err) + ctx.Error(500, "", err) return } } diff --git a/routers/api/v1/misc/markdown_test.go b/routers/api/v1/misc/markdown_test.go index 47e99d2f06ac..ed80023bc283 100644 --- a/routers/api/v1/misc/markdown_test.go +++ b/routers/api/v1/misc/markdown_test.go @@ -2,7 +2,6 @@ package misc import ( "io/ioutil" - "net/http" "net/http/httptest" "net/url" "strings" diff --git a/routers/api/v1/misc/signing.go b/routers/api/v1/misc/signing.go index f5428670af67..e8bff381cf0d 100644 --- a/routers/api/v1/misc/signing.go +++ b/routers/api/v1/misc/signing.go @@ -2,7 +2,6 @@ package misc import ( "fmt" - "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -57,6 +56,6 @@ func SigningKey(ctx *context.Context) { _, err = ctx.Write([]byte(content)) if err != nil { log.Error("Error writing key content %v", err) - ctx.Error(http.StatusInternalServerError, fmt.Sprintf("%v", err)) + ctx.Error(500, fmt.Sprintf("%v", err)) } } diff --git a/routers/api/v1/repo/blob.go b/routers/api/v1/repo/blob.go index d6265e16ce9b..70f7a8bbe266 100644 --- a/routers/api/v1/repo/blob.go +++ b/routers/api/v1/repo/blob.go @@ -5,7 +5,6 @@ package repo import ( - "net/http" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/repofiles" @@ -40,12 +39,12 @@ func GetBlob(ctx *context.APIContext) { sha := ctx.Params("sha") if len(sha) == 0 { - ctx.Error(http.StatusBadRequest, "", "sha not provided") + ctx.Error(400, "", "sha not provided") return } if blob, err := repofiles.GetBlobBySHA(ctx.Repo.Repository, sha); err != nil { - ctx.Error(http.StatusBadRequest, "", err) + ctx.Error(400, "", err) } else { - ctx.JSON(http.StatusOK, blob) + ctx.JSON(200, blob) } } diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 175235c5ef37..20ef4f8841ab 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -7,7 +7,6 @@ package repo import ( "encoding/base64" - "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -53,12 +52,12 @@ func GetRawFile(ctx *context.APIContext) { if git.IsErrNotExist(err) { ctx.NotFound() } else { - ctx.Error(http.StatusInternalServerError, "GetBlobByPath", err) + ctx.Error(500, "GetBlobByPath", err) } return } if err = repo.ServeBlob(ctx.Context, blob); err != nil { - ctx.Error(http.StatusInternalServerError, "ServeBlob", err) + ctx.Error(500, "ServeBlob", err) } } @@ -91,7 +90,7 @@ func GetArchive(ctx *context.APIContext) { repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) gitRepo, err := git.OpenRepository(repoPath) if err != nil { - ctx.Error(http.StatusInternalServerError, "OpenRepository", err) + ctx.Error(500, "OpenRepository", err) return } ctx.Repo.GitRepo = gitRepo @@ -131,7 +130,7 @@ func GetEditorconfig(ctx *context.APIContext) { if git.IsErrNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(http.StatusInternalServerError, "GetEditorconfig", err) + ctx.Error(500, "GetEditorconfig", err) } return } @@ -142,7 +141,7 @@ func GetEditorconfig(ctx *context.APIContext) { ctx.NotFound(err) return } - ctx.JSON(http.StatusOK, def) + ctx.JSON(200, def) } // CanWriteFiles returns true if repository is editable and user has proper access level. @@ -211,9 +210,9 @@ func CreateFile(ctx *context.APIContext, apiOpts api.CreateFileOptions) { } if fileResponse, err := createOrUpdateFile(ctx, opts); err != nil { - ctx.Error(http.StatusInternalServerError, "CreateFile", err) + ctx.Error(500, "CreateFile", err) } else { - ctx.JSON(http.StatusCreated, fileResponse) + ctx.JSON(201, fileResponse) } } @@ -275,9 +274,9 @@ func UpdateFile(ctx *context.APIContext, apiOpts api.UpdateFileOptions) { } if fileResponse, err := createOrUpdateFile(ctx, opts); err != nil { - ctx.Error(http.StatusInternalServerError, "UpdateFile", err) + ctx.Error(500, "UpdateFile", err) } else { - ctx.JSON(http.StatusOK, fileResponse) + ctx.JSON(200, fileResponse) } } @@ -333,7 +332,7 @@ func DeleteFile(ctx *context.APIContext, apiOpts api.DeleteFileOptions) { // "200": // "$ref": "#/responses/FileDeleteResponse" if !CanWriteFiles(ctx.Repo) { - ctx.Error(http.StatusInternalServerError, "DeleteFile", models.ErrUserDoesNotHaveAccessToRepo{ + ctx.Error(500, "DeleteFile", models.ErrUserDoesNotHaveAccessToRepo{ UserID: ctx.User.ID, RepoName: ctx.Repo.Repository.LowerName, }) @@ -361,9 +360,9 @@ func DeleteFile(ctx *context.APIContext, apiOpts api.DeleteFileOptions) { } if fileResponse, err := repofiles.DeleteRepoFile(ctx.Repo.Repository, ctx.User, opts); err != nil { - ctx.Error(http.StatusInternalServerError, "DeleteFile", err) + ctx.Error(500, "DeleteFile", err) } else { - ctx.JSON(http.StatusOK, fileResponse) + ctx.JSON(200, fileResponse) } } @@ -400,7 +399,7 @@ func GetContents(ctx *context.APIContext) { // "$ref": "#/responses/ContentsResponse" if !CanReadFiles(ctx.Repo) { - ctx.Error(http.StatusInternalServerError, "GetContentsOrList", models.ErrUserDoesNotHaveAccessToRepo{ + ctx.Error(500, "GetContentsOrList", models.ErrUserDoesNotHaveAccessToRepo{ UserID: ctx.User.ID, RepoName: ctx.Repo.Repository.LowerName, }) @@ -411,9 +410,9 @@ func GetContents(ctx *context.APIContext) { ref := ctx.QueryTrim("ref") if fileList, err := repofiles.GetContentsOrList(ctx.Repo.Repository, treePath, ref); err != nil { - ctx.Error(http.StatusInternalServerError, "GetContentsOrList", err) + ctx.Error(500, "GetContentsOrList", err) } else { - ctx.JSON(http.StatusOK, fileList) + ctx.JSON(200, fileList) } } diff --git a/routers/api/v1/repo/hook_test.go b/routers/api/v1/repo/hook_test.go index 8ed4bc4b0c3c..ec68df66975a 100644 --- a/routers/api/v1/repo/hook_test.go +++ b/routers/api/v1/repo/hook_test.go @@ -5,7 +5,6 @@ package repo import ( - "net/http" "testing" "code.gitea.io/gitea/models" @@ -24,7 +23,7 @@ func TestTestHook(t *testing.T) { test.LoadRepoCommit(t, ctx) test.LoadUser(t, ctx, 2) TestHook(&context.APIContext{Context: ctx, Org: nil}) - assert.EqualValues(t, http.StatusNoContent, ctx.Resp.Status()) + assert.EqualValues(t, 204, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.HookTask{ RepoID: 1, diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 6972d447a621..3c5e02e3625e 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -7,7 +7,6 @@ package repo import ( "fmt" - "net/http" "strings" "time" @@ -379,7 +378,7 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { if form.Closed { if err := issue_service.ChangeStatus(issue, ctx.User, true); err != nil { if models.IsErrDependenciesLeft(err) { - ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this issue because it still has open dependencies") + ctx.Error(412, "DependenciesLeft", "cannot close this issue because it still has open dependencies") return } ctx.Error(500, "ChangeStatus", err) @@ -513,7 +512,7 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { if form.State != nil { if err = issue_service.ChangeStatus(issue, ctx.User, api.StateClosed == api.StateType(*form.State)); err != nil { if models.IsErrDependenciesLeft(err) { - ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this issue because it still has open dependencies") + ctx.Error(412, "DependenciesLeft", "cannot close this issue because it still has open dependencies") return } ctx.Error(500, "ChangeStatus", err) diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 1c273b7dc94e..aa7b5edf5da3 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -6,7 +6,6 @@ package repo import ( "fmt" - "net/http" "strings" "time" @@ -360,7 +359,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { err = pr.LoadIssue() if err != nil { - ctx.Error(http.StatusInternalServerError, "LoadIssue", err) + ctx.Error(500, "LoadIssue", err) return } issue := pr.Issue @@ -443,7 +442,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { if form.State != nil { if err = issue_service.ChangeStatus(issue, ctx.User, api.StateClosed == api.StateType(*form.State)); err != nil { if models.IsErrDependenciesLeft(err) { - ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this pull request because it still has open dependencies") + ctx.Error(412, "DependenciesLeft", "cannot close this pull request because it still has open dependencies") return } ctx.Error(500, "ChangeStatus", err) @@ -561,7 +560,7 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { err = pr.LoadIssue() if err != nil { - ctx.Error(http.StatusInternalServerError, "LoadIssue", err) + ctx.Error(500, "LoadIssue", err) return } pr.Issue.Repo = ctx.Repo.Repository @@ -620,15 +619,15 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { return } else if models.IsErrMergeConflicts(err) { conflictError := err.(models.ErrMergeConflicts) - ctx.JSON(http.StatusConflict, conflictError) + ctx.JSON(409, conflictError) } else if models.IsErrRebaseConflicts(err) { conflictError := err.(models.ErrRebaseConflicts) - ctx.JSON(http.StatusConflict, conflictError) + ctx.JSON(409, conflictError) } else if models.IsErrMergeUnrelatedHistories(err) { conflictError := err.(models.ErrMergeUnrelatedHistories) - ctx.JSON(http.StatusConflict, conflictError) + ctx.JSON(409, conflictError) } else if models.IsErrMergePushOutOfDate(err) { - ctx.Status(http.StatusConflict) + ctx.Status(409) return } ctx.Error(500, "Merge", err) diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index be226c343886..4f789e4ef4ad 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -9,7 +9,6 @@ import ( "bytes" "errors" "fmt" - "net/http" "net/url" "strings" @@ -162,7 +161,7 @@ func Search(ctx *context.APIContext) { opts.Collaborate = util.OptionalBoolTrue case "": default: - ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid search mode: \"%s\"", mode)) + ctx.Error(422, "", fmt.Errorf("Invalid search mode: \"%s\"", mode)) return } @@ -176,11 +175,11 @@ func Search(ctx *context.APIContext) { if orderBy, ok := searchModeMap[sortMode]; ok { opts.OrderBy = orderBy } else { - ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid sort mode: \"%s\"", sortMode)) + ctx.Error(422, "", fmt.Errorf("Invalid sort mode: \"%s\"", sortMode)) return } } else { - ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid sort order: \"%s\"", sortOrder)) + ctx.Error(422, "", fmt.Errorf("Invalid sort order: \"%s\"", sortOrder)) return } } @@ -626,7 +625,7 @@ func Edit(ctx *context.APIContext, opts api.EditRepoOption) { } } - ctx.JSON(http.StatusOK, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode)) + ctx.JSON(200, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode)) } // updateBasicProperties updates the basic properties of a repo: Name, Description, Website and Visibility @@ -642,13 +641,13 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err if err := repo_service.ChangeRepositoryName(ctx.User, repo, newRepoName); err != nil { switch { case models.IsErrRepoAlreadyExist(err): - ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name is already taken [name: %s]", newRepoName), err) + ctx.Error(422, fmt.Sprintf("repo name is already taken [name: %s]", newRepoName), err) case models.IsErrNameReserved(err): - ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name is reserved [name: %s]", newRepoName), err) + ctx.Error(422, fmt.Sprintf("repo name is reserved [name: %s]", newRepoName), err) case models.IsErrNamePatternNotAllowed(err): - ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name's pattern is not allowed [name: %s, pattern: %s]", newRepoName, err.(models.ErrNamePatternNotAllowed).Pattern), err) + ctx.Error(422, fmt.Sprintf("repo name's pattern is not allowed [name: %s, pattern: %s]", newRepoName, err.(models.ErrNamePatternNotAllowed).Pattern), err) default: - ctx.Error(http.StatusUnprocessableEntity, "ChangeRepositoryName", err) + ctx.Error(422, "ChangeRepositoryName", err) } return err } @@ -678,7 +677,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err // when ForcePrivate enabled, you could change public repo to private, but only admin users can change private to public if visibilityChanged && setting.Repository.ForcePrivate && !*opts.Private && !ctx.User.IsAdmin { err := fmt.Errorf("cannot change private repository to public") - ctx.Error(http.StatusUnprocessableEntity, "Force Private enabled", err) + ctx.Error(422, "Force Private enabled", err) return err } @@ -693,7 +692,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err if opts.DefaultBranch != nil && repo.DefaultBranch != *opts.DefaultBranch && ctx.Repo.GitRepo.IsBranchExist(*opts.DefaultBranch) { if err := ctx.Repo.GitRepo.SetDefaultBranch(*opts.DefaultBranch); err != nil { if !git.IsErrUnsupportedVersion(err) { - ctx.Error(http.StatusInternalServerError, "SetDefaultBranch", err) + ctx.Error(500, "SetDefaultBranch", err) return err } } @@ -701,7 +700,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err } if err := models.UpdateRepository(repo, visibilityChanged); err != nil { - ctx.Error(http.StatusInternalServerError, "UpdateRepository", err) + ctx.Error(500, "UpdateRepository", err) return err } @@ -737,12 +736,12 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { // Check that values are valid if !validation.IsValidExternalURL(opts.ExternalTracker.ExternalTrackerURL) { err := fmt.Errorf("External tracker URL not valid") - ctx.Error(http.StatusUnprocessableEntity, "Invalid external tracker URL", err) + ctx.Error(422, "Invalid external tracker URL", err) return err } if len(opts.ExternalTracker.ExternalTrackerFormat) != 0 && !validation.IsValidExternalTrackerURLFormat(opts.ExternalTracker.ExternalTrackerFormat) { err := fmt.Errorf("External tracker URL format not valid") - ctx.Error(http.StatusUnprocessableEntity, "Invalid external tracker URL format", err) + ctx.Error(422, "Invalid external tracker URL format", err) return err } @@ -797,7 +796,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { // Check that values are valid if !validation.IsValidExternalURL(opts.ExternalWiki.ExternalWikiURL) { err := fmt.Errorf("External wiki URL not valid") - ctx.Error(http.StatusUnprocessableEntity, "", "Invalid external wiki URL") + ctx.Error(422, "", "Invalid external wiki URL") return err } @@ -866,7 +865,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { } if err := models.UpdateRepositoryUnits(repo, units); err != nil { - ctx.Error(http.StatusInternalServerError, "UpdateRepositoryUnits", err) + ctx.Error(500, "UpdateRepositoryUnits", err) return err } @@ -881,20 +880,20 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e if opts.Archived != nil { if repo.IsMirror { err := fmt.Errorf("repo is a mirror, cannot archive/un-archive") - ctx.Error(http.StatusUnprocessableEntity, err.Error(), err) + ctx.Error(422, err.Error(), err) return err } if *opts.Archived { if err := repo.SetArchiveRepoState(*opts.Archived); err != nil { log.Error("Tried to archive a repo: %s", err) - ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err) + ctx.Error(500, "ArchiveRepoState", err) return err } log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name) } else { if err := repo.SetArchiveRepoState(*opts.Archived); err != nil { log.Error("Tried to un-archive a repo: %s", err) - ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err) + ctx.Error(500, "ArchiveRepoState", err) return err } log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name) diff --git a/routers/api/v1/repo/repo_test.go b/routers/api/v1/repo/repo_test.go index 053134ec6199..74ea884e5aa8 100644 --- a/routers/api/v1/repo/repo_test.go +++ b/routers/api/v1/repo/repo_test.go @@ -5,7 +5,6 @@ package repo import ( - "net/http" "testing" "code.gitea.io/gitea/models" @@ -55,7 +54,7 @@ func TestRepoEdit(t *testing.T) { Edit(&context.APIContext{Context: ctx, Org: nil}, opts) - assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) + assert.EqualValues(t, 200, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.Repository{ ID: 1, }, models.Cond("name = ? AND is_archived = 1", *opts.Name)) @@ -74,7 +73,7 @@ func TestRepoEditNameChange(t *testing.T) { } Edit(&context.APIContext{Context: ctx, Org: nil}, opts) - assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) + assert.EqualValues(t, 200, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.Repository{ ID: 1, diff --git a/routers/api/v1/repo/tag.go b/routers/api/v1/repo/tag.go index 0a764113ab80..9f8b749afd4a 100644 --- a/routers/api/v1/repo/tag.go +++ b/routers/api/v1/repo/tag.go @@ -5,7 +5,6 @@ package repo import ( - "net/http" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -76,17 +75,17 @@ func GetTag(ctx *context.APIContext) { sha := ctx.Params("sha") if len(sha) == 0 { - ctx.Error(http.StatusBadRequest, "", "SHA not provided") + ctx.Error(400, "", "SHA not provided") return } if tag, err := ctx.Repo.GitRepo.GetAnnotatedTag(sha); err != nil { - ctx.Error(http.StatusBadRequest, "GetTag", err) + ctx.Error(400, "GetTag", err) } else { commit, err := tag.Commit() if err != nil { - ctx.Error(http.StatusBadRequest, "GetTag", err) + ctx.Error(400, "GetTag", err) } - ctx.JSON(http.StatusOK, convert.ToAnnotatedTag(ctx.Repo.Repository, tag, commit)) + ctx.JSON(200, convert.ToAnnotatedTag(ctx.Repo.Repository, tag, commit)) } } diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index 1656fd1b16c7..65701d4ff5c2 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -5,7 +5,6 @@ package repo import ( - "net/http" "strings" "code.gitea.io/gitea/models" @@ -42,7 +41,7 @@ func ListTopics(ctx *context.APIContext) { }) if err != nil { log.Error("ListTopics failed: %v", err) - ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ + ctx.JSON(500, map[string]interface{}{ "message": "ListTopics failed.", }) return @@ -52,7 +51,7 @@ func ListTopics(ctx *context.APIContext) { for i, topic := range topics { topicNames[i] = topic.Name } - ctx.JSON(http.StatusOK, map[string]interface{}{ + ctx.JSON(200, map[string]interface{}{ "topics": topicNames, }) } @@ -82,20 +81,20 @@ func UpdateTopics(ctx *context.APIContext, form api.RepoTopicOptions) { // responses: // "204": // "$ref": "#/responses/empty" + // "422": + // "$ref": "#/responses/validationError" topicNames := form.Topics validTopics, invalidTopics := models.SanitizeAndValidateTopics(topicNames) if len(validTopics) > 25 { - ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{ - "invalidTopics": nil, - "message": "Exceeding maximum number of topics per repo", - }) + ctx.Error(422, "", "Exceeding maximum number of topics per repo") return } if len(invalidTopics) > 0 { - ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{ + ctx.JSON(422, map[string]interface{}{ + "invalidTopics": invalidTopics, "message": "Topic names are invalid", }) @@ -105,13 +104,13 @@ func UpdateTopics(ctx *context.APIContext, form api.RepoTopicOptions) { err := models.SaveTopics(ctx.Repo.Repository.ID, validTopics...) if err != nil { log.Error("SaveTopics failed: %v", err) - ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ + ctx.JSON(500, map[string]interface{}{ "message": "Save topics failed.", }) return } - ctx.Status(http.StatusNoContent) + ctx.Status(204) } // AddTopic adds a topic name to a repo @@ -144,7 +143,7 @@ func AddTopic(ctx *context.APIContext) { topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) if !models.ValidateTopic(topicName) { - ctx.Error(http.StatusUnprocessableEntity, "", "Topic name is invalid") + ctx.Error(422, "", "Topic name is invalid") return } @@ -154,13 +153,13 @@ func AddTopic(ctx *context.APIContext) { }) if err != nil { log.Error("AddTopic failed: %v", err) - ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ + ctx.JSON(500, map[string]interface{}{ "message": "ListTopics failed.", }) return } if len(topics) >= 25 { - ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{ + ctx.JSON(422, map[string]interface{}{ "message": "Exceeding maximum allowed topics per repo.", }) return @@ -169,13 +168,13 @@ func AddTopic(ctx *context.APIContext) { _, err = models.AddTopic(ctx.Repo.Repository.ID, topicName) if err != nil { log.Error("AddTopic failed: %v", err) - ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ + ctx.JSON(500, map[string]interface{}{ "message": "AddTopic failed.", }) return } - ctx.Status(http.StatusNoContent) + ctx.Status(204) } // DeleteTopic removes topic name from repo @@ -207,14 +206,14 @@ func DeleteTopic(ctx *context.APIContext) { topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) if !models.ValidateTopic(topicName) { - ctx.Error(http.StatusUnprocessableEntity, "", "Topic name is invalid") + ctx.Error(422, "", "Topic name is invalid") return } topic, err := models.DeleteTopic(ctx.Repo.Repository.ID, topicName) if err != nil { log.Error("DeleteTopic failed: %v", err) - ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ + ctx.JSON(500, map[string]interface{}{ "message": "DeleteTopic failed.", }) return @@ -224,7 +223,7 @@ func DeleteTopic(ctx *context.APIContext) { ctx.NotFound() } - ctx.Status(http.StatusNoContent) + ctx.Status(204) } // TopicSearch search for creating topic @@ -244,7 +243,7 @@ func TopicSearch(ctx *context.Context) { // "200": // "$ref": "#/responses/TopicListResponse" if ctx.User == nil { - ctx.JSON(http.StatusForbidden, map[string]interface{}{ + ctx.JSON(403, map[string]interface{}{ "message": "Only owners could change the topics.", }) return @@ -258,7 +257,7 @@ func TopicSearch(ctx *context.Context) { }) if err != nil { log.Error("SearchTopics failed: %v", err) - ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ + ctx.JSON(500, map[string]interface{}{ "message": "Search topics failed.", }) return @@ -268,7 +267,7 @@ func TopicSearch(ctx *context.Context) { for i, topic := range topics { topicResponses[i] = convert.ToTopicResponse(topic) } - ctx.JSON(http.StatusOK, map[string]interface{}{ + ctx.JSON(200, map[string]interface{}{ "topics": topicResponses, }) } diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index 6f3fc4d32bbb..a22be39b51b5 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -5,7 +5,6 @@ package user import ( - "net/http" "strings" "code.gitea.io/gitea/models" @@ -143,16 +142,16 @@ func GetUserHeatmapData(ctx *context.APIContext) { user, err := models.GetUserByName(ctx.Params(":username")) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Status(http.StatusNotFound) + ctx.Status(404) } else { - ctx.Error(http.StatusInternalServerError, "GetUserByName", err) + ctx.Error(500, "GetUserByName", err) } return } heatmap, err := models.GetUserHeatmapDataByUser(user) if err != nil { - ctx.Error(http.StatusInternalServerError, "GetUserHeatmapDataByUser", err) + ctx.Error(500, "GetUserHeatmapDataByUser", err) return } ctx.JSON(200, heatmap) diff --git a/routers/api/v1/utils/hook.go b/routers/api/v1/utils/hook.go index f88b15200389..1f2a4fafc609 100644 --- a/routers/api/v1/utils/hook.go +++ b/routers/api/v1/utils/hook.go @@ -6,7 +6,6 @@ package utils import ( "encoding/json" - "net/http" "strings" "code.gitea.io/gitea/models" @@ -74,7 +73,7 @@ func AddOrgHook(ctx *context.APIContext, form *api.CreateHookOption) { org := ctx.Org.Organization hook, ok := addHook(ctx, form, org.ID, 0) if ok { - ctx.JSON(http.StatusCreated, convert.ToHook(org.HomeLink(), hook)) + ctx.JSON(201, convert.ToHook(org.HomeLink(), hook)) } } @@ -83,7 +82,7 @@ func AddRepoHook(ctx *context.APIContext, form *api.CreateHookOption) { repo := ctx.Repo hook, ok := addHook(ctx, form, 0, repo.Repository.ID) if ok { - ctx.JSON(http.StatusCreated, convert.ToHook(repo.RepoLink, hook)) + ctx.JSON(201, convert.ToHook(repo.RepoLink, hook)) } } From 2bc9d526a3681ea425549c4efa6ce2ef1e26f657 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 00:44:55 +0100 Subject: [PATCH 02/13] fix test --- routers/api/v1/misc/markdown_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/routers/api/v1/misc/markdown_test.go b/routers/api/v1/misc/markdown_test.go index ed80023bc283..47e99d2f06ac 100644 --- a/routers/api/v1/misc/markdown_test.go +++ b/routers/api/v1/misc/markdown_test.go @@ -2,6 +2,7 @@ package misc import ( "io/ioutil" + "net/http" "net/http/httptest" "net/url" "strings" From 4f5b0248d1f42fda9e09d0fb31260964a4590e1a Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 00:55:26 +0100 Subject: [PATCH 03/13] add many missing swagger responses --- routers/api/v1/admin/repo.go | 4 + routers/api/v1/admin/user.go | 2 + routers/api/v1/org/member.go | 8 + routers/api/v1/org/team.go | 18 ++ routers/api/v1/repo/blob.go | 3 +- routers/api/v1/repo/collaborators.go | 11 +- routers/api/v1/repo/file.go | 9 + routers/api/v1/repo/fork.go | 6 + routers/api/v1/repo/hook.go | 3 + routers/api/v1/repo/issue.go | 21 +- routers/api/v1/repo/issue_comment.go | 14 ++ routers/api/v1/repo/issue_label.go | 14 ++ routers/api/v1/repo/issue_reaction.go | 26 ++- routers/api/v1/repo/issue_stopwatch.go | 6 +- routers/api/v1/repo/issue_subscription.go | 9 +- routers/api/v1/repo/issue_tracked_time.go | 12 +- routers/api/v1/repo/key.go | 6 + routers/api/v1/repo/pull.go | 15 ++ routers/api/v1/repo/release.go | 3 + routers/api/v1/repo/release_attachment.go | 2 + routers/api/v1/repo/repo.go | 8 + routers/api/v1/repo/status.go | 11 + routers/api/v1/repo/tag.go | 3 +- routers/api/v1/repo/topic.go | 8 + routers/api/v1/repo/tree.go | 2 + routers/api/v1/user/email.go | 3 + templates/swagger/v1_json.tmpl | 236 +++++++++++++++++++++- 27 files changed, 438 insertions(+), 25 deletions(-) diff --git a/routers/api/v1/admin/repo.go b/routers/api/v1/admin/repo.go index 1f64b4223807..cbcd3fcb3ac0 100644 --- a/routers/api/v1/admin/repo.go +++ b/routers/api/v1/admin/repo.go @@ -35,6 +35,10 @@ func CreateRepo(ctx *context.APIContext, form api.CreateRepoOption) { // "$ref": "#/responses/Repository" // "403": // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + // "409": + // "$ref": "#/responses/error" // "422": // "$ref": "#/responses/validationError" owner := user.GetUserByParams(ctx) diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 3a4750c6ba5a..3e3299df57c5 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -57,6 +57,8 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { // "$ref": "#/responses/User" // "403": // "$ref": "#/responses/forbidden" + // "400": + // "$ref": "#/responses/error" // "422": // "$ref": "#/responses/validationError" u := &models.User{ diff --git a/routers/api/v1/org/member.go b/routers/api/v1/org/member.go index 45519e56062a..53c500f6264d 100644 --- a/routers/api/v1/org/member.go +++ b/routers/api/v1/org/member.go @@ -100,6 +100,8 @@ func IsMember(ctx *context.APIContext) { // responses: // "204": // description: user is a member + // "302": + // description: redirection to /orgs/{org}/public_members/{username} // "404": // description: user is not a member userToCheck := user.GetUserByParams(ctx) @@ -185,6 +187,9 @@ func PublicizeMember(ctx *context.APIContext) { // responses: // "204": // description: membership publicized + // "403": + // "$ref": "#/responses/forbidden" + userToPublicize := user.GetUserByParams(ctx) if ctx.Written() { return @@ -222,6 +227,9 @@ func ConcealMember(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + userToConceal := user.GetUserByParams(ctx) if ctx.Written() { return diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index c14742e3a4e6..d78a25a849f5 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -127,6 +127,9 @@ func CreateTeam(ctx *context.APIContext, form api.CreateTeamOption) { // responses: // "201": // "$ref": "#/responses/Team" + // "422": + // "$ref": "#/responses/validationError" + team := &models.Team{ OrgID: ctx.Org.Organization.ID, Name: form.Name, @@ -305,6 +308,9 @@ func GetTeamMember(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/User" + // "404": + // "$ref": "#/responses/notFound" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -343,6 +349,9 @@ func AddTeamMember(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "404": + // "$ref": "#/responses/notFound" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -376,6 +385,9 @@ func RemoveTeamMember(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "404": + // "$ref": "#/responses/notFound" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -462,6 +474,9 @@ func AddTeamRepository(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + repo := getRepositoryByParams(ctx) if ctx.Written() { return @@ -509,6 +524,9 @@ func RemoveTeamRepository(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + repo := getRepositoryByParams(ctx) if ctx.Written() { return diff --git a/routers/api/v1/repo/blob.go b/routers/api/v1/repo/blob.go index 70f7a8bbe266..d1a3366510f8 100644 --- a/routers/api/v1/repo/blob.go +++ b/routers/api/v1/repo/blob.go @@ -5,7 +5,6 @@ package repo import ( - "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/repofiles" ) @@ -36,6 +35,8 @@ func GetBlob(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/GitBlobResponse" + // "400": + // "$ref": "#/responses/error" sha := ctx.Params("sha") if len(sha) == 0 { diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index 81d472dffb3a..1a42d44ca2a2 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -74,7 +74,10 @@ func IsCollaborator(ctx *context.APIContext) { // "204": // "$ref": "#/responses/empty" // "404": - // "$ref": "#/responses/empty" + // "$ref": "#/responses/notFound" + // "422": + // "$ref": "#/responses/validationError" + user, err := models.GetUserByName(ctx.Params(":collaborator")) if err != nil { if models.IsErrUserNotExist(err) { @@ -126,6 +129,9 @@ func AddCollaborator(ctx *context.APIContext, form api.AddCollaboratorOption) { // responses: // "204": // "$ref": "#/responses/empty" + // "422": + // "$ref": "#/responses/validationError" + collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) if err != nil { if models.IsErrUserNotExist(err) { @@ -182,6 +188,9 @@ func DeleteCollaborator(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "422": + // "$ref": "#/responses/validationError" + collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) if err != nil { if models.IsErrUserNotExist(err) { diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 20ef4f8841ab..3680c523e691 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -42,6 +42,9 @@ func GetRawFile(ctx *context.APIContext) { // responses: // 200: // description: success + // "404": + // "$ref": "#/responses/notFound" + if ctx.Repo.Repository.IsEmpty { ctx.NotFound() return @@ -87,6 +90,9 @@ func GetArchive(ctx *context.APIContext) { // responses: // 200: // description: success + // "404": + // "$ref": "#/responses/notFound" + repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) gitRepo, err := git.OpenRepository(repoPath) if err != nil { @@ -125,6 +131,9 @@ func GetEditorconfig(ctx *context.APIContext) { // responses: // 200: // description: success + // "404": + // "$ref": "#/responses/notFound" + ec, err := ctx.Repo.GetEditorconfig() if err != nil { if git.IsErrNotExist(err) { diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index 31f2389478c7..a34140ef7058 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -74,6 +74,11 @@ func CreateFork(ctx *context.APIContext, form api.CreateForkOption) { // responses: // "202": // "$ref": "#/responses/Repository" + // "403": + // "$ref": "#/responses/forbidden" + // "422": + // "$ref": "#/responses/validationError" + repo := ctx.Repo.Repository var forker *models.User // user/org that will own the fork if form.Organization == nil { @@ -105,5 +110,6 @@ func CreateFork(ctx *context.APIContext, form api.CreateForkOption) { return } + //TODO change back to 201 ctx.JSON(202, fork.APIFormat(models.AccessModeOwner)) } diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index 3666d79fa08b..81deb666058c 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -75,6 +75,9 @@ func GetHook(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Hook" + // "404": + // "$ref": "#/responses/notFound" + repo := ctx.Repo hookID := ctx.ParamsInt64(":id") hook, err := utils.GetRepoHook(ctx, repo.Repository.ID, hookID) diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 3c5e02e3625e..9500b7bc3641 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -274,6 +274,9 @@ func GetIssue(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Issue" + // "404": + // "$ref": "#/responses/notFound" + issue, err := models.GetIssueWithAttrsByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { @@ -313,6 +316,13 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { // responses: // "201": // "$ref": "#/responses/Issue" + // "403": + // "$ref": "#/responses/forbidden" + // "412": + // "$ref": "#/responses/error" + // description: cannot close this issue because it still has open dependencies + // "422": + // "$ref": "#/responses/validationError" var deadlineUnix timeutil.TimeStamp if form.Deadline != nil && ctx.Repo.CanWrite(models.UnitTypeIssues) { @@ -428,6 +438,14 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { // responses: // "201": // "$ref": "#/responses/Issue" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + // "412": + // "$ref": "#/responses/error" + // description: cannot close this issue because it still has open dependencies + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { @@ -564,8 +582,9 @@ func UpdateIssueDeadline(ctx *context.APIContext, form api.EditDeadlineOption) { // "$ref": "#/responses/IssueDeadline" // "403": // description: Not repo writer + // "$ref": "#/responses/forbidden" // "404": - // description: Issue not found + // "$ref": "#/responses/notFound" 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 3a5f6d24474f..ea9a84b8337d 100644 --- a/routers/api/v1/repo/issue_comment.go +++ b/routers/api/v1/repo/issue_comment.go @@ -178,6 +178,9 @@ func CreateIssueComment(ctx *context.APIContext, form api.CreateIssueCommentOpti // responses: // "201": // "$ref": "#/responses/Comment" + // "403": + // "$ref": "#/responses/forbidden" + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { ctx.Error(500, "GetIssueByIndex", err) @@ -273,6 +276,11 @@ func EditIssueCommentDeprecated(ctx *context.APIContext, form api.EditIssueComme // responses: // "200": // "$ref": "#/responses/Comment" + // "204": + // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + editIssueComment(ctx, form) } @@ -330,6 +338,9 @@ func DeleteIssueComment(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + deleteIssueComment(ctx) } @@ -364,6 +375,9 @@ func DeleteIssueCommentDeprecated(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + deleteIssueComment(ctx) } diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go index e41c1512e2ca..fd501abcd10a 100644 --- a/routers/api/v1/repo/issue_label.go +++ b/routers/api/v1/repo/issue_label.go @@ -96,6 +96,9 @@ func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { // responses: // "200": // "$ref": "#/responses/LabelList" + // "403": + // "$ref": "#/responses/forbidden" + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { @@ -168,6 +171,11 @@ func DeleteIssueLabel(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + // "422": + // "$ref": "#/responses/validationError" + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { @@ -234,6 +242,9 @@ func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { // responses: // "200": // "$ref": "#/responses/LabelList" + // "403": + // "$ref": "#/responses/forbidden" + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { @@ -300,6 +311,9 @@ func ClearIssueLabels(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { diff --git a/routers/api/v1/repo/issue_reaction.go b/routers/api/v1/repo/issue_reaction.go index 56e12ccdcc3c..9caca378dc46 100644 --- a/routers/api/v1/repo/issue_reaction.go +++ b/routers/api/v1/repo/issue_reaction.go @@ -41,6 +41,9 @@ func GetIssueCommentReactions(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/ReactionResponseList" + // "403": + // "$ref": "#/responses/forbidden" + comment, err := models.GetCommentByID(ctx.ParamsInt64(":id")) if err != nil { if models.IsErrCommentNotExist(err) { @@ -112,6 +115,9 @@ func PostIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOpti // responses: // "201": // "$ref": "#/responses/ReactionResponse" + // "403": + // "$ref": "#/responses/forbidden" + changeIssueCommentReaction(ctx, form, true) } @@ -146,8 +152,11 @@ func DeleteIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp // schema: // "$ref": "#/definitions/EditReactionOption" // responses: - // "200": + // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + changeIssueCommentReaction(ctx, form, false) } @@ -201,7 +210,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp ctx.Error(500, "DeleteCommentReaction", err) return } - ctx.Status(200) + ctx.Status(204) } } @@ -234,6 +243,9 @@ func GetIssueReactions(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/ReactionResponseList" + // "403": + // "$ref": "#/responses/forbidden" + issue, err := models.GetIssueWithAttrsByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { @@ -305,6 +317,9 @@ func PostIssueReaction(ctx *context.APIContext, form api.EditReactionOption) { // responses: // "201": // "$ref": "#/responses/ReactionResponse" + // "403": + // "$ref": "#/responses/forbidden" + changeIssueReaction(ctx, form, true) } @@ -339,8 +354,11 @@ func DeleteIssueReaction(ctx *context.APIContext, form api.EditReactionOption) { // schema: // "$ref": "#/definitions/EditReactionOption" // responses: - // "200": + // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + changeIssueReaction(ctx, form, false) } @@ -389,6 +407,6 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i ctx.Error(500, "DeleteIssueReaction", err) return } - ctx.Status(200) + ctx.Status(204) } } diff --git a/routers/api/v1/repo/issue_stopwatch.go b/routers/api/v1/repo/issue_stopwatch.go index 48b2f6498f0f..8bd442a67c03 100644 --- a/routers/api/v1/repo/issue_stopwatch.go +++ b/routers/api/v1/repo/issue_stopwatch.go @@ -41,7 +41,7 @@ func StartIssueStopwatch(ctx *context.APIContext) { // "403": // description: Not repo writer, user does not have rights to toggle stopwatch // "404": - // description: Issue not found + // "$ref": "#/responses/notFound" // "409": // description: Cannot start a stopwatch again if it already exists issue, err := prepareIssueStopwatch(ctx, false) @@ -89,7 +89,7 @@ func StopIssueStopwatch(ctx *context.APIContext) { // "403": // description: Not repo writer, user does not have rights to toggle stopwatch // "404": - // description: Issue not found + // "$ref": "#/responses/notFound" // "409": // description: Cannot stop a non existent stopwatch issue, err := prepareIssueStopwatch(ctx, true) @@ -137,7 +137,7 @@ func DeleteIssueStopwatch(ctx *context.APIContext) { // "403": // description: Not repo writer, user does not have rights to toggle stopwatch // "404": - // description: Issue not found + // "$ref": "#/responses/notFound" // "409": // description: Cannot cancel a non existent stopwatch issue, err := prepareIssueStopwatch(ctx, true) diff --git a/routers/api/v1/repo/issue_subscription.go b/routers/api/v1/repo/issue_subscription.go index 2c5f75f1eca0..9f0ce3ca7f77 100644 --- a/routers/api/v1/repo/issue_subscription.go +++ b/routers/api/v1/repo/issue_subscription.go @@ -46,7 +46,8 @@ func AddIssueSubscription(ctx *context.APIContext) { // "304": // description: User can only subscribe itself if he is no admin // "404": - // description: Issue not found + // "$ref": "#/responses/notFound" + setIssueSubscription(ctx, true) } @@ -87,7 +88,8 @@ func DelIssueSubscription(ctx *context.APIContext) { // "304": // description: User can only subscribe itself if he is no admin // "404": - // description: Issue not found + // "$ref": "#/responses/notFound" + setIssueSubscription(ctx, false) } @@ -158,7 +160,8 @@ func GetIssueSubscribers(ctx *context.APIContext) { // "200": // "$ref": "#/responses/UserList" // "404": - // description: Issue not found + // "$ref": "#/responses/notFound" + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go index c38ea05c363f..c3ace26fc993 100644 --- a/routers/api/v1/repo/issue_tracked_time.go +++ b/routers/api/v1/repo/issue_tracked_time.go @@ -45,6 +45,9 @@ func ListTrackedTimes(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/TrackedTimeList" + // "404": + // "$ref": "#/responses/notFound" + if !ctx.Repo.Repository.IsTimetrackerEnabled() { ctx.NotFound("Timetracker is disabled") return @@ -104,7 +107,8 @@ func AddTime(ctx *context.APIContext, form api.AddTimeOption) { // "400": // "$ref": "#/responses/error" // "403": - // "$ref": "#/responses/error" + // "$ref": "#/responses/forbidden" + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { @@ -157,6 +161,9 @@ func ListTrackedTimesByUser(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/TrackedTimeList" + // "400": + // "$ref": "#/responses/error" + if !ctx.Repo.Repository.IsTimetrackerEnabled() { ctx.JSON(400, struct{ Message string }{Message: "time tracking disabled"}) return @@ -206,6 +213,9 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/TrackedTimeList" + // "400": + // "$ref": "#/responses/error" + if !ctx.Repo.Repository.IsTimetrackerEnabled() { ctx.JSON(400, struct{ Message string }{Message: "time tracking disabled"}) return diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index 6b499d2fb110..eb547df17551 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -196,6 +196,9 @@ func CreateDeployKey(ctx *context.APIContext, form api.CreateKeyOption) { // responses: // "201": // "$ref": "#/responses/DeployKey" + // "422": + // "$ref": "#/responses/validationError" + content, err := models.CheckPublicKeyString(form.Key) if err != nil { HandleCheckKeyStringError(ctx, err) @@ -238,6 +241,9 @@ func DeleteDeploykey(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + if err := models.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if models.IsErrKeyAccessDenied(err) { ctx.Error(403, "", "You do not have access to this key") diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index aa7b5edf5da3..462c42646250 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -182,6 +182,11 @@ func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption // responses: // "201": // "$ref": "#/responses/PullRequest" + // "409": + // "$ref": "#/responses/error" + // "422": + // "$ref": "#/responses/validationError" + var ( repo = ctx.Repo.Repository labelIDs []int64 @@ -347,6 +352,13 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { // responses: // "201": // "$ref": "#/responses/PullRequest" + // "403": + // "$ref": "#/responses/forbidden" + // "412": + // "$ref": "#/responses/error" + // "422": + // "$ref": "#/responses/validationError" + pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrPullRequestNotExist(err) { @@ -543,6 +555,9 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { // "$ref": "#/responses/empty" // "405": // "$ref": "#/responses/empty" + // "409": + // "$ref": "#/responses/error" + pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrPullRequestNotExist(err) { diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go index 8bcebf6b4098..cf7b9676b479 100644 --- a/routers/api/v1/repo/release.go +++ b/routers/api/v1/repo/release.go @@ -146,6 +146,9 @@ func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) { // responses: // "201": // "$ref": "#/responses/Release" + // "409": + // "$ref": "#/responses/error" + rel, err := models.GetRelease(ctx.Repo.Repository.ID, form.TagName) if err != nil { if !models.IsErrReleaseNotExist(err) { diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go index c49e4d3e346e..479b6e291d34 100644 --- a/routers/api/v1/repo/release_attachment.go +++ b/routers/api/v1/repo/release_attachment.go @@ -147,6 +147,8 @@ func CreateReleaseAttachment(ctx *context.APIContext) { // responses: // "201": // "$ref": "#/responses/Attachment" + // "400": + // "$ref": "#/responses/error" // Check if attachments are enabled if !setting.AttachmentEnabled { diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 4f789e4ef4ad..99f971eed5d9 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -351,6 +351,11 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { // responses: // "201": // "$ref": "#/responses/Repository" + // "403": + // "$ref": "#/responses/forbidden" + // "422": + // "$ref": "#/responses/validationError" + ctxUser := ctx.User // Not equal means context user is an organization, // or is another user/organization if current user is admin. @@ -967,6 +972,9 @@ func MirrorSync(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/empty" + // "403": + // "$ref": "#/responses/forbidden" + repo := ctx.Repo.Repository if !ctx.Repo.CanWrite(models.UnitTypeCode) { diff --git a/routers/api/v1/repo/status.go b/routers/api/v1/repo/status.go index 7d4a2de38911..d8592f4de4a1 100644 --- a/routers/api/v1/repo/status.go +++ b/routers/api/v1/repo/status.go @@ -43,6 +43,9 @@ func NewCommitStatus(ctx *context.APIContext, form api.CreateStatusOption) { // responses: // "201": // "$ref": "#/responses/Status" + // "400": + // "$ref": "#/responses/error" + sha := ctx.Params("sha") if len(sha) == 0 { ctx.Error(400, "sha not given", nil) @@ -105,6 +108,9 @@ func GetCommitStatuses(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/StatusList" + // "400": + // "$ref": "#/responses/error" + getCommitStatuses(ctx, ctx.Params("sha")) } @@ -151,6 +157,8 @@ func GetCommitStatusesByRef(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/StatusList" + // "400": + // "$ref": "#/responses/error" filter := ctx.Params("ref") if len(filter) == 0 { @@ -251,6 +259,9 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Status" + // "400": + // "$ref": "#/responses/error" + sha := ctx.Params("ref") if len(sha) == 0 { ctx.Error(400, "ref/sha not given", nil) diff --git a/routers/api/v1/repo/tag.go b/routers/api/v1/repo/tag.go index 9f8b749afd4a..15c8b6fd2ced 100644 --- a/routers/api/v1/repo/tag.go +++ b/routers/api/v1/repo/tag.go @@ -5,7 +5,6 @@ package repo import ( - "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" @@ -72,6 +71,8 @@ func GetTag(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/AnnotatedTag" + // "400": + // "$ref": "#/responses/error" sha := ctx.Params("sha") if len(sha) == 0 { diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index 65701d4ff5c2..f0f6c954f015 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -139,6 +139,8 @@ func AddTopic(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "422": + // "$ref": "#/responses/validationError" topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) @@ -203,6 +205,9 @@ func DeleteTopic(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + // "422": + // "$ref": "#/responses/validationError" + topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) if !models.ValidateTopic(topicName) { @@ -242,6 +247,9 @@ func TopicSearch(ctx *context.Context) { // responses: // "200": // "$ref": "#/responses/TopicListResponse" + // "403": + // "$ref": "#/responses/forbidden" + if ctx.User == nil { ctx.JSON(403, map[string]interface{}{ "message": "Only owners could change the topics.", diff --git a/routers/api/v1/repo/tree.go b/routers/api/v1/repo/tree.go index 066ca662f84b..2066ab5a5937 100644 --- a/routers/api/v1/repo/tree.go +++ b/routers/api/v1/repo/tree.go @@ -50,6 +50,8 @@ func GetTree(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/GitTreeResponse" + // "400": + // "$ref": "#/responses/error" sha := ctx.Params(":sha") if len(sha) == 0 { diff --git a/routers/api/v1/user/email.go b/routers/api/v1/user/email.go index 8c0eb889ed12..04cd55971f30 100644 --- a/routers/api/v1/user/email.go +++ b/routers/api/v1/user/email.go @@ -55,6 +55,9 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { // responses: // '201': // "$ref": "#/responses/EmailList" + // "422": + // "$ref": "#/responses/validationError" + if len(form.Emails) == 0 { ctx.Status(422) return diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index f1789535bafa..c7a4e8a2369c 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -101,6 +101,9 @@ "201": { "$ref": "#/responses/User" }, + "400": { + "$ref": "#/responses/error" + }, "403": { "$ref": "#/responses/forbidden" }, @@ -344,6 +347,12 @@ "403": { "$ref": "#/responses/forbidden" }, + "404": { + "$ref": "#/responses/notFound" + }, + "409": { + "$ref": "#/responses/error" + }, "422": { "$ref": "#/responses/validationError" } @@ -803,6 +812,9 @@ "204": { "description": "user is a member" }, + "302": { + "description": "redirection to /orgs/{org}/public_members/{username}" + }, "404": { "description": "user is not a member" } @@ -926,6 +938,9 @@ "responses": { "204": { "description": "membership publicized" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -957,6 +972,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -1043,6 +1061,9 @@ "responses": { "201": { "$ref": "#/responses/Team" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -1186,6 +1207,12 @@ "responses": { "201": { "$ref": "#/responses/Repository" + }, + "403": { + "$ref": "#/responses/forbidden" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -1447,6 +1474,9 @@ "responses": { "200": { "description": "success" + }, + "404": { + "$ref": "#/responses/notFound" } } } @@ -1595,7 +1625,10 @@ "$ref": "#/responses/empty" }, "404": { - "$ref": "#/responses/empty" + "$ref": "#/responses/notFound" + }, + "422": { + "$ref": "#/responses/validationError" } } }, @@ -1641,6 +1674,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "422": { + "$ref": "#/responses/validationError" } } }, @@ -1679,6 +1715,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -1776,6 +1815,9 @@ "responses": { "200": { "$ref": "#/responses/Status" + }, + "400": { + "$ref": "#/responses/error" } } } @@ -2048,6 +2090,9 @@ "responses": { "200": { "description": "success" + }, + "404": { + "$ref": "#/responses/notFound" } } } @@ -2119,6 +2164,12 @@ "responses": { "202": { "$ref": "#/responses/Repository" + }, + "403": { + "$ref": "#/responses/forbidden" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -2159,6 +2210,9 @@ "responses": { "200": { "$ref": "#/responses/GitBlobResponse" + }, + "400": { + "$ref": "#/responses/error" } } } @@ -2321,6 +2375,9 @@ "responses": { "200": { "$ref": "#/responses/AnnotatedTag" + }, + "400": { + "$ref": "#/responses/error" } } } @@ -2379,6 +2436,9 @@ "responses": { "200": { "$ref": "#/responses/GitTreeResponse" + }, + "400": { + "$ref": "#/responses/error" } } } @@ -2659,6 +2719,9 @@ "responses": { "200": { "$ref": "#/responses/Hook" + }, + "404": { + "$ref": "#/responses/notFound" } } }, @@ -2886,6 +2949,16 @@ "responses": { "201": { "$ref": "#/responses/Issue" + }, + "403": { + "$ref": "#/responses/forbidden" + }, + "412": { + "description": "cannot close this issue because it still has open dependencies", + "$ref": "#/responses/error" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -2963,6 +3036,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -3056,6 +3132,9 @@ "responses": { "200": { "$ref": "#/responses/ReactionResponseList" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -3105,6 +3184,9 @@ "responses": { "201": { "$ref": "#/responses/ReactionResponse" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -3154,6 +3236,9 @@ "responses": { "200": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -3195,6 +3280,9 @@ "responses": { "200": { "$ref": "#/responses/TrackedTimeList" + }, + "404": { + "$ref": "#/responses/notFound" } } }, @@ -3249,7 +3337,7 @@ "$ref": "#/responses/error" }, "403": { - "$ref": "#/responses/error" + "$ref": "#/responses/forbidden" } } } @@ -3291,6 +3379,9 @@ "responses": { "200": { "$ref": "#/responses/Issue" + }, + "404": { + "$ref": "#/responses/notFound" } } }, @@ -3340,6 +3431,16 @@ "responses": { "201": { "$ref": "#/responses/Issue" + }, + "403": { + "$ref": "#/responses/forbidden" + }, + "404": { + "$ref": "#/responses/notFound" + }, + "412": { + "description": "cannot close this issue because it still has open dependencies", + "$ref": "#/responses/error" } } } @@ -3436,6 +3537,9 @@ "responses": { "201": { "$ref": "#/responses/Comment" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -3482,6 +3586,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -3539,6 +3646,12 @@ "responses": { "200": { "$ref": "#/responses/Comment" + }, + "204": { + "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -3592,10 +3705,11 @@ "$ref": "#/responses/IssueDeadline" }, "403": { - "description": "Not repo writer" + "description": "Not repo writer", + "$ref": "#/responses/forbidden" }, "404": { - "description": "Issue not found" + "$ref": "#/responses/notFound" } } } @@ -3689,6 +3803,9 @@ "responses": { "200": { "$ref": "#/responses/LabelList" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -3738,6 +3855,9 @@ "responses": { "200": { "$ref": "#/responses/LabelList" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -3777,6 +3897,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -3826,6 +3949,12 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -3870,6 +3999,9 @@ "responses": { "200": { "$ref": "#/responses/ReactionResponseList" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -3919,6 +4051,9 @@ "responses": { "201": { "$ref": "#/responses/ReactionResponse" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -3968,6 +4103,9 @@ "responses": { "200": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -4017,7 +4155,7 @@ "description": "Not repo writer, user does not have rights to toggle stopwatch" }, "404": { - "description": "Issue not found" + "$ref": "#/responses/notFound" }, "409": { "description": "Cannot cancel a non existent stopwatch" @@ -4070,7 +4208,7 @@ "description": "Not repo writer, user does not have rights to toggle stopwatch" }, "404": { - "description": "Issue not found" + "$ref": "#/responses/notFound" }, "409": { "description": "Cannot start a stopwatch again if it already exists" @@ -4123,7 +4261,7 @@ "description": "Not repo writer, user does not have rights to toggle stopwatch" }, "404": { - "description": "Issue not found" + "$ref": "#/responses/notFound" }, "409": { "description": "Cannot stop a non existent stopwatch" @@ -4173,7 +4311,7 @@ "$ref": "#/responses/UserList" }, "404": { - "description": "Issue not found" + "$ref": "#/responses/notFound" } } } @@ -4230,7 +4368,7 @@ "description": "User can only subscribe itself if he is no admin" }, "404": { - "description": "Issue not found" + "$ref": "#/responses/notFound" } } }, @@ -4285,7 +4423,7 @@ "description": "User can only subscribe itself if he is no admin" }, "404": { - "description": "Issue not found" + "$ref": "#/responses/notFound" } } } @@ -4372,6 +4510,9 @@ "responses": { "201": { "$ref": "#/responses/DeployKey" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -4449,6 +4590,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -4888,6 +5032,9 @@ "responses": { "200": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -5011,6 +5158,12 @@ "responses": { "201": { "$ref": "#/responses/PullRequest" + }, + "409": { + "$ref": "#/responses/error" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -5101,6 +5254,15 @@ "responses": { "201": { "$ref": "#/responses/PullRequest" + }, + "403": { + "$ref": "#/responses/forbidden" + }, + "412": { + "$ref": "#/responses/error" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -5194,6 +5356,9 @@ }, "405": { "$ref": "#/responses/empty" + }, + "409": { + "$ref": "#/responses/error" } } } @@ -5234,6 +5399,9 @@ "responses": { "200": { "description": "success" + }, + "404": { + "$ref": "#/responses/notFound" } } } @@ -5320,6 +5488,9 @@ "responses": { "201": { "$ref": "#/responses/Release" + }, + "409": { + "$ref": "#/responses/error" } } } @@ -5542,6 +5713,9 @@ "responses": { "201": { "$ref": "#/responses/Attachment" + }, + "400": { + "$ref": "#/responses/error" } } } @@ -5836,6 +6010,9 @@ "responses": { "200": { "$ref": "#/responses/StatusList" + }, + "400": { + "$ref": "#/responses/error" } } }, @@ -5881,6 +6058,9 @@ "responses": { "201": { "$ref": "#/responses/Status" + }, + "400": { + "$ref": "#/responses/error" } } } @@ -6066,6 +6246,9 @@ "responses": { "200": { "$ref": "#/responses/TrackedTimeList" + }, + "400": { + "$ref": "#/responses/error" } } } @@ -6106,6 +6289,9 @@ "responses": { "200": { "$ref": "#/responses/TrackedTimeList" + }, + "400": { + "$ref": "#/responses/error" } } } @@ -6177,6 +6363,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -6217,6 +6406,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "422": { + "$ref": "#/responses/validationError" } } }, @@ -6255,6 +6447,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "422": { + "$ref": "#/responses/validationError" } } } @@ -6446,6 +6641,9 @@ "responses": { "200": { "$ref": "#/responses/User" + }, + "404": { + "$ref": "#/responses/notFound" } } }, @@ -6478,6 +6676,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "404": { + "$ref": "#/responses/notFound" } } }, @@ -6510,6 +6711,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "404": { + "$ref": "#/responses/notFound" } } } @@ -6578,6 +6782,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } }, @@ -6618,6 +6825,9 @@ "responses": { "204": { "$ref": "#/responses/empty" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -6644,6 +6854,9 @@ "responses": { "200": { "$ref": "#/responses/TopicListResponse" + }, + "403": { + "$ref": "#/responses/forbidden" } } } @@ -6702,6 +6915,9 @@ "responses": { "201": { "$ref": "#/responses/EmailList" + }, + "422": { + "$ref": "#/responses/validationError" } } }, From 563b8e5b54d4bc5333c48b2141de766b9da9b2df Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 00:57:42 +0100 Subject: [PATCH 04/13] code format --- routers/api/v1/admin/org.go | 2 ++ routers/api/v1/admin/repo.go | 1 + routers/api/v1/admin/user.go | 6 ++++++ routers/api/v1/org/hook.go | 3 +++ routers/api/v1/org/member.go | 5 +++++ routers/api/v1/org/org.go | 5 +++++ routers/api/v1/org/team.go | 8 ++++++++ routers/api/v1/repo/branch.go | 2 ++ routers/api/v1/repo/collaborators.go | 1 + routers/api/v1/repo/file.go | 1 + routers/api/v1/repo/fork.go | 1 + routers/api/v1/repo/git_hook.go | 4 ++++ routers/api/v1/repo/hook.go | 2 ++ routers/api/v1/repo/issue.go | 2 ++ routers/api/v1/repo/issue_comment.go | 2 ++ routers/api/v1/repo/issue_label.go | 1 + routers/api/v1/repo/issue_stopwatch.go | 3 +++ routers/api/v1/repo/issue_tracked_time.go | 1 + routers/api/v1/repo/key.go | 2 ++ routers/api/v1/repo/label.go | 5 +++++ routers/api/v1/repo/milestone.go | 5 +++++ routers/api/v1/repo/pull.go | 3 +++ routers/api/v1/repo/release.go | 4 ++++ routers/api/v1/repo/release_attachment.go | 2 ++ routers/api/v1/repo/repo.go | 7 +++++++ routers/api/v1/repo/star.go | 1 + routers/api/v1/repo/subscriber.go | 1 + routers/api/v1/repo/tag.go | 1 + routers/api/v1/repo/topic.go | 1 + routers/api/v1/user/app.go | 3 +++ routers/api/v1/user/email.go | 2 ++ routers/api/v1/user/follower.go | 8 ++++++++ routers/api/v1/user/gpg_key.go | 5 +++++ routers/api/v1/user/key.go | 5 +++++ routers/api/v1/user/repo.go | 3 +++ routers/api/v1/user/star.go | 5 +++++ routers/api/v1/user/user.go | 3 +++ routers/api/v1/user/watch.go | 5 +++++ 38 files changed, 121 insertions(+) diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go index 8d3b0123c532..26a627def541 100644 --- a/routers/api/v1/admin/org.go +++ b/routers/api/v1/admin/org.go @@ -39,6 +39,7 @@ func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) { // "$ref": "#/responses/forbidden" // "422": // "$ref": "#/responses/validationError" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -95,6 +96,7 @@ func GetAllOrgs(ctx *context.APIContext) { // "$ref": "#/responses/OrganizationList" // "403": // "$ref": "#/responses/forbidden" + users, _, err := models.SearchUsers(&models.SearchUserOptions{ Type: models.UserTypeOrganization, OrderBy: models.SearchOrderByAlphabetically, diff --git a/routers/api/v1/admin/repo.go b/routers/api/v1/admin/repo.go index cbcd3fcb3ac0..c3ca525510aa 100644 --- a/routers/api/v1/admin/repo.go +++ b/routers/api/v1/admin/repo.go @@ -41,6 +41,7 @@ func CreateRepo(ctx *context.APIContext, form api.CreateRepoOption) { // "$ref": "#/responses/error" // "422": // "$ref": "#/responses/validationError" + owner := user.GetUserByParams(ctx) if ctx.Written() { return diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 3e3299df57c5..0ba2e4b9bc90 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -61,6 +61,7 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { // "$ref": "#/responses/error" // "422": // "$ref": "#/responses/validationError" + u := &models.User{ Name: form.Username, FullName: form.FullName, @@ -129,6 +130,7 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) { // "$ref": "#/responses/forbidden" // "422": // "$ref": "#/responses/validationError" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -217,6 +219,7 @@ func DeleteUser(ctx *context.APIContext) { // "$ref": "#/responses/forbidden" // "422": // "$ref": "#/responses/validationError" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -262,6 +265,7 @@ func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) { // "$ref": "#/responses/forbidden" // "422": // "$ref": "#/responses/validationError" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -295,6 +299,7 @@ func DeleteUserPublicKey(ctx *context.APIContext) { // "$ref": "#/responses/forbidden" // "404": // "$ref": "#/responses/notFound" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -327,6 +332,7 @@ func GetAllUsers(ctx *context.APIContext) { // "$ref": "#/responses/UserList" // "403": // "$ref": "#/responses/forbidden" + users, _, err := models.SearchUsers(&models.SearchUserOptions{ Type: models.UserTypeIndividual, OrderBy: models.SearchOrderByAlphabetically, diff --git a/routers/api/v1/org/hook.go b/routers/api/v1/org/hook.go index c7b0bd5b6b15..f807aff41b11 100644 --- a/routers/api/v1/org/hook.go +++ b/routers/api/v1/org/hook.go @@ -28,6 +28,7 @@ func ListHooks(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/HookList" + org := ctx.Org.Organization orgHooks, err := models.GetWebhooksByOrgID(org.ID) if err != nil { @@ -63,6 +64,7 @@ func GetHook(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Hook" + org := ctx.Org.Organization hookID := ctx.ParamsInt64(":id") hook, err := utils.GetOrgHook(ctx, org.ID, hookID) @@ -159,6 +161,7 @@ func DeleteHook(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + org := ctx.Org.Organization hookID := ctx.ParamsInt64(":id") if err := models.DeleteWebhookByOrgID(org.ID, hookID); err != nil { diff --git a/routers/api/v1/org/member.go b/routers/api/v1/org/member.go index 53c500f6264d..89260a0b4dda 100644 --- a/routers/api/v1/org/member.go +++ b/routers/api/v1/org/member.go @@ -50,6 +50,7 @@ func ListMembers(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + publicOnly := true if ctx.User != nil { isMember, err := ctx.Org.Organization.IsOrgMember(ctx.User.ID) @@ -78,6 +79,7 @@ func ListPublicMembers(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + listMembers(ctx, true) } @@ -104,6 +106,7 @@ func IsMember(ctx *context.APIContext) { // description: redirection to /orgs/{org}/public_members/{username} // "404": // description: user is not a member + userToCheck := user.GetUserByParams(ctx) if ctx.Written() { return @@ -155,6 +158,7 @@ func IsPublicMember(ctx *context.APIContext) { // description: user is a public member // "404": // description: user is not a public member + userToCheck := user.GetUserByParams(ctx) if ctx.Written() { return @@ -267,6 +271,7 @@ func DeleteMember(ctx *context.APIContext) { // responses: // "204": // description: member removed + member := user.GetUserByParams(ctx) if ctx.Written() { return diff --git a/routers/api/v1/org/org.go b/routers/api/v1/org/org.go index d698592361d2..636bf88141cc 100644 --- a/routers/api/v1/org/org.go +++ b/routers/api/v1/org/org.go @@ -36,6 +36,7 @@ func ListMyOrgs(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/OrganizationList" + listUserOrgs(ctx, ctx.User, true) } @@ -55,6 +56,7 @@ func ListUserOrgs(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/OrganizationList" + u := user.GetUserByParams(ctx) if ctx.Written() { return @@ -135,6 +137,7 @@ func Get(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Organization" + if !models.HasOrgVisible(ctx.Org.Organization, ctx.User) { ctx.NotFound("HasOrgVisible", nil) return @@ -165,6 +168,7 @@ func Edit(ctx *context.APIContext, form api.EditOrgOption) { // responses: // "200": // "$ref": "#/responses/Organization" + org := ctx.Org.Organization org.FullName = form.FullName org.Description = form.Description @@ -197,6 +201,7 @@ func Delete(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + if err := models.DeleteOrganization(ctx.Org.Organization); err != nil { ctx.Error(500, "DeleteOrganization", err) return diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index d78a25a849f5..98929f047298 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -32,6 +32,7 @@ func ListTeams(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/TeamList" + org := ctx.Org.Organization if err := org.GetTeams(); err != nil { ctx.Error(500, "GetTeams", err) @@ -60,6 +61,7 @@ func ListUserTeams(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/TeamList" + teams, err := models.GetUserTeams(ctx.User.ID) if err != nil { ctx.Error(500, "GetUserTeams", err) @@ -102,6 +104,7 @@ func GetTeam(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Team" + ctx.JSON(200, convert.ToTeam(ctx.Org.Team)) } @@ -186,6 +189,7 @@ func EditTeam(ctx *context.APIContext, form api.EditTeamOption) { // responses: // "200": // "$ref": "#/responses/Team" + team := ctx.Org.Team team.Description = form.Description unitTypes := models.FindUnitTypes(form.Units...) @@ -242,6 +246,7 @@ func DeleteTeam(ctx *context.APIContext) { // responses: // "204": // description: team deleted + if err := models.DeleteTeam(ctx.Org.Team); err != nil { ctx.Error(500, "DeleteTeam", err) return @@ -266,6 +271,7 @@ func GetTeamMembers(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + isMember, err := models.IsOrganizationMember(ctx.Org.Team.OrgID, ctx.User.ID) if err != nil { ctx.Error(500, "IsOrganizationMember", err) @@ -417,6 +423,7 @@ func GetTeamRepos(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + team := ctx.Org.Team if err := team.GetRepositories(); err != nil { ctx.Error(500, "GetTeamRepos", err) @@ -586,6 +593,7 @@ func SearchTeam(ctx *context.APIContext) { // type: array // items: // "$ref": "#/definitions/Team" + opts := &models.SearchTeamOptions{ UserID: ctx.User.ID, Keyword: strings.TrimSpace(ctx.Query("q")), diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 9745903a9598..71483a58f6f7 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -38,6 +38,7 @@ func GetBranch(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Branch" + if ctx.Repo.TreePath != "" { // if TreePath != "", then URL contained extra slashes // (i.e. "master/subbranch" instead of "master"), so branch does @@ -91,6 +92,7 @@ func ListBranches(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/BranchList" + branches, err := ctx.Repo.Repository.GetBranches() if err != nil { ctx.Error(500, "GetBranches", err) diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index 1a42d44ca2a2..96be9e4639ae 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -35,6 +35,7 @@ func ListCollaborators(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + collaborators, err := ctx.Repo.Repository.GetCollaborators() if err != nil { ctx.Error(500, "ListCollaborators", err) diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 3680c523e691..021bd92e3922 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -340,6 +340,7 @@ func DeleteFile(ctx *context.APIContext, apiOpts api.DeleteFileOptions) { // responses: // "200": // "$ref": "#/responses/FileDeleteResponse" + if !CanWriteFiles(ctx.Repo) { ctx.Error(500, "DeleteFile", models.ErrUserDoesNotHaveAccessToRepo{ UserID: ctx.User.ID, diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index a34140ef7058..6f03cb76e49f 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -32,6 +32,7 @@ func ListForks(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + forks, err := ctx.Repo.Repository.GetForks() if err != nil { ctx.Error(500, "GetForks", err) diff --git a/routers/api/v1/repo/git_hook.go b/routers/api/v1/repo/git_hook.go index 46651ef61406..46e0b5174595 100644 --- a/routers/api/v1/repo/git_hook.go +++ b/routers/api/v1/repo/git_hook.go @@ -32,6 +32,7 @@ func ListGitHooks(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/GitHookList" + hooks, err := ctx.Repo.GitRepo.Hooks() if err != nil { ctx.Error(500, "Hooks", err) @@ -73,6 +74,7 @@ func GetGitHook(ctx *context.APIContext) { // "$ref": "#/responses/GitHook" // "404": // "$ref": "#/responses/notFound" + hookID := ctx.Params(":id") hook, err := ctx.Repo.GitRepo.GetHook(hookID) if err != nil { @@ -118,6 +120,7 @@ func EditGitHook(ctx *context.APIContext, form api.EditGitHookOption) { // "$ref": "#/responses/GitHook" // "404": // "$ref": "#/responses/notFound" + hookID := ctx.Params(":id") hook, err := ctx.Repo.GitRepo.GetHook(hookID) if err != nil { @@ -166,6 +169,7 @@ func DeleteGitHook(ctx *context.APIContext) { // "$ref": "#/responses/empty" // "404": // "$ref": "#/responses/notFound" + hookID := ctx.Params(":id") hook, err := ctx.Repo.GitRepo.GetHook(hookID) if err != nil { diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index 81deb666058c..cefd0b161f07 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -35,6 +35,7 @@ func ListHooks(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/HookList" + hooks, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID) if err != nil { ctx.Error(500, "GetWebhooksByRepoID", err) @@ -114,6 +115,7 @@ func TestHook(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + if ctx.Repo.Commit == nil { // if repo does not have any commits, then don't send a webhook ctx.Status(204) diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 9500b7bc3641..92dba8ba5405 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -53,6 +53,7 @@ func SearchIssues(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/IssueList" + var isClosed util.OptionalBool switch ctx.Query("state") { case "closed": @@ -189,6 +190,7 @@ func ListIssues(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/IssueList" + var isClosed util.OptionalBool switch ctx.Query("state") { case "closed": diff --git a/routers/api/v1/repo/issue_comment.go b/routers/api/v1/repo/issue_comment.go index ea9a84b8337d..e633895a1f79 100644 --- a/routers/api/v1/repo/issue_comment.go +++ b/routers/api/v1/repo/issue_comment.go @@ -45,6 +45,7 @@ func ListIssueComments(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/CommentList" + var since time.Time if len(ctx.Query("since")) > 0 { since, _ = time.Parse(time.RFC3339, ctx.Query("since")) @@ -106,6 +107,7 @@ func ListRepoIssueComments(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/CommentList" + var since time.Time if len(ctx.Query("since")) > 0 { since, _ = time.Parse(time.RFC3339, ctx.Query("since")) diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go index fd501abcd10a..a759afe9d625 100644 --- a/routers/api/v1/repo/issue_label.go +++ b/routers/api/v1/repo/issue_label.go @@ -41,6 +41,7 @@ func ListIssueLabels(ctx *context.APIContext) { // "$ref": "#/responses/LabelList" // "404": // "$ref": "#/responses/notFound" + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { diff --git a/routers/api/v1/repo/issue_stopwatch.go b/routers/api/v1/repo/issue_stopwatch.go index 8bd442a67c03..5b8fc680c3c8 100644 --- a/routers/api/v1/repo/issue_stopwatch.go +++ b/routers/api/v1/repo/issue_stopwatch.go @@ -44,6 +44,7 @@ func StartIssueStopwatch(ctx *context.APIContext) { // "$ref": "#/responses/notFound" // "409": // description: Cannot start a stopwatch again if it already exists + issue, err := prepareIssueStopwatch(ctx, false) if err != nil { return @@ -92,6 +93,7 @@ func StopIssueStopwatch(ctx *context.APIContext) { // "$ref": "#/responses/notFound" // "409": // description: Cannot stop a non existent stopwatch + issue, err := prepareIssueStopwatch(ctx, true) if err != nil { return @@ -140,6 +142,7 @@ func DeleteIssueStopwatch(ctx *context.APIContext) { // "$ref": "#/responses/notFound" // "409": // description: Cannot cancel a non existent stopwatch + issue, err := prepareIssueStopwatch(ctx, true) if err != nil { return diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go index c3ace26fc993..cc5b2e5020d0 100644 --- a/routers/api/v1/repo/issue_tracked_time.go +++ b/routers/api/v1/repo/issue_tracked_time.go @@ -240,6 +240,7 @@ func ListMyTrackedTimes(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/TrackedTimeList" + trackedTimes, err := models.GetTrackedTimes(models.FindTrackedTimesOptions{UserID: ctx.User.ID}) if err != nil { ctx.Error(500, "GetTrackedTimesByUser", err) diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index eb547df17551..d351880b4422 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -62,6 +62,7 @@ func ListDeployKeys(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/DeployKeyList" + var keys []*models.DeployKey var err error @@ -121,6 +122,7 @@ func GetDeployKey(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/DeployKey" + key, err := models.GetDeployKeyByID(ctx.ParamsInt64(":id")) if err != nil { if models.IsErrDeployKeyNotExist(err) { diff --git a/routers/api/v1/repo/label.go b/routers/api/v1/repo/label.go index 33574c481e8e..c8deb45b0b88 100644 --- a/routers/api/v1/repo/label.go +++ b/routers/api/v1/repo/label.go @@ -34,6 +34,7 @@ func ListLabels(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/LabelList" + labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID, ctx.Query("sort")) if err != nil { ctx.Error(500, "GetLabelsByRepoID", err) @@ -74,6 +75,7 @@ func GetLabel(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Label" + var ( label *models.Label err error @@ -123,6 +125,7 @@ func CreateLabel(ctx *context.APIContext, form api.CreateLabelOption) { // responses: // "201": // "$ref": "#/responses/Label" + label := &models.Label{ Name: form.Name, Color: form.Color, @@ -169,6 +172,7 @@ func EditLabel(ctx *context.APIContext, form api.EditLabelOption) { // responses: // "200": // "$ref": "#/responses/Label" + label, err := models.GetLabelInRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { if models.IsErrLabelNotExist(err) { @@ -220,6 +224,7 @@ func DeleteLabel(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + if err := models.DeleteLabel(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { ctx.Error(500, "DeleteLabel", err) return diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go index 9bc73852ca93..3e6c39fea56c 100644 --- a/routers/api/v1/repo/milestone.go +++ b/routers/api/v1/repo/milestone.go @@ -38,6 +38,7 @@ func ListMilestones(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/MilestoneList" + milestones, err := models.GetMilestonesByRepoID(ctx.Repo.Repository.ID, api.StateType(ctx.Query("state"))) if err != nil { ctx.Error(500, "GetMilestonesByRepoID", err) @@ -78,6 +79,7 @@ func GetMilestone(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Milestone" + milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { if models.IsErrMilestoneNotExist(err) { @@ -117,6 +119,7 @@ func CreateMilestone(ctx *context.APIContext, form api.CreateMilestoneOption) { // responses: // "201": // "$ref": "#/responses/Milestone" + if form.Deadline == nil { defaultDeadline, _ := time.ParseInLocation("2006-01-02", "9999-12-31", time.Local) form.Deadline = &defaultDeadline @@ -169,6 +172,7 @@ func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) { // responses: // "200": // "$ref": "#/responses/Milestone" + milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { if models.IsErrMilestoneNotExist(err) { @@ -221,6 +225,7 @@ func DeleteMilestone(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { ctx.Error(500, "DeleteMilestoneByRepoID", err) return diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 462c42646250..33af6a403b42 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -69,6 +69,7 @@ func ListPullRequests(ctx *context.APIContext, form api.ListPullRequestsOptions) // responses: // "200": // "$ref": "#/responses/PullRequestList" + prs, maxResults, err := models.PullRequests(ctx.Repo.Repository.ID, &models.PullRequestsOptions{ Page: ctx.QueryInt("page"), State: ctx.QueryTrim("state"), @@ -134,6 +135,7 @@ func GetPullRequest(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/PullRequest" + pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrPullRequestNotExist(err) { @@ -506,6 +508,7 @@ func IsPullRequestMerged(ctx *context.APIContext) { // description: pull request has been merged // "404": // description: pull request has not been merged + pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrPullRequestNotExist(err) { diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go index cf7b9676b479..dcc7cc89c86d 100644 --- a/routers/api/v1/repo/release.go +++ b/routers/api/v1/repo/release.go @@ -39,6 +39,7 @@ func GetRelease(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Release" + id := ctx.ParamsInt64(":id") release, err := models.GetReleaseByID(id) if err != nil { @@ -99,6 +100,7 @@ func ListReleases(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/ReleaseList" + page, limit := getPagesInfo(ctx) releases, err := models.GetReleasesByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{ IncludeDrafts: ctx.Repo.AccessMode >= models.AccessModeWrite, @@ -236,6 +238,7 @@ func EditRelease(ctx *context.APIContext, form api.EditReleaseOption) { // responses: // "200": // "$ref": "#/responses/Release" + id := ctx.ParamsInt64(":id") rel, err := models.GetReleaseByID(id) if err != nil && !models.IsErrReleaseNotExist(err) { @@ -308,6 +311,7 @@ func DeleteRelease(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + id := ctx.ParamsInt64(":id") rel, err := models.GetReleaseByID(id) if err != nil && !models.IsErrReleaseNotExist(err) { diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go index 479b6e291d34..b5888d2ca286 100644 --- a/routers/api/v1/repo/release_attachment.go +++ b/routers/api/v1/repo/release_attachment.go @@ -48,6 +48,7 @@ func GetReleaseAttachment(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Attachment" + releaseID := ctx.ParamsInt64(":id") attachID := ctx.ParamsInt64(":asset") attach, err := models.GetAttachmentByID(attachID) @@ -91,6 +92,7 @@ func ListReleaseAttachments(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/AttachmentList" + releaseID := ctx.ParamsInt64(":id") release, err := models.GetReleaseByID(releaseID) if err != nil { diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 99f971eed5d9..67d9be91220f 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -123,6 +123,7 @@ func Search(ctx *context.APIContext) { // "$ref": "#/responses/SearchResults" // "422": // "$ref": "#/responses/validationError" + opts := &models.SearchRepoOptions{ Keyword: strings.Trim(ctx.Query("q"), " "), OwnerID: ctx.QueryInt64("uid"), @@ -272,6 +273,7 @@ func Create(ctx *context.APIContext, opt api.CreateRepoOption) { // description: The repository with the same name already exists. // "422": // "$ref": "#/responses/validationError" + if ctx.User.IsOrganization() { // Shouldn't reach this condition, but just in case. ctx.Error(422, "", "not allowed creating repository for organization") @@ -306,6 +308,7 @@ func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) { // "$ref": "#/responses/validationError" // "403": // "$ref": "#/responses/forbidden" + org, err := models.GetOrgByName(ctx.Params(":org")) if err != nil { if models.IsErrOrgNotExist(err) { @@ -544,6 +547,7 @@ func Get(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Repository" + ctx.JSON(200, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode)) } @@ -564,6 +568,7 @@ func GetByID(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/Repository" + repo, err := models.GetRepositoryByID(ctx.ParamsInt64(":id")) if err != nil { if models.IsErrRepoNotExist(err) { @@ -616,6 +621,7 @@ func Edit(ctx *context.APIContext, opts api.EditRepoOption) { // "$ref": "#/responses/forbidden" // "422": // "$ref": "#/responses/validationError" + if err := updateBasicProperties(ctx, opts); err != nil { return } @@ -930,6 +936,7 @@ func Delete(ctx *context.APIContext) { // "$ref": "#/responses/empty" // "403": // "$ref": "#/responses/forbidden" + owner := ctx.Repo.Owner repo := ctx.Repo.Repository diff --git a/routers/api/v1/repo/star.go b/routers/api/v1/repo/star.go index 8fe5b17c5f2e..609a93295491 100644 --- a/routers/api/v1/repo/star.go +++ b/routers/api/v1/repo/star.go @@ -31,6 +31,7 @@ func ListStargazers(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + stargazers, err := ctx.Repo.Repository.GetStargazers(-1) if err != nil { ctx.Error(500, "GetStargazers", err) diff --git a/routers/api/v1/repo/subscriber.go b/routers/api/v1/repo/subscriber.go index 0e576b4ff0f5..1d09687052ba 100644 --- a/routers/api/v1/repo/subscriber.go +++ b/routers/api/v1/repo/subscriber.go @@ -31,6 +31,7 @@ func ListSubscribers(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + subscribers, err := ctx.Repo.Repository.GetWatchers(0) if err != nil { ctx.Error(500, "GetWatchers", err) diff --git a/routers/api/v1/repo/tag.go b/routers/api/v1/repo/tag.go index 15c8b6fd2ced..64aab644b214 100644 --- a/routers/api/v1/repo/tag.go +++ b/routers/api/v1/repo/tag.go @@ -31,6 +31,7 @@ func ListTags(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/TagList" + tags, err := ctx.Repo.GitRepo.GetTagInfos() if err != nil { ctx.Error(500, "GetTags", err) diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index f0f6c954f015..250f2f75f4bd 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -41,6 +41,7 @@ func ListTopics(ctx *context.APIContext) { }) if err != nil { log.Error("ListTopics failed: %v", err) + ctx.JSON(500, map[string]interface{}{ "message": "ListTopics failed.", }) diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index 1123dadfd4eb..de9b919ca1c1 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -27,6 +27,7 @@ func ListAccessTokens(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/AccessTokenList" + tokens, err := models.ListAccessTokens(ctx.User.ID) if err != nil { ctx.Error(500, "ListAccessTokens", err) @@ -71,6 +72,7 @@ func CreateAccessToken(ctx *context.APIContext, form api.CreateAccessTokenOption // responses: // "200": // "$ref": "#/responses/AccessToken" + t := &models.AccessToken{ UID: ctx.User.ID, Name: form.Name, @@ -109,6 +111,7 @@ func DeleteAccessToken(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + tokenID := ctx.ParamsInt64(":id") if err := models.DeleteAccessTokenByID(tokenID, ctx.User.ID); err != nil { if models.IsErrAccessTokenNotExist(err) { diff --git a/routers/api/v1/user/email.go b/routers/api/v1/user/email.go index 04cd55971f30..dfea18cd2906 100644 --- a/routers/api/v1/user/email.go +++ b/routers/api/v1/user/email.go @@ -23,6 +23,7 @@ func ListEmails(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/EmailList" + emails, err := models.GetEmailAddresses(ctx.User.ID) if err != nil { ctx.Error(500, "GetEmailAddresses", err) @@ -103,6 +104,7 @@ func DeleteEmail(ctx *context.APIContext, form api.DeleteEmailOption) { // responses: // "204": // "$ref": "#/responses/empty" + if len(form.Emails) == 0 { ctx.Status(204) return diff --git a/routers/api/v1/user/follower.go b/routers/api/v1/user/follower.go index ec512b9806e9..b58c6e6038ab 100644 --- a/routers/api/v1/user/follower.go +++ b/routers/api/v1/user/follower.go @@ -38,6 +38,7 @@ func ListMyFollowers(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + listUserFollowers(ctx, ctx.User) } @@ -57,6 +58,7 @@ func ListFollowers(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + u := GetUserByParams(ctx) if ctx.Written() { return @@ -83,6 +85,7 @@ func ListMyFollowing(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + listUserFollowing(ctx, ctx.User) } @@ -102,6 +105,7 @@ func ListFollowing(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/UserList" + u := GetUserByParams(ctx) if ctx.Written() { return @@ -133,6 +137,7 @@ func CheckMyFollowing(ctx *context.APIContext) { // "$ref": "#/responses/empty" // "404": // "$ref": "#/responses/notFound" + target := GetUserByParams(ctx) if ctx.Written() { return @@ -161,6 +166,7 @@ func CheckFollowing(ctx *context.APIContext) { // "$ref": "#/responses/empty" // "404": // "$ref": "#/responses/notFound" + u := GetUserByParams(ctx) if ctx.Written() { return @@ -186,6 +192,7 @@ func Follow(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + target := GetUserByParams(ctx) if ctx.Written() { return @@ -211,6 +218,7 @@ func Unfollow(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + target := GetUserByParams(ctx) if ctx.Written() { return diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go index 82113caf0cbc..719095f4bf03 100644 --- a/routers/api/v1/user/gpg_key.go +++ b/routers/api/v1/user/gpg_key.go @@ -42,6 +42,7 @@ func ListGPGKeys(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/GPGKeyList" + user := GetUserByParams(ctx) if ctx.Written() { return @@ -59,6 +60,7 @@ func ListMyGPGKeys(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/GPGKeyList" + listGPGKeys(ctx, ctx.User.ID) } @@ -81,6 +83,7 @@ func GetGPGKey(ctx *context.APIContext) { // "$ref": "#/responses/GPGKey" // "404": // "$ref": "#/responses/notFound" + key, err := models.GetGPGKeyByID(ctx.ParamsInt64(":id")) if err != nil { if models.IsErrGPGKeyNotExist(err) { @@ -123,6 +126,7 @@ func CreateGPGKey(ctx *context.APIContext, form api.CreateGPGKeyOption) { // "$ref": "#/responses/GPGKey" // "422": // "$ref": "#/responses/validationError" + CreateUserGPGKey(ctx, form, ctx.User.ID) } @@ -145,6 +149,7 @@ func DeleteGPGKey(ctx *context.APIContext) { // "$ref": "#/responses/empty" // "403": // "$ref": "#/responses/forbidden" + if err := models.DeleteGPGKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if models.IsErrGPGKeyAccessDenied(err) { ctx.Error(403, "", "You do not have access to this key") diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index a812edfcc7a4..5e413b71e12b 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -112,6 +112,7 @@ func ListMyPublicKeys(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/PublicKeyList" + listPublicKeys(ctx, ctx.User) } @@ -135,6 +136,7 @@ func ListPublicKeys(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/PublicKeyList" + user := GetUserByParams(ctx) if ctx.Written() { return @@ -161,6 +163,7 @@ func GetPublicKey(ctx *context.APIContext) { // "$ref": "#/responses/PublicKey" // "404": // "$ref": "#/responses/notFound" + key, err := models.GetPublicKeyByID(ctx.ParamsInt64(":id")) if err != nil { if models.IsErrKeyNotExist(err) { @@ -219,6 +222,7 @@ func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) { // "$ref": "#/responses/PublicKey" // "422": // "$ref": "#/responses/validationError" + CreateUserPublicKey(ctx, form, ctx.User.ID) } @@ -243,6 +247,7 @@ func DeletePublicKey(ctx *context.APIContext) { // "$ref": "#/responses/forbidden" // "404": // "$ref": "#/responses/notFound" + if err := models.DeletePublicKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if models.IsErrKeyNotExist(err) { ctx.NotFound() diff --git a/routers/api/v1/user/repo.go b/routers/api/v1/user/repo.go index 99839b020aa9..5f2ee53610bb 100644 --- a/routers/api/v1/user/repo.go +++ b/routers/api/v1/user/repo.go @@ -48,6 +48,7 @@ func ListUserRepos(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + user := GetUserByParams(ctx) if ctx.Written() { return @@ -66,6 +67,7 @@ func ListMyRepos(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + ownRepos, err := models.GetUserRepositories(ctx.User.ID, true, 1, ctx.User.NumRepos, "") if err != nil { ctx.Error(500, "GetUserRepositories", err) @@ -105,5 +107,6 @@ func ListOrgRepos(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + listUserRepos(ctx, ctx.Org.Organization, ctx.IsSigned) } diff --git a/routers/api/v1/user/star.go b/routers/api/v1/user/star.go index 744e0bf7d5fd..751d4bf082b0 100644 --- a/routers/api/v1/user/star.go +++ b/routers/api/v1/user/star.go @@ -45,6 +45,7 @@ func GetStarredRepos(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + user := GetUserByParams(ctx) private := user.ID == ctx.User.ID repos, err := getStarredRepos(user, private) @@ -64,6 +65,7 @@ func GetMyStarredRepos(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + repos, err := getStarredRepos(ctx.User, true) if err != nil { ctx.Error(500, "getStarredRepos", err) @@ -92,6 +94,7 @@ func IsStarring(ctx *context.APIContext) { // "$ref": "#/responses/empty" // "404": // "$ref": "#/responses/notFound" + if models.IsStaring(ctx.User.ID, ctx.Repo.Repository.ID) { ctx.Status(204) } else { @@ -118,6 +121,7 @@ func Star(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + err := models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, true) if err != nil { ctx.Error(500, "StarRepo", err) @@ -145,6 +149,7 @@ func Unstar(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + err := models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, false) if err != nil { ctx.Error(500, "StarRepo", err) diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index a22be39b51b5..a9c4ddb47076 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -48,6 +48,7 @@ func Search(ctx *context.APIContext) { // type: array // items: // "$ref": "#/definitions/User" + opts := &models.SearchUserOptions{ Keyword: strings.Trim(ctx.Query("q"), " "), UID: com.StrTo(ctx.Query("uid")).MustInt64(), @@ -93,6 +94,7 @@ func GetInfo(ctx *context.APIContext) { // "$ref": "#/responses/User" // "404": // "$ref": "#/responses/notFound" + u, err := models.GetUserByName(ctx.Params(":username")) if err != nil { if models.IsErrUserNotExist(err) { @@ -116,6 +118,7 @@ func GetAuthenticatedUser(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/User" + ctx.JSON(200, convert.ToUser(ctx.User, ctx.IsSigned, ctx.User != nil)) } diff --git a/routers/api/v1/user/watch.go b/routers/api/v1/user/watch.go index 87739b15fbca..a6fa551f344b 100644 --- a/routers/api/v1/user/watch.go +++ b/routers/api/v1/user/watch.go @@ -46,6 +46,7 @@ func GetWatchedRepos(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + user := GetUserByParams(ctx) private := user.ID == ctx.User.ID repos, err := getWatchedRepos(user, private) @@ -65,6 +66,7 @@ func GetMyWatchedRepos(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/RepositoryList" + repos, err := getWatchedRepos(ctx.User, true) if err != nil { ctx.Error(500, "getWatchedRepos", err) @@ -92,6 +94,7 @@ func IsWatching(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/WatchInfo" + if models.IsWatching(ctx.User.ID, ctx.Repo.Repository.ID) { ctx.JSON(200, api.WatchInfo{ Subscribed: true, @@ -125,6 +128,7 @@ func Watch(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/WatchInfo" + err := models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, true) if err != nil { ctx.Error(500, "WatchRepo", err) @@ -160,6 +164,7 @@ func Unwatch(ctx *context.APIContext) { // responses: // "204": // "$ref": "#/responses/empty" + err := models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, false) if err != nil { ctx.Error(500, "UnwatchRepo", err) From 1f5cb2ad97c1d1b0bb2d26c378c65ad1c6231a4a Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 01:02:46 +0100 Subject: [PATCH 05/13] Deletion Sould return 204 ... --- routers/api/v1/repo/issue_reaction.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/routers/api/v1/repo/issue_reaction.go b/routers/api/v1/repo/issue_reaction.go index 9caca378dc46..8550fa7ea6cd 100644 --- a/routers/api/v1/repo/issue_reaction.go +++ b/routers/api/v1/repo/issue_reaction.go @@ -152,7 +152,7 @@ func DeleteIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp // schema: // "$ref": "#/definitions/EditReactionOption" // responses: - // "204": + // "200": // "$ref": "#/responses/empty" // "403": // "$ref": "#/responses/forbidden" @@ -210,7 +210,8 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp ctx.Error(500, "DeleteCommentReaction", err) return } - ctx.Status(204) + //ToDo respond 204 + ctx.Status(200) } } @@ -354,7 +355,7 @@ func DeleteIssueReaction(ctx *context.APIContext, form api.EditReactionOption) { // schema: // "$ref": "#/definitions/EditReactionOption" // responses: - // "204": + // "200": // "$ref": "#/responses/empty" // "403": // "$ref": "#/responses/forbidden" @@ -407,6 +408,7 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i ctx.Error(500, "DeleteIssueReaction", err) return } - ctx.Status(204) + //ToDo respond 204 + ctx.Status(200) } } From 636bafe92844304f24566889fbb09c705b4c53a9 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 02:37:45 +0100 Subject: [PATCH 06/13] error handling improvements --- routers/api/v1/repo/fork.go | 4 ++- routers/api/v1/repo/issue_tracked_time.go | 6 ++--- routers/api/v1/repo/pull.go | 2 +- routers/api/v1/repo/release.go | 4 +-- routers/api/v1/repo/topic.go | 33 ++++++++--------------- routers/api/v1/user/email.go | 2 +- 6 files changed, 21 insertions(+), 30 deletions(-) diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index 6f03cb76e49f..e67eb3b1b1da 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -5,6 +5,8 @@ package repo import ( + "fmt" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" @@ -99,7 +101,7 @@ func CreateFork(ctx *context.APIContext, form api.CreateForkOption) { ctx.ServerError("IsOrgMember", err) return } else if !isMember { - ctx.Status(403) + ctx.Error(403, "isMemberNot", fmt.Sprintf("User is no Member of Organisation '%s'", org.Name)) return } forker = org diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go index cc5b2e5020d0..0c09eb1cf3ea 100644 --- a/routers/api/v1/repo/issue_tracked_time.go +++ b/routers/api/v1/repo/issue_tracked_time.go @@ -121,7 +121,7 @@ func AddTime(ctx *context.APIContext, form api.AddTimeOption) { if !ctx.Repo.CanUseTimetracker(issue, ctx.User) { if !ctx.Repo.Repository.IsTimetrackerEnabled() { - ctx.JSON(400, struct{ Message string }{Message: "time tracking disabled"}) + ctx.Error(400, "", "time tracking disabled") return } ctx.Status(403) @@ -165,7 +165,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) { // "$ref": "#/responses/error" if !ctx.Repo.Repository.IsTimetrackerEnabled() { - ctx.JSON(400, struct{ Message string }{Message: "time tracking disabled"}) + ctx.Error(400, "", "time tracking disabled") return } user, err := models.GetUserByName(ctx.Params(":timetrackingusername")) @@ -217,7 +217,7 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) { // "$ref": "#/responses/error" if !ctx.Repo.Repository.IsTimetrackerEnabled() { - ctx.JSON(400, struct{ Message string }{Message: "time tracking disabled"}) + ctx.Error(400, "", "time tracking disabled") return } trackedTimes, err := models.GetTrackedTimes(models.FindTrackedTimesOptions{ diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 33af6a403b42..aca26cec777b 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -645,7 +645,7 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { conflictError := err.(models.ErrMergeUnrelatedHistories) ctx.JSON(409, conflictError) } else if models.IsErrMergePushOutOfDate(err) { - ctx.Status(409) + ctx.Error(409, "Merge", "merge push out of date") return } ctx.Error(500, "Merge", err) diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go index dcc7cc89c86d..4959f5bdcde8 100644 --- a/routers/api/v1/repo/release.go +++ b/routers/api/v1/repo/release.go @@ -176,7 +176,7 @@ func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) { } if err := releaseservice.CreateRelease(ctx.Repo.GitRepo, rel, nil); err != nil { if models.IsErrReleaseAlreadyExist(err) { - ctx.Status(409) + ctx.Error(409, "ReleaseAlreadyExist", err) } else { ctx.Error(500, "CreateRelease", err) } @@ -184,7 +184,7 @@ func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) { } } else { if !rel.IsTag { - ctx.Status(409) + ctx.Error(409, "GetRelease", "Release is has no Tag") return } diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index 250f2f75f4bd..c8936988e9c7 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -41,10 +41,7 @@ func ListTopics(ctx *context.APIContext) { }) if err != nil { log.Error("ListTopics failed: %v", err) - - ctx.JSON(500, map[string]interface{}{ - "message": "ListTopics failed.", - }) + ctx.InternalServerError(err) return } @@ -95,7 +92,6 @@ func UpdateTopics(ctx *context.APIContext, form api.RepoTopicOptions) { if len(invalidTopics) > 0 { ctx.JSON(422, map[string]interface{}{ - "invalidTopics": invalidTopics, "message": "Topic names are invalid", }) @@ -105,9 +101,7 @@ func UpdateTopics(ctx *context.APIContext, form api.RepoTopicOptions) { err := models.SaveTopics(ctx.Repo.Repository.ID, validTopics...) if err != nil { log.Error("SaveTopics failed: %v", err) - ctx.JSON(500, map[string]interface{}{ - "message": "Save topics failed.", - }) + ctx.InternalServerError(err) return } @@ -156,9 +150,7 @@ func AddTopic(ctx *context.APIContext) { }) if err != nil { log.Error("AddTopic failed: %v", err) - ctx.JSON(500, map[string]interface{}{ - "message": "ListTopics failed.", - }) + ctx.InternalServerError(err) return } if len(topics) >= 25 { @@ -171,9 +163,7 @@ func AddTopic(ctx *context.APIContext) { _, err = models.AddTopic(ctx.Repo.Repository.ID, topicName) if err != nil { log.Error("AddTopic failed: %v", err) - ctx.JSON(500, map[string]interface{}{ - "message": "AddTopic failed.", - }) + ctx.InternalServerError(err) return } @@ -207,21 +197,22 @@ func DeleteTopic(ctx *context.APIContext) { // "204": // "$ref": "#/responses/empty" // "422": - // "$ref": "#/responses/validationError" + // "$ref": "#/responses/invalidTopicsError" topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) if !models.ValidateTopic(topicName) { - ctx.Error(422, "", "Topic name is invalid") + ctx.JSON(422, map[string]interface{}{ + "invalidTopics": topicName, + "message": "Topic name is invalid", + }) return } topic, err := models.DeleteTopic(ctx.Repo.Repository.ID, topicName) if err != nil { log.Error("DeleteTopic failed: %v", err) - ctx.JSON(500, map[string]interface{}{ - "message": "DeleteTopic failed.", - }) + ctx.InternalServerError(err) return } @@ -266,9 +257,7 @@ func TopicSearch(ctx *context.Context) { }) if err != nil { log.Error("SearchTopics failed: %v", err) - ctx.JSON(500, map[string]interface{}{ - "message": "Search topics failed.", - }) + ctx.InternalServerError(err) return } diff --git a/routers/api/v1/user/email.go b/routers/api/v1/user/email.go index dfea18cd2906..0f81fc3745f5 100644 --- a/routers/api/v1/user/email.go +++ b/routers/api/v1/user/email.go @@ -60,7 +60,7 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { // "$ref": "#/responses/validationError" if len(form.Emails) == 0 { - ctx.Status(422) + ctx.Error(422, "", "Email list empty") return } From 810711221efe504ef577e393508cf5abb30d56c9 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 02:39:16 +0100 Subject: [PATCH 07/13] if special error type ... then add it to swagger too --- modules/context/api.go | 7 +++++++ routers/api/v1/repo/topic.go | 4 ++-- templates/swagger/v1_json.tmpl | 17 ++++++++++++++--- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/modules/context/api.go b/modules/context/api.go index c1de37dd21a0..69f6fc527ede 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -39,6 +39,13 @@ type APIValidationError struct { URL string `json:"url"` } +// APIInvalidTopicsError is error format response to invalid topics +// swagger:response invalidTopicsError +type APIInvalidTopicsError struct { + Topics string `json:"invalidTopics"` + Message string `json:"message"` +} + //APIEmpty is an empty response // swagger:response empty type APIEmpty struct{} diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index c8936988e9c7..b43d4fea1674 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -80,7 +80,7 @@ func UpdateTopics(ctx *context.APIContext, form api.RepoTopicOptions) { // "204": // "$ref": "#/responses/empty" // "422": - // "$ref": "#/responses/validationError" + // "$ref": "#/responses/invalidTopicsError" topicNames := form.Topics validTopics, invalidTopics := models.SanitizeAndValidateTopics(topicNames) @@ -135,7 +135,7 @@ func AddTopic(ctx *context.APIContext) { // "204": // "$ref": "#/responses/empty" // "422": - // "$ref": "#/responses/validationError" + // "$ref": "#/responses/invalidTopicsError" topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index c7a4e8a2369c..2cf548d25f24 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -6365,7 +6365,7 @@ "$ref": "#/responses/empty" }, "422": { - "$ref": "#/responses/validationError" + "$ref": "#/responses/invalidTopicsError" } } } @@ -6408,7 +6408,7 @@ "$ref": "#/responses/empty" }, "422": { - "$ref": "#/responses/validationError" + "$ref": "#/responses/invalidTopicsError" } } }, @@ -6449,7 +6449,7 @@ "$ref": "#/responses/empty" }, "422": { - "$ref": "#/responses/validationError" + "$ref": "#/responses/invalidTopicsError" } } } @@ -11989,6 +11989,17 @@ } } }, + "invalidTopicsError": { + "description": "APIInvalidTopicsError is error format response to invalid topics", + "headers": { + "invalidTopics": { + "type": "string" + }, + "message": { + "type": "string" + } + } + }, "notFound": { "description": "APINotFound is a not found empty response" }, From b4fdad9fc24dbb9375525ea570baf8d05274f850 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 02:47:02 +0100 Subject: [PATCH 08/13] one smal nit --- routers/api/v1/repo/topic.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index b43d4fea1674..fffe8468a13c 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -243,9 +243,7 @@ func TopicSearch(ctx *context.Context) { // "$ref": "#/responses/forbidden" if ctx.User == nil { - ctx.JSON(403, map[string]interface{}{ - "message": "Only owners could change the topics.", - }) + ctx.Error(403, "UserIsNil", "Only owners could change the topics.") return } From f508b0b3b98d81713dc6b7166b4f53e340de1680 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 02:54:20 +0100 Subject: [PATCH 09/13] invalidTopicsError is []string --- modules/context/api.go | 4 ++-- routers/api/v1/repo/topic.go | 5 ++++- templates/swagger/v1_json.tmpl | 5 ++++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/modules/context/api.go b/modules/context/api.go index 69f6fc527ede..fd9983c52b5b 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -42,8 +42,8 @@ type APIValidationError struct { // APIInvalidTopicsError is error format response to invalid topics // swagger:response invalidTopicsError type APIInvalidTopicsError struct { - Topics string `json:"invalidTopics"` - Message string `json:"message"` + Topics []string `json:"invalidTopics"` + Message string `json:"message"` } //APIEmpty is an empty response diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index fffe8468a13c..5d8a37a33bbe 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -140,7 +140,10 @@ func AddTopic(ctx *context.APIContext) { topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) if !models.ValidateTopic(topicName) { - ctx.Error(422, "", "Topic name is invalid") + ctx.JSON(422, map[string]interface{}{ + "invalidTopics": topicName, + "message": "Topic name is invalid", + }) return } diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index 2cf548d25f24..cc4d62403f8a 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -11993,7 +11993,10 @@ "description": "APIInvalidTopicsError is error format response to invalid topics", "headers": { "invalidTopics": { - "type": "string" + "type": "array", + "items": { + "type": "string" + } }, "message": { "type": "string" From 76c3e1f78468a2a8824d62ccf0841e5839e9305e Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 03:06:15 +0100 Subject: [PATCH 10/13] valid swagger specification 2.0 - if you add responses swagger can tell you if you do it right :+1: --- routers/api/v1/repo/issue.go | 5 +---- templates/swagger/v1_json.tmpl | 3 --- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 92dba8ba5405..1c3abffd327f 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -322,7 +322,6 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { // "$ref": "#/responses/forbidden" // "412": // "$ref": "#/responses/error" - // description: cannot close this issue because it still has open dependencies // "422": // "$ref": "#/responses/validationError" @@ -446,7 +445,6 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { // "$ref": "#/responses/notFound" // "412": // "$ref": "#/responses/error" - // description: cannot close this issue because it still has open dependencies issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { @@ -583,7 +581,6 @@ func UpdateIssueDeadline(ctx *context.APIContext, form api.EditDeadlineOption) { // "201": // "$ref": "#/responses/IssueDeadline" // "403": - // description: Not repo writer // "$ref": "#/responses/forbidden" // "404": // "$ref": "#/responses/notFound" @@ -599,7 +596,7 @@ func UpdateIssueDeadline(ctx *context.APIContext, form api.EditDeadlineOption) { } if !ctx.Repo.CanWrite(models.UnitTypeIssues) { - ctx.Status(403) + ctx.Error(403, "", "Not repo writer") return } diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index cc4d62403f8a..dc9dd2395fe8 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -2954,7 +2954,6 @@ "$ref": "#/responses/forbidden" }, "412": { - "description": "cannot close this issue because it still has open dependencies", "$ref": "#/responses/error" }, "422": { @@ -3439,7 +3438,6 @@ "$ref": "#/responses/notFound" }, "412": { - "description": "cannot close this issue because it still has open dependencies", "$ref": "#/responses/error" } } @@ -3705,7 +3703,6 @@ "$ref": "#/responses/IssueDeadline" }, "403": { - "description": "Not repo writer", "$ref": "#/responses/forbidden" }, "404": { From 2b578e2f9a54077ddbd044d69b31310c51527dea Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 03:32:33 +0100 Subject: [PATCH 11/13] use ctx.InternalServerError --- routers/api/v1/misc/markdown.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index 3d099ae0c07c..721c09503c92 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -64,20 +64,20 @@ func Markdown(ctx *context.APIContext, form api.MarkdownOption) { if form.Wiki { _, err := ctx.Write([]byte(markdown.RenderWiki(md, urlPrefix, meta))) if err != nil { - ctx.Error(500, "", err) + ctx.InternalServerError(err) return } } else { _, err := ctx.Write(markdown.Render(md, urlPrefix, meta)) if err != nil { - ctx.Error(500, "", err) + ctx.InternalServerError(err) return } } default: _, err := ctx.Write(markdown.RenderRaw([]byte(form.Text), "", false)) if err != nil { - ctx.Error(500, "", err) + ctx.InternalServerError(err) return } } @@ -111,7 +111,7 @@ func MarkdownRaw(ctx *context.APIContext) { } _, err = ctx.Write(markdown.RenderRaw(body, "", false)) if err != nil { - ctx.Error(500, "", err) + ctx.InternalServerError(err) return } } From 912528970f157b30babef66736d1fc5367f568d9 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 13:06:26 +0100 Subject: [PATCH 12/13] Revert "use numbers and not http.Status___ enum" This reverts commit b1ff386e2418ed6a7f183e756b13277d701278ef. --- routers/api/v1/misc/markdown.go | 2 ++ routers/api/v1/misc/signing.go | 3 ++- routers/api/v1/repo/blob.go | 8 ++++--- routers/api/v1/repo/file.go | 31 +++++++++++++------------- routers/api/v1/repo/hook_test.go | 3 ++- routers/api/v1/repo/issue.go | 5 +++-- routers/api/v1/repo/pull.go | 15 +++++++------ routers/api/v1/repo/repo.go | 37 ++++++++++++++++---------------- routers/api/v1/repo/repo_test.go | 5 +++-- routers/api/v1/repo/tag.go | 10 +++++---- routers/api/v1/repo/topic.go | 26 ++++++++++++---------- routers/api/v1/user/user.go | 7 +++--- routers/api/v1/utils/hook.go | 5 +++-- 13 files changed, 88 insertions(+), 69 deletions(-) diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index 721c09503c92..d420ac9b9338 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -35,6 +35,7 @@ func Markdown(ctx *context.APIContext, form api.MarkdownOption) { // "$ref": "#/responses/MarkdownRender" // "422": // "$ref": "#/responses/validationError" + if ctx.HasAPIError() { ctx.Error(422, "", ctx.GetErrMsg()) return @@ -104,6 +105,7 @@ func MarkdownRaw(ctx *context.APIContext) { // "$ref": "#/responses/MarkdownRender" // "422": // "$ref": "#/responses/validationError" + body, err := ctx.Req.Body().Bytes() if err != nil { ctx.Error(422, "", err) diff --git a/routers/api/v1/misc/signing.go b/routers/api/v1/misc/signing.go index e8bff381cf0d..f5428670af67 100644 --- a/routers/api/v1/misc/signing.go +++ b/routers/api/v1/misc/signing.go @@ -2,6 +2,7 @@ package misc import ( "fmt" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -56,6 +57,6 @@ func SigningKey(ctx *context.Context) { _, err = ctx.Write([]byte(content)) if err != nil { log.Error("Error writing key content %v", err) - ctx.Error(500, fmt.Sprintf("%v", err)) + ctx.Error(http.StatusInternalServerError, fmt.Sprintf("%v", err)) } } diff --git a/routers/api/v1/repo/blob.go b/routers/api/v1/repo/blob.go index d1a3366510f8..3918a49d5147 100644 --- a/routers/api/v1/repo/blob.go +++ b/routers/api/v1/repo/blob.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/repofiles" ) @@ -40,12 +42,12 @@ func GetBlob(ctx *context.APIContext) { sha := ctx.Params("sha") if len(sha) == 0 { - ctx.Error(400, "", "sha not provided") + ctx.Error(http.StatusBadRequest, "", "sha not provided") return } if blob, err := repofiles.GetBlobBySHA(ctx.Repo.Repository, sha); err != nil { - ctx.Error(400, "", err) + ctx.Error(http.StatusBadRequest, "", err) } else { - ctx.JSON(200, blob) + ctx.JSON(http.StatusOK, blob) } } diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 021bd92e3922..8cfe039df573 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -7,6 +7,7 @@ package repo import ( "encoding/base64" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -55,12 +56,12 @@ func GetRawFile(ctx *context.APIContext) { if git.IsErrNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetBlobByPath", err) + ctx.Error(http.StatusInternalServerError, "GetBlobByPath", err) } return } if err = repo.ServeBlob(ctx.Context, blob); err != nil { - ctx.Error(500, "ServeBlob", err) + ctx.Error(http.StatusInternalServerError, "ServeBlob", err) } } @@ -96,7 +97,7 @@ func GetArchive(ctx *context.APIContext) { repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) gitRepo, err := git.OpenRepository(repoPath) if err != nil { - ctx.Error(500, "OpenRepository", err) + ctx.Error(http.StatusInternalServerError, "OpenRepository", err) return } ctx.Repo.GitRepo = gitRepo @@ -139,7 +140,7 @@ func GetEditorconfig(ctx *context.APIContext) { if git.IsErrNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetEditorconfig", err) + ctx.Error(http.StatusInternalServerError, "GetEditorconfig", err) } return } @@ -150,7 +151,7 @@ func GetEditorconfig(ctx *context.APIContext) { ctx.NotFound(err) return } - ctx.JSON(200, def) + ctx.JSON(http.StatusOK, def) } // CanWriteFiles returns true if repository is editable and user has proper access level. @@ -219,9 +220,9 @@ func CreateFile(ctx *context.APIContext, apiOpts api.CreateFileOptions) { } if fileResponse, err := createOrUpdateFile(ctx, opts); err != nil { - ctx.Error(500, "CreateFile", err) + ctx.Error(http.StatusInternalServerError, "CreateFile", err) } else { - ctx.JSON(201, fileResponse) + ctx.JSON(http.StatusCreated, fileResponse) } } @@ -283,9 +284,9 @@ func UpdateFile(ctx *context.APIContext, apiOpts api.UpdateFileOptions) { } if fileResponse, err := createOrUpdateFile(ctx, opts); err != nil { - ctx.Error(500, "UpdateFile", err) + ctx.Error(http.StatusInternalServerError, "UpdateFile", err) } else { - ctx.JSON(200, fileResponse) + ctx.JSON(http.StatusOK, fileResponse) } } @@ -342,7 +343,7 @@ func DeleteFile(ctx *context.APIContext, apiOpts api.DeleteFileOptions) { // "$ref": "#/responses/FileDeleteResponse" if !CanWriteFiles(ctx.Repo) { - ctx.Error(500, "DeleteFile", models.ErrUserDoesNotHaveAccessToRepo{ + ctx.Error(http.StatusInternalServerError, "DeleteFile", models.ErrUserDoesNotHaveAccessToRepo{ UserID: ctx.User.ID, RepoName: ctx.Repo.Repository.LowerName, }) @@ -370,9 +371,9 @@ func DeleteFile(ctx *context.APIContext, apiOpts api.DeleteFileOptions) { } if fileResponse, err := repofiles.DeleteRepoFile(ctx.Repo.Repository, ctx.User, opts); err != nil { - ctx.Error(500, "DeleteFile", err) + ctx.Error(http.StatusInternalServerError, "DeleteFile", err) } else { - ctx.JSON(200, fileResponse) + ctx.JSON(http.StatusOK, fileResponse) } } @@ -409,7 +410,7 @@ func GetContents(ctx *context.APIContext) { // "$ref": "#/responses/ContentsResponse" if !CanReadFiles(ctx.Repo) { - ctx.Error(500, "GetContentsOrList", models.ErrUserDoesNotHaveAccessToRepo{ + ctx.Error(http.StatusInternalServerError, "GetContentsOrList", models.ErrUserDoesNotHaveAccessToRepo{ UserID: ctx.User.ID, RepoName: ctx.Repo.Repository.LowerName, }) @@ -420,9 +421,9 @@ func GetContents(ctx *context.APIContext) { ref := ctx.QueryTrim("ref") if fileList, err := repofiles.GetContentsOrList(ctx.Repo.Repository, treePath, ref); err != nil { - ctx.Error(500, "GetContentsOrList", err) + ctx.Error(http.StatusInternalServerError, "GetContentsOrList", err) } else { - ctx.JSON(200, fileList) + ctx.JSON(http.StatusOK, fileList) } } diff --git a/routers/api/v1/repo/hook_test.go b/routers/api/v1/repo/hook_test.go index ec68df66975a..8ed4bc4b0c3c 100644 --- a/routers/api/v1/repo/hook_test.go +++ b/routers/api/v1/repo/hook_test.go @@ -5,6 +5,7 @@ package repo import ( + "net/http" "testing" "code.gitea.io/gitea/models" @@ -23,7 +24,7 @@ func TestTestHook(t *testing.T) { test.LoadRepoCommit(t, ctx) test.LoadUser(t, ctx, 2) TestHook(&context.APIContext{Context: ctx, Org: nil}) - assert.EqualValues(t, 204, ctx.Resp.Status()) + assert.EqualValues(t, http.StatusNoContent, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.HookTask{ RepoID: 1, diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 1c3abffd327f..741b713f6781 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -7,6 +7,7 @@ package repo import ( "fmt" + "net/http" "strings" "time" @@ -389,7 +390,7 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { if form.Closed { if err := issue_service.ChangeStatus(issue, ctx.User, true); err != nil { if models.IsErrDependenciesLeft(err) { - ctx.Error(412, "DependenciesLeft", "cannot close this issue because it still has open dependencies") + ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this issue because it still has open dependencies") return } ctx.Error(500, "ChangeStatus", err) @@ -530,7 +531,7 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { if form.State != nil { if err = issue_service.ChangeStatus(issue, ctx.User, api.StateClosed == api.StateType(*form.State)); err != nil { if models.IsErrDependenciesLeft(err) { - ctx.Error(412, "DependenciesLeft", "cannot close this issue because it still has open dependencies") + ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this issue because it still has open dependencies") return } ctx.Error(500, "ChangeStatus", err) diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index aca26cec777b..e6876ad65185 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -6,6 +6,7 @@ package repo import ( "fmt" + "net/http" "strings" "time" @@ -373,7 +374,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { err = pr.LoadIssue() if err != nil { - ctx.Error(500, "LoadIssue", err) + ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return } issue := pr.Issue @@ -456,7 +457,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { if form.State != nil { if err = issue_service.ChangeStatus(issue, ctx.User, api.StateClosed == api.StateType(*form.State)); err != nil { if models.IsErrDependenciesLeft(err) { - ctx.Error(412, "DependenciesLeft", "cannot close this pull request because it still has open dependencies") + ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this pull request because it still has open dependencies") return } ctx.Error(500, "ChangeStatus", err) @@ -578,7 +579,7 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { err = pr.LoadIssue() if err != nil { - ctx.Error(500, "LoadIssue", err) + ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return } pr.Issue.Repo = ctx.Repo.Repository @@ -637,15 +638,15 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { return } else if models.IsErrMergeConflicts(err) { conflictError := err.(models.ErrMergeConflicts) - ctx.JSON(409, conflictError) + ctx.JSON(http.StatusConflict, conflictError) } else if models.IsErrRebaseConflicts(err) { conflictError := err.(models.ErrRebaseConflicts) - ctx.JSON(409, conflictError) + ctx.JSON(http.StatusConflict, conflictError) } else if models.IsErrMergeUnrelatedHistories(err) { conflictError := err.(models.ErrMergeUnrelatedHistories) - ctx.JSON(409, conflictError) + ctx.JSON(http.StatusConflict, conflictError) } else if models.IsErrMergePushOutOfDate(err) { - ctx.Error(409, "Merge", "merge push out of date") + ctx.Error(http.StatusConflict, "Merge", "merge push out of date") return } ctx.Error(500, "Merge", err) diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 67d9be91220f..6861379f93c3 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -9,6 +9,7 @@ import ( "bytes" "errors" "fmt" + "net/http" "net/url" "strings" @@ -162,7 +163,7 @@ func Search(ctx *context.APIContext) { opts.Collaborate = util.OptionalBoolTrue case "": default: - ctx.Error(422, "", fmt.Errorf("Invalid search mode: \"%s\"", mode)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid search mode: \"%s\"", mode)) return } @@ -176,11 +177,11 @@ func Search(ctx *context.APIContext) { if orderBy, ok := searchModeMap[sortMode]; ok { opts.OrderBy = orderBy } else { - ctx.Error(422, "", fmt.Errorf("Invalid sort mode: \"%s\"", sortMode)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid sort mode: \"%s\"", sortMode)) return } } else { - ctx.Error(422, "", fmt.Errorf("Invalid sort order: \"%s\"", sortOrder)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid sort order: \"%s\"", sortOrder)) return } } @@ -636,7 +637,7 @@ func Edit(ctx *context.APIContext, opts api.EditRepoOption) { } } - ctx.JSON(200, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode)) + ctx.JSON(http.StatusOK, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode)) } // updateBasicProperties updates the basic properties of a repo: Name, Description, Website and Visibility @@ -652,13 +653,13 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err if err := repo_service.ChangeRepositoryName(ctx.User, repo, newRepoName); err != nil { switch { case models.IsErrRepoAlreadyExist(err): - ctx.Error(422, fmt.Sprintf("repo name is already taken [name: %s]", newRepoName), err) + ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name is already taken [name: %s]", newRepoName), err) case models.IsErrNameReserved(err): - ctx.Error(422, fmt.Sprintf("repo name is reserved [name: %s]", newRepoName), err) + ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name is reserved [name: %s]", newRepoName), err) case models.IsErrNamePatternNotAllowed(err): - ctx.Error(422, fmt.Sprintf("repo name's pattern is not allowed [name: %s, pattern: %s]", newRepoName, err.(models.ErrNamePatternNotAllowed).Pattern), err) + ctx.Error(http.StatusUnprocessableEntity, fmt.Sprintf("repo name's pattern is not allowed [name: %s, pattern: %s]", newRepoName, err.(models.ErrNamePatternNotAllowed).Pattern), err) default: - ctx.Error(422, "ChangeRepositoryName", err) + ctx.Error(http.StatusUnprocessableEntity, "ChangeRepositoryName", err) } return err } @@ -688,7 +689,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err // when ForcePrivate enabled, you could change public repo to private, but only admin users can change private to public if visibilityChanged && setting.Repository.ForcePrivate && !*opts.Private && !ctx.User.IsAdmin { err := fmt.Errorf("cannot change private repository to public") - ctx.Error(422, "Force Private enabled", err) + ctx.Error(http.StatusUnprocessableEntity, "Force Private enabled", err) return err } @@ -703,7 +704,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err if opts.DefaultBranch != nil && repo.DefaultBranch != *opts.DefaultBranch && ctx.Repo.GitRepo.IsBranchExist(*opts.DefaultBranch) { if err := ctx.Repo.GitRepo.SetDefaultBranch(*opts.DefaultBranch); err != nil { if !git.IsErrUnsupportedVersion(err) { - ctx.Error(500, "SetDefaultBranch", err) + ctx.Error(http.StatusInternalServerError, "SetDefaultBranch", err) return err } } @@ -711,7 +712,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err } if err := models.UpdateRepository(repo, visibilityChanged); err != nil { - ctx.Error(500, "UpdateRepository", err) + ctx.Error(http.StatusInternalServerError, "UpdateRepository", err) return err } @@ -747,12 +748,12 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { // Check that values are valid if !validation.IsValidExternalURL(opts.ExternalTracker.ExternalTrackerURL) { err := fmt.Errorf("External tracker URL not valid") - ctx.Error(422, "Invalid external tracker URL", err) + ctx.Error(http.StatusUnprocessableEntity, "Invalid external tracker URL", err) return err } if len(opts.ExternalTracker.ExternalTrackerFormat) != 0 && !validation.IsValidExternalTrackerURLFormat(opts.ExternalTracker.ExternalTrackerFormat) { err := fmt.Errorf("External tracker URL format not valid") - ctx.Error(422, "Invalid external tracker URL format", err) + ctx.Error(http.StatusUnprocessableEntity, "Invalid external tracker URL format", err) return err } @@ -807,7 +808,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { // Check that values are valid if !validation.IsValidExternalURL(opts.ExternalWiki.ExternalWikiURL) { err := fmt.Errorf("External wiki URL not valid") - ctx.Error(422, "", "Invalid external wiki URL") + ctx.Error(http.StatusUnprocessableEntity, "", "Invalid external wiki URL") return err } @@ -876,7 +877,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { } if err := models.UpdateRepositoryUnits(repo, units); err != nil { - ctx.Error(500, "UpdateRepositoryUnits", err) + ctx.Error(http.StatusInternalServerError, "UpdateRepositoryUnits", err) return err } @@ -891,20 +892,20 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e if opts.Archived != nil { if repo.IsMirror { err := fmt.Errorf("repo is a mirror, cannot archive/un-archive") - ctx.Error(422, err.Error(), err) + ctx.Error(http.StatusUnprocessableEntity, err.Error(), err) return err } if *opts.Archived { if err := repo.SetArchiveRepoState(*opts.Archived); err != nil { log.Error("Tried to archive a repo: %s", err) - ctx.Error(500, "ArchiveRepoState", err) + ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err) return err } log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name) } else { if err := repo.SetArchiveRepoState(*opts.Archived); err != nil { log.Error("Tried to un-archive a repo: %s", err) - ctx.Error(500, "ArchiveRepoState", err) + ctx.Error(http.StatusInternalServerError, "ArchiveRepoState", err) return err } log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name) diff --git a/routers/api/v1/repo/repo_test.go b/routers/api/v1/repo/repo_test.go index 74ea884e5aa8..053134ec6199 100644 --- a/routers/api/v1/repo/repo_test.go +++ b/routers/api/v1/repo/repo_test.go @@ -5,6 +5,7 @@ package repo import ( + "net/http" "testing" "code.gitea.io/gitea/models" @@ -54,7 +55,7 @@ func TestRepoEdit(t *testing.T) { Edit(&context.APIContext{Context: ctx, Org: nil}, opts) - assert.EqualValues(t, 200, ctx.Resp.Status()) + assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.Repository{ ID: 1, }, models.Cond("name = ? AND is_archived = 1", *opts.Name)) @@ -73,7 +74,7 @@ func TestRepoEditNameChange(t *testing.T) { } Edit(&context.APIContext{Context: ctx, Org: nil}, opts) - assert.EqualValues(t, 200, ctx.Resp.Status()) + assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.Repository{ ID: 1, diff --git a/routers/api/v1/repo/tag.go b/routers/api/v1/repo/tag.go index 64aab644b214..64abd53cf08f 100644 --- a/routers/api/v1/repo/tag.go +++ b/routers/api/v1/repo/tag.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" @@ -77,17 +79,17 @@ func GetTag(ctx *context.APIContext) { sha := ctx.Params("sha") if len(sha) == 0 { - ctx.Error(400, "", "SHA not provided") + ctx.Error(http.StatusBadRequest, "", "SHA not provided") return } if tag, err := ctx.Repo.GitRepo.GetAnnotatedTag(sha); err != nil { - ctx.Error(400, "GetTag", err) + ctx.Error(http.StatusBadRequest, "GetTag", err) } else { commit, err := tag.Commit() if err != nil { - ctx.Error(400, "GetTag", err) + ctx.Error(http.StatusBadRequest, "GetTag", err) } - ctx.JSON(200, convert.ToAnnotatedTag(ctx.Repo.Repository, tag, commit)) + ctx.JSON(http.StatusOK, convert.ToAnnotatedTag(ctx.Repo.Repository, tag, commit)) } } diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index 5d8a37a33bbe..0c56f2a76962 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -5,6 +5,7 @@ package repo import ( + "net/http" "strings" "code.gitea.io/gitea/models" @@ -49,7 +50,7 @@ func ListTopics(ctx *context.APIContext) { for i, topic := range topics { topicNames[i] = topic.Name } - ctx.JSON(200, map[string]interface{}{ + ctx.JSON(http.StatusOK, map[string]interface{}{ "topics": topicNames, }) } @@ -86,12 +87,15 @@ func UpdateTopics(ctx *context.APIContext, form api.RepoTopicOptions) { validTopics, invalidTopics := models.SanitizeAndValidateTopics(topicNames) if len(validTopics) > 25 { - ctx.Error(422, "", "Exceeding maximum number of topics per repo") + ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{ + "invalidTopics": nil, + "message": "Exceeding maximum number of topics per repo", + }) return } if len(invalidTopics) > 0 { - ctx.JSON(422, map[string]interface{}{ + ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{ "invalidTopics": invalidTopics, "message": "Topic names are invalid", }) @@ -105,7 +109,7 @@ func UpdateTopics(ctx *context.APIContext, form api.RepoTopicOptions) { return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // AddTopic adds a topic name to a repo @@ -140,7 +144,7 @@ func AddTopic(ctx *context.APIContext) { topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) if !models.ValidateTopic(topicName) { - ctx.JSON(422, map[string]interface{}{ + ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{ "invalidTopics": topicName, "message": "Topic name is invalid", }) @@ -157,7 +161,7 @@ func AddTopic(ctx *context.APIContext) { return } if len(topics) >= 25 { - ctx.JSON(422, map[string]interface{}{ + ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{ "message": "Exceeding maximum allowed topics per repo.", }) return @@ -170,7 +174,7 @@ func AddTopic(ctx *context.APIContext) { return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // DeleteTopic removes topic name from repo @@ -205,7 +209,7 @@ func DeleteTopic(ctx *context.APIContext) { topicName := strings.TrimSpace(strings.ToLower(ctx.Params(":topic"))) if !models.ValidateTopic(topicName) { - ctx.JSON(422, map[string]interface{}{ + ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{ "invalidTopics": topicName, "message": "Topic name is invalid", }) @@ -223,7 +227,7 @@ func DeleteTopic(ctx *context.APIContext) { ctx.NotFound() } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // TopicSearch search for creating topic @@ -246,7 +250,7 @@ func TopicSearch(ctx *context.Context) { // "$ref": "#/responses/forbidden" if ctx.User == nil { - ctx.Error(403, "UserIsNil", "Only owners could change the topics.") + ctx.Error(http.StatusForbidden, "UserIsNil", "Only owners could change the topics.") return } @@ -266,7 +270,7 @@ func TopicSearch(ctx *context.Context) { for i, topic := range topics { topicResponses[i] = convert.ToTopicResponse(topic) } - ctx.JSON(200, map[string]interface{}{ + ctx.JSON(http.StatusOK, map[string]interface{}{ "topics": topicResponses, }) } diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index a9c4ddb47076..4f5b596a577e 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -5,6 +5,7 @@ package user import ( + "net/http" "strings" "code.gitea.io/gitea/models" @@ -145,16 +146,16 @@ func GetUserHeatmapData(ctx *context.APIContext) { user, err := models.GetUserByName(ctx.Params(":username")) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Status(404) + ctx.Status(http.StatusNotFound) } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return } heatmap, err := models.GetUserHeatmapDataByUser(user) if err != nil { - ctx.Error(500, "GetUserHeatmapDataByUser", err) + ctx.Error(http.StatusInternalServerError, "GetUserHeatmapDataByUser", err) return } ctx.JSON(200, heatmap) diff --git a/routers/api/v1/utils/hook.go b/routers/api/v1/utils/hook.go index 1f2a4fafc609..f88b15200389 100644 --- a/routers/api/v1/utils/hook.go +++ b/routers/api/v1/utils/hook.go @@ -6,6 +6,7 @@ package utils import ( "encoding/json" + "net/http" "strings" "code.gitea.io/gitea/models" @@ -73,7 +74,7 @@ func AddOrgHook(ctx *context.APIContext, form *api.CreateHookOption) { org := ctx.Org.Organization hook, ok := addHook(ctx, form, org.ID, 0) if ok { - ctx.JSON(201, convert.ToHook(org.HomeLink(), hook)) + ctx.JSON(http.StatusCreated, convert.ToHook(org.HomeLink(), hook)) } } @@ -82,7 +83,7 @@ func AddRepoHook(ctx *context.APIContext, form *api.CreateHookOption) { repo := ctx.Repo hook, ok := addHook(ctx, form, 0, repo.Repository.ID) if ok { - ctx.JSON(201, convert.ToHook(repo.RepoLink, hook)) + ctx.JSON(http.StatusCreated, convert.ToHook(repo.RepoLink, hook)) } } From d2e83bebfc2e3ba9ac0d54be36fdad5665e47008 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 20 Dec 2019 13:33:19 +0100 Subject: [PATCH 13/13] use http.Status* enum everywhere --- routers/api/v1/admin/org.go | 12 +-- routers/api/v1/admin/user.go | 39 +++++----- routers/api/v1/api.go | 57 +++++++------- routers/api/v1/misc/markdown.go | 5 +- routers/api/v1/misc/swagger.go | 4 +- routers/api/v1/misc/version.go | 4 +- routers/api/v1/org/hook.go | 12 +-- routers/api/v1/org/member.go | 31 ++++---- routers/api/v1/org/org.go | 24 +++--- routers/api/v1/org/team.go | 77 +++++++++---------- routers/api/v1/repo/branch.go | 18 +++-- routers/api/v1/repo/collaborators.go | 33 ++++---- routers/api/v1/repo/commits.go | 7 +- routers/api/v1/repo/fork.go | 17 +++-- routers/api/v1/repo/git_hook.go | 22 +++--- routers/api/v1/repo/git_ref.go | 8 +- routers/api/v1/repo/hook.go | 18 +++-- routers/api/v1/repo/issue.go | 66 ++++++++-------- routers/api/v1/repo/issue_comment.go | 49 ++++++------ routers/api/v1/repo/issue_label.go | 52 +++++++------ routers/api/v1/repo/issue_reaction.go | 55 +++++++------- routers/api/v1/repo/issue_stopwatch.go | 30 ++++---- routers/api/v1/repo/issue_subscription.go | 20 ++--- routers/api/v1/repo/issue_tracked_time.go | 36 ++++----- routers/api/v1/repo/key.go | 35 ++++----- routers/api/v1/repo/label.go | 21 +++--- routers/api/v1/repo/milestone.go | 21 +++--- routers/api/v1/repo/pull.go | 92 +++++++++++------------ routers/api/v1/repo/release.go | 38 +++++----- routers/api/v1/repo/release_attachment.go | 33 ++++---- routers/api/v1/repo/repo.go | 86 ++++++++++----------- routers/api/v1/repo/star.go | 6 +- routers/api/v1/repo/status.go | 25 +++--- routers/api/v1/repo/subscriber.go | 6 +- routers/api/v1/repo/tag.go | 4 +- routers/api/v1/repo/tree.go | 8 +- routers/api/v1/user/app.go | 14 ++-- routers/api/v1/user/email.go | 20 ++--- routers/api/v1/user/follower.go | 18 +++-- routers/api/v1/user/gpg_key.go | 24 +++--- routers/api/v1/user/key.go | 20 ++--- routers/api/v1/user/repo.go | 14 ++-- routers/api/v1/user/star.go | 20 ++--- routers/api/v1/user/user.go | 12 +-- routers/api/v1/user/watch.go | 20 ++--- routers/api/v1/utils/hook.go | 32 ++++---- 46 files changed, 665 insertions(+), 600 deletions(-) diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go index 26a627def541..1db4e592ff49 100644 --- a/routers/api/v1/admin/org.go +++ b/routers/api/v1/admin/org.go @@ -6,6 +6,8 @@ package admin import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -65,14 +67,14 @@ func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) { if models.IsErrUserAlreadyExist(err) || models.IsErrNameReserved(err) || models.IsErrNamePatternNotAllowed(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "CreateOrganization", err) + ctx.Error(http.StatusInternalServerError, "CreateOrganization", err) } return } - ctx.JSON(201, convert.ToOrganization(org)) + ctx.JSON(http.StatusCreated, convert.ToOrganization(org)) } //GetAllOrgs API for getting information of all the organizations @@ -105,12 +107,12 @@ func GetAllOrgs(ctx *context.APIContext) { Private: true, }) if err != nil { - ctx.Error(500, "SearchOrganizations", err) + ctx.Error(http.StatusInternalServerError, "SearchOrganizations", err) return } orgs := make([]*api.Organization, len(users)) for i := range users { orgs[i] = convert.ToOrganization(users[i]) } - ctx.JSON(200, &orgs) + ctx.JSON(http.StatusOK, &orgs) } diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 0ba2e4b9bc90..7387037d333c 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -7,6 +7,7 @@ package admin import ( "errors" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -26,9 +27,9 @@ func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, l source, err := models.GetLoginSourceByID(sourceID) if err != nil { if models.IsErrLoginSourceNotExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "GetLoginSourceByID", err) + ctx.Error(http.StatusInternalServerError, "GetLoginSourceByID", err) } return } @@ -81,7 +82,7 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { } if !password.IsComplexEnough(form.Password) { err := errors.New("PasswordComplexity") - ctx.Error(400, "PasswordComplexity", err) + ctx.Error(http.StatusBadRequest, "PasswordComplexity", err) return } if err := models.CreateUser(u); err != nil { @@ -89,9 +90,9 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { models.IsErrEmailAlreadyUsed(err) || models.IsErrNameReserved(err) || models.IsErrNamePatternNotAllowed(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "CreateUser", err) + ctx.Error(http.StatusInternalServerError, "CreateUser", err) } return } @@ -101,7 +102,7 @@ func CreateUser(ctx *context.APIContext, form api.CreateUserOption) { if form.SendNotify { mailer.SendRegisterNotifyMail(ctx.Locale, u) } - ctx.JSON(201, convert.ToUser(u, ctx.IsSigned, ctx.User.IsAdmin)) + ctx.JSON(http.StatusCreated, convert.ToUser(u, ctx.IsSigned, ctx.User.IsAdmin)) } // EditUser api for modifying a user's information @@ -144,12 +145,12 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) { if len(form.Password) > 0 { if !password.IsComplexEnough(form.Password) { err := errors.New("PasswordComplexity") - ctx.Error(400, "PasswordComplexity", err) + ctx.Error(http.StatusBadRequest, "PasswordComplexity", err) return } var err error if u.Salt, err = models.GetUserSalt(); err != nil { - ctx.Error(500, "UpdateUser", err) + ctx.Error(http.StatusInternalServerError, "UpdateUser", err) return } u.HashPassword(form.Password) @@ -188,15 +189,15 @@ func EditUser(ctx *context.APIContext, form api.EditUserOption) { if err := models.UpdateUser(u); err != nil { if models.IsErrEmailAlreadyUsed(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "UpdateUser", err) + ctx.Error(http.StatusInternalServerError, "UpdateUser", err) } return } log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name) - ctx.JSON(200, convert.ToUser(u, ctx.IsSigned, ctx.User.IsAdmin)) + ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.IsSigned, ctx.User.IsAdmin)) } // DeleteUser api for deleting a user @@ -228,15 +229,15 @@ func DeleteUser(ctx *context.APIContext) { if err := models.DeleteUser(u); err != nil { if models.IsErrUserOwnRepos(err) || models.IsErrUserHasOrgs(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "DeleteUser", err) + ctx.Error(http.StatusInternalServerError, "DeleteUser", err) } return } log.Trace("Account deleted by admin(%s): %s", ctx.User.Name, u.Name) - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // CreatePublicKey api for creating a public key to a user @@ -309,15 +310,15 @@ func DeleteUserPublicKey(ctx *context.APIContext) { if models.IsErrKeyNotExist(err) { ctx.NotFound() } else if models.IsErrKeyAccessDenied(err) { - ctx.Error(403, "", "You do not have access to this key") + ctx.Error(http.StatusForbidden, "", "You do not have access to this key") } else { - ctx.Error(500, "DeleteUserPublicKey", err) + ctx.Error(http.StatusInternalServerError, "DeleteUserPublicKey", err) } return } log.Trace("Key deleted by admin(%s): %s", ctx.User.Name, u.Name) - ctx.Status(204) + ctx.Status(http.StatusNoContent) } //GetAllUsers API for getting information of all the users @@ -339,7 +340,7 @@ func GetAllUsers(ctx *context.APIContext) { PageSize: -1, }) if err != nil { - ctx.Error(500, "GetAllUsers", err) + ctx.Error(http.StatusInternalServerError, "GetAllUsers", err) return } @@ -348,5 +349,5 @@ func GetAllUsers(ctx *context.APIContext) { results[i] = convert.ToUser(users[i], ctx.IsSigned, ctx.User.IsAdmin) } - ctx.JSON(200, &results) + ctx.JSON(http.StatusOK, &results) } diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 7526d3f5efe6..c2f019eb41e5 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -59,6 +59,7 @@ package v1 import ( + "net/http" "strings" "code.gitea.io/gitea/models" @@ -92,14 +93,14 @@ func sudo() macaron.Handler { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return } log.Trace("Sudo from (%s) to: %s", ctx.User.Name, user.Name) ctx.User = user } else { - ctx.JSON(403, map[string]string{ + ctx.JSON(http.StatusForbidden, map[string]string{ "message": "Only administrators allowed to sudo.", }) return @@ -127,7 +128,7 @@ func repoAssignment() macaron.Handler { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return } @@ -144,10 +145,10 @@ func repoAssignment() macaron.Handler { } else if models.IsErrRepoRedirectNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "LookupRepoRedirect", err) + ctx.Error(http.StatusInternalServerError, "LookupRepoRedirect", err) } } else { - ctx.Error(500, "GetRepositoryByName", err) + ctx.Error(http.StatusInternalServerError, "GetRepositoryByName", err) } return } @@ -157,7 +158,7 @@ func repoAssignment() macaron.Handler { ctx.Repo.Permission, err = models.GetUserRepoPermission(repo, ctx.User) if err != nil { - ctx.Error(500, "GetUserRepoPermission", err) + ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err) return } @@ -182,14 +183,14 @@ func reqToken() macaron.Handler { ctx.RequireCSRF() return } - ctx.Context.Error(401) + ctx.Context.Error(http.StatusUnauthorized) } } func reqBasicAuth() macaron.Handler { return func(ctx *context.APIContext) { if !ctx.Context.IsBasicAuth { - ctx.Context.Error(401) + ctx.Context.Error(http.StatusUnauthorized) return } ctx.CheckForOTP() @@ -200,7 +201,7 @@ func reqBasicAuth() macaron.Handler { func reqSiteAdmin() macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserSiteAdmin() { - ctx.Error(403) + ctx.Error(http.StatusForbidden) return } } @@ -210,7 +211,7 @@ func reqSiteAdmin() macaron.Handler { func reqOwner() macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoOwner() && !ctx.IsUserSiteAdmin() { - ctx.Error(403) + ctx.Error(http.StatusForbidden) return } } @@ -220,7 +221,7 @@ func reqOwner() macaron.Handler { func reqAdmin() macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() { - ctx.Error(403) + ctx.Error(http.StatusForbidden) return } } @@ -230,7 +231,7 @@ func reqAdmin() macaron.Handler { func reqRepoWriter(unitTypes ...models.UnitType) macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoWriter(unitTypes) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() { - ctx.Error(403) + ctx.Error(http.StatusForbidden) return } } @@ -240,7 +241,7 @@ func reqRepoWriter(unitTypes ...models.UnitType) macaron.Handler { func reqRepoReader(unitType models.UnitType) macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoReaderSpecific(unitType) && !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() { - ctx.Error(403) + ctx.Error(http.StatusForbidden) return } } @@ -250,7 +251,7 @@ func reqRepoReader(unitType models.UnitType) macaron.Handler { func reqAnyRepoReader() macaron.Handler { return func(ctx *context.Context) { if !ctx.IsUserRepoReaderAny() && !ctx.IsUserSiteAdmin() { - ctx.Error(403) + ctx.Error(http.StatusForbidden) return } } @@ -269,17 +270,17 @@ func reqOrgOwnership() macaron.Handler { } else if ctx.Org.Team != nil { orgID = ctx.Org.Team.OrgID } else { - ctx.Error(500, "", "reqOrgOwnership: unprepared context") + ctx.Error(http.StatusInternalServerError, "", "reqOrgOwnership: unprepared context") return } isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID) if err != nil { - ctx.Error(500, "IsOrganizationOwner", err) + ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err) return } else if !isOwner { if ctx.Org.Organization != nil { - ctx.Error(403, "", "Must be an organization owner") + ctx.Error(http.StatusForbidden, "", "Must be an organization owner") } else { ctx.NotFound() } @@ -295,28 +296,28 @@ func reqTeamMembership() macaron.Handler { return } if ctx.Org.Team == nil { - ctx.Error(500, "", "reqTeamMembership: unprepared context") + ctx.Error(http.StatusInternalServerError, "", "reqTeamMembership: unprepared context") return } var orgID = ctx.Org.Team.OrgID isOwner, err := models.IsOrganizationOwner(orgID, ctx.User.ID) if err != nil { - ctx.Error(500, "IsOrganizationOwner", err) + ctx.Error(http.StatusInternalServerError, "IsOrganizationOwner", err) return } else if isOwner { return } if isTeamMember, err := models.IsTeamMember(orgID, ctx.Org.Team.ID, ctx.User.ID); err != nil { - ctx.Error(500, "IsTeamMember", err) + ctx.Error(http.StatusInternalServerError, "IsTeamMember", err) return } else if !isTeamMember { isOrgMember, err := models.IsOrganizationMember(orgID, ctx.User.ID) if err != nil { - ctx.Error(500, "IsOrganizationMember", err) + ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err) } else if isOrgMember { - ctx.Error(403, "", "Must be a team member") + ctx.Error(http.StatusForbidden, "", "Must be a team member") } else { ctx.NotFound() } @@ -338,16 +339,16 @@ func reqOrgMembership() macaron.Handler { } else if ctx.Org.Team != nil { orgID = ctx.Org.Team.OrgID } else { - ctx.Error(500, "", "reqOrgMembership: unprepared context") + ctx.Error(http.StatusInternalServerError, "", "reqOrgMembership: unprepared context") return } if isMember, err := models.IsOrganizationMember(orgID, ctx.User.ID); err != nil { - ctx.Error(500, "IsOrganizationMember", err) + ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err) return } else if !isMember { if ctx.Org.Organization != nil { - ctx.Error(403, "", "Must be an organization member") + ctx.Error(http.StatusForbidden, "", "Must be an organization member") } else { ctx.NotFound() } @@ -359,7 +360,7 @@ func reqOrgMembership() macaron.Handler { func reqGitHook() macaron.Handler { return func(ctx *context.APIContext) { if !ctx.User.CanEditGitHook() { - ctx.Error(403, "", "must be allowed to edit Git hooks") + ctx.Error(http.StatusForbidden, "", "must be allowed to edit Git hooks") return } } @@ -386,7 +387,7 @@ func orgAssignment(args ...bool) macaron.Handler { if models.IsErrOrgNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetOrgByName", err) + ctx.Error(http.StatusInternalServerError, "GetOrgByName", err) } return } @@ -398,7 +399,7 @@ func orgAssignment(args ...bool) macaron.Handler { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetTeamById", err) + ctx.Error(http.StatusInternalServerError, "GetTeamById", err) } return } diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index d420ac9b9338..5a44db5e8bcc 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -5,6 +5,7 @@ package misc import ( + "net/http" "strings" "code.gitea.io/gitea/modules/context" @@ -37,7 +38,7 @@ func Markdown(ctx *context.APIContext, form api.MarkdownOption) { // "$ref": "#/responses/validationError" if ctx.HasAPIError() { - ctx.Error(422, "", ctx.GetErrMsg()) + ctx.Error(http.StatusUnprocessableEntity, "", ctx.GetErrMsg()) return } @@ -108,7 +109,7 @@ func MarkdownRaw(ctx *context.APIContext) { body, err := ctx.Req.Body().Bytes() if err != nil { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) return } _, err = ctx.Write(markdown.RenderRaw(body, "", false)) diff --git a/routers/api/v1/misc/swagger.go b/routers/api/v1/misc/swagger.go index e17b77522769..e46d4194b46e 100644 --- a/routers/api/v1/misc/swagger.go +++ b/routers/api/v1/misc/swagger.go @@ -5,6 +5,8 @@ package misc import ( + "net/http" + "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" ) @@ -15,5 +17,5 @@ const tplSwagger base.TplName = "swagger/ui" // Swagger render swagger-ui page with v1 json func Swagger(ctx *context.Context) { ctx.Data["APIJSONVersion"] = "v1" - ctx.HTML(200, tplSwagger) + ctx.HTML(http.StatusOK, tplSwagger) } diff --git a/routers/api/v1/misc/version.go b/routers/api/v1/misc/version.go index 803f5ac716f5..b8c7d4f9ada2 100644 --- a/routers/api/v1/misc/version.go +++ b/routers/api/v1/misc/version.go @@ -5,6 +5,8 @@ package misc import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" @@ -20,5 +22,5 @@ func Version(ctx *context.APIContext) { // responses: // "200": // "$ref": "#/responses/ServerVersion" - ctx.JSON(200, &structs.ServerVersion{Version: setting.AppVer}) + ctx.JSON(http.StatusOK, &structs.ServerVersion{Version: setting.AppVer}) } diff --git a/routers/api/v1/org/hook.go b/routers/api/v1/org/hook.go index f807aff41b11..b3faac7b516f 100644 --- a/routers/api/v1/org/hook.go +++ b/routers/api/v1/org/hook.go @@ -5,6 +5,8 @@ package org import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -32,14 +34,14 @@ func ListHooks(ctx *context.APIContext) { org := ctx.Org.Organization orgHooks, err := models.GetWebhooksByOrgID(org.ID) if err != nil { - ctx.Error(500, "GetWebhooksByOrgID", err) + ctx.Error(http.StatusInternalServerError, "GetWebhooksByOrgID", err) return } hooks := make([]*api.Hook, len(orgHooks)) for i, hook := range orgHooks { hooks[i] = convert.ToHook(org.HomeLink(), hook) } - ctx.JSON(200, hooks) + ctx.JSON(http.StatusOK, hooks) } // GetHook get an organization's hook by id @@ -71,7 +73,7 @@ func GetHook(ctx *context.APIContext) { if err != nil { return } - ctx.JSON(200, convert.ToHook(org.HomeLink(), hook)) + ctx.JSON(http.StatusOK, convert.ToHook(org.HomeLink(), hook)) } // CreateHook create a hook for an organization @@ -168,9 +170,9 @@ func DeleteHook(ctx *context.APIContext) { if models.IsErrWebhookNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "DeleteWebhookByOrgID", err) + ctx.Error(http.StatusInternalServerError, "DeleteWebhookByOrgID", err) } return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/org/member.go b/routers/api/v1/org/member.go index 89260a0b4dda..1575600a652d 100644 --- a/routers/api/v1/org/member.go +++ b/routers/api/v1/org/member.go @@ -6,6 +6,7 @@ package org import ( "fmt" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -23,7 +24,7 @@ func listMembers(ctx *context.APIContext, publicOnly bool) { PublicOnly: publicOnly, }) if err != nil { - ctx.Error(500, "GetUsersByIDs", err) + ctx.Error(http.StatusInternalServerError, "GetUsersByIDs", err) return } @@ -31,7 +32,7 @@ func listMembers(ctx *context.APIContext, publicOnly bool) { for i, member := range members { apiMembers[i] = convert.ToUser(member, ctx.IsSigned, ctx.User != nil && ctx.User.IsAdmin) } - ctx.JSON(200, apiMembers) + ctx.JSON(http.StatusOK, apiMembers) } // ListMembers list an organization's members @@ -55,7 +56,7 @@ func ListMembers(ctx *context.APIContext) { if ctx.User != nil { isMember, err := ctx.Org.Organization.IsOrgMember(ctx.User.ID) if err != nil { - ctx.Error(500, "IsOrgMember", err) + ctx.Error(http.StatusInternalServerError, "IsOrgMember", err) return } publicOnly = !isMember @@ -114,14 +115,14 @@ func IsMember(ctx *context.APIContext) { if ctx.User != nil { userIsMember, err := ctx.Org.Organization.IsOrgMember(ctx.User.ID) if err != nil { - ctx.Error(500, "IsOrgMember", err) + ctx.Error(http.StatusInternalServerError, "IsOrgMember", err) return } else if userIsMember { userToCheckIsMember, err := ctx.Org.Organization.IsOrgMember(userToCheck.ID) if err != nil { - ctx.Error(500, "IsOrgMember", err) + ctx.Error(http.StatusInternalServerError, "IsOrgMember", err) } else if userToCheckIsMember { - ctx.Status(204) + ctx.Status(http.StatusNoContent) } else { ctx.NotFound() } @@ -164,7 +165,7 @@ func IsPublicMember(ctx *context.APIContext) { return } if userToCheck.IsPublicMember(ctx.Org.Organization.ID) { - ctx.Status(204) + ctx.Status(http.StatusNoContent) } else { ctx.NotFound() } @@ -199,15 +200,15 @@ func PublicizeMember(ctx *context.APIContext) { return } if userToPublicize.ID != ctx.User.ID { - ctx.Error(403, "", "Cannot publicize another member") + ctx.Error(http.StatusForbidden, "", "Cannot publicize another member") return } err := models.ChangeOrgUserStatus(ctx.Org.Organization.ID, userToPublicize.ID, true) if err != nil { - ctx.Error(500, "ChangeOrgUserStatus", err) + ctx.Error(http.StatusInternalServerError, "ChangeOrgUserStatus", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // ConcealMember make a member's membership not public @@ -239,15 +240,15 @@ func ConcealMember(ctx *context.APIContext) { return } if userToConceal.ID != ctx.User.ID { - ctx.Error(403, "", "Cannot conceal another member") + ctx.Error(http.StatusForbidden, "", "Cannot conceal another member") return } err := models.ChangeOrgUserStatus(ctx.Org.Organization.ID, userToConceal.ID, false) if err != nil { - ctx.Error(500, "ChangeOrgUserStatus", err) + ctx.Error(http.StatusInternalServerError, "ChangeOrgUserStatus", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // DeleteMember remove a member from an organization @@ -277,7 +278,7 @@ func DeleteMember(ctx *context.APIContext) { return } if err := ctx.Org.Organization.RemoveMember(member.ID); err != nil { - ctx.Error(500, "RemoveMember", err) + ctx.Error(http.StatusInternalServerError, "RemoveMember", err) } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/org/org.go b/routers/api/v1/org/org.go index 636bf88141cc..67770e70aa62 100644 --- a/routers/api/v1/org/org.go +++ b/routers/api/v1/org/org.go @@ -6,6 +6,8 @@ package org import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -15,7 +17,7 @@ import ( func listUserOrgs(ctx *context.APIContext, u *models.User, all bool) { if err := u.GetOrganizations(all); err != nil { - ctx.Error(500, "GetOrganizations", err) + ctx.Error(http.StatusInternalServerError, "GetOrganizations", err) return } @@ -23,7 +25,7 @@ func listUserOrgs(ctx *context.APIContext, u *models.User, all bool) { for i := range u.Orgs { apiOrgs[i] = convert.ToOrganization(u.Orgs[i]) } - ctx.JSON(200, &apiOrgs) + ctx.JSON(http.StatusOK, &apiOrgs) } // ListMyOrgs list all my orgs @@ -87,7 +89,7 @@ func Create(ctx *context.APIContext, form api.CreateOrgOption) { // "$ref": "#/responses/validationError" if !ctx.User.CanCreateOrganization() { - ctx.Error(403, "Create organization not allowed", nil) + ctx.Error(http.StatusForbidden, "Create organization not allowed", nil) return } @@ -111,14 +113,14 @@ func Create(ctx *context.APIContext, form api.CreateOrgOption) { if models.IsErrUserAlreadyExist(err) || models.IsErrNameReserved(err) || models.IsErrNamePatternNotAllowed(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "CreateOrganization", err) + ctx.Error(http.StatusInternalServerError, "CreateOrganization", err) } return } - ctx.JSON(201, convert.ToOrganization(org)) + ctx.JSON(http.StatusCreated, convert.ToOrganization(org)) } // Get get an organization @@ -142,7 +144,7 @@ func Get(ctx *context.APIContext) { ctx.NotFound("HasOrgVisible", nil) return } - ctx.JSON(200, convert.ToOrganization(ctx.Org.Organization)) + ctx.JSON(http.StatusOK, convert.ToOrganization(ctx.Org.Organization)) } // Edit change an organization's information @@ -178,11 +180,11 @@ func Edit(ctx *context.APIContext, form api.EditOrgOption) { org.Visibility = api.VisibilityModes[form.Visibility] } if err := models.UpdateUserCols(org, "full_name", "description", "website", "location", "visibility"); err != nil { - ctx.Error(500, "EditOrganization", err) + ctx.Error(http.StatusInternalServerError, "EditOrganization", err) return } - ctx.JSON(200, convert.ToOrganization(org)) + ctx.JSON(http.StatusOK, convert.ToOrganization(org)) } //Delete an organization @@ -203,8 +205,8 @@ func Delete(ctx *context.APIContext) { // "$ref": "#/responses/empty" if err := models.DeleteOrganization(ctx.Org.Organization); err != nil { - ctx.Error(500, "DeleteOrganization", err) + ctx.Error(http.StatusInternalServerError, "DeleteOrganization", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index 98929f047298..73714e6a6635 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -6,6 +6,7 @@ package org import ( + "net/http" "strings" "code.gitea.io/gitea/models" @@ -35,20 +36,20 @@ func ListTeams(ctx *context.APIContext) { org := ctx.Org.Organization if err := org.GetTeams(); err != nil { - ctx.Error(500, "GetTeams", err) + ctx.Error(http.StatusInternalServerError, "GetTeams", err) return } apiTeams := make([]*api.Team, len(org.Teams)) for i := range org.Teams { if err := org.Teams[i].GetUnits(); err != nil { - ctx.Error(500, "GetUnits", err) + ctx.Error(http.StatusInternalServerError, "GetUnits", err) return } apiTeams[i] = convert.ToTeam(org.Teams[i]) } - ctx.JSON(200, apiTeams) + ctx.JSON(http.StatusOK, apiTeams) } // ListUserTeams list all the teams a user belongs to @@ -64,7 +65,7 @@ func ListUserTeams(ctx *context.APIContext) { teams, err := models.GetUserTeams(ctx.User.ID) if err != nil { - ctx.Error(500, "GetUserTeams", err) + ctx.Error(http.StatusInternalServerError, "GetUserTeams", err) return } @@ -75,7 +76,7 @@ func ListUserTeams(ctx *context.APIContext) { if !ok { org, err := models.GetUserByID(teams[i].OrgID) if err != nil { - ctx.Error(500, "GetUserByID", err) + ctx.Error(http.StatusInternalServerError, "GetUserByID", err) return } apiOrg = convert.ToOrganization(org) @@ -84,7 +85,7 @@ func ListUserTeams(ctx *context.APIContext) { apiTeams[i] = convert.ToTeam(teams[i]) apiTeams[i].Organization = apiOrg } - ctx.JSON(200, apiTeams) + ctx.JSON(http.StatusOK, apiTeams) } // GetTeam api for get a team @@ -105,7 +106,7 @@ func GetTeam(ctx *context.APIContext) { // "200": // "$ref": "#/responses/Team" - ctx.JSON(200, convert.ToTeam(ctx.Org.Team)) + ctx.JSON(http.StatusOK, convert.ToTeam(ctx.Org.Team)) } // CreateTeam api for create a team @@ -157,14 +158,14 @@ func CreateTeam(ctx *context.APIContext, form api.CreateTeamOption) { if err := models.NewTeam(team); err != nil { if models.IsErrTeamAlreadyExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "NewTeam", err) + ctx.Error(http.StatusInternalServerError, "NewTeam", err) } return } - ctx.JSON(201, convert.ToTeam(team)) + ctx.JSON(http.StatusCreated, convert.ToTeam(team)) } // EditTeam api for edit a team @@ -225,10 +226,10 @@ func EditTeam(ctx *context.APIContext, form api.EditTeamOption) { } if err := models.UpdateTeam(team, isAuthChanged, isIncludeAllChanged); err != nil { - ctx.Error(500, "EditTeam", err) + ctx.Error(http.StatusInternalServerError, "EditTeam", err) return } - ctx.JSON(200, convert.ToTeam(team)) + ctx.JSON(http.StatusOK, convert.ToTeam(team)) } // DeleteTeam api for delete a team @@ -248,10 +249,10 @@ func DeleteTeam(ctx *context.APIContext) { // description: team deleted if err := models.DeleteTeam(ctx.Org.Team); err != nil { - ctx.Error(500, "DeleteTeam", err) + ctx.Error(http.StatusInternalServerError, "DeleteTeam", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // GetTeamMembers api for get a team's members @@ -274,7 +275,7 @@ func GetTeamMembers(ctx *context.APIContext) { isMember, err := models.IsOrganizationMember(ctx.Org.Team.OrgID, ctx.User.ID) if err != nil { - ctx.Error(500, "IsOrganizationMember", err) + ctx.Error(http.StatusInternalServerError, "IsOrganizationMember", err) return } else if !isMember { ctx.NotFound() @@ -282,14 +283,14 @@ func GetTeamMembers(ctx *context.APIContext) { } team := ctx.Org.Team if err := team.GetMembers(); err != nil { - ctx.Error(500, "GetTeamMembers", err) + ctx.Error(http.StatusInternalServerError, "GetTeamMembers", err) return } members := make([]*api.User, len(team.Members)) for i, member := range team.Members { members[i] = convert.ToUser(member, ctx.IsSigned, ctx.User.IsAdmin) } - ctx.JSON(200, members) + ctx.JSON(http.StatusOK, members) } // GetTeamMember api for get a particular member of team @@ -324,13 +325,13 @@ func GetTeamMember(ctx *context.APIContext) { teamID := ctx.ParamsInt64("teamid") isTeamMember, err := models.IsUserInTeams(u.ID, []int64{teamID}) if err != nil { - ctx.Error(500, "IsUserInTeams", err) + ctx.Error(http.StatusInternalServerError, "IsUserInTeams", err) return } else if !isTeamMember { ctx.NotFound() return } - ctx.JSON(200, convert.ToUser(u, ctx.IsSigned, ctx.User.IsAdmin)) + ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.IsSigned, ctx.User.IsAdmin)) } // AddTeamMember api for add a member to a team @@ -363,10 +364,10 @@ func AddTeamMember(ctx *context.APIContext) { return } if err := ctx.Org.Team.AddMember(u.ID); err != nil { - ctx.Error(500, "AddMember", err) + ctx.Error(http.StatusInternalServerError, "AddMember", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // RemoveTeamMember api for remove one member from a team @@ -400,10 +401,10 @@ func RemoveTeamMember(ctx *context.APIContext) { } if err := ctx.Org.Team.RemoveMember(u.ID); err != nil { - ctx.Error(500, "RemoveMember", err) + ctx.Error(http.StatusInternalServerError, "RemoveMember", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // GetTeamRepos api for get a team's repos @@ -426,18 +427,18 @@ func GetTeamRepos(ctx *context.APIContext) { team := ctx.Org.Team if err := team.GetRepositories(); err != nil { - ctx.Error(500, "GetTeamRepos", err) + ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err) } repos := make([]*api.Repository, len(team.Repos)) for i, repo := range team.Repos { access, err := models.AccessLevel(ctx.User, repo) if err != nil { - ctx.Error(500, "GetTeamRepos", err) + ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err) return } repos[i] = repo.APIFormat(access) } - ctx.JSON(200, repos) + ctx.JSON(http.StatusOK, repos) } // getRepositoryByParams get repository by a team's organization ID and repo name @@ -447,7 +448,7 @@ func getRepositoryByParams(ctx *context.APIContext) *models.Repository { if models.IsErrRepoNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetRepositoryByName", err) + ctx.Error(http.StatusInternalServerError, "GetRepositoryByName", err) } return nil } @@ -489,17 +490,17 @@ func AddTeamRepository(ctx *context.APIContext) { return } if access, err := models.AccessLevel(ctx.User, repo); err != nil { - ctx.Error(500, "AccessLevel", err) + ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } else if access < models.AccessModeAdmin { - ctx.Error(403, "", "Must have admin-level access to the repository") + ctx.Error(http.StatusForbidden, "", "Must have admin-level access to the repository") return } if err := ctx.Org.Team.AddRepository(repo); err != nil { - ctx.Error(500, "AddRepository", err) + ctx.Error(http.StatusInternalServerError, "AddRepository", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // RemoveTeamRepository api for removing a repository from a team @@ -539,17 +540,17 @@ func RemoveTeamRepository(ctx *context.APIContext) { return } if access, err := models.AccessLevel(ctx.User, repo); err != nil { - ctx.Error(500, "AccessLevel", err) + ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } else if access < models.AccessModeAdmin { - ctx.Error(403, "", "Must have admin-level access to the repository") + ctx.Error(http.StatusForbidden, "", "Must have admin-level access to the repository") return } if err := ctx.Org.Team.RemoveRepository(repo.ID); err != nil { - ctx.Error(500, "RemoveRepository", err) + ctx.Error(http.StatusInternalServerError, "RemoveRepository", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // SearchTeam api for searching teams @@ -606,7 +607,7 @@ func SearchTeam(ctx *context.APIContext) { teams, _, err := models.SearchTeam(opts) if err != nil { log.Error("SearchTeam failed: %v", err) - ctx.JSON(500, map[string]interface{}{ + ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ "ok": false, "error": "SearchTeam internal failure", }) @@ -617,7 +618,7 @@ func SearchTeam(ctx *context.APIContext) { for i := range teams { if err := teams[i].GetUnits(); err != nil { log.Error("Team GetUnits failed: %v", err) - ctx.JSON(500, map[string]interface{}{ + ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ "ok": false, "error": "SearchTeam failed to get units", }) @@ -626,7 +627,7 @@ func SearchTeam(ctx *context.APIContext) { apiTeams[i] = convert.ToTeam(teams[i]) } - ctx.JSON(200, map[string]interface{}{ + ctx.JSON(http.StatusOK, map[string]interface{}{ "ok": true, "data": apiTeams, }) diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 71483a58f6f7..afc4763b522c 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -6,6 +6,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/git" @@ -51,24 +53,24 @@ func GetBranch(ctx *context.APIContext) { if git.IsErrBranchNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetBranch", err) + ctx.Error(http.StatusInternalServerError, "GetBranch", err) } return } c, err := branch.GetCommit() if err != nil { - ctx.Error(500, "GetCommit", err) + ctx.Error(http.StatusInternalServerError, "GetCommit", err) return } branchProtection, err := ctx.Repo.Repository.GetBranchProtection(ctx.Repo.BranchName) if err != nil { - ctx.Error(500, "GetBranchProtection", err) + ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err) return } - ctx.JSON(200, convert.ToBranch(ctx.Repo.Repository, branch, c, branchProtection, ctx.User)) + ctx.JSON(http.StatusOK, convert.ToBranch(ctx.Repo.Repository, branch, c, branchProtection, ctx.User)) } // ListBranches list all the branches of a repository @@ -95,7 +97,7 @@ func ListBranches(ctx *context.APIContext) { branches, err := ctx.Repo.Repository.GetBranches() if err != nil { - ctx.Error(500, "GetBranches", err) + ctx.Error(http.StatusInternalServerError, "GetBranches", err) return } @@ -103,16 +105,16 @@ func ListBranches(ctx *context.APIContext) { for i := range branches { c, err := branches[i].GetCommit() if err != nil { - ctx.Error(500, "GetCommit", err) + ctx.Error(http.StatusInternalServerError, "GetCommit", err) return } branchProtection, err := ctx.Repo.Repository.GetBranchProtection(branches[i].Name) if err != nil { - ctx.Error(500, "GetBranchProtection", err) + ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err) return } apiBranches[i] = convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.User) } - ctx.JSON(200, &apiBranches) + ctx.JSON(http.StatusOK, &apiBranches) } diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index 96be9e4639ae..aec389ab310b 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -7,6 +7,7 @@ package repo import ( "errors" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -38,14 +39,14 @@ func ListCollaborators(ctx *context.APIContext) { collaborators, err := ctx.Repo.Repository.GetCollaborators() if err != nil { - ctx.Error(500, "ListCollaborators", err) + ctx.Error(http.StatusInternalServerError, "ListCollaborators", err) return } users := make([]*api.User, len(collaborators)) for i, collaborator := range collaborators { users[i] = convert.ToUser(collaborator.User, ctx.IsSigned, ctx.User != nil && ctx.User.IsAdmin) } - ctx.JSON(200, users) + ctx.JSON(http.StatusOK, users) } // IsCollaborator check if a user is a collaborator of a repository @@ -82,19 +83,19 @@ func IsCollaborator(ctx *context.APIContext) { user, err := models.GetUserByName(ctx.Params(":collaborator")) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return } isColab, err := ctx.Repo.Repository.IsCollaborator(user.ID) if err != nil { - ctx.Error(500, "IsCollaborator", err) + ctx.Error(http.StatusInternalServerError, "IsCollaborator", err) return } if isColab { - ctx.Status(204) + ctx.Status(http.StatusNoContent) } else { ctx.NotFound() } @@ -136,31 +137,31 @@ func AddCollaborator(ctx *context.APIContext, form api.AddCollaboratorOption) { collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return } if !collaborator.IsActive { - ctx.Error(500, "InactiveCollaborator", errors.New("collaborator's account is inactive")) + ctx.Error(http.StatusInternalServerError, "InactiveCollaborator", errors.New("collaborator's account is inactive")) return } if err := ctx.Repo.Repository.AddCollaborator(collaborator); err != nil { - ctx.Error(500, "AddCollaborator", err) + ctx.Error(http.StatusInternalServerError, "AddCollaborator", err) return } if form.Permission != nil { if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(collaborator.ID, models.ParseAccessMode(*form.Permission)); err != nil { - ctx.Error(500, "ChangeCollaborationAccessMode", err) + ctx.Error(http.StatusInternalServerError, "ChangeCollaborationAccessMode", err) return } } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // DeleteCollaborator delete a collaborator from a repository @@ -195,16 +196,16 @@ func DeleteCollaborator(ctx *context.APIContext) { collaborator, err := models.GetUserByName(ctx.Params(":collaborator")) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return } if err := ctx.Repo.Repository.DeleteCollaboration(collaborator.ID); err != nil { - ctx.Error(500, "DeleteCollaboration", err) + ctx.Error(http.StatusInternalServerError, "DeleteCollaboration", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/commits.go b/routers/api/v1/repo/commits.go index 163a06a95e8e..d8777eaf3aca 100644 --- a/routers/api/v1/repo/commits.go +++ b/routers/api/v1/repo/commits.go @@ -7,6 +7,7 @@ package repo import ( "math" + "net/http" "strconv" "time" @@ -64,7 +65,7 @@ func GetSingleCommit(ctx *context.APIContext) { return } - ctx.JSON(200, json) + ctx.JSON(http.StatusOK, json) } // GetAllCommits get all commits via @@ -102,7 +103,7 @@ func GetAllCommits(ctx *context.APIContext) { // "$ref": "#/responses/EmptyRepository" if ctx.Repo.Repository.IsEmpty { - ctx.JSON(409, api.APIError{ + ctx.JSON(http.StatusConflict, api.APIError{ Message: "Git Repository is empty.", URL: setting.API.SwaggerURL, }) @@ -188,7 +189,7 @@ func GetAllCommits(ctx *context.APIContext) { ctx.Header().Set("X-PageCount", strconv.Itoa(pageCount)) ctx.Header().Set("X-HasMore", strconv.FormatBool(page < pageCount)) - ctx.JSON(200, &apiCommits) + ctx.JSON(http.StatusOK, &apiCommits) } func toCommit(ctx *context.APIContext, repo *models.Repository, commit *git.Commit, userCache map[string]*models.User) (*api.Commit, error) { diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index e67eb3b1b1da..0bf7fc6cefdf 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -6,6 +6,7 @@ package repo import ( "fmt" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -37,19 +38,19 @@ func ListForks(ctx *context.APIContext) { forks, err := ctx.Repo.Repository.GetForks() if err != nil { - ctx.Error(500, "GetForks", err) + ctx.Error(http.StatusInternalServerError, "GetForks", err) return } apiForks := make([]*api.Repository, len(forks)) for i, fork := range forks { access, err := models.AccessLevel(ctx.User, fork) if err != nil { - ctx.Error(500, "AccessLevel", err) + ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } apiForks[i] = fork.APIFormat(access) } - ctx.JSON(200, apiForks) + ctx.JSON(http.StatusOK, apiForks) } // CreateFork create a fork of a repo @@ -90,9 +91,9 @@ func CreateFork(ctx *context.APIContext, form api.CreateForkOption) { org, err := models.GetOrgByName(*form.Organization) if err != nil { if models.IsErrOrgNotExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "GetOrgByName", err) + ctx.Error(http.StatusInternalServerError, "GetOrgByName", err) } return } @@ -101,7 +102,7 @@ func CreateFork(ctx *context.APIContext, form api.CreateForkOption) { ctx.ServerError("IsOrgMember", err) return } else if !isMember { - ctx.Error(403, "isMemberNot", fmt.Sprintf("User is no Member of Organisation '%s'", org.Name)) + ctx.Error(http.StatusForbidden, "isMemberNot", fmt.Sprintf("User is no Member of Organisation '%s'", org.Name)) return } forker = org @@ -109,10 +110,10 @@ func CreateFork(ctx *context.APIContext, form api.CreateForkOption) { fork, err := repo_service.ForkRepository(ctx.User, forker, repo, repo.Name, repo.Description) if err != nil { - ctx.Error(500, "ForkRepository", err) + ctx.Error(http.StatusInternalServerError, "ForkRepository", err) return } //TODO change back to 201 - ctx.JSON(202, fork.APIFormat(models.AccessModeOwner)) + ctx.JSON(http.StatusAccepted, fork.APIFormat(models.AccessModeOwner)) } diff --git a/routers/api/v1/repo/git_hook.go b/routers/api/v1/repo/git_hook.go index 46e0b5174595..0c538ac6b319 100644 --- a/routers/api/v1/repo/git_hook.go +++ b/routers/api/v1/repo/git_hook.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/git" @@ -35,7 +37,7 @@ func ListGitHooks(ctx *context.APIContext) { hooks, err := ctx.Repo.GitRepo.Hooks() if err != nil { - ctx.Error(500, "Hooks", err) + ctx.Error(http.StatusInternalServerError, "Hooks", err) return } @@ -43,7 +45,7 @@ func ListGitHooks(ctx *context.APIContext) { for i := range hooks { apiHooks[i] = convert.ToGitHook(hooks[i]) } - ctx.JSON(200, &apiHooks) + ctx.JSON(http.StatusOK, &apiHooks) } // GetGitHook get a repo's Git hook by id @@ -81,11 +83,11 @@ func GetGitHook(ctx *context.APIContext) { if err == git.ErrNotValidHook { ctx.NotFound() } else { - ctx.Error(500, "GetHook", err) + ctx.Error(http.StatusInternalServerError, "GetHook", err) } return } - ctx.JSON(200, convert.ToGitHook(hook)) + ctx.JSON(http.StatusOK, convert.ToGitHook(hook)) } // EditGitHook modify a Git hook of a repository @@ -127,18 +129,18 @@ func EditGitHook(ctx *context.APIContext, form api.EditGitHookOption) { if err == git.ErrNotValidHook { ctx.NotFound() } else { - ctx.Error(500, "GetHook", err) + ctx.Error(http.StatusInternalServerError, "GetHook", err) } return } hook.Content = form.Content if err = hook.Update(); err != nil { - ctx.Error(500, "hook.Update", err) + ctx.Error(http.StatusInternalServerError, "hook.Update", err) return } - ctx.JSON(200, convert.ToGitHook(hook)) + ctx.JSON(http.StatusOK, convert.ToGitHook(hook)) } // DeleteGitHook delete a Git hook of a repository @@ -176,16 +178,16 @@ func DeleteGitHook(ctx *context.APIContext) { if err == git.ErrNotValidHook { ctx.NotFound() } else { - ctx.Error(500, "GetHook", err) + ctx.Error(http.StatusInternalServerError, "GetHook", err) } return } hook.Content = "" if err = hook.Update(); err != nil { - ctx.Error(500, "hook.Update", err) + ctx.Error(http.StatusInternalServerError, "hook.Update", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/git_ref.go b/routers/api/v1/repo/git_ref.go index c2bcbb360386..bd43ad4fc8ab 100644 --- a/routers/api/v1/repo/git_ref.go +++ b/routers/api/v1/repo/git_ref.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" @@ -88,7 +90,7 @@ func getGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, strin func getGitRefsInternal(ctx *context.APIContext, filter string) { refs, lastMethodName, err := getGitRefs(ctx, filter) if err != nil { - ctx.Error(500, lastMethodName, err) + ctx.Error(http.StatusInternalServerError, lastMethodName, err) return } @@ -111,8 +113,8 @@ func getGitRefsInternal(ctx *context.APIContext, filter string) { } // If single reference is found and it matches filter exactly return it as object if len(apiRefs) == 1 && apiRefs[0].Ref == filter { - ctx.JSON(200, &apiRefs[0]) + ctx.JSON(http.StatusOK, &apiRefs[0]) return } - ctx.JSON(200, &apiRefs) + ctx.JSON(http.StatusOK, &apiRefs) } diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index cefd0b161f07..7fd7cd1be35c 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -38,7 +40,7 @@ func ListHooks(ctx *context.APIContext) { hooks, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID) if err != nil { - ctx.Error(500, "GetWebhooksByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetWebhooksByRepoID", err) return } @@ -46,7 +48,7 @@ func ListHooks(ctx *context.APIContext) { for i := range hooks { apiHooks[i] = convert.ToHook(ctx.Repo.RepoLink, hooks[i]) } - ctx.JSON(200, &apiHooks) + ctx.JSON(http.StatusOK, &apiHooks) } // GetHook get a repo's hook by id @@ -85,7 +87,7 @@ func GetHook(ctx *context.APIContext) { if err != nil { return } - ctx.JSON(200, convert.ToHook(repo.RepoLink, hook)) + ctx.JSON(http.StatusOK, convert.ToHook(repo.RepoLink, hook)) } // TestHook tests a hook @@ -118,7 +120,7 @@ func TestHook(ctx *context.APIContext) { if ctx.Repo.Commit == nil { // if repo does not have any commits, then don't send a webhook - ctx.Status(204) + ctx.Status(http.StatusNoContent) return } @@ -139,11 +141,11 @@ func TestHook(ctx *context.APIContext) { Pusher: convert.ToUser(ctx.User, ctx.IsSigned, false), Sender: convert.ToUser(ctx.User, ctx.IsSigned, false), }); err != nil { - ctx.Error(500, "PrepareWebhook: ", err) + ctx.Error(http.StatusInternalServerError, "PrepareWebhook: ", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // CreateHook create a hook for a repository @@ -247,9 +249,9 @@ func DeleteHook(ctx *context.APIContext) { if models.IsErrWebhookNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "DeleteWebhookByRepoID", err) + ctx.Error(http.StatusInternalServerError, "DeleteWebhookByRepoID", err) } return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 741b713f6781..4396e6faaebe 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -82,7 +82,7 @@ func SearchIssues(ctx *context.APIContext) { OrderBy: models.SearchOrderByRecentUpdated, }) if err != nil { - ctx.Error(500, "SearchRepositoryByName", err) + ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err) return } @@ -120,7 +120,7 @@ func SearchIssues(ctx *context.APIContext) { if splitted := strings.Split(labels, ","); labels != "" && len(splitted) > 0 { labelIDs, err = models.GetLabelIDsInReposByNames(repoIDs, splitted) if err != nil { - ctx.Error(500, "GetLabelIDsInRepoByNames", err) + ctx.Error(http.StatusInternalServerError, "GetLabelIDsInRepoByNames", err) return } } @@ -141,7 +141,7 @@ func SearchIssues(ctx *context.APIContext) { } if err != nil { - ctx.Error(500, "Issues", err) + ctx.Error(http.StatusInternalServerError, "Issues", err) return } @@ -151,7 +151,7 @@ func SearchIssues(ctx *context.APIContext) { } ctx.SetLinkHeader(issueCount, setting.UI.IssuePagingNum) - ctx.JSON(200, &apiIssues) + ctx.JSON(http.StatusOK, &apiIssues) } // ListIssues list the issues of a repository @@ -218,7 +218,7 @@ func ListIssues(ctx *context.APIContext) { if splitted := strings.Split(ctx.Query("labels"), ","); len(splitted) > 0 { labelIDs, err = models.GetLabelIDsInRepoByNames(ctx.Repo.Repository.ID, splitted) if err != nil { - ctx.Error(500, "GetLabelIDsInRepoByNames", err) + ctx.Error(http.StatusInternalServerError, "GetLabelIDsInRepoByNames", err) return } } @@ -237,7 +237,7 @@ func ListIssues(ctx *context.APIContext) { } if err != nil { - ctx.Error(500, "Issues", err) + ctx.Error(http.StatusInternalServerError, "Issues", err) return } @@ -247,7 +247,7 @@ func ListIssues(ctx *context.APIContext) { } ctx.SetLinkHeader(ctx.Repo.Repository.NumIssues, setting.UI.IssuePagingNum) - ctx.JSON(200, &apiIssues) + ctx.JSON(http.StatusOK, &apiIssues) } // GetIssue get an issue of a repository @@ -285,11 +285,11 @@ func GetIssue(ctx *context.APIContext) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } - ctx.JSON(200, issue.APIFormat()) + ctx.JSON(http.StatusOK, issue.APIFormat()) } // CreateIssue create an issue of a repository @@ -348,9 +348,9 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { assigneeIDs, err = models.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) } else { - ctx.Error(500, "AddAssigneeByName", err) + ctx.Error(http.StatusInternalServerError, "AddAssigneeByName", err) } return } @@ -359,17 +359,17 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { for _, aID := range assigneeIDs { assignee, err := models.GetUserByID(aID) if err != nil { - ctx.Error(500, "GetUserByID", err) + ctx.Error(http.StatusInternalServerError, "GetUserByID", err) return } valid, err := models.CanBeAssigned(assignee, ctx.Repo.Repository, false) if err != nil { - ctx.Error(500, "canBeAssigned", err) + ctx.Error(http.StatusInternalServerError, "canBeAssigned", err) return } if !valid { - ctx.Error(422, "canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: ctx.Repo.Repository.Name}) + ctx.Error(http.StatusUnprocessableEntity, "canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: ctx.Repo.Repository.Name}) return } } @@ -380,10 +380,10 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { if err := issue_service.NewIssue(ctx.Repo.Repository, issue, form.Labels, nil, assigneeIDs); err != nil { if models.IsErrUserDoesNotHaveAccessToRepo(err) { - ctx.Error(400, "UserDoesNotHaveAccessToRepo", err) + ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err) return } - ctx.Error(500, "NewIssue", err) + ctx.Error(http.StatusInternalServerError, "NewIssue", err) return } @@ -393,7 +393,7 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this issue because it still has open dependencies") return } - ctx.Error(500, "ChangeStatus", err) + ctx.Error(http.StatusInternalServerError, "ChangeStatus", err) return } } @@ -401,10 +401,10 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { // Refetch from database to assign some automatic values issue, err = models.GetIssueByID(issue.ID) if err != nil { - ctx.Error(500, "GetIssueByID", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByID", err) return } - ctx.JSON(201, issue.APIFormat()) + ctx.JSON(http.StatusCreated, issue.APIFormat()) } // EditIssue modify an issue of a repository @@ -452,7 +452,7 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } @@ -460,12 +460,12 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { err = issue.LoadAttributes() if err != nil { - ctx.Error(500, "LoadAttributes", err) + ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } if !issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWrite(models.UnitTypeIssues) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } @@ -487,7 +487,7 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { } if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil { - ctx.Error(500, "UpdateIssueDeadline", err) + ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err) return } issue.DeadlineUnix = deadlineUnix @@ -509,7 +509,7 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { err = issue_service.UpdateAssignees(issue, oneAssignee, form.Assignees, ctx.User) if err != nil { - ctx.Error(500, "UpdateAssignees", err) + ctx.Error(http.StatusInternalServerError, "UpdateAssignees", err) return } } @@ -519,13 +519,13 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { oldMilestoneID := issue.MilestoneID issue.MilestoneID = *form.Milestone if err = issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil { - ctx.Error(500, "ChangeMilestoneAssign", err) + ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err) return } } if err = models.UpdateIssue(issue); err != nil { - ctx.Error(500, "UpdateIssue", err) + ctx.Error(http.StatusInternalServerError, "UpdateIssue", err) return } if form.State != nil { @@ -534,7 +534,7 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this issue because it still has open dependencies") return } - ctx.Error(500, "ChangeStatus", err) + ctx.Error(http.StatusInternalServerError, "ChangeStatus", err) return } } @@ -542,10 +542,10 @@ func EditIssue(ctx *context.APIContext, form api.EditIssueOption) { // Refetch from database to assign some automatic values issue, err = models.GetIssueByID(issue.ID) if err != nil { - ctx.Error(500, "GetIssueByID", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByID", err) return } - ctx.JSON(201, issue.APIFormat()) + ctx.JSON(http.StatusCreated, issue.APIFormat()) } // UpdateIssueDeadline updates an issue deadline @@ -591,13 +591,13 @@ func UpdateIssueDeadline(ctx *context.APIContext, form api.EditDeadlineOption) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if !ctx.Repo.CanWrite(models.UnitTypeIssues) { - ctx.Error(403, "", "Not repo writer") + ctx.Error(http.StatusForbidden, "", "Not repo writer") return } @@ -610,9 +610,9 @@ func UpdateIssueDeadline(ctx *context.APIContext, form api.EditDeadlineOption) { } if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil { - ctx.Error(500, "UpdateIssueDeadline", err) + ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err) return } - ctx.JSON(201, api.IssueDeadline{Deadline: &deadline}) + ctx.JSON(http.StatusCreated, api.IssueDeadline{Deadline: &deadline}) } diff --git a/routers/api/v1/repo/issue_comment.go b/routers/api/v1/repo/issue_comment.go index e633895a1f79..c13fc93cdfb7 100644 --- a/routers/api/v1/repo/issue_comment.go +++ b/routers/api/v1/repo/issue_comment.go @@ -6,6 +6,7 @@ package repo import ( "errors" + "net/http" "time" "code.gitea.io/gitea/models" @@ -54,7 +55,7 @@ func ListIssueComments(ctx *context.APIContext) { // comments,err:=models.GetCommentsByIssueIDSince(, since) issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { - ctx.Error(500, "GetRawIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetRawIssueByIndex", err) return } issue.Repo = ctx.Repo.Repository @@ -65,12 +66,12 @@ func ListIssueComments(ctx *context.APIContext) { Type: models.CommentTypeComment, }) if err != nil { - ctx.Error(500, "FindComments", err) + ctx.Error(http.StatusInternalServerError, "FindComments", err) return } if err := models.CommentList(comments).LoadPosters(); err != nil { - ctx.Error(500, "LoadPosters", err) + ctx.Error(http.StatusInternalServerError, "LoadPosters", err) return } @@ -79,7 +80,7 @@ func ListIssueComments(ctx *context.APIContext) { comment.Issue = issue apiComments[i] = comments[i].APIFormat() } - ctx.JSON(200, &apiComments) + ctx.JSON(http.StatusOK, &apiComments) } // ListRepoIssueComments returns all issue-comments for a repo @@ -119,32 +120,32 @@ func ListRepoIssueComments(ctx *context.APIContext) { Type: models.CommentTypeComment, }) if err != nil { - ctx.Error(500, "FindComments", err) + ctx.Error(http.StatusInternalServerError, "FindComments", err) return } if err = models.CommentList(comments).LoadPosters(); err != nil { - ctx.Error(500, "LoadPosters", err) + ctx.Error(http.StatusInternalServerError, "LoadPosters", err) return } apiComments := make([]*api.Comment, len(comments)) if err := models.CommentList(comments).LoadIssues(); err != nil { - ctx.Error(500, "LoadIssues", err) + ctx.Error(http.StatusInternalServerError, "LoadIssues", err) return } if err := models.CommentList(comments).LoadPosters(); err != nil { - ctx.Error(500, "LoadPosters", err) + ctx.Error(http.StatusInternalServerError, "LoadPosters", err) return } if _, err := models.CommentList(comments).Issues().LoadRepositories(); err != nil { - ctx.Error(500, "LoadRepositories", err) + ctx.Error(http.StatusInternalServerError, "LoadRepositories", err) return } for i := range comments { apiComments[i] = comments[i].APIFormat() } - ctx.JSON(200, &apiComments) + ctx.JSON(http.StatusOK, &apiComments) } // CreateIssueComment create a comment for an issue @@ -185,22 +186,22 @@ func CreateIssueComment(ctx *context.APIContext, form api.CreateIssueCommentOpti issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) return } if issue.IsLocked && !ctx.Repo.CanWrite(models.UnitTypeIssues) && !ctx.User.IsAdmin { - ctx.Error(403, "CreateIssueComment", errors.New(ctx.Tr("repo.issues.comment_on_locked"))) + ctx.Error(http.StatusForbidden, "CreateIssueComment", errors.New(ctx.Tr("repo.issues.comment_on_locked"))) return } comment, err := comment_service.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Body, nil) if err != nil { - ctx.Error(500, "CreateIssueComment", err) + ctx.Error(http.StatusInternalServerError, "CreateIssueComment", err) return } - ctx.JSON(201, comment.APIFormat()) + ctx.JSON(http.StatusCreated, comment.APIFormat()) } // EditIssueComment modify a comment of an issue @@ -292,27 +293,27 @@ func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) if models.IsErrCommentNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetCommentByID", err) + ctx.Error(http.StatusInternalServerError, "GetCommentByID", err) } return } if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } else if comment.Type != models.CommentTypeComment { - ctx.Status(204) + ctx.Status(http.StatusNoContent) return } oldContent := comment.Content comment.Content = form.Body if err := comment_service.UpdateComment(comment, ctx.User, oldContent); err != nil { - ctx.Error(500, "UpdateComment", err) + ctx.Error(http.StatusInternalServerError, "UpdateComment", err) return } - ctx.JSON(200, comment.APIFormat()) + ctx.JSON(http.StatusOK, comment.APIFormat()) } // DeleteIssueComment delete a comment from an issue @@ -389,23 +390,23 @@ func deleteIssueComment(ctx *context.APIContext) { if models.IsErrCommentNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetCommentByID", err) + ctx.Error(http.StatusInternalServerError, "GetCommentByID", err) } return } if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } else if comment.Type != models.CommentTypeComment { - ctx.Status(204) + ctx.Status(http.StatusNoContent) return } if err = comment_service.DeleteComment(comment, ctx.User); err != nil { - ctx.Error(500, "DeleteCommentByID", err) + ctx.Error(http.StatusInternalServerError, "DeleteCommentByID", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go index a759afe9d625..492da244f22e 100644 --- a/routers/api/v1/repo/issue_label.go +++ b/routers/api/v1/repo/issue_label.go @@ -6,6 +6,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" @@ -47,13 +49,13 @@ func ListIssueLabels(ctx *context.APIContext) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if err := issue.LoadAttributes(); err != nil { - ctx.Error(500, "LoadAttributes", err) + ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } @@ -61,7 +63,7 @@ func ListIssueLabels(ctx *context.APIContext) { for i := range issue.Labels { apiLabels[i] = issue.Labels[i].APIFormat() } - ctx.JSON(200, &apiLabels) + ctx.JSON(http.StatusOK, &apiLabels) } // AddIssueLabels add labels for an issue @@ -105,30 +107,30 @@ func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) if err != nil { - ctx.Error(500, "GetLabelsInRepoByIDs", err) + ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDs", err) return } if err = issue_service.AddLabels(issue, ctx.User, labels); err != nil { - ctx.Error(500, "AddLabels", err) + ctx.Error(http.StatusInternalServerError, "AddLabels", err) return } labels, err = models.GetLabelsByIssueID(issue.ID) if err != nil { - ctx.Error(500, "GetLabelsByIssueID", err) + ctx.Error(http.StatusInternalServerError, "GetLabelsByIssueID", err) return } @@ -136,7 +138,7 @@ func AddIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { for i := range labels { apiLabels[i] = labels[i].APIFormat() } - ctx.JSON(200, &apiLabels) + ctx.JSON(http.StatusOK, &apiLabels) } // DeleteIssueLabel delete a label for an issue @@ -182,32 +184,32 @@ func DeleteIssueLabel(ctx *context.APIContext) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } label, err := models.GetLabelInRepoByID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")) if err != nil { if models.IsErrLabelNotExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "GetLabelInRepoByID", err) + ctx.Error(http.StatusInternalServerError, "GetLabelInRepoByID", err) } return } if err := models.DeleteIssueLabel(issue, label, ctx.User); err != nil { - ctx.Error(500, "DeleteIssueLabel", err) + ctx.Error(http.StatusInternalServerError, "DeleteIssueLabel", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // ReplaceIssueLabels replace labels for an issue @@ -251,30 +253,30 @@ func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) if err != nil { - ctx.Error(500, "GetLabelsInRepoByIDs", err) + ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDs", err) return } if err := issue.ReplaceLabels(labels, ctx.User); err != nil { - ctx.Error(500, "ReplaceLabels", err) + ctx.Error(http.StatusInternalServerError, "ReplaceLabels", err) return } labels, err = models.GetLabelsByIssueID(issue.ID) if err != nil { - ctx.Error(500, "GetLabelsByIssueID", err) + ctx.Error(http.StatusInternalServerError, "GetLabelsByIssueID", err) return } @@ -282,7 +284,7 @@ func ReplaceIssueLabels(ctx *context.APIContext, form api.IssueLabelsOption) { for i := range labels { apiLabels[i] = labels[i].APIFormat() } - ctx.JSON(200, &apiLabels) + ctx.JSON(http.StatusOK, &apiLabels) } // ClearIssueLabels delete all the labels for an issue @@ -320,20 +322,20 @@ func ClearIssueLabels(ctx *context.APIContext) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } if err := issue_service.ClearLabels(issue, ctx.User); err != nil { - ctx.Error(500, "ClearLabels", err) + ctx.Error(http.StatusInternalServerError, "ClearLabels", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/issue_reaction.go b/routers/api/v1/repo/issue_reaction.go index 8550fa7ea6cd..4b06bb987c9f 100644 --- a/routers/api/v1/repo/issue_reaction.go +++ b/routers/api/v1/repo/issue_reaction.go @@ -6,6 +6,7 @@ package repo import ( "errors" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -49,24 +50,24 @@ func GetIssueCommentReactions(ctx *context.APIContext) { if models.IsErrCommentNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetCommentByID", err) + ctx.Error(http.StatusInternalServerError, "GetCommentByID", err) } return } if !ctx.Repo.CanRead(models.UnitTypeIssues) && !ctx.User.IsAdmin { - ctx.Error(403, "GetIssueCommentReactions", errors.New("no permission to get reactions")) + ctx.Error(http.StatusForbidden, "GetIssueCommentReactions", errors.New("no permission to get reactions")) return } reactions, err := models.FindCommentReactions(comment) if err != nil { - ctx.Error(500, "FindIssueReactions", err) + ctx.Error(http.StatusInternalServerError, "FindIssueReactions", err) return } _, err = reactions.LoadUsers() if err != nil { - ctx.Error(500, "ReactionList.LoadUsers()", err) + ctx.Error(http.StatusInternalServerError, "ReactionList.LoadUsers()", err) return } @@ -79,7 +80,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) { }) } - ctx.JSON(200, result) + ctx.JSON(http.StatusOK, result) } // PostIssueCommentReaction add a reaction to a comment of a issue @@ -166,18 +167,18 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp if models.IsErrCommentNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetCommentByID", err) + ctx.Error(http.StatusInternalServerError, "GetCommentByID", err) } return } err = comment.LoadIssue() if err != nil { - ctx.Error(500, "comment.LoadIssue() failed", err) + ctx.Error(http.StatusInternalServerError, "comment.LoadIssue() failed", err) } if comment.Issue.IsLocked && !ctx.Repo.CanWrite(models.UnitTypeIssues) && !ctx.User.IsAdmin { - ctx.Error(403, "ChangeIssueCommentReaction", errors.New("no permission to change reaction")) + ctx.Error(http.StatusForbidden, "ChangeIssueCommentReaction", errors.New("no permission to change reaction")) return } @@ -186,19 +187,19 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp reaction, err := models.CreateCommentReaction(ctx.User, comment.Issue, comment, form.Reaction) if err != nil { if models.IsErrForbiddenIssueReaction(err) { - ctx.Error(403, err.Error(), err) + ctx.Error(http.StatusForbidden, err.Error(), err) } else { - ctx.Error(500, "CreateCommentReaction", err) + ctx.Error(http.StatusInternalServerError, "CreateCommentReaction", err) } return } _, err = reaction.LoadUser() if err != nil { - ctx.Error(500, "Reaction.LoadUser()", err) + ctx.Error(http.StatusInternalServerError, "Reaction.LoadUser()", err) return } - ctx.JSON(201, api.ReactionResponse{ + ctx.JSON(http.StatusCreated, api.ReactionResponse{ User: reaction.User.APIFormat(), Reaction: reaction.Type, Created: reaction.CreatedUnix.AsTime(), @@ -207,11 +208,11 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp // DeleteIssueCommentReaction part err = models.DeleteCommentReaction(ctx.User, comment.Issue, comment, form.Reaction) if err != nil { - ctx.Error(500, "DeleteCommentReaction", err) + ctx.Error(http.StatusInternalServerError, "DeleteCommentReaction", err) return } //ToDo respond 204 - ctx.Status(200) + ctx.Status(http.StatusOK) } } @@ -252,24 +253,24 @@ func GetIssueReactions(ctx *context.APIContext) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if !ctx.Repo.CanRead(models.UnitTypeIssues) && !ctx.User.IsAdmin { - ctx.Error(403, "GetIssueReactions", errors.New("no permission to get reactions")) + ctx.Error(http.StatusForbidden, "GetIssueReactions", errors.New("no permission to get reactions")) return } reactions, err := models.FindIssueReactions(issue) if err != nil { - ctx.Error(500, "FindIssueReactions", err) + ctx.Error(http.StatusInternalServerError, "FindIssueReactions", err) return } _, err = reactions.LoadUsers() if err != nil { - ctx.Error(500, "ReactionList.LoadUsers()", err) + ctx.Error(http.StatusInternalServerError, "ReactionList.LoadUsers()", err) return } @@ -282,7 +283,7 @@ func GetIssueReactions(ctx *context.APIContext) { }) } - ctx.JSON(200, result) + ctx.JSON(http.StatusOK, result) } // PostIssueReaction add a reaction to a comment of a issue @@ -369,13 +370,13 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if issue.IsLocked && !ctx.Repo.CanWrite(models.UnitTypeIssues) && !ctx.User.IsAdmin { - ctx.Error(403, "ChangeIssueCommentReaction", errors.New("no permission to change reaction")) + ctx.Error(http.StatusForbidden, "ChangeIssueCommentReaction", errors.New("no permission to change reaction")) return } @@ -384,19 +385,19 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Reaction) if err != nil { if models.IsErrForbiddenIssueReaction(err) { - ctx.Error(403, err.Error(), err) + ctx.Error(http.StatusForbidden, err.Error(), err) } else { - ctx.Error(500, "CreateCommentReaction", err) + ctx.Error(http.StatusInternalServerError, "CreateCommentReaction", err) } return } _, err = reaction.LoadUser() if err != nil { - ctx.Error(500, "Reaction.LoadUser()", err) + ctx.Error(http.StatusInternalServerError, "Reaction.LoadUser()", err) return } - ctx.JSON(201, api.ReactionResponse{ + ctx.JSON(http.StatusCreated, api.ReactionResponse{ User: reaction.User.APIFormat(), Reaction: reaction.Type, Created: reaction.CreatedUnix.AsTime(), @@ -405,10 +406,10 @@ func changeIssueReaction(ctx *context.APIContext, form api.EditReactionOption, i // DeleteIssueReaction part err = models.DeleteIssueReaction(ctx.User, issue, form.Reaction) if err != nil { - ctx.Error(500, "DeleteIssueReaction", err) + ctx.Error(http.StatusInternalServerError, "DeleteIssueReaction", err) return } //ToDo respond 204 - ctx.Status(200) + ctx.Status(http.StatusOK) } } diff --git a/routers/api/v1/repo/issue_stopwatch.go b/routers/api/v1/repo/issue_stopwatch.go index 5b8fc680c3c8..3ffdf2440412 100644 --- a/routers/api/v1/repo/issue_stopwatch.go +++ b/routers/api/v1/repo/issue_stopwatch.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" ) @@ -51,11 +53,11 @@ func StartIssueStopwatch(ctx *context.APIContext) { } if err := models.CreateOrStopIssueStopwatch(ctx.User, issue); err != nil { - ctx.Error(500, "CreateOrStopIssueStopwatch", err) + ctx.Error(http.StatusInternalServerError, "CreateOrStopIssueStopwatch", err) return } - ctx.Status(201) + ctx.Status(http.StatusCreated) } // StopIssueStopwatch stops a stopwatch for the given issue. @@ -100,11 +102,11 @@ func StopIssueStopwatch(ctx *context.APIContext) { } if err := models.CreateOrStopIssueStopwatch(ctx.User, issue); err != nil { - ctx.Error(500, "CreateOrStopIssueStopwatch", err) + ctx.Error(http.StatusInternalServerError, "CreateOrStopIssueStopwatch", err) return } - ctx.Status(201) + ctx.Status(http.StatusCreated) } // DeleteIssueStopwatch delete a specific stopwatch @@ -149,11 +151,11 @@ func DeleteIssueStopwatch(ctx *context.APIContext) { } if err := models.CancelStopwatch(ctx.User, issue); err != nil { - ctx.Error(500, "CancelStopwatch", err) + ctx.Error(http.StatusInternalServerError, "CancelStopwatch", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } func prepareIssueStopwatch(ctx *context.APIContext, shouldExist bool) (*models.Issue, error) { @@ -162,27 +164,27 @@ func prepareIssueStopwatch(ctx *context.APIContext, shouldExist bool) (*models.I if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return nil, err } if !ctx.Repo.CanWrite(models.UnitTypeIssues) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return nil, err } if !ctx.Repo.CanUseTimetracker(issue, ctx.User) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return nil, err } if models.StopwatchExists(ctx.User.ID, issue.ID) != shouldExist { if shouldExist { - ctx.Error(409, "StopwatchExists", "cannot stop/cancel a non existent stopwatch") + ctx.Error(http.StatusConflict, "StopwatchExists", "cannot stop/cancel a non existent stopwatch") } else { - ctx.Error(409, "StopwatchExists", "cannot start a stopwatch again if it already exists") + ctx.Error(http.StatusConflict, "StopwatchExists", "cannot start a stopwatch again if it already exists") } return nil, err } @@ -205,15 +207,15 @@ func GetStopwatches(ctx *context.APIContext) { sws, err := models.GetUserStopwatches(ctx.User.ID) if err != nil { - ctx.Error(500, "GetUserStopwatches", err) + ctx.Error(http.StatusInternalServerError, "GetUserStopwatches", err) return } apiSWs, err := sws.APIFormat() if err != nil { - ctx.Error(500, "APIFormat", err) + ctx.Error(http.StatusInternalServerError, "APIFormat", err) return } - ctx.JSON(200, apiSWs) + ctx.JSON(http.StatusOK, apiSWs) } diff --git a/routers/api/v1/repo/issue_subscription.go b/routers/api/v1/repo/issue_subscription.go index 9f0ce3ca7f77..153b01de61d3 100644 --- a/routers/api/v1/repo/issue_subscription.go +++ b/routers/api/v1/repo/issue_subscription.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" ) @@ -99,7 +101,7 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return @@ -110,7 +112,7 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return @@ -118,16 +120,16 @@ func setIssueSubscription(ctx *context.APIContext, watch bool) { //only admin and user for itself can change subscription if user.ID != ctx.User.ID && !ctx.User.IsAdmin { - ctx.Error(403, "User", nil) + ctx.Error(http.StatusForbidden, "User", nil) return } if err := models.CreateOrUpdateIssueWatch(user.ID, issue.ID, watch); err != nil { - ctx.Error(500, "CreateOrUpdateIssueWatch", err) + ctx.Error(http.StatusInternalServerError, "CreateOrUpdateIssueWatch", err) return } - ctx.Status(201) + ctx.Status(http.StatusCreated) } // GetIssueSubscribers return subscribers of an issue @@ -167,7 +169,7 @@ func GetIssueSubscribers(ctx *context.APIContext) { if models.IsErrIssueNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return @@ -175,15 +177,15 @@ func GetIssueSubscribers(ctx *context.APIContext) { iwl, err := models.GetIssueWatchers(issue.ID) if err != nil { - ctx.Error(500, "GetIssueWatchers", err) + ctx.Error(http.StatusInternalServerError, "GetIssueWatchers", err) return } users, err := iwl.LoadWatchUsers() if err != nil { - ctx.Error(500, "LoadWatchUsers", err) + ctx.Error(http.StatusInternalServerError, "LoadWatchUsers", err) return } - ctx.JSON(200, users.APIFormat()) + ctx.JSON(http.StatusOK, users.APIFormat()) } diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go index 0c09eb1cf3ea..0d3ca5c177da 100644 --- a/routers/api/v1/repo/issue_tracked_time.go +++ b/routers/api/v1/repo/issue_tracked_time.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" @@ -57,18 +59,18 @@ func ListTrackedTimes(ctx *context.APIContext) { if models.IsErrIssueNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } trackedTimes, err := models.GetTrackedTimes(models.FindTrackedTimesOptions{IssueID: issue.ID}) if err != nil { - ctx.Error(500, "GetTrackedTimesByIssue", err) + ctx.Error(http.StatusInternalServerError, "GetTrackedTimesByIssue", err) return } apiTrackedTimes := trackedTimesToAPIFormat(trackedTimes) - ctx.JSON(200, &apiTrackedTimes) + ctx.JSON(http.StatusOK, &apiTrackedTimes) } // AddTime adds time manual to the given issue @@ -114,25 +116,25 @@ func AddTime(ctx *context.APIContext, form api.AddTimeOption) { if models.IsErrIssueNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetIssueByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) } return } if !ctx.Repo.CanUseTimetracker(issue, ctx.User) { if !ctx.Repo.Repository.IsTimetrackerEnabled() { - ctx.Error(400, "", "time tracking disabled") + ctx.Error(http.StatusBadRequest, "", "time tracking disabled") return } - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } trackedTime, err := models.AddTime(ctx.User, issue, form.Time) if err != nil { - ctx.Error(500, "AddTime", err) + ctx.Error(http.StatusInternalServerError, "AddTime", err) return } - ctx.JSON(200, trackedTime.APIFormat()) + ctx.JSON(http.StatusOK, trackedTime.APIFormat()) } // ListTrackedTimesByUser lists all tracked times of the user @@ -165,7 +167,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) { // "$ref": "#/responses/error" if !ctx.Repo.Repository.IsTimetrackerEnabled() { - ctx.Error(400, "", "time tracking disabled") + ctx.Error(http.StatusBadRequest, "", "time tracking disabled") return } user, err := models.GetUserByName(ctx.Params(":timetrackingusername")) @@ -173,7 +175,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) { if models.IsErrUserNotExist(err) { ctx.NotFound(err) } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return } @@ -185,11 +187,11 @@ func ListTrackedTimesByUser(ctx *context.APIContext) { UserID: user.ID, RepositoryID: ctx.Repo.Repository.ID}) if err != nil { - ctx.Error(500, "GetTrackedTimesByUser", err) + ctx.Error(http.StatusInternalServerError, "GetTrackedTimesByUser", err) return } apiTrackedTimes := trackedTimesToAPIFormat(trackedTimes) - ctx.JSON(200, &apiTrackedTimes) + ctx.JSON(http.StatusOK, &apiTrackedTimes) } // ListTrackedTimesByRepository lists all tracked times of the repository @@ -217,17 +219,17 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) { // "$ref": "#/responses/error" if !ctx.Repo.Repository.IsTimetrackerEnabled() { - ctx.Error(400, "", "time tracking disabled") + ctx.Error(http.StatusBadRequest, "", "time tracking disabled") return } trackedTimes, err := models.GetTrackedTimes(models.FindTrackedTimesOptions{ RepositoryID: ctx.Repo.Repository.ID}) if err != nil { - ctx.Error(500, "GetTrackedTimesByUser", err) + ctx.Error(http.StatusInternalServerError, "GetTrackedTimesByUser", err) return } apiTrackedTimes := trackedTimesToAPIFormat(trackedTimes) - ctx.JSON(200, &apiTrackedTimes) + ctx.JSON(http.StatusOK, &apiTrackedTimes) } // ListMyTrackedTimes lists all tracked times of the current user @@ -243,9 +245,9 @@ func ListMyTrackedTimes(ctx *context.APIContext) { trackedTimes, err := models.GetTrackedTimes(models.FindTrackedTimesOptions{UserID: ctx.User.ID}) if err != nil { - ctx.Error(500, "GetTrackedTimesByUser", err) + ctx.Error(http.StatusInternalServerError, "GetTrackedTimesByUser", err) return } apiTrackedTimes := trackedTimesToAPIFormat(trackedTimes) - ctx.JSON(200, &apiTrackedTimes) + ctx.JSON(http.StatusOK, &apiTrackedTimes) } diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index d351880b4422..4ced8ec42fc1 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -6,6 +6,7 @@ package repo import ( "fmt" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -75,7 +76,7 @@ func ListDeployKeys(ctx *context.APIContext) { } if err != nil { - ctx.Error(500, "ListDeployKeys", err) + ctx.Error(http.StatusInternalServerError, "ListDeployKeys", err) return } @@ -83,7 +84,7 @@ func ListDeployKeys(ctx *context.APIContext) { apiKeys := make([]*api.DeployKey, len(keys)) for i := range keys { if err = keys[i].GetContent(); err != nil { - ctx.Error(500, "GetContent", err) + ctx.Error(http.StatusInternalServerError, "GetContent", err) return } apiKeys[i] = convert.ToDeployKey(apiLink, keys[i]) @@ -92,7 +93,7 @@ func ListDeployKeys(ctx *context.APIContext) { } } - ctx.JSON(200, &apiKeys) + ctx.JSON(http.StatusOK, &apiKeys) } // GetDeployKey get a deploy key by id @@ -128,13 +129,13 @@ func GetDeployKey(ctx *context.APIContext) { if models.IsErrDeployKeyNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetDeployKeyByID", err) + ctx.Error(http.StatusInternalServerError, "GetDeployKeyByID", err) } return } if err = key.GetContent(); err != nil { - ctx.Error(500, "GetContent", err) + ctx.Error(http.StatusInternalServerError, "GetContent", err) return } @@ -143,17 +144,17 @@ func GetDeployKey(ctx *context.APIContext) { if ctx.User.IsAdmin || ((ctx.Repo.Repository.ID == key.RepoID) && (ctx.User.ID == ctx.Repo.Owner.ID)) { apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Repo.Repository) } - ctx.JSON(200, apiKey) + ctx.JSON(http.StatusOK, apiKey) } // HandleCheckKeyStringError handle check key error func HandleCheckKeyStringError(ctx *context.APIContext, err error) { if models.IsErrSSHDisabled(err) { - ctx.Error(422, "", "SSH is disabled") + ctx.Error(http.StatusUnprocessableEntity, "", "SSH is disabled") } else if models.IsErrKeyUnableVerify(err) { - ctx.Error(422, "", "Unable to verify key content") + ctx.Error(http.StatusUnprocessableEntity, "", "Unable to verify key content") } else { - ctx.Error(422, "", fmt.Errorf("Invalid key content: %v", err)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid key content: %v", err)) } } @@ -161,13 +162,13 @@ func HandleCheckKeyStringError(ctx *context.APIContext, err error) { func HandleAddKeyError(ctx *context.APIContext, err error) { switch { case models.IsErrDeployKeyAlreadyExist(err): - ctx.Error(422, "", "This key has already been added to this repository") + ctx.Error(http.StatusUnprocessableEntity, "", "This key has already been added to this repository") case models.IsErrKeyAlreadyExist(err): - ctx.Error(422, "", "Key content has been used as non-deploy key") + ctx.Error(http.StatusUnprocessableEntity, "", "Key content has been used as non-deploy key") case models.IsErrKeyNameAlreadyUsed(err): - ctx.Error(422, "", "Key title has been used") + ctx.Error(http.StatusUnprocessableEntity, "", "Key title has been used") default: - ctx.Error(500, "AddKey", err) + ctx.Error(http.StatusInternalServerError, "AddKey", err) } } @@ -215,7 +216,7 @@ func CreateDeployKey(ctx *context.APIContext, form api.CreateKeyOption) { key.Content = content apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name) - ctx.JSON(201, convert.ToDeployKey(apiLink, key)) + ctx.JSON(http.StatusCreated, convert.ToDeployKey(apiLink, key)) } // DeleteDeploykey delete deploy key for a repository @@ -248,12 +249,12 @@ func DeleteDeploykey(ctx *context.APIContext) { if err := models.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if models.IsErrKeyAccessDenied(err) { - ctx.Error(403, "", "You do not have access to this key") + ctx.Error(http.StatusForbidden, "", "You do not have access to this key") } else { - ctx.Error(500, "DeleteDeployKey", err) + ctx.Error(http.StatusInternalServerError, "DeleteDeployKey", err) } return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/label.go b/routers/api/v1/repo/label.go index c8deb45b0b88..16c905878d9c 100644 --- a/routers/api/v1/repo/label.go +++ b/routers/api/v1/repo/label.go @@ -6,6 +6,7 @@ package repo import ( + "net/http" "strconv" "code.gitea.io/gitea/models" @@ -37,7 +38,7 @@ func ListLabels(ctx *context.APIContext) { labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID, ctx.Query("sort")) if err != nil { - ctx.Error(500, "GetLabelsByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetLabelsByRepoID", err) return } @@ -45,7 +46,7 @@ func ListLabels(ctx *context.APIContext) { for i := range labels { apiLabels[i] = labels[i].APIFormat() } - ctx.JSON(200, &apiLabels) + ctx.JSON(http.StatusOK, &apiLabels) } // GetLabel get label by repository and label id @@ -90,12 +91,12 @@ func GetLabel(ctx *context.APIContext) { if models.IsErrLabelNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetLabelByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetLabelByRepoID", err) } return } - ctx.JSON(200, label.APIFormat()) + ctx.JSON(http.StatusOK, label.APIFormat()) } // CreateLabel create a label for a repository @@ -133,10 +134,10 @@ func CreateLabel(ctx *context.APIContext, form api.CreateLabelOption) { Description: form.Description, } if err := models.NewLabel(label); err != nil { - ctx.Error(500, "NewLabel", err) + ctx.Error(http.StatusInternalServerError, "NewLabel", err) return } - ctx.JSON(201, label.APIFormat()) + ctx.JSON(http.StatusCreated, label.APIFormat()) } // EditLabel modify a label for a repository @@ -178,7 +179,7 @@ func EditLabel(ctx *context.APIContext, form api.EditLabelOption) { if models.IsErrLabelNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetLabelByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetLabelByRepoID", err) } return } @@ -196,7 +197,7 @@ func EditLabel(ctx *context.APIContext, form api.EditLabelOption) { ctx.ServerError("UpdateLabel", err) return } - ctx.JSON(200, label.APIFormat()) + ctx.JSON(http.StatusOK, label.APIFormat()) } // DeleteLabel delete a label for a repository @@ -226,9 +227,9 @@ func DeleteLabel(ctx *context.APIContext) { // "$ref": "#/responses/empty" if err := models.DeleteLabel(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { - ctx.Error(500, "DeleteLabel", err) + ctx.Error(http.StatusInternalServerError, "DeleteLabel", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go index 3e6c39fea56c..a979e2b69b7c 100644 --- a/routers/api/v1/repo/milestone.go +++ b/routers/api/v1/repo/milestone.go @@ -5,6 +5,7 @@ package repo import ( + "net/http" "time" "code.gitea.io/gitea/models" @@ -41,7 +42,7 @@ func ListMilestones(ctx *context.APIContext) { milestones, err := models.GetMilestonesByRepoID(ctx.Repo.Repository.ID, api.StateType(ctx.Query("state"))) if err != nil { - ctx.Error(500, "GetMilestonesByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetMilestonesByRepoID", err) return } @@ -49,7 +50,7 @@ func ListMilestones(ctx *context.APIContext) { for i := range milestones { apiMilestones[i] = milestones[i].APIFormat() } - ctx.JSON(200, &apiMilestones) + ctx.JSON(http.StatusOK, &apiMilestones) } // GetMilestone get a milestone for a repository @@ -85,11 +86,11 @@ func GetMilestone(ctx *context.APIContext) { if models.IsErrMilestoneNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetMilestoneByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoID", err) } return } - ctx.JSON(200, milestone.APIFormat()) + ctx.JSON(http.StatusOK, milestone.APIFormat()) } // CreateMilestone create a milestone for a repository @@ -133,10 +134,10 @@ func CreateMilestone(ctx *context.APIContext, form api.CreateMilestoneOption) { } if err := models.NewMilestone(milestone); err != nil { - ctx.Error(500, "NewMilestone", err) + ctx.Error(http.StatusInternalServerError, "NewMilestone", err) return } - ctx.JSON(201, milestone.APIFormat()) + ctx.JSON(http.StatusCreated, milestone.APIFormat()) } // EditMilestone modify a milestone for a repository @@ -178,7 +179,7 @@ func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) { if models.IsErrMilestoneNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetMilestoneByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoID", err) } return } @@ -197,7 +198,7 @@ func EditMilestone(ctx *context.APIContext, form api.EditMilestoneOption) { ctx.ServerError("UpdateMilestone", err) return } - ctx.JSON(200, milestone.APIFormat()) + ctx.JSON(http.StatusOK, milestone.APIFormat()) } // DeleteMilestone delete a milestone for a repository @@ -227,8 +228,8 @@ func DeleteMilestone(ctx *context.APIContext) { // "$ref": "#/responses/empty" if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id")); err != nil { - ctx.Error(500, "DeleteMilestoneByRepoID", err) + ctx.Error(http.StatusInternalServerError, "DeleteMilestoneByRepoID", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index e6876ad65185..0392eb8e8c48 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -80,33 +80,33 @@ func ListPullRequests(ctx *context.APIContext, form api.ListPullRequestsOptions) }) if err != nil { - ctx.Error(500, "PullRequests", err) + ctx.Error(http.StatusInternalServerError, "PullRequests", err) return } apiPrs := make([]*api.PullRequest, len(prs)) for i := range prs { if err = prs[i].LoadIssue(); err != nil { - ctx.Error(500, "LoadIssue", err) + ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return } if err = prs[i].LoadAttributes(); err != nil { - ctx.Error(500, "LoadAttributes", err) + ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } if err = prs[i].GetBaseRepo(); err != nil { - ctx.Error(500, "GetBaseRepo", err) + ctx.Error(http.StatusInternalServerError, "GetBaseRepo", err) return } if err = prs[i].GetHeadRepo(); err != nil { - ctx.Error(500, "GetHeadRepo", err) + ctx.Error(http.StatusInternalServerError, "GetHeadRepo", err) return } apiPrs[i] = prs[i].APIFormat() } ctx.SetLinkHeader(int(maxResults), models.ItemsPerPage) - ctx.JSON(200, &apiPrs) + ctx.JSON(http.StatusOK, &apiPrs) } // GetPullRequest returns a single PR based on index @@ -142,20 +142,20 @@ func GetPullRequest(ctx *context.APIContext) { if models.IsErrPullRequestNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetPullRequestByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err) } return } if err = pr.GetBaseRepo(); err != nil { - ctx.Error(500, "GetBaseRepo", err) + ctx.Error(http.StatusInternalServerError, "GetBaseRepo", err) return } if err = pr.GetHeadRepo(); err != nil { - ctx.Error(500, "GetHeadRepo", err) + ctx.Error(http.StatusInternalServerError, "GetHeadRepo", err) return } - ctx.JSON(200, pr.APIFormat()) + ctx.JSON(http.StatusOK, pr.APIFormat()) } // CreatePullRequest does what it says @@ -208,7 +208,7 @@ func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption existingPr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch) if err != nil { if !models.IsErrPullRequestNotExist(err) { - ctx.Error(500, "GetUnmergedPullRequest", err) + ctx.Error(http.StatusInternalServerError, "GetUnmergedPullRequest", err) return } } else { @@ -220,14 +220,14 @@ func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption HeadBranch: existingPr.HeadBranch, BaseBranch: existingPr.BaseBranch, } - ctx.Error(409, "GetUnmergedPullRequest", err) + ctx.Error(http.StatusConflict, "GetUnmergedPullRequest", err) return } if len(form.Labels) > 0 { labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) if err != nil { - ctx.Error(500, "GetLabelsInRepoByIDs", err) + ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDs", err) return } @@ -243,7 +243,7 @@ func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption if models.IsErrMilestoneNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetMilestoneByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoID", err) } return } @@ -282,9 +282,9 @@ func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption assigneeIDs, err := models.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) } else { - ctx.Error(500, "AddAssigneeByName", err) + ctx.Error(http.StatusInternalServerError, "AddAssigneeByName", err) } return } @@ -292,34 +292,34 @@ func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption for _, aID := range assigneeIDs { assignee, err := models.GetUserByID(aID) if err != nil { - ctx.Error(500, "GetUserByID", err) + ctx.Error(http.StatusInternalServerError, "GetUserByID", err) return } valid, err := models.CanBeAssigned(assignee, repo, true) if err != nil { - ctx.Error(500, "canBeAssigned", err) + ctx.Error(http.StatusInternalServerError, "canBeAssigned", err) return } if !valid { - ctx.Error(422, "canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: repo.Name}) + ctx.Error(http.StatusUnprocessableEntity, "canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: repo.Name}) return } } if err := pull_service.NewPullRequest(repo, prIssue, labelIDs, []string{}, pr, assigneeIDs); err != nil { if models.IsErrUserDoesNotHaveAccessToRepo(err) { - ctx.Error(400, "UserDoesNotHaveAccessToRepo", err) + ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err) return } - ctx.Error(500, "NewPullRequest", err) + ctx.Error(http.StatusInternalServerError, "NewPullRequest", err) return } notification.NotifyNewPullRequest(pr) log.Trace("Pull request created: %d/%d", repo.ID, prIssue.ID) - ctx.JSON(201, pr.APIFormat()) + ctx.JSON(http.StatusCreated, pr.APIFormat()) } // EditPullRequest does what it says @@ -367,7 +367,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { if models.IsErrPullRequestNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetPullRequestByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err) } return } @@ -381,7 +381,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { issue.Repo = ctx.Repo.Repository if !issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWrite(models.UnitTypePullRequests) { - ctx.Status(403) + ctx.Status(http.StatusForbidden) return } @@ -402,7 +402,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { } if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil { - ctx.Error(500, "UpdateIssueDeadline", err) + ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err) return } issue.DeadlineUnix = deadlineUnix @@ -420,9 +420,9 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { err = issue_service.UpdateAssignees(issue, form.Assignee, form.Assignees, ctx.User) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) } else { - ctx.Error(500, "UpdateAssignees", err) + ctx.Error(http.StatusInternalServerError, "UpdateAssignees", err) } return } @@ -433,7 +433,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { oldMilestoneID := issue.MilestoneID issue.MilestoneID = form.Milestone if err = issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil { - ctx.Error(500, "ChangeMilestoneAssign", err) + ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err) return } } @@ -441,17 +441,17 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { if ctx.Repo.CanWrite(models.UnitTypePullRequests) && form.Labels != nil { labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) if err != nil { - ctx.Error(500, "GetLabelsInRepoByIDsError", err) + ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDsError", err) return } if err = issue.ReplaceLabels(labels, ctx.User); err != nil { - ctx.Error(500, "ReplaceLabelsError", err) + ctx.Error(http.StatusInternalServerError, "ReplaceLabelsError", err) return } } if err = models.UpdateIssue(issue); err != nil { - ctx.Error(500, "UpdateIssue", err) + ctx.Error(http.StatusInternalServerError, "UpdateIssue", err) return } if form.State != nil { @@ -460,7 +460,7 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this pull request because it still has open dependencies") return } - ctx.Error(500, "ChangeStatus", err) + ctx.Error(http.StatusInternalServerError, "ChangeStatus", err) return } } @@ -471,13 +471,13 @@ func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) { if models.IsErrPullRequestNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetPullRequestByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err) } return } // TODO this should be 200, not 201 - ctx.JSON(201, pr.APIFormat()) + ctx.JSON(http.StatusCreated, pr.APIFormat()) } // IsPullRequestMerged checks if a PR exists given an index @@ -515,13 +515,13 @@ func IsPullRequestMerged(ctx *context.APIContext) { if models.IsErrPullRequestNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetPullRequestByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err) } return } if pr.HasMerged { - ctx.Status(204) + ctx.Status(http.StatusNoContent) } ctx.NotFound() } @@ -567,7 +567,7 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { if models.IsErrPullRequestNotExist(err) { ctx.NotFound("GetPullRequestByIndex", err) } else { - ctx.Error(500, "GetPullRequestByIndex", err) + ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err) } return } @@ -587,7 +587,7 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { if ctx.IsSigned { // Update issue-user. if err = pr.Issue.ReadBy(ctx.User.ID); err != nil { - ctx.Error(500, "ReadBy", err) + ctx.Error(http.StatusInternalServerError, "ReadBy", err) return } } @@ -598,18 +598,18 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { } if !pr.CanAutoMerge() || pr.HasMerged || pr.IsWorkInProgress() { - ctx.Status(405) + ctx.Status(http.StatusMethodNotAllowed) return } isPass, err := pull_service.IsPullCommitStatusPass(pr) if err != nil { - ctx.Error(500, "IsPullCommitStatusPass", err) + ctx.Error(http.StatusInternalServerError, "IsPullCommitStatusPass", err) return } if !isPass && !ctx.IsUserRepoAdmin() { - ctx.Status(405) + ctx.Status(http.StatusMethodNotAllowed) return } @@ -634,7 +634,7 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { if err := pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil { if models.IsErrInvalidMergeStyle(err) { - ctx.Status(405) + ctx.Status(http.StatusMethodNotAllowed) return } else if models.IsErrMergeConflicts(err) { conflictError := err.(models.ErrMergeConflicts) @@ -649,12 +649,12 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { ctx.Error(http.StatusConflict, "Merge", "merge push out of date") return } - ctx.Error(500, "Merge", err) + ctx.Error(http.StatusInternalServerError, "Merge", err) return } log.Trace("Pull request merged: %d", pr.ID) - ctx.Status(200) + ctx.Status(http.StatusOK) } func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) (*models.User, *models.Repository, *git.Repository, *git.CompareInfo, string, string) { @@ -724,7 +724,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) } else { headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name)) if err != nil { - ctx.Error(500, "OpenRepository", err) + ctx.Error(http.StatusInternalServerError, "OpenRepository", err) return nil, nil, nil, nil, "", "" } } @@ -777,7 +777,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch) if err != nil { headGitRepo.Close() - ctx.Error(500, "GetCompareInfo", err) + ctx.Error(http.StatusInternalServerError, "GetCompareInfo", err) return nil, nil, nil, nil, "", "" } diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go index 4959f5bdcde8..f94d6ba63556 100644 --- a/routers/api/v1/repo/release.go +++ b/routers/api/v1/repo/release.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" @@ -43,7 +45,7 @@ func GetRelease(ctx *context.APIContext) { id := ctx.ParamsInt64(":id") release, err := models.GetReleaseByID(id) if err != nil { - ctx.Error(500, "GetReleaseByID", err) + ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err) return } if release.RepoID != ctx.Repo.Repository.ID { @@ -51,10 +53,10 @@ func GetRelease(ctx *context.APIContext) { return } if err := release.LoadAttributes(); err != nil { - ctx.Error(500, "LoadAttributes", err) + ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(200, release.APIFormat()) + ctx.JSON(http.StatusOK, release.APIFormat()) } func getPagesInfo(ctx *context.APIContext) (int, int) { @@ -107,18 +109,18 @@ func ListReleases(ctx *context.APIContext) { IncludeTags: false, }, page, limit) if err != nil { - ctx.Error(500, "GetReleasesByRepoID", err) + ctx.Error(http.StatusInternalServerError, "GetReleasesByRepoID", err) return } rels := make([]*api.Release, len(releases)) for i, release := range releases { if err := release.LoadAttributes(); err != nil { - ctx.Error(500, "LoadAttributes", err) + ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } rels[i] = release.APIFormat() } - ctx.JSON(200, rels) + ctx.JSON(http.StatusOK, rels) } // CreateRelease create a release @@ -176,15 +178,15 @@ func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) { } if err := releaseservice.CreateRelease(ctx.Repo.GitRepo, rel, nil); err != nil { if models.IsErrReleaseAlreadyExist(err) { - ctx.Error(409, "ReleaseAlreadyExist", err) + ctx.Error(http.StatusConflict, "ReleaseAlreadyExist", err) } else { - ctx.Error(500, "CreateRelease", err) + ctx.Error(http.StatusInternalServerError, "CreateRelease", err) } return } } else { if !rel.IsTag { - ctx.Error(409, "GetRelease", "Release is has no Tag") + ctx.Error(http.StatusConflict, "GetRelease", "Release is has no Tag") return } @@ -202,7 +204,7 @@ func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) { return } } - ctx.JSON(201, rel.APIFormat()) + ctx.JSON(http.StatusCreated, rel.APIFormat()) } // EditRelease edit a release @@ -242,7 +244,7 @@ func EditRelease(ctx *context.APIContext, form api.EditReleaseOption) { id := ctx.ParamsInt64(":id") rel, err := models.GetReleaseByID(id) if err != nil && !models.IsErrReleaseNotExist(err) { - ctx.Error(500, "GetReleaseByID", err) + ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err) return } if err != nil && models.IsErrReleaseNotExist(err) || @@ -270,20 +272,20 @@ func EditRelease(ctx *context.APIContext, form api.EditReleaseOption) { rel.IsPrerelease = *form.IsPrerelease } if err := releaseservice.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil); err != nil { - ctx.Error(500, "UpdateRelease", err) + ctx.Error(http.StatusInternalServerError, "UpdateRelease", err) return } rel, err = models.GetReleaseByID(id) if err != nil { - ctx.Error(500, "GetReleaseByID", err) + ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err) return } if err := rel.LoadAttributes(); err != nil { - ctx.Error(500, "LoadAttributes", err) + ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(200, rel.APIFormat()) + ctx.JSON(http.StatusOK, rel.APIFormat()) } // DeleteRelease delete a release from a repository @@ -315,7 +317,7 @@ func DeleteRelease(ctx *context.APIContext) { id := ctx.ParamsInt64(":id") rel, err := models.GetReleaseByID(id) if err != nil && !models.IsErrReleaseNotExist(err) { - ctx.Error(500, "GetReleaseByID", err) + ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err) return } if err != nil && models.IsErrReleaseNotExist(err) || @@ -324,8 +326,8 @@ func DeleteRelease(ctx *context.APIContext) { return } if err := releaseservice.DeleteReleaseByID(id, ctx.User, false); err != nil { - ctx.Error(500, "DeleteReleaseByID", err) + ctx.Error(http.StatusInternalServerError, "DeleteReleaseByID", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go index b5888d2ca286..6ba6489e2770 100644 --- a/routers/api/v1/repo/release_attachment.go +++ b/routers/api/v1/repo/release_attachment.go @@ -5,6 +5,7 @@ package repo import ( + "net/http" "strings" "code.gitea.io/gitea/models" @@ -53,7 +54,7 @@ func GetReleaseAttachment(ctx *context.APIContext) { attachID := ctx.ParamsInt64(":asset") attach, err := models.GetAttachmentByID(attachID) if err != nil { - ctx.Error(500, "GetAttachmentByID", err) + ctx.Error(http.StatusInternalServerError, "GetAttachmentByID", err) return } if attach.ReleaseID != releaseID { @@ -62,7 +63,7 @@ func GetReleaseAttachment(ctx *context.APIContext) { return } // FIXME Should prove the existence of the given repo, but results in unnecessary database requests - ctx.JSON(200, attach.APIFormat()) + ctx.JSON(http.StatusOK, attach.APIFormat()) } // ListReleaseAttachments lists all attachments of the release @@ -96,7 +97,7 @@ func ListReleaseAttachments(ctx *context.APIContext) { releaseID := ctx.ParamsInt64(":id") release, err := models.GetReleaseByID(releaseID) if err != nil { - ctx.Error(500, "GetReleaseByID", err) + ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err) return } if release.RepoID != ctx.Repo.Repository.ID { @@ -104,10 +105,10 @@ func ListReleaseAttachments(ctx *context.APIContext) { return } if err := release.LoadAttributes(); err != nil { - ctx.Error(500, "LoadAttributes", err) + ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(200, release.APIFormat().Attachments) + ctx.JSON(http.StatusOK, release.APIFormat().Attachments) } // CreateReleaseAttachment creates an attachment and saves the given file @@ -162,14 +163,14 @@ func CreateReleaseAttachment(ctx *context.APIContext) { releaseID := ctx.ParamsInt64(":id") release, err := models.GetReleaseByID(releaseID) if err != nil { - ctx.Error(500, "GetReleaseByID", err) + ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err) return } // Get uploaded file from request file, header, err := ctx.GetFile("attachment") if err != nil { - ctx.Error(500, "GetFile", err) + ctx.Error(http.StatusInternalServerError, "GetFile", err) return } defer file.Close() @@ -183,7 +184,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) { // Check if the filetype is allowed by the settings err = upload.VerifyAllowedContentType(buf, strings.Split(setting.AttachmentAllowedTypes, ",")) if err != nil { - ctx.Error(400, "DetectContentType", err) + ctx.Error(http.StatusBadRequest, "DetectContentType", err) return } @@ -199,11 +200,11 @@ func CreateReleaseAttachment(ctx *context.APIContext) { ReleaseID: release.ID, }, buf, file) if err != nil { - ctx.Error(500, "NewAttachment", err) + ctx.Error(http.StatusInternalServerError, "NewAttachment", err) return } - ctx.JSON(201, attach.APIFormat()) + ctx.JSON(http.StatusCreated, attach.APIFormat()) } // EditReleaseAttachment updates the given attachment @@ -251,7 +252,7 @@ func EditReleaseAttachment(ctx *context.APIContext, form api.EditAttachmentOptio attachID := ctx.ParamsInt64(":asset") attach, err := models.GetAttachmentByID(attachID) if err != nil { - ctx.Error(500, "GetAttachmentByID", err) + ctx.Error(http.StatusInternalServerError, "GetAttachmentByID", err) return } if attach.ReleaseID != releaseID { @@ -265,9 +266,9 @@ func EditReleaseAttachment(ctx *context.APIContext, form api.EditAttachmentOptio } if err := models.UpdateAttachment(attach); err != nil { - ctx.Error(500, "UpdateAttachment", attach) + ctx.Error(http.StatusInternalServerError, "UpdateAttachment", attach) } - ctx.JSON(201, attach.APIFormat()) + ctx.JSON(http.StatusCreated, attach.APIFormat()) } // DeleteReleaseAttachment delete a given attachment @@ -309,7 +310,7 @@ func DeleteReleaseAttachment(ctx *context.APIContext) { attachID := ctx.ParamsInt64(":asset") attach, err := models.GetAttachmentByID(attachID) if err != nil { - ctx.Error(500, "GetAttachmentByID", err) + ctx.Error(http.StatusInternalServerError, "GetAttachmentByID", err) return } if attach.ReleaseID != releaseID { @@ -320,8 +321,8 @@ func DeleteReleaseAttachment(ctx *context.APIContext) { // FIXME Should prove the existence of the given repo, but results in unnecessary database requests if err := models.DeleteAttachment(attach, true); err != nil { - ctx.Error(500, "DeleteAttachment", err) + ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 6861379f93c3..8f34d8cca3f7 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -189,7 +189,7 @@ func Search(ctx *context.APIContext) { var err error repos, count, err := models.SearchRepository(opts) if err != nil { - ctx.JSON(500, api.SearchError{ + ctx.JSON(http.StatusInternalServerError, api.SearchError{ OK: false, Error: err.Error(), }) @@ -199,7 +199,7 @@ func Search(ctx *context.APIContext) { results := make([]*api.Repository, len(repos)) for i, repo := range repos { if err = repo.GetOwner(); err != nil { - ctx.JSON(500, api.SearchError{ + ctx.JSON(http.StatusInternalServerError, api.SearchError{ OK: false, Error: err.Error(), }) @@ -207,7 +207,7 @@ func Search(ctx *context.APIContext) { } accessMode, err := models.AccessLevel(ctx.User, repo) if err != nil { - ctx.JSON(500, api.SearchError{ + ctx.JSON(http.StatusInternalServerError, api.SearchError{ OK: false, Error: err.Error(), }) @@ -217,7 +217,7 @@ func Search(ctx *context.APIContext) { ctx.SetLinkHeader(int(count), setting.API.MaxResponseItems) ctx.Header().Set("X-Total-Count", fmt.Sprintf("%d", count)) - ctx.JSON(200, api.SearchResults{ + ctx.JSON(http.StatusOK, api.SearchResults{ OK: true, Data: results, }) @@ -240,17 +240,17 @@ func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateR }) if err != nil { if models.IsErrRepoAlreadyExist(err) { - ctx.Error(409, "", "The repository with the same name already exists.") + ctx.Error(http.StatusConflict, "", "The repository with the same name already exists.") } else if models.IsErrNameReserved(err) || models.IsErrNamePatternNotAllowed(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "CreateRepository", err) + ctx.Error(http.StatusInternalServerError, "CreateRepository", err) } return } - ctx.JSON(201, repo.APIFormat(models.AccessModeOwner)) + ctx.JSON(http.StatusCreated, repo.APIFormat(models.AccessModeOwner)) } // Create one repository of mine @@ -277,7 +277,7 @@ func Create(ctx *context.APIContext, opt api.CreateRepoOption) { if ctx.User.IsOrganization() { // Shouldn't reach this condition, but just in case. - ctx.Error(422, "", "not allowed creating repository for organization") + ctx.Error(http.StatusUnprocessableEntity, "", "not allowed creating repository for organization") return } CreateUserRepo(ctx, ctx.User, opt) @@ -313,9 +313,9 @@ func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) { org, err := models.GetOrgByName(ctx.Params(":org")) if err != nil { if models.IsErrOrgNotExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "GetOrgByName", err) + ctx.Error(http.StatusInternalServerError, "GetOrgByName", err) } return } @@ -331,7 +331,7 @@ func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) { ctx.ServerError("CanCreateOrgRepo", err) return } else if !canCreate { - ctx.Error(403, "", "Given user is not allowed to create repository in organization.") + ctx.Error(http.StatusForbidden, "", "Given user is not allowed to create repository in organization.") return } } @@ -367,9 +367,9 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { org, err := models.GetUserByID(form.UID) if err != nil { if models.IsErrUserNotExist(err) { - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) } else { - ctx.Error(500, "GetUserByID", err) + ctx.Error(http.StatusInternalServerError, "GetUserByID", err) } return } @@ -377,13 +377,13 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { } if ctx.HasError() { - ctx.Error(422, "", ctx.GetErrMsg()) + ctx.Error(http.StatusUnprocessableEntity, "", ctx.GetErrMsg()) return } if !ctx.User.IsAdmin { if !ctxUser.IsOrganization() && ctx.User.ID != ctxUser.ID { - ctx.Error(403, "", "Given user is not an organization.") + ctx.Error(http.StatusForbidden, "", "Given user is not an organization.") return } @@ -391,10 +391,10 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { // Check ownership of organization. isOwner, err := ctxUser.IsOwnedBy(ctx.User.ID) if err != nil { - ctx.Error(500, "IsOwnedBy", err) + ctx.Error(http.StatusInternalServerError, "IsOwnedBy", err) return } else if !isOwner { - ctx.Error(403, "", "Given user is not owner of organization.") + ctx.Error(http.StatusForbidden, "", "Given user is not owner of organization.") return } } @@ -406,16 +406,16 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { addrErr := err.(models.ErrInvalidCloneAddr) switch { case addrErr.IsURLError: - ctx.Error(422, "", err) + ctx.Error(http.StatusUnprocessableEntity, "", err) case addrErr.IsPermissionDenied: - ctx.Error(422, "", "You are not allowed to import local repositories.") + ctx.Error(http.StatusUnprocessableEntity, "", "You are not allowed to import local repositories.") case addrErr.IsInvalidPath: - ctx.Error(422, "", "Invalid local path, it does not exist or not a directory.") + ctx.Error(http.StatusUnprocessableEntity, "", "Invalid local path, it does not exist or not a directory.") default: - ctx.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error()) + ctx.Error(http.StatusInternalServerError, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error()) } } else { - ctx.Error(500, "ParseRemoteAddr", err) + ctx.Error(http.StatusInternalServerError, "ParseRemoteAddr", err) } return } @@ -496,33 +496,33 @@ func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) { } log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName) - ctx.JSON(201, repo.APIFormat(models.AccessModeAdmin)) + ctx.JSON(http.StatusCreated, repo.APIFormat(models.AccessModeAdmin)) } func handleMigrateError(ctx *context.APIContext, repoOwner *models.User, remoteAddr string, err error) { switch { case models.IsErrRepoAlreadyExist(err): - ctx.Error(409, "", "The repository with the same name already exists.") + ctx.Error(http.StatusConflict, "", "The repository with the same name already exists.") case migrations.IsRateLimitError(err): - ctx.Error(422, "", "Remote visit addressed rate limitation.") + ctx.Error(http.StatusUnprocessableEntity, "", "Remote visit addressed rate limitation.") case migrations.IsTwoFactorAuthError(err): - ctx.Error(422, "", "Remote visit required two factors authentication.") + ctx.Error(http.StatusUnprocessableEntity, "", "Remote visit required two factors authentication.") case models.IsErrReachLimitOfRepo(err): - ctx.Error(422, "", fmt.Sprintf("You have already reached your limit of %d repositories.", repoOwner.MaxCreationLimit())) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("You have already reached your limit of %d repositories.", repoOwner.MaxCreationLimit())) case models.IsErrNameReserved(err): - ctx.Error(422, "", fmt.Sprintf("The username '%s' is reserved.", err.(models.ErrNameReserved).Name)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("The username '%s' is reserved.", err.(models.ErrNameReserved).Name)) case models.IsErrNamePatternNotAllowed(err): - ctx.Error(422, "", fmt.Sprintf("The pattern '%s' is not allowed in a username.", err.(models.ErrNamePatternNotAllowed).Pattern)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("The pattern '%s' is not allowed in a username.", err.(models.ErrNamePatternNotAllowed).Pattern)) default: err = util.URLSanitizedError(err, remoteAddr) if strings.Contains(err.Error(), "Authentication failed") || strings.Contains(err.Error(), "Bad credentials") || strings.Contains(err.Error(), "could not read Username") { - ctx.Error(422, "", fmt.Sprintf("Authentication failed: %v.", err)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Authentication failed: %v.", err)) } else if strings.Contains(err.Error(), "fatal:") { - ctx.Error(422, "", fmt.Sprintf("Migration failed: %v.", err)) + ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Migration failed: %v.", err)) } else { - ctx.Error(500, "MigrateRepository", err) + ctx.Error(http.StatusInternalServerError, "MigrateRepository", err) } } } @@ -549,7 +549,7 @@ func Get(ctx *context.APIContext) { // "200": // "$ref": "#/responses/Repository" - ctx.JSON(200, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode)) + ctx.JSON(http.StatusOK, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode)) } // GetByID returns a single Repository @@ -575,20 +575,20 @@ func GetByID(ctx *context.APIContext) { if models.IsErrRepoNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetRepositoryByID", err) + ctx.Error(http.StatusInternalServerError, "GetRepositoryByID", err) } return } perm, err := models.GetUserRepoPermission(repo, ctx.User) if err != nil { - ctx.Error(500, "AccessLevel", err) + ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } else if !perm.HasAccess() { ctx.NotFound() return } - ctx.JSON(200, repo.APIFormat(perm.AccessMode)) + ctx.JSON(http.StatusOK, repo.APIFormat(perm.AccessMode)) } // Edit edit repository properties @@ -943,20 +943,20 @@ func Delete(ctx *context.APIContext) { canDelete, err := repo.CanUserDelete(ctx.User) if err != nil { - ctx.Error(500, "CanUserDelete", err) + ctx.Error(http.StatusInternalServerError, "CanUserDelete", err) return } else if !canDelete { - ctx.Error(403, "", "Given user is not owner of organization.") + ctx.Error(http.StatusForbidden, "", "Given user is not owner of organization.") return } if err := repo_service.DeleteRepository(ctx.User, repo); err != nil { - ctx.Error(500, "DeleteRepository", err) + ctx.Error(http.StatusInternalServerError, "DeleteRepository", err) return } log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name) - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // MirrorSync adds a mirrored repository to the sync queue @@ -986,10 +986,10 @@ func MirrorSync(ctx *context.APIContext) { repo := ctx.Repo.Repository if !ctx.Repo.CanWrite(models.UnitTypeCode) { - ctx.Error(403, "MirrorSync", "Must have write access") + ctx.Error(http.StatusForbidden, "MirrorSync", "Must have write access") } mirror_service.StartToMirror(repo.ID) - ctx.Status(200) + ctx.Status(http.StatusOK) } diff --git a/routers/api/v1/repo/star.go b/routers/api/v1/repo/star.go index 609a93295491..65a99d442abc 100644 --- a/routers/api/v1/repo/star.go +++ b/routers/api/v1/repo/star.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" @@ -34,12 +36,12 @@ func ListStargazers(ctx *context.APIContext) { stargazers, err := ctx.Repo.Repository.GetStargazers(-1) if err != nil { - ctx.Error(500, "GetStargazers", err) + ctx.Error(http.StatusInternalServerError, "GetStargazers", err) return } users := make([]*api.User, len(stargazers)) for i, stargazer := range stargazers { users[i] = convert.ToUser(stargazer, ctx.IsSigned, ctx.User != nil && ctx.User.IsAdmin) } - ctx.JSON(200, users) + ctx.JSON(http.StatusOK, users) } diff --git a/routers/api/v1/repo/status.go b/routers/api/v1/repo/status.go index d8592f4de4a1..c137b64f5c82 100644 --- a/routers/api/v1/repo/status.go +++ b/routers/api/v1/repo/status.go @@ -6,6 +6,7 @@ package repo import ( "fmt" + "net/http" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -48,7 +49,7 @@ func NewCommitStatus(ctx *context.APIContext, form api.CreateStatusOption) { sha := ctx.Params("sha") if len(sha) == 0 { - ctx.Error(400, "sha not given", nil) + ctx.Error(http.StatusBadRequest, "sha not given", nil) return } status := &models.CommitStatus{ @@ -58,11 +59,11 @@ func NewCommitStatus(ctx *context.APIContext, form api.CreateStatusOption) { Context: form.Context, } if err := repofiles.CreateCommitStatus(ctx.Repo.Repository, ctx.User, sha, status); err != nil { - ctx.Error(500, "CreateCommitStatus", err) + ctx.Error(http.StatusInternalServerError, "CreateCommitStatus", err) return } - ctx.JSON(201, status.APIFormat()) + ctx.JSON(http.StatusCreated, status.APIFormat()) } // GetCommitStatuses returns all statuses for any given commit hash @@ -162,14 +163,14 @@ func GetCommitStatusesByRef(ctx *context.APIContext) { filter := ctx.Params("ref") if len(filter) == 0 { - ctx.Error(400, "ref not given", nil) + ctx.Error(http.StatusBadRequest, "ref not given", nil) return } for _, reftype := range []string{"heads", "tags"} { //Search branches and tags refSHA, lastMethodName, err := searchRefCommitByType(ctx, reftype, filter) if err != nil { - ctx.Error(500, lastMethodName, err) + ctx.Error(http.StatusInternalServerError, lastMethodName, err) return } if refSHA != "" { @@ -195,7 +196,7 @@ func searchRefCommitByType(ctx *context.APIContext, refType, filter string) (str func getCommitStatuses(ctx *context.APIContext, sha string) { if len(sha) == 0 { - ctx.Error(400, "ref/sha not given", nil) + ctx.Error(http.StatusBadRequest, "ref/sha not given", nil) return } repo := ctx.Repo.Repository @@ -206,7 +207,7 @@ func getCommitStatuses(ctx *context.APIContext, sha string) { State: ctx.QueryTrim("state"), }) if err != nil { - ctx.Error(500, "GetCommitStatuses", fmt.Errorf("GetCommitStatuses[%s, %s, %d]: %v", repo.FullName(), sha, ctx.QueryInt("page"), err)) + ctx.Error(http.StatusInternalServerError, "GetCommitStatuses", fmt.Errorf("GetCommitStatuses[%s, %s, %d]: %v", repo.FullName(), sha, ctx.QueryInt("page"), err)) return } @@ -215,7 +216,7 @@ func getCommitStatuses(ctx *context.APIContext, sha string) { apiStatuses = append(apiStatuses, status.APIFormat()) } - ctx.JSON(200, apiStatuses) + ctx.JSON(http.StatusOK, apiStatuses) } type combinedCommitStatus struct { @@ -264,7 +265,7 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) { sha := ctx.Params("ref") if len(sha) == 0 { - ctx.Error(400, "ref/sha not given", nil) + ctx.Error(http.StatusBadRequest, "ref/sha not given", nil) return } repo := ctx.Repo.Repository @@ -273,12 +274,12 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) { statuses, err := models.GetLatestCommitStatus(repo, sha, page) if err != nil { - ctx.Error(500, "GetLatestCommitStatus", fmt.Errorf("GetLatestCommitStatus[%s, %s, %d]: %v", repo.FullName(), sha, page, err)) + ctx.Error(http.StatusInternalServerError, "GetLatestCommitStatus", fmt.Errorf("GetLatestCommitStatus[%s, %s, %d]: %v", repo.FullName(), sha, page, err)) return } if len(statuses) == 0 { - ctx.Status(200) + ctx.Status(http.StatusOK) return } @@ -297,5 +298,5 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) { } } - ctx.JSON(200, retStatus) + ctx.JSON(http.StatusOK, retStatus) } diff --git a/routers/api/v1/repo/subscriber.go b/routers/api/v1/repo/subscriber.go index 1d09687052ba..352f842884ac 100644 --- a/routers/api/v1/repo/subscriber.go +++ b/routers/api/v1/repo/subscriber.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" @@ -34,12 +36,12 @@ func ListSubscribers(ctx *context.APIContext) { subscribers, err := ctx.Repo.Repository.GetWatchers(0) if err != nil { - ctx.Error(500, "GetWatchers", err) + ctx.Error(http.StatusInternalServerError, "GetWatchers", err) return } users := make([]*api.User, len(subscribers)) for i, subscriber := range subscribers { users[i] = convert.ToUser(subscriber, ctx.IsSigned, ctx.User != nil && ctx.User.IsAdmin) } - ctx.JSON(200, users) + ctx.JSON(http.StatusOK, users) } diff --git a/routers/api/v1/repo/tag.go b/routers/api/v1/repo/tag.go index 64abd53cf08f..eb99895c6447 100644 --- a/routers/api/v1/repo/tag.go +++ b/routers/api/v1/repo/tag.go @@ -36,7 +36,7 @@ func ListTags(ctx *context.APIContext) { tags, err := ctx.Repo.GitRepo.GetTagInfos() if err != nil { - ctx.Error(500, "GetTags", err) + ctx.Error(http.StatusInternalServerError, "GetTags", err) return } @@ -45,7 +45,7 @@ func ListTags(ctx *context.APIContext) { apiTags[i] = convert.ToTag(ctx.Repo.Repository, tags[i]) } - ctx.JSON(200, &apiTags) + ctx.JSON(http.StatusOK, &apiTags) } // GetTag get the tag of a repository. diff --git a/routers/api/v1/repo/tree.go b/routers/api/v1/repo/tree.go index 2066ab5a5937..987f2fb80876 100644 --- a/routers/api/v1/repo/tree.go +++ b/routers/api/v1/repo/tree.go @@ -5,6 +5,8 @@ package repo import ( + "net/http" + "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/repofiles" ) @@ -55,12 +57,12 @@ func GetTree(ctx *context.APIContext) { sha := ctx.Params(":sha") if len(sha) == 0 { - ctx.Error(400, "", "sha not provided") + ctx.Error(http.StatusBadRequest, "", "sha not provided") return } if tree, err := repofiles.GetTreeBySHA(ctx.Repo.Repository, sha, ctx.QueryInt("page"), ctx.QueryInt("per_page"), ctx.QueryBool("recursive")); err != nil { - ctx.Error(400, "", err.Error()) + ctx.Error(http.StatusBadRequest, "", err.Error()) } else { - ctx.JSON(200, tree) + ctx.JSON(http.StatusOK, tree) } } diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index de9b919ca1c1..ec52f02d3865 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -6,6 +6,8 @@ package user import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" @@ -30,7 +32,7 @@ func ListAccessTokens(ctx *context.APIContext) { tokens, err := models.ListAccessTokens(ctx.User.ID) if err != nil { - ctx.Error(500, "ListAccessTokens", err) + ctx.Error(http.StatusInternalServerError, "ListAccessTokens", err) return } @@ -42,7 +44,7 @@ func ListAccessTokens(ctx *context.APIContext) { TokenLastEight: tokens[i].TokenLastEight, } } - ctx.JSON(200, &apiTokens) + ctx.JSON(http.StatusOK, &apiTokens) } // CreateAccessToken create access tokens @@ -78,10 +80,10 @@ func CreateAccessToken(ctx *context.APIContext, form api.CreateAccessTokenOption Name: form.Name, } if err := models.NewAccessToken(t); err != nil { - ctx.Error(500, "NewAccessToken", err) + ctx.Error(http.StatusInternalServerError, "NewAccessToken", err) return } - ctx.JSON(201, &api.AccessToken{ + ctx.JSON(http.StatusCreated, &api.AccessToken{ Name: t.Name, Token: t.Token, ID: t.ID, @@ -117,10 +119,10 @@ func DeleteAccessToken(ctx *context.APIContext) { if models.IsErrAccessTokenNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "DeleteAccessTokenByID", err) + ctx.Error(http.StatusInternalServerError, "DeleteAccessTokenByID", err) } return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/user/email.go b/routers/api/v1/user/email.go index 0f81fc3745f5..07fcde625e73 100644 --- a/routers/api/v1/user/email.go +++ b/routers/api/v1/user/email.go @@ -5,6 +5,8 @@ package user import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -26,14 +28,14 @@ func ListEmails(ctx *context.APIContext) { emails, err := models.GetEmailAddresses(ctx.User.ID) if err != nil { - ctx.Error(500, "GetEmailAddresses", err) + ctx.Error(http.StatusInternalServerError, "GetEmailAddresses", err) return } apiEmails := make([]*api.Email, len(emails)) for i := range emails { apiEmails[i] = convert.ToEmail(emails[i]) } - ctx.JSON(200, &apiEmails) + ctx.JSON(http.StatusOK, &apiEmails) } // AddEmail add an email address @@ -60,7 +62,7 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { // "$ref": "#/responses/validationError" if len(form.Emails) == 0 { - ctx.Error(422, "", "Email list empty") + ctx.Error(http.StatusUnprocessableEntity, "", "Email list empty") return } @@ -75,9 +77,9 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { if err := models.AddEmailAddresses(emails); err != nil { if models.IsErrEmailAlreadyUsed(err) { - ctx.Error(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email) + ctx.Error(http.StatusUnprocessableEntity, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email) } else { - ctx.Error(500, "AddEmailAddresses", err) + ctx.Error(http.StatusInternalServerError, "AddEmailAddresses", err) } return } @@ -86,7 +88,7 @@ func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) { for i := range emails { apiEmails[i] = convert.ToEmail(emails[i]) } - ctx.JSON(201, &apiEmails) + ctx.JSON(http.StatusCreated, &apiEmails) } // DeleteEmail delete email @@ -106,7 +108,7 @@ func DeleteEmail(ctx *context.APIContext, form api.DeleteEmailOption) { // "$ref": "#/responses/empty" if len(form.Emails) == 0 { - ctx.Status(204) + ctx.Status(http.StatusNoContent) return } @@ -119,8 +121,8 @@ func DeleteEmail(ctx *context.APIContext, form api.DeleteEmailOption) { } if err := models.DeleteEmailAddresses(emails); err != nil { - ctx.Error(500, "DeleteEmailAddresses", err) + ctx.Error(http.StatusInternalServerError, "DeleteEmailAddresses", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/user/follower.go b/routers/api/v1/user/follower.go index b58c6e6038ab..bd680702651b 100644 --- a/routers/api/v1/user/follower.go +++ b/routers/api/v1/user/follower.go @@ -5,6 +5,8 @@ package user import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -16,13 +18,13 @@ func responseAPIUsers(ctx *context.APIContext, users []*models.User) { for i := range users { apiUsers[i] = convert.ToUser(users[i], ctx.IsSigned, ctx.User != nil && ctx.User.IsAdmin) } - ctx.JSON(200, &apiUsers) + ctx.JSON(http.StatusOK, &apiUsers) } func listUserFollowers(ctx *context.APIContext, u *models.User) { users, err := u.GetFollowers(ctx.QueryInt("page")) if err != nil { - ctx.Error(500, "GetUserFollowers", err) + ctx.Error(http.StatusInternalServerError, "GetUserFollowers", err) return } responseAPIUsers(ctx, users) @@ -69,7 +71,7 @@ func ListFollowers(ctx *context.APIContext) { func listUserFollowing(ctx *context.APIContext, u *models.User) { users, err := u.GetFollowing(ctx.QueryInt("page")) if err != nil { - ctx.Error(500, "GetFollowing", err) + ctx.Error(http.StatusInternalServerError, "GetFollowing", err) return } responseAPIUsers(ctx, users) @@ -115,7 +117,7 @@ func ListFollowing(ctx *context.APIContext) { func checkUserFollowing(ctx *context.APIContext, u *models.User, followID int64) { if u.IsFollowing(followID) { - ctx.Status(204) + ctx.Status(http.StatusNoContent) } else { ctx.NotFound() } @@ -198,10 +200,10 @@ func Follow(ctx *context.APIContext) { return } if err := models.FollowUser(ctx.User.ID, target.ID); err != nil { - ctx.Error(500, "FollowUser", err) + ctx.Error(http.StatusInternalServerError, "FollowUser", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // Unfollow unfollow a user @@ -224,8 +226,8 @@ func Unfollow(ctx *context.APIContext) { return } if err := models.UnfollowUser(ctx.User.ID, target.ID); err != nil { - ctx.Error(500, "UnfollowUser", err) + ctx.Error(http.StatusInternalServerError, "UnfollowUser", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go index 719095f4bf03..b6133ca7be45 100644 --- a/routers/api/v1/user/gpg_key.go +++ b/routers/api/v1/user/gpg_key.go @@ -5,6 +5,8 @@ package user import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -14,7 +16,7 @@ import ( func listGPGKeys(ctx *context.APIContext, uid int64) { keys, err := models.ListGPGKeys(uid) if err != nil { - ctx.Error(500, "ListGPGKeys", err) + ctx.Error(http.StatusInternalServerError, "ListGPGKeys", err) return } @@ -23,7 +25,7 @@ func listGPGKeys(ctx *context.APIContext, uid int64) { apiKeys[i] = convert.ToGPGKey(keys[i]) } - ctx.JSON(200, &apiKeys) + ctx.JSON(http.StatusOK, &apiKeys) } //ListGPGKeys get the GPG key list of a user @@ -89,11 +91,11 @@ func GetGPGKey(ctx *context.APIContext) { if models.IsErrGPGKeyNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetGPGKeyByID", err) + ctx.Error(http.StatusInternalServerError, "GetGPGKeyByID", err) } return } - ctx.JSON(200, convert.ToGPGKey(key)) + ctx.JSON(http.StatusOK, convert.ToGPGKey(key)) } // CreateUserGPGKey creates new GPG key to given user by ID. @@ -103,7 +105,7 @@ func CreateUserGPGKey(ctx *context.APIContext, form api.CreateGPGKeyOption, uid HandleAddGPGKeyError(ctx, err) return } - ctx.JSON(201, convert.ToGPGKey(key)) + ctx.JSON(http.StatusCreated, convert.ToGPGKey(key)) } // swagger:parameters userCurrentPostGPGKey @@ -152,24 +154,24 @@ func DeleteGPGKey(ctx *context.APIContext) { if err := models.DeleteGPGKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if models.IsErrGPGKeyAccessDenied(err) { - ctx.Error(403, "", "You do not have access to this key") + ctx.Error(http.StatusForbidden, "", "You do not have access to this key") } else { - ctx.Error(500, "DeleteGPGKey", err) + ctx.Error(http.StatusInternalServerError, "DeleteGPGKey", err) } return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // HandleAddGPGKeyError handle add GPGKey error func HandleAddGPGKeyError(ctx *context.APIContext, err error) { switch { case models.IsErrGPGKeyAccessDenied(err): - ctx.Error(422, "", "You do not have access to this GPG key") + ctx.Error(http.StatusUnprocessableEntity, "", "You do not have access to this GPG key") case models.IsErrGPGKeyIDAlreadyUsed(err): - ctx.Error(422, "", "A key with the same id already exists") + ctx.Error(http.StatusUnprocessableEntity, "", "A key with the same id already exists") default: - ctx.Error(500, "AddGPGKey", err) + ctx.Error(http.StatusInternalServerError, "AddGPGKey", err) } } diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index 5e413b71e12b..7cf6fa383d86 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -5,6 +5,8 @@ package user import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/convert" @@ -43,7 +45,7 @@ func GetUserByParamsName(ctx *context.APIContext, name string) *models.User { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return nil } @@ -81,7 +83,7 @@ func listPublicKeys(ctx *context.APIContext, user *models.User) { } if err != nil { - ctx.Error(500, "ListPublicKeys", err) + ctx.Error(http.StatusInternalServerError, "ListPublicKeys", err) return } @@ -94,7 +96,7 @@ func listPublicKeys(ctx *context.APIContext, user *models.User) { } } - ctx.JSON(200, &apiKeys) + ctx.JSON(http.StatusOK, &apiKeys) } // ListMyPublicKeys list all of the authenticated user's public keys @@ -169,7 +171,7 @@ func GetPublicKey(ctx *context.APIContext) { if models.IsErrKeyNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetPublicKeyByID", err) + ctx.Error(http.StatusInternalServerError, "GetPublicKeyByID", err) } return } @@ -179,7 +181,7 @@ func GetPublicKey(ctx *context.APIContext) { if ctx.User.IsAdmin || ctx.User.ID == key.OwnerID { apiKey, _ = appendPrivateInformation(apiKey, key, ctx.User) } - ctx.JSON(200, apiKey) + ctx.JSON(http.StatusOK, apiKey) } // CreateUserPublicKey creates new public key to given user by ID. @@ -200,7 +202,7 @@ func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid if ctx.User.IsAdmin || ctx.User.ID == key.OwnerID { apiKey, _ = appendPrivateInformation(apiKey, key, ctx.User) } - ctx.JSON(201, apiKey) + ctx.JSON(http.StatusCreated, apiKey) } // CreatePublicKey create one public key for me @@ -252,12 +254,12 @@ func DeletePublicKey(ctx *context.APIContext) { if models.IsErrKeyNotExist(err) { ctx.NotFound() } else if models.IsErrKeyAccessDenied(err) { - ctx.Error(403, "", "You do not have access to this key") + ctx.Error(http.StatusForbidden, "", "You do not have access to this key") } else { - ctx.Error(500, "DeletePublicKey", err) + ctx.Error(http.StatusInternalServerError, "DeletePublicKey", err) } return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/user/repo.go b/routers/api/v1/user/repo.go index 5f2ee53610bb..90518f95e58c 100644 --- a/routers/api/v1/user/repo.go +++ b/routers/api/v1/user/repo.go @@ -5,6 +5,8 @@ package user import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" @@ -14,7 +16,7 @@ import ( func listUserRepos(ctx *context.APIContext, u *models.User, private bool) { repos, err := models.GetUserRepositories(u.ID, private, 1, u.NumRepos, "") if err != nil { - ctx.Error(500, "GetUserRepositories", err) + ctx.Error(http.StatusInternalServerError, "GetUserRepositories", err) return } @@ -22,14 +24,14 @@ func listUserRepos(ctx *context.APIContext, u *models.User, private bool) { for i := range repos { access, err := models.AccessLevel(ctx.User, repos[i]) if err != nil { - ctx.Error(500, "AccessLevel", err) + ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } if ctx.IsSigned && ctx.User.IsAdmin || access >= models.AccessModeRead { apiRepos = append(apiRepos, repos[i].APIFormat(access)) } } - ctx.JSON(200, &apiRepos) + ctx.JSON(http.StatusOK, &apiRepos) } // ListUserRepos - list the repos owned by the given user. @@ -70,12 +72,12 @@ func ListMyRepos(ctx *context.APIContext) { ownRepos, err := models.GetUserRepositories(ctx.User.ID, true, 1, ctx.User.NumRepos, "") if err != nil { - ctx.Error(500, "GetUserRepositories", err) + ctx.Error(http.StatusInternalServerError, "GetUserRepositories", err) return } accessibleReposMap, err := ctx.User.GetRepositoryAccesses() if err != nil { - ctx.Error(500, "GetRepositoryAccesses", err) + ctx.Error(http.StatusInternalServerError, "GetRepositoryAccesses", err) return } @@ -88,7 +90,7 @@ func ListMyRepos(ctx *context.APIContext) { apiRepos[i] = repo.APIFormat(access) i++ } - ctx.JSON(200, &apiRepos) + ctx.JSON(http.StatusOK, &apiRepos) } // ListOrgRepos - list the repositories of an organization. diff --git a/routers/api/v1/user/star.go b/routers/api/v1/user/star.go index 751d4bf082b0..e5d3a8f0a01f 100644 --- a/routers/api/v1/user/star.go +++ b/routers/api/v1/user/star.go @@ -5,6 +5,8 @@ package user import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" @@ -50,9 +52,9 @@ func GetStarredRepos(ctx *context.APIContext) { private := user.ID == ctx.User.ID repos, err := getStarredRepos(user, private) if err != nil { - ctx.Error(500, "getStarredRepos", err) + ctx.Error(http.StatusInternalServerError, "getStarredRepos", err) } - ctx.JSON(200, &repos) + ctx.JSON(http.StatusOK, &repos) } // GetMyStarredRepos returns the repos that the authenticated user has starred @@ -68,9 +70,9 @@ func GetMyStarredRepos(ctx *context.APIContext) { repos, err := getStarredRepos(ctx.User, true) if err != nil { - ctx.Error(500, "getStarredRepos", err) + ctx.Error(http.StatusInternalServerError, "getStarredRepos", err) } - ctx.JSON(200, &repos) + ctx.JSON(http.StatusOK, &repos) } // IsStarring returns whether the authenticated is starring the repo @@ -96,7 +98,7 @@ func IsStarring(ctx *context.APIContext) { // "$ref": "#/responses/notFound" if models.IsStaring(ctx.User.ID, ctx.Repo.Repository.ID) { - ctx.Status(204) + ctx.Status(http.StatusNoContent) } else { ctx.NotFound() } @@ -124,10 +126,10 @@ func Star(ctx *context.APIContext) { err := models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, true) if err != nil { - ctx.Error(500, "StarRepo", err) + ctx.Error(http.StatusInternalServerError, "StarRepo", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // Unstar the repo specified in the APIContext, as the authenticated user @@ -152,8 +154,8 @@ func Unstar(ctx *context.APIContext) { err := models.StarRepo(ctx.User.ID, ctx.Repo.Repository.ID, false) if err != nil { - ctx.Error(500, "StarRepo", err) + ctx.Error(http.StatusInternalServerError, "StarRepo", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index 4f5b596a577e..3f17a6f91b3e 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -59,7 +59,7 @@ func Search(ctx *context.APIContext) { users, _, err := models.SearchUsers(opts) if err != nil { - ctx.JSON(500, map[string]interface{}{ + ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ "ok": false, "error": err.Error(), }) @@ -71,7 +71,7 @@ func Search(ctx *context.APIContext) { results[i] = convert.ToUser(users[i], ctx.IsSigned, ctx.User != nil && ctx.User.IsAdmin) } - ctx.JSON(200, map[string]interface{}{ + ctx.JSON(http.StatusOK, map[string]interface{}{ "ok": true, "data": results, }) @@ -101,12 +101,12 @@ func GetInfo(ctx *context.APIContext) { if models.IsErrUserNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetUserByName", err) + ctx.Error(http.StatusInternalServerError, "GetUserByName", err) } return } - ctx.JSON(200, convert.ToUser(u, ctx.IsSigned, ctx.User != nil && (ctx.User.ID == u.ID || ctx.User.IsAdmin))) + ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.IsSigned, ctx.User != nil && (ctx.User.ID == u.ID || ctx.User.IsAdmin))) } // GetAuthenticatedUser get current user's information @@ -120,7 +120,7 @@ func GetAuthenticatedUser(ctx *context.APIContext) { // "200": // "$ref": "#/responses/User" - ctx.JSON(200, convert.ToUser(ctx.User, ctx.IsSigned, ctx.User != nil)) + ctx.JSON(http.StatusOK, convert.ToUser(ctx.User, ctx.IsSigned, ctx.User != nil)) } // GetUserHeatmapData is the handler to get a users heatmap @@ -158,5 +158,5 @@ func GetUserHeatmapData(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetUserHeatmapDataByUser", err) return } - ctx.JSON(200, heatmap) + ctx.JSON(http.StatusOK, heatmap) } diff --git a/routers/api/v1/user/watch.go b/routers/api/v1/user/watch.go index a6fa551f344b..ec8543dcf0c4 100644 --- a/routers/api/v1/user/watch.go +++ b/routers/api/v1/user/watch.go @@ -5,6 +5,8 @@ package user import ( + "net/http" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" @@ -51,9 +53,9 @@ func GetWatchedRepos(ctx *context.APIContext) { private := user.ID == ctx.User.ID repos, err := getWatchedRepos(user, private) if err != nil { - ctx.Error(500, "getWatchedRepos", err) + ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err) } - ctx.JSON(200, &repos) + ctx.JSON(http.StatusOK, &repos) } // GetMyWatchedRepos returns the repos that the authenticated user is watching @@ -69,9 +71,9 @@ func GetMyWatchedRepos(ctx *context.APIContext) { repos, err := getWatchedRepos(ctx.User, true) if err != nil { - ctx.Error(500, "getWatchedRepos", err) + ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err) } - ctx.JSON(200, &repos) + ctx.JSON(http.StatusOK, &repos) } // IsWatching returns whether the authenticated user is watching the repo @@ -96,7 +98,7 @@ func IsWatching(ctx *context.APIContext) { // "$ref": "#/responses/WatchInfo" if models.IsWatching(ctx.User.ID, ctx.Repo.Repository.ID) { - ctx.JSON(200, api.WatchInfo{ + ctx.JSON(http.StatusOK, api.WatchInfo{ Subscribed: true, Ignored: false, Reason: nil, @@ -131,10 +133,10 @@ func Watch(ctx *context.APIContext) { err := models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, true) if err != nil { - ctx.Error(500, "WatchRepo", err) + ctx.Error(http.StatusInternalServerError, "WatchRepo", err) return } - ctx.JSON(200, api.WatchInfo{ + ctx.JSON(http.StatusOK, api.WatchInfo{ Subscribed: true, Ignored: false, Reason: nil, @@ -167,10 +169,10 @@ func Unwatch(ctx *context.APIContext) { err := models.WatchRepo(ctx.User.ID, ctx.Repo.Repository.ID, false) if err != nil { - ctx.Error(500, "UnwatchRepo", err) + ctx.Error(http.StatusInternalServerError, "UnwatchRepo", err) return } - ctx.Status(204) + ctx.Status(http.StatusNoContent) } // subscriptionURL returns the URL of the subscription API endpoint of a repo diff --git a/routers/api/v1/utils/hook.go b/routers/api/v1/utils/hook.go index f88b15200389..9a6733f9dc14 100644 --- a/routers/api/v1/utils/hook.go +++ b/routers/api/v1/utils/hook.go @@ -27,7 +27,7 @@ func GetOrgHook(ctx *context.APIContext, orgID, hookID int64) (*models.Webhook, if models.IsErrWebhookNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetWebhookByOrgID", err) + ctx.Error(http.StatusInternalServerError, "GetWebhookByOrgID", err) } return nil, err } @@ -42,7 +42,7 @@ func GetRepoHook(ctx *context.APIContext, repoID, hookID int64) (*models.Webhook if models.IsErrWebhookNotExist(err) { ctx.NotFound() } else { - ctx.Error(500, "GetWebhookByID", err) + ctx.Error(http.StatusInternalServerError, "GetWebhookByID", err) } return nil, err } @@ -53,17 +53,17 @@ func GetRepoHook(ctx *context.APIContext, repoID, hookID int64) (*models.Webhook // write the appropriate error to `ctx`. Return whether the form is valid func CheckCreateHookOption(ctx *context.APIContext, form *api.CreateHookOption) bool { if !models.IsValidHookTaskType(form.Type) { - ctx.Error(422, "", "Invalid hook type") + ctx.Error(http.StatusUnprocessableEntity, "", "Invalid hook type") return false } for _, name := range []string{"url", "content_type"} { if _, ok := form.Config[name]; !ok { - ctx.Error(422, "", "Missing config option: "+name) + ctx.Error(http.StatusUnprocessableEntity, "", "Missing config option: "+name) return false } } if !models.IsValidHookContentType(form.Config["content_type"]) { - ctx.Error(422, "", "Invalid content type") + ctx.Error(http.StatusUnprocessableEntity, "", "Invalid content type") return false } return true @@ -121,12 +121,12 @@ func addHook(ctx *context.APIContext, form *api.CreateHookOption, orgID, repoID if w.HookTaskType == models.SLACK { channel, ok := form.Config["channel"] if !ok { - ctx.Error(422, "", "Missing config option: channel") + ctx.Error(http.StatusUnprocessableEntity, "", "Missing config option: channel") return nil, false } if !utils.IsValidSlackChannel(channel) { - ctx.Error(400, "", "Invalid slack channel name") + ctx.Error(http.StatusBadRequest, "", "Invalid slack channel name") return nil, false } @@ -137,17 +137,17 @@ func addHook(ctx *context.APIContext, form *api.CreateHookOption, orgID, repoID Color: form.Config["color"], }) if err != nil { - ctx.Error(500, "slack: JSON marshal failed", err) + ctx.Error(http.StatusInternalServerError, "slack: JSON marshal failed", err) return nil, false } w.Meta = string(meta) } if err := w.UpdateEvent(); err != nil { - ctx.Error(500, "UpdateEvent", err) + ctx.Error(http.StatusInternalServerError, "UpdateEvent", err) return nil, false } else if err := models.CreateWebhook(w); err != nil { - ctx.Error(500, "CreateWebhook", err) + ctx.Error(http.StatusInternalServerError, "CreateWebhook", err) return nil, false } return w, true @@ -167,7 +167,7 @@ func EditOrgHook(ctx *context.APIContext, form *api.EditHookOption, hookID int64 if err != nil { return } - ctx.JSON(200, convert.ToHook(org.HomeLink(), updated)) + ctx.JSON(http.StatusOK, convert.ToHook(org.HomeLink(), updated)) } // EditRepoHook edit webhook `w` according to `form`. Writes to `ctx` accordingly @@ -184,7 +184,7 @@ func EditRepoHook(ctx *context.APIContext, form *api.EditHookOption, hookID int6 if err != nil { return } - ctx.JSON(200, convert.ToHook(repo.RepoLink, updated)) + ctx.JSON(http.StatusOK, convert.ToHook(repo.RepoLink, updated)) } // editHook edit the webhook `w` according to `form`. If an error occurs, write @@ -196,7 +196,7 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *models.Webho } if ct, ok := form.Config["content_type"]; ok { if !models.IsValidHookContentType(ct) { - ctx.Error(422, "", "Invalid content type") + ctx.Error(http.StatusUnprocessableEntity, "", "Invalid content type") return false } w.ContentType = models.ToHookContentType(ct) @@ -211,7 +211,7 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *models.Webho Color: form.Config["color"], }) if err != nil { - ctx.Error(500, "slack: JSON marshal failed", err) + ctx.Error(http.StatusInternalServerError, "slack: JSON marshal failed", err) return false } w.Meta = string(meta) @@ -241,7 +241,7 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *models.Webho w.BranchFilter = form.BranchFilter if err := w.UpdateEvent(); err != nil { - ctx.Error(500, "UpdateEvent", err) + ctx.Error(http.StatusInternalServerError, "UpdateEvent", err) return false } @@ -250,7 +250,7 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *models.Webho } if err := models.UpdateWebhook(w); err != nil { - ctx.Error(500, "UpdateWebhook", err) + ctx.Error(http.StatusInternalServerError, "UpdateWebhook", err) return false } return true