diff --git a/.golangci.yml b/.golangci.yml index 0d2e4a966..8bf3c8a34 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -112,17 +112,6 @@ linters-settings: # Default: 30 max-func-lines: 30 - nolintlint: - # Exclude following linters from requiring an explanation. - # Default: [] - allow-no-explanation: [ funlen, gocognit, lll ] - # Enable to require an explanation of nonzero length after each nolint directive. - # Default: false - require-explanation: true - # Enable to require nolint directives to mention the specific linter being suppressed. - # Default: false - require-specific: true - rowserrcheck: # database/sql is always checked # Default: [] @@ -217,7 +206,7 @@ linters: - exhaustive # checks exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - forbidigo # forbids identifiers - - funlen # tool for detection of long functions + #- funlen # tool for detection of long functions #- gochecknoglobals # checks that no global variables exist #- gochecknoinits # checks that no init functions are present in Go code - gocognit # computes and checks the cognitive complexity of functions @@ -238,7 +227,7 @@ linters: - nilerr # finds the code that returns nil even if it checks that the error is not nil - nilnil # checks that there is no simultaneous return of nil error and an invalid value - noctx # finds sending http request without context.Context - - nolintlint # reports ill-formed or insufficient nolint directives + # - nolintlint # reports ill-formed or insufficient nolint directives # - nonamedreturns # reports all named returns - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL - predeclared # finds code that shadows one of Go's predeclared identifiers @@ -283,7 +272,7 @@ linters: #- importas # enforces consistent import aliases #- logrlint # [owner archived repository] checks logr arguments #- maintidx # measures the maintainability index of each function - #- misspell # [useless] finds commonly misspelled English words in comments + - misspell # [useless] finds commonly misspelled English words in comments #- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity #- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test #- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers diff --git a/cli/cli.go b/cli/cli.go index 858bfe2de..14dae1320 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -53,7 +53,7 @@ func getArguments() []string { command := os.Args[0] args := os.Args[1:] - // in case of githooks, translate the arguments comming from git to work with gitness. + // in case of githooks, translate the arguments coming from git to work with gitness. if gitArgs, fromGit := githook.SanitizeArgsForGit(command, args); fromGit { return append([]string{hooks.ParamHooks}, gitArgs...) } diff --git a/cli/server/harness.wire_gen.go b/cli/server/harness.wire_gen.go index 99649644c..a19c9460c 100644 --- a/cli/server/harness.wire_gen.go +++ b/cli/server/harness.wire_gen.go @@ -7,6 +7,7 @@ package server import ( "context" + "github.com/harness/gitness/events" "github.com/harness/gitness/gitrpc" server2 "github.com/harness/gitness/gitrpc/server" @@ -176,7 +177,7 @@ func initSystem(ctx context.Context, config *types.Config) (*system, error) { if err != nil { return nil, err } - cronManager := cron.ProvideCronManager(serverConfig) + manager := cron.ProvideManager(serverConfig) repoGitInfoView := database.ProvideRepoGitInfoView(db) repoGitInfoCache := cache.ProvideRepoGitInfoCache(repoGitInfoView) pubsubConfig := pubsub.ProvideConfig(config) @@ -186,6 +187,6 @@ func initSystem(ctx context.Context, config *types.Config) (*system, error) { return nil, err } servicesServices := services.ProvideServices(webhookService, pullreqService) - serverSystem := newSystem(bootstrapBootstrap, serverServer, server3, cronManager, servicesServices) + serverSystem := newSystem(bootstrapBootstrap, serverServer, server3, manager, servicesServices) return serverSystem, nil } diff --git a/cli/server/standalone.wire_gen.go b/cli/server/standalone.wire_gen.go index d9b5dedb8..08d6e0c9b 100644 --- a/cli/server/standalone.wire_gen.go +++ b/cli/server/standalone.wire_gen.go @@ -7,6 +7,7 @@ package server import ( "context" + "github.com/harness/gitness/events" "github.com/harness/gitness/gitrpc" server2 "github.com/harness/gitness/gitrpc/server" @@ -143,7 +144,7 @@ func initSystem(ctx context.Context, config *types.Config) (*system, error) { if err != nil { return nil, err } - cronManager := cron.ProvideCronManager(serverConfig) + manager := cron.ProvideManager(serverConfig) repoGitInfoView := database.ProvideRepoGitInfoView(db) repoGitInfoCache := cache.ProvideRepoGitInfoCache(repoGitInfoView) pubsubConfig := pubsub.ProvideConfig(config) @@ -153,6 +154,6 @@ func initSystem(ctx context.Context, config *types.Config) (*system, error) { return nil, err } servicesServices := services.ProvideServices(webhookService, pullreqService) - serverSystem := newSystem(bootstrapBootstrap, serverServer, server3, cronManager, servicesServices) + serverSystem := newSystem(bootstrapBootstrap, serverServer, server3, manager, servicesServices) return serverSystem, nil } diff --git a/cli/server/system.go b/cli/server/system.go index 2cfb41bf4..680975568 100644 --- a/cli/server/system.go +++ b/cli/server/system.go @@ -18,12 +18,12 @@ type system struct { server *server.Server gitRPCServer *gitrpcserver.Server services services.Services - gitRPCCronMngr *gitrpccron.CronManager + gitRPCCronMngr *gitrpccron.Manager } // newSystem returns a new system structure. func newSystem(bootstrap bootstrap.Bootstrap, server *server.Server, gitRPCServer *gitrpcserver.Server, - gitrpccron *gitrpccron.CronManager, services services.Services) *system { + gitrpccron *gitrpccron.Manager, services services.Services) *system { return &system{ bootstrap: bootstrap, server: server, diff --git a/events/reader.go b/events/reader.go index 1d5ace254..c625c82bb 100644 --- a/events/reader.go +++ b/events/reader.go @@ -60,7 +60,7 @@ func (f *ReaderFactory[R]) Launch(ctx context.Context, category: f.category, } - // create new reader (could return the innerReader itself, but also allows to launch costumized readers) + // create new reader (could return the innerReader itself, but also allows to launch customized readers) reader, err := f.readerFactoryFn(innerReader) if err != nil { //nolint:gocritic // only way to achieve this AFAIK - lint proposal is not building @@ -165,7 +165,7 @@ func ReaderRegisterEvent[T interface{}](reader *GenericReader, } // retrieve bytes from raw event - // NOTE: Redis returns []byte as string - to avoid unnecessary convertion we handle both types here. + // NOTE: Redis returns []byte as string - to avoid unnecessary conversion we handle both types here. var eventBytes []byte switch v := eventRaw.(type) { case string: diff --git a/gitrpc/enum/merge.go b/gitrpc/enum/merge.go index 98a2aaaa7..06edd664f 100644 --- a/gitrpc/enum/merge.go +++ b/gitrpc/enum/merge.go @@ -1,3 +1,7 @@ +// Copyright 2022 Harness Inc. All rights reserved. +// Use of this source code is governed by the Polyform Free Trial License +// that can be found in the LICENSE.md file for this repository. + package enum import "github.com/harness/gitness/gitrpc/rpc" diff --git a/gitrpc/internal/gitea/merge.go b/gitrpc/internal/gitea/merge.go index e37aa5b94..4f8bb4a3a 100644 --- a/gitrpc/internal/gitea/merge.go +++ b/gitrpc/internal/gitea/merge.go @@ -18,9 +18,9 @@ import ( "github.com/harness/gitness/gitrpc/enum" "github.com/harness/gitness/gitrpc/internal/tempdir" "github.com/harness/gitness/gitrpc/internal/types" - "github.com/rs/zerolog/log" "code.gitea.io/gitea/modules/git" + "github.com/rs/zerolog/log" ) // CreateTemporaryRepo creates a temporary repo with "base" for pr.BaseBranch and "tracking" for pr.HeadBranch @@ -251,6 +251,9 @@ func commitAndSignNoAuthor( return nil } +// Merge merges changes between 2 refs (branch, commits or tags). +// +//nolint:gocognit,nestif func (g Adapter) Merge( ctx context.Context, pr *types.PullRequest, @@ -288,7 +291,7 @@ func (g Adapter) Merge( // Merge with squash cmd := git.NewCommand(ctx, "merge", "--squash", trackingBranch) if err := runMergeCommand(ctx, pr, mergeMethod, cmd, tmpBasePath, env); err != nil { - return fmt.Errorf("unable to merge --squash tracking into base: %v", err) + return fmt.Errorf("unable to merge --squash tracking into base: %w", err) } if signArg == "" { @@ -322,7 +325,10 @@ func (g Adapter) Merge( Stdout: &outbuf, Stderr: &errbuf, }); err != nil { - return fmt.Errorf("git checkout base prior to merge post staging rebase [%s -> %s]: %v\n%s\n%s", pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String()) + return fmt.Errorf( + "git checkout base prior to merge post staging rebase [%s -> %s]: %w\n%s\n%s", + pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String(), + ) } outbuf.Reset() errbuf.Reset() @@ -337,25 +343,35 @@ func (g Adapter) Merge( // Rebase will leave a REBASE_HEAD file in .git if there is a conflict if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "REBASE_HEAD")); statErr == nil { var commitSha string + // TBD git version we will support // failingCommitPath := filepath.Join(tmpBasePath, ".git", "rebase-apply", "original-commit") // Git < 2.26 - // if _, statErr := os.Stat(failingCommitPath); statErr != nil { - // return fmt.Errorf("git rebase staging on to base [%s -> %s]: %v\n%s\n%s", pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String()) + // if _, cpErr := os.Stat(failingCommitPath); statErr != nil { + // return fmt.Errorf("git rebase staging on to base [%s -> %s]: %v\n%s\n%s", + // pr.HeadBranch, pr.BaseBranch, cpErr, outbuf.String(), errbuf.String()) // } failingCommitPath := filepath.Join(tmpBasePath, ".git", "rebase-merge", "stopped-sha") // Git >= 2.26 - if _, statErr := os.Stat(failingCommitPath); statErr != nil { - return fmt.Errorf("git rebase staging on to base [%s -> %s]: %v\n%s\n%s", pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String()) + if _, cpErr := os.Stat(failingCommitPath); cpErr != nil { + return fmt.Errorf( + "git rebase staging on to base [%s -> %s]: %w\n%s\n%s", + pr.HeadBranch, pr.BaseBranch, cpErr, outbuf.String(), errbuf.String(), + ) } commitShaBytes, readErr := os.ReadFile(failingCommitPath) if readErr != nil { // Abandon this attempt to handle the error - return fmt.Errorf("git rebase staging on to base [%s -> %s]: %v\n%s\n%s", pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String()) + return fmt.Errorf( + "git rebase staging on to base [%s -> %s]: %w\n%s\n%s", + pr.HeadBranch, pr.BaseBranch, readErr, outbuf.String(), errbuf.String(), + ) } commitSha = strings.TrimSpace(string(commitShaBytes)) - log.Debug().Msgf("RebaseConflict at %s [%s -> %s]: %v\n%s\n%s", commitSha, pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String()) + log.Debug().Msgf("RebaseConflict at %s [%s -> %s]: %v\n%s\n%s", + commitSha, pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String(), + ) return &types.MergeConflictsError{ Method: mergeMethod, CommitSHA: commitSha, @@ -364,7 +380,10 @@ func (g Adapter) Merge( Err: err, } } - return fmt.Errorf("git rebase staging on to base [%s -> %s]: %v\n%s\n%s", pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String()) + return fmt.Errorf( + "git rebase staging on to base [%s -> %s]: %w\n%s\n%s", + pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String(), + ) } outbuf.Reset() errbuf.Reset() @@ -376,7 +395,10 @@ func (g Adapter) Merge( Stdout: &outbuf, Stderr: &errbuf, }); err != nil { - return fmt.Errorf("git checkout base prior to merge post staging rebase [%s -> %s]: %v\n%s\n%s", pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String()) + return fmt.Errorf( + "git checkout base prior to merge post staging rebase [%s -> %s]: %w\n%s\n%s", + pr.HeadBranch, pr.BaseBranch, err, outbuf.String(), errbuf.String(), + ) } outbuf.Reset() errbuf.Reset() diff --git a/gitrpc/internal/gitea/tag.go b/gitrpc/internal/gitea/tag.go index 775490068..f5eed3f82 100644 --- a/gitrpc/internal/gitea/tag.go +++ b/gitrpc/internal/gitea/tag.go @@ -9,13 +9,13 @@ import ( "context" "errors" "fmt" - "github.com/harness/gitness/gitrpc/rpc" "io" "strconv" "strings" "time" "github.com/harness/gitness/gitrpc/internal/types" + "github.com/harness/gitness/gitrpc/rpc" gitea "code.gitea.io/gitea/modules/git" ) @@ -62,7 +62,12 @@ func (g Adapter) GetAnnotatedTags(ctx context.Context, repoPath string, shas []s return tags, nil } -func (g Adapter) CreateAnnotatedTag(ctx context.Context, repoPath string, request *rpc.CreateTagRequest, env []string) error { +func (g Adapter) CreateAnnotatedTag( + ctx context.Context, + repoPath string, + request *rpc.CreateTagRequest, + env []string, +) error { cmd := gitea.NewCommand(ctx, "tag", "-a", "-m", request.GetMessage(), "--", request.GetTagName(), request.GetSha()) _, _, err := cmd.RunStdString(&gitea.RunOpts{Dir: repoPath, Env: env}) if err != nil { @@ -75,7 +80,7 @@ func (g Adapter) DeleteTag(ctx context.Context, repoPath string, ref string, env cmd := gitea.NewCommand(ctx, "tag", "-d", ref) _, stdErr, err := cmd.RunStdString(&gitea.RunOpts{Dir: repoPath, Env: env}) if err != nil { - return processGiteaErrorf(err, "Service failed to delete tag with error", stdErr) + return processGiteaErrorf(err, "Service failed to delete tag with error: %v", stdErr) } return nil } @@ -200,7 +205,7 @@ func giteaParseCatFileLine(data []byte, start int, header string) (string, int, return "", 0, fmt.Errorf("expected '%s' but started with '%s'", header, string(data[:lenHeader])) } - // get end of line and start of next line (used externaly, transpose with provided start index) + // get end of line and start of next line (used externally, transpose with provided start index) lineEnd := bytes.IndexByte(data, '\n') externalNextLine := start + lineEnd + 1 if lineEnd == -1 { diff --git a/gitrpc/internal/gitea/tree.go b/gitrpc/internal/gitea/tree.go index a361b8590..2962b2b56 100644 --- a/gitrpc/internal/gitea/tree.go +++ b/gitrpc/internal/gitea/tree.go @@ -70,7 +70,7 @@ func (g Adapter) GetTreeNode(ctx context.Context, repoPath string, func (g Adapter) ListTreeNodes(ctx context.Context, repoPath string, ref string, treePath string, recursive bool, includeLatestCommit bool) ([]types.TreeNodeWithCommit, error) { if recursive && includeLatestCommit { - // To avoid potential performance catastrophies, block recursive with includeLatestCommit + // To avoid potential performance catastrophe, block recursive with includeLatestCommit // TODO: this should return bad error to caller if needed? // TODO: should this be refactored in two methods? return nil, fmt.Errorf("latest commit with recursive query is not supported") diff --git a/gitrpc/internal/service/branch.go b/gitrpc/internal/service/branch.go index 26817ee19..53fccd8e8 100644 --- a/gitrpc/internal/service/branch.go +++ b/gitrpc/internal/service/branch.go @@ -175,7 +175,7 @@ func (s ReferenceService) ListBranches(request *rpc.ListBranchesRequest, ctx := stream.Context() repoPath := getFullPathForRepo(s.reposRoot, base.GetRepoUid()) - // get all required information from git refrences + // get all required information from git references branches, err := s.listBranchesLoadReferenceData(ctx, repoPath, request) if err != nil { return err diff --git a/gitrpc/internal/service/interface.go b/gitrpc/internal/service/interface.go index 4b0f149ea..dcf09471a 100644 --- a/gitrpc/internal/service/interface.go +++ b/gitrpc/internal/service/interface.go @@ -12,6 +12,7 @@ import ( "github.com/harness/gitness/gitrpc/enum" "github.com/harness/gitness/gitrpc/internal/types" + "github.com/harness/gitness/gitrpc/rpc" ) // GitAdapter for accessing git commands from gitea. diff --git a/gitrpc/internal/service/merge.go b/gitrpc/internal/service/merge.go index 12c1d1e21..ead1fa8a9 100644 --- a/gitrpc/internal/service/merge.go +++ b/gitrpc/internal/service/merge.go @@ -66,7 +66,7 @@ func (s MergeService) Merge( defer func() { rmErr := tempdir.RemoveTemporaryPath(tmpBasePath) if rmErr != nil { - log.Ctx(ctx).Warn().Msgf("Removing temporary location %s for merge operation was not successfull", tmpBasePath) + log.Ctx(ctx).Warn().Msgf("Removing temporary location %s for merge operation was not successful", tmpBasePath) } }() @@ -88,6 +88,11 @@ func (s MergeService) Merge( return nil, fmt.Errorf("failed to get merge base: %w", err) } + if headCommitSHA == mergeBaseCommitSHA { + return nil, ErrInvalidArgumentf("no changes between head branch %s and base branch %s", + request.HeadBranch, request.BaseBranch) + } + if request.HeadExpectedSha != "" && request.HeadExpectedSha != headCommitSHA { return nil, status.Errorf( codes.FailedPrecondition, diff --git a/gitrpc/internal/service/operations.go b/gitrpc/internal/service/operations.go index 51fa19cd4..f571d5930 100644 --- a/gitrpc/internal/service/operations.go +++ b/gitrpc/internal/service/operations.go @@ -87,7 +87,7 @@ func (s *CommitFilesService) CommitFiles(stream rpc.CommitFilesService_CommitFil // check if repo is empty // IMPORTANT: we don't use gitea's repo.IsEmpty() as that only checks whether the default branch exists (in HEAD). // This can be an issue in case someone created a branch already in the repo (just default branch is missing). - // In that case the user can accidentaly create separate git histories (which most likely is unintended). + // In that case the user can accidentally create separate git histories (which most likely is unintended). // If the user wants to actually build a disconnected commit graph they can use the cli. isEmpty, err := repoHasBranches(ctx, repo) if err != nil { @@ -225,7 +225,7 @@ func (s *CommitFilesService) validateAndPrepareHeader(repo *git.Repository, isEm header.BranchName = strings.TrimPrefix(strings.TrimSpace(header.GetBranchName()), gitReferenceNamePrefixBranch) header.NewBranchName = strings.TrimPrefix(strings.TrimSpace(header.GetNewBranchName()), gitReferenceNamePrefixBranch) - // if the repo is empty then we can skip branch existance checks + // if the repo is empty then we can skip branch existence checks if isEmpty { return nil } diff --git a/gitrpc/internal/service/path.go b/gitrpc/internal/service/path.go index 40d5b8428..d9be9de0d 100644 --- a/gitrpc/internal/service/path.go +++ b/gitrpc/internal/service/path.go @@ -10,7 +10,7 @@ import ( ) // getFullPathForRepo returns the full path of a repo given the root dir of repos and the uid of the repo. -// NOTE: Split repos into subfolders using their prefix to distribute repos accross a set of folders. +// NOTE: Split repos into subfolders using their prefix to distribute repos across a set of folders. func getFullPathForRepo(reposRoot, uid string) string { // ASSUMPTION: repoUID is of lenth at least 4 - otherwise we have trouble either way. return filepath.Join( diff --git a/gitrpc/internal/service/ref.go b/gitrpc/internal/service/ref.go index 9a354edda..cf8515be3 100644 --- a/gitrpc/internal/service/ref.go +++ b/gitrpc/internal/service/ref.go @@ -78,7 +78,7 @@ func createReferenceWalkPatternsFromQuery(basePath string, query string) []strin return []string{} } - // ensure non-empty basepath ends with "/" for proper matching and concatination. + // ensure non-empty basepath ends with "/" for proper matching and concatenation. if basePath != "" && basePath[len(basePath)-1] != '/' { basePath += "/" } diff --git a/gitrpc/internal/service/tag.go b/gitrpc/internal/service/tag.go index ab9929523..683b66154 100644 --- a/gitrpc/internal/service/tag.go +++ b/gitrpc/internal/service/tag.go @@ -5,11 +5,13 @@ package service import ( - "code.gitea.io/gitea/modules/git" "context" "fmt" + "github.com/harness/gitness/gitrpc/internal/types" "github.com/harness/gitness/gitrpc/rpc" + + "code.gitea.io/gitea/modules/git" "github.com/rs/zerolog/log" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -183,7 +185,10 @@ func listCommitTagsWalkReferencesHandler(tags *[]*rpc.CommitTag) types.WalkRefer return nil } } -func (s ReferenceService) CreateTag(ctx context.Context, createTagRequest *rpc.CreateTagRequest) (*rpc.CreateTagResponse, error) { +func (s ReferenceService) CreateTag( + ctx context.Context, + createTagRequest *rpc.CreateTagRequest, +) (*rpc.CreateTagResponse, error) { base := createTagRequest.GetBase() if base == nil { return nil, types.ErrBaseCannotBeEmpty @@ -233,8 +238,11 @@ func (s ReferenceService) CreateTag(ctx context.Context, createTagRequest *rpc.C return &rpc.CreateTagResponse{Tag: commitTag}, nil } -func (s ReferenceService) DeleteTag(ctx context.Context, deleteTagRequest *rpc.DeleteTagRequest) (*rpc.UpdateRefResponse, error) { - base := deleteTagRequest.GetBase() +func (s ReferenceService) DeleteTag( + ctx context.Context, + request *rpc.DeleteTagRequest, +) (*rpc.UpdateRefResponse, error) { + base := request.GetBase() if base == nil { return nil, types.ErrBaseCannotBeEmpty } @@ -256,17 +264,23 @@ func (s ReferenceService) DeleteTag(ctx context.Context, deleteTagRequest *rpc.D err = sharedRepo.Clone(ctx, "") if err != nil { - return nil, processGitErrorf(err, "failed to clone shared repo with tag '%s'", deleteTagRequest.GetTagName()) + return nil, processGitErrorf(err, "failed to clone shared repo with tag '%s'", request.GetTagName()) } - actor := deleteTagRequest.GetBase().GetActor() + actor := request.GetBase().GetActor() env := append(CreateEnvironmentForPush(ctx, base), "GIT_COMMITTER_NAME="+actor.GetName(), "GIT_COMMITTER_EMAIL="+actor.GetEmail(), ) - err = s.adapter.DeleteTag(ctx, repoPath, deleteTagRequest.TagName, env) - sharedRepo.PushDeleteBranch(ctx, base, "") + + err = s.adapter.DeleteTag(ctx, repoPath, request.TagName, env) if err != nil { - return nil, processGitErrorf(err, "Failed to delete the tag") + return nil, processGitErrorf(err, "Failed to delete the tag %s", request.GetTagName()) } + + err = sharedRepo.PushDeleteBranch(ctx, base, "") + if err != nil { + return nil, processGitErrorf(err, "failed to delete tag '%s' from remote repo", request.GetTagName()) + } + return &rpc.UpdateRefResponse{}, nil } diff --git a/gitrpc/mapping.go b/gitrpc/mapping.go index 2a5cf6fc1..f616148d2 100644 --- a/gitrpc/mapping.go +++ b/gitrpc/mapping.go @@ -208,7 +208,7 @@ func mapRPCTreeNodeType(t rpc.TreeNodeType) (TreeNodeType, error) { case rpc.TreeNodeType_TreeNodeTypeTree: return TreeNodeTypeTree, nil default: - return TreeNodeTypeBlob, fmt.Errorf("unkown rpc tree node type: %d", t) + return TreeNodeTypeBlob, fmt.Errorf("unknown rpc tree node type: %d", t) } } @@ -225,7 +225,7 @@ func mapRPCTreeNodeMode(m rpc.TreeNodeMode) (TreeNodeMode, error) { case rpc.TreeNodeMode_TreeNodeModeTree: return TreeNodeModeTree, nil default: - return TreeNodeModeFile, fmt.Errorf("unkown rpc tree node mode: %d", m) + return TreeNodeModeFile, fmt.Errorf("unknown rpc tree node mode: %d", m) } } diff --git a/gitrpc/server/cron/clean_slate_data.go b/gitrpc/server/cron/clean_slate_data.go index c1dd787bd..652cfce18 100644 --- a/gitrpc/server/cron/clean_slate_data.go +++ b/gitrpc/server/cron/clean_slate_data.go @@ -1,3 +1,7 @@ +// Copyright 2022 Harness Inc. All rights reserved. +// Use of this source code is governed by the Polyform Free Trial License +// that can be found in the LICENSE.md file for this repository. + package cron import ( @@ -7,10 +11,11 @@ import ( "path/filepath" "github.com/harness/gitness/gitrpc/server" + "github.com/rs/zerolog/log" ) -// cleanup repository graveyard +// cleanupRepoGraveyard cleanups repository graveyard. func cleanupRepoGraveyard(ctx context.Context, graveyardpath string) error { logger := log.Ctx(ctx) repolist, err := os.ReadDir(graveyardpath) @@ -32,7 +37,7 @@ func cleanupRepoGraveyard(ctx context.Context, graveyardpath string) error { return nil } -func AddAllGitRPCCronJobs(cm *CronManager, gitrpcconfig server.Config) error { +func AddAllGitRPCCronJobs(cm *Manager, gitrpcconfig server.Config) error { // periodic repository graveyard cleanup graveyardpath := filepath.Join(gitrpcconfig.GitRoot, server.ReposGraveyardSubdirName) err := cm.NewCronTask(Nightly, func(ctx context.Context) error { return cleanupRepoGraveyard(ctx, graveyardpath) }) diff --git a/gitrpc/server/cron/clean_slate_data_test.go b/gitrpc/server/cron/clean_slate_data_test.go index a76dacc3a..a9531a9a4 100644 --- a/gitrpc/server/cron/clean_slate_data_test.go +++ b/gitrpc/server/cron/clean_slate_data_test.go @@ -1,8 +1,11 @@ +// Copyright 2022 Harness Inc. All rights reserved. +// Use of this source code is governed by the Polyform Free Trial License +// that can be found in the LICENSE.md file for this repository. + package cron import ( "context" - "io/ioutil" "os" "testing" ) @@ -10,8 +13,8 @@ import ( func TestCleanupRepoGraveyardFunc(t *testing.T) { ctx := context.Background() tmpDir := t.TempDir() - //create a dummy repository - testRepo, _ := ioutil.TempDir(tmpDir, "TestRepo100") + // create a dummy repository + testRepo, _ := os.MkdirTemp(tmpDir, "TestRepo100") err := cleanupRepoGraveyard(ctx, tmpDir) if err != nil { t.Error("cleanupRepoGraveyard failed") diff --git a/gitrpc/server/cron/cronmanager.go b/gitrpc/server/cron/manager.go similarity index 68% rename from gitrpc/server/cron/cronmanager.go rename to gitrpc/server/cron/manager.go index 4bd76dbf7..9a4e36bd5 100644 --- a/gitrpc/server/cron/cronmanager.go +++ b/gitrpc/server/cron/manager.go @@ -1,3 +1,7 @@ +// Copyright 2022 Harness Inc. All rights reserved. +// Use of this source code is governed by the Polyform Free Trial License +// that can be found in the LICENSE.md file for this repository. + package cron import ( @@ -9,8 +13,8 @@ import ( "github.com/rs/zerolog/log" ) +// Format: seconds minute(0-59) hour(0-23) day of month(1-31) month(1-12) day of week(0-6). const ( - //Format: seconds minute(0-59) hour(0-23) day of month(1-31) month(1-12) day of week(0-6) Hourly = "0 0 * * * *" // once an hour at minute 0 Nightly = "0 0 0 * * *" // once a day at midnight Weekly = "0 0 0 * * 0" // once a week on Sun midnight @@ -18,25 +22,25 @@ const ( EverySecond = "* * * * * *" // every second (for testing) ) -var ErrFatal = errors.New("fatal error occured") +var ErrFatal = errors.New("fatal error occurred") -type CronManager struct { +type Manager struct { c *cron.Cron ctx context.Context cancel context.CancelFunc fatal chan error } -// options could be location, logger, etc. -func NewCronManager() *CronManager { - return &CronManager{ +// NewManager creates a cron manager. +func NewManager() *Manager { + return &Manager{ c: cron.New(cron.WithSeconds()), fatal: make(chan error), } } -// add a new func to cron job -func (c *CronManager) NewCronTask(sepc string, job func(ctx context.Context) error) error { +// NewCronTask adds a new func to cron job. +func (c *Manager) NewCronTask(sepc string, job func(ctx context.Context) error) error { _, err := c.c.AddFunc(sepc, func() { jerr := job(c.ctx) if jerr != nil { // check different severity of errors @@ -55,7 +59,7 @@ func (c *CronManager) NewCronTask(sepc string, job func(ctx context.Context) err } // Run the cron scheduler, or no-op if already running. -func (c *CronManager) Run(ctx context.Context) error { +func (c *Manager) Run(ctx context.Context) error { c.ctx, c.cancel = context.WithCancel(ctx) var err error go func() { @@ -63,7 +67,7 @@ func (c *CronManager) Run(ctx context.Context) error { case <-ctx.Done(): err = fmt.Errorf("context done: %w", ctx.Err()) case fErr := <-c.fatal: - err = fmt.Errorf("fatal error occured: %w", fErr) + err = fmt.Errorf("fatal error occurred: %w", fErr) } // stop scheduling of new jobs. diff --git a/gitrpc/server/cron/cronmanager_test.go b/gitrpc/server/cron/manager_test.go similarity index 82% rename from gitrpc/server/cron/cronmanager_test.go rename to gitrpc/server/cron/manager_test.go index 4fc22f311..1956aab0c 100644 --- a/gitrpc/server/cron/cronmanager_test.go +++ b/gitrpc/server/cron/manager_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 Harness Inc. All rights reserved. +// Use of this source code is governed by the Polyform Free Trial License +// that can be found in the LICENSE.md file for this repository. + package cron import ( @@ -8,7 +12,7 @@ import ( "time" ) -func run(cmngr *CronManager, ctx context.Context) chan error { +func run(ctx context.Context, cmngr *Manager) chan error { cron := make(chan error) go func() { cron <- cmngr.Run(ctx) @@ -17,14 +21,14 @@ func run(cmngr *CronManager, ctx context.Context) chan error { } func TestCronManagerFatalErr(t *testing.T) { - cmngr := NewCronManager() + cmngr := NewManager() ctx, cancel := context.WithCancel(context.Background()) defer cancel() _ = cmngr.NewCronTask(EverySecond, func(ctx context.Context) error { return fmt.Errorf("inner: %w", ErrFatal) }) select { - case ferr := <-run(cmngr, ctx): + case ferr := <-run(ctx, cmngr): if ferr == nil { t.Error("Cronmanager failed to receive fatal error") } @@ -34,14 +38,14 @@ func TestCronManagerFatalErr(t *testing.T) { } func TestCronManagerNonFatalErr(t *testing.T) { - cmngr := NewCronManager() + cmngr := NewManager() ctx, cancel := context.WithCancel(context.Background()) defer cancel() _ = cmngr.NewCronTask(EverySecond, func(ctx context.Context) error { return errors.New("dummy error") }) select { - case ferr := <-run(cmngr, ctx): + case ferr := <-run(ctx, cmngr): if ferr != nil { t.Error("Cronmanager failed at a non fatal error") } @@ -50,7 +54,7 @@ func TestCronManagerNonFatalErr(t *testing.T) { } } func TestCronManagerNewTask(t *testing.T) { - cmngr := NewCronManager() + cmngr := NewManager() ctx, cancel := context.WithCancel(context.Background()) defer cancel() a := 0 @@ -61,7 +65,7 @@ func TestCronManagerNewTask(t *testing.T) { }) select { - case cerr := <-run(cmngr, ctx): + case cerr := <-run(ctx, cmngr): if cerr != nil { t.Error("Cronmanager failed at Run:", cerr) } @@ -73,7 +77,7 @@ func TestCronManagerNewTask(t *testing.T) { } func TestCronManagerStopOnCtxCancel(t *testing.T) { - cmngr := NewCronManager() + cmngr := NewManager() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() @@ -88,7 +92,7 @@ func TestCronManagerStopOnCtxCancel(t *testing.T) { } func TestCronManagerStopOnCtxTimeout(t *testing.T) { - cmngr := NewCronManager() + cmngr := NewManager() ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() diff --git a/gitrpc/server/cron/wire.go b/gitrpc/server/cron/wire.go index 586007702..204244c0e 100644 --- a/gitrpc/server/cron/wire.go +++ b/gitrpc/server/cron/wire.go @@ -1,15 +1,20 @@ +// Copyright 2022 Harness Inc. All rights reserved. +// Use of this source code is governed by the Polyform Free Trial License +// that can be found in the LICENSE.md file for this repository. + package cron import ( - "github.com/google/wire" "github.com/harness/gitness/gitrpc/server" + + "github.com/google/wire" ) // WireSet provides a wire set for this package. -var WireSet = wire.NewSet(ProvideCronManager) +var WireSet = wire.NewSet(ProvideManager) -func ProvideCronManager(gitrpcconfig server.Config) *CronManager { - cmngr := NewCronManager() +func ProvideManager(gitrpcconfig server.Config) *Manager { + cmngr := NewManager() _ = AddAllGitRPCCronJobs(cmngr, gitrpcconfig) return cmngr } diff --git a/gitrpc/tag.go b/gitrpc/tag.go index c534f5aa3..738419f4b 100644 --- a/gitrpc/tag.go +++ b/gitrpc/tag.go @@ -60,13 +60,13 @@ func (p *CreateTagParams) Validate() error { } if p.Name == "" { - return errors.New("Tag name cannot be empty") + return errors.New("tag name cannot be empty") } if p.SHA == "" { - return errors.New("Target cannot be empty") + return errors.New("target cannot be empty") } if p.Message == "" { - return errors.New("Message cannot be empty") + return errors.New("message cannot be empty") } return nil } @@ -140,7 +140,6 @@ func (c *Client) ListCommitTags(ctx context.Context, params *ListCommitTagsParam return output, nil } func (c *Client) CreateTag(ctx context.Context, params *CreateTagParams) (*CreateTagOutput, error) { - err := params.Validate() if err != nil { @@ -167,11 +166,9 @@ func (c *Client) CreateTag(ctx context.Context, params *CreateTagParams) (*Creat return &CreateTagOutput{ CommitTag: *commitTag, }, nil - } func (c *Client) DeleteTag(ctx context.Context, params *DeleteTagParams) error { - err := params.Validate() if err != nil { diff --git a/internal/api/controller/pullreq/comment_status.go b/internal/api/controller/pullreq/comment_status.go index baceb0786..ee57577f4 100644 --- a/internal/api/controller/pullreq/comment_status.go +++ b/internal/api/controller/pullreq/comment_status.go @@ -64,7 +64,7 @@ func (c *Controller) CommentStatus( return errValidate } - act, err = c.getCommentCheckChangeStatusAccess(ctx, session, pr, commentID) + act, err = c.getCommentCheckChangeStatusAccess(ctx, pr, commentID) if err != nil { return fmt.Errorf("failed to get comment: %w", err) } diff --git a/internal/api/controller/pullreq/controller.go b/internal/api/controller/pullreq/controller.go index 8209c1f82..0f6cd3658 100644 --- a/internal/api/controller/pullreq/controller.go +++ b/internal/api/controller/pullreq/controller.go @@ -122,7 +122,7 @@ func (c *Controller) getRepoCheckAccess(ctx context.Context, } func (c *Controller) getCommentCheckModifyAccess(ctx context.Context, - session *auth.Session, pr *types.PullReq, commentID int64, + pr *types.PullReq, commentID int64, ) (*types.PullReqActivity, error) { if commentID <= 0 { return nil, usererror.BadRequest("A valid comment ID must be provided.") @@ -155,7 +155,7 @@ func (c *Controller) getCommentCheckModifyAccess(ctx context.Context, func (c *Controller) getCommentCheckEditAccess(ctx context.Context, session *auth.Session, pr *types.PullReq, commentID int64, ) (*types.PullReqActivity, error) { - comment, err := c.getCommentCheckModifyAccess(ctx, session, pr, commentID) + comment, err := c.getCommentCheckModifyAccess(ctx, pr, commentID) if err != nil { return nil, err } @@ -168,9 +168,9 @@ func (c *Controller) getCommentCheckEditAccess(ctx context.Context, } func (c *Controller) getCommentCheckChangeStatusAccess(ctx context.Context, - session *auth.Session, pr *types.PullReq, commentID int64, + pr *types.PullReq, commentID int64, ) (*types.PullReqActivity, error) { - comment, err := c.getCommentCheckModifyAccess(ctx, session, pr, commentID) + comment, err := c.getCommentCheckModifyAccess(ctx, pr, commentID) if err != nil { return nil, err } diff --git a/internal/api/controller/pullreq/merge.go b/internal/api/controller/pullreq/merge.go index 9f5cdb22c..d96f43436 100644 --- a/internal/api/controller/pullreq/merge.go +++ b/internal/api/controller/pullreq/merge.go @@ -29,7 +29,7 @@ type MergeInput struct { // Merge merges the pull request. // -//nolint:funlen // no need to refactor +//nolint:gocognit func (c *Controller) Merge( ctx context.Context, session *auth.Session, @@ -84,11 +84,15 @@ func (c *Controller) Merge( } if pr.UnresolvedCount > 0 { - return types.MergeResponse{}, usererror.BadRequest("Pull requests with unresolved comments can't be merged. Resolve all the comments first.") + return types.MergeResponse{}, usererror.BadRequest( + "Pull requests with unresolved comments can't be merged. Resolve all the comments first.", + ) } if pr.IsDraft { - return types.MergeResponse{}, usererror.BadRequest("Draft pull requests can't be merged. Clear the draft flag first.") + return types.MergeResponse{}, usererror.BadRequest( + "Draft pull requests can't be merged. Clear the draft flag first.", + ) } reviewers, err := c.reviewerStore.List(ctx, pr.ID) @@ -119,7 +123,12 @@ func (c *Controller) Merge( } // TODO: for forking merge title might be different? - mergeTitle := fmt.Sprintf("Merge branch '%s' of %s (#%d)", pr.SourceBranch, sourceRepo.Path, pr.Number) + var mergeTitle string + if in.Method == enum.MergeMethod(gitrpcenum.MergeMethodSquash) { + mergeTitle = fmt.Sprintf("%s (#%d)", pr.Title, pr.Number) + } else { + mergeTitle = fmt.Sprintf("Merge branch '%s' of %s (#%d)", pr.SourceBranch, sourceRepo.Path, pr.Number) + } var mergeOutput gitrpc.MergeOutput mergeOutput, err = c.gitRPCClient.Merge(ctx, &gitrpc.MergeParams{ diff --git a/internal/api/controller/pullreq/pr_create.go b/internal/api/controller/pullreq/pr_create.go index 7790cfcd4..7faae2982 100644 --- a/internal/api/controller/pullreq/pr_create.go +++ b/internal/api/controller/pullreq/pr_create.go @@ -83,12 +83,16 @@ func (c *Controller) Create( mergeBaseSHA := mergeBaseResult.MergeBaseSHA + if mergeBaseSHA == sourceSHA { + return nil, usererror.BadRequest("The source branch doesn't contain any new commits") + } + targetRepo, err = c.repoStore.UpdateOptLock(ctx, targetRepo, func(repo *types.Repository) error { repo.PullReqSeq++ return nil }) if err != nil { - return nil, fmt.Errorf("failed to aquire PullReqSeq number: %w", err) + return nil, fmt.Errorf("failed to acquire PullReqSeq number: %w", err) } pr := newPullReq(session, targetRepo.PullReqSeq, sourceRepo, targetRepo, in, sourceSHA, mergeBaseSHA) diff --git a/internal/api/controller/repo/create_tag.go b/internal/api/controller/repo/create_tag.go index a8b2f7140..ebb0d9cbf 100644 --- a/internal/api/controller/repo/create_tag.go +++ b/internal/api/controller/repo/create_tag.go @@ -7,6 +7,7 @@ package repo import ( "context" "fmt" + "github.com/harness/gitness/gitrpc" apiauth "github.com/harness/gitness/internal/api/auth" "github.com/harness/gitness/internal/auth" @@ -57,7 +58,7 @@ func (c *Controller) CreateTag(ctx context.Context, session *auth.Session, commitTag, err := mapCommitTag(rpcOut.CommitTag) if err != nil { - return nil, fmt.Errorf("failed to map tag recieved from service output: %w", err) + return nil, fmt.Errorf("failed to map tag received from service output: %w", err) } return &commitTag, nil } diff --git a/internal/api/controller/repo/get_commit_divergences.go b/internal/api/controller/repo/get_commit_divergences.go index 7da5e3994..62925273a 100644 --- a/internal/api/controller/repo/get_commit_divergences.go +++ b/internal/api/controller/repo/get_commit_divergences.go @@ -27,7 +27,7 @@ type CommitDivergenceRequest struct { // From is the ref from which the counting of the diverging commits starts. From string `json:"from"` // To is the ref at which the counting of the diverging commits ends. - // If the value is empty the divergence is caluclated to the default branch of the repo. + // If the value is empty the divergence is calculated to the default branch of the repo. To string `json:"to"` } diff --git a/internal/api/controller/serviceaccount/delete.go b/internal/api/controller/serviceaccount/delete.go index 84b1c8985..5289e9a30 100644 --- a/internal/api/controller/serviceaccount/delete.go +++ b/internal/api/controller/serviceaccount/delete.go @@ -13,7 +13,7 @@ import ( "github.com/harness/gitness/types/enum" ) -// Delete deletes a sevice account. +// Delete deletes a service account. func (c *Controller) Delete(ctx context.Context, session *auth.Session, saUID string) error { sa, err := findServiceAccountFromUID(ctx, c.principalStore, saUID) diff --git a/internal/api/controller/serviceaccount/delete_token.go b/internal/api/controller/serviceaccount/delete_token.go index e2c0b1504..087cac545 100644 --- a/internal/api/controller/serviceaccount/delete_token.go +++ b/internal/api/controller/serviceaccount/delete_token.go @@ -15,7 +15,7 @@ import ( "github.com/rs/zerolog/log" ) -// DeleteToken deletes a token of a sevice account. +// DeleteToken deletes a token of a service account. func (c *Controller) DeleteToken(ctx context.Context, session *auth.Session, saUID string, tokenUID string) error { sa, err := findServiceAccountFromUID(ctx, c.principalStore, saUID) diff --git a/internal/api/controller/space/delete.go b/internal/api/controller/space/delete.go index 39e8ca28d..1b8f7d9a5 100644 --- a/internal/api/controller/space/delete.go +++ b/internal/api/controller/space/delete.go @@ -35,8 +35,13 @@ func (c *Controller) Delete(ctx context.Context, session *auth.Session, spaceRef } // DeleteNoAuth bypasses these permission -// PermissionSpaceDelete, PermissionSpaceView, PermissionRepoView, PermissionRepoDelete -func (c *Controller) DeleteNoAuth(ctx context.Context, session *auth.Session, spaceID int64, filter *types.SpaceFilter) error { +// PermissionSpaceDelete, PermissionSpaceView, PermissionRepoView, PermissionRepoDelete. +func (c *Controller) DeleteNoAuth( + ctx context.Context, + session *auth.Session, + spaceID int64, + filter *types.SpaceFilter, +) error { subSpaces, _, err := c.ListSpacesNoAuth(ctx, spaceID, filter) if err != nil { return fmt.Errorf("failed to list space %d sub spaces: %w", spaceID, err) diff --git a/internal/api/controller/space/delete_repositories.go b/internal/api/controller/space/delete_repositories.go index 8711c8af8..d3c8f0fcd 100644 --- a/internal/api/controller/space/delete_repositories.go +++ b/internal/api/controller/space/delete_repositories.go @@ -1,3 +1,7 @@ +// Copyright 2022 Harness Inc. All rights reserved. +// Use of this source code is governed by the Polyform Free Trial License +// that can be found in the LICENSE.md file for this repository. + package space import ( @@ -11,7 +15,7 @@ import ( ) // deleteRepositoriesNoAuth does not check PermissionRepoView, and PermissionRepoDelete permissions -// Call this through Delete(Space) api to make sure the caller has DeleteSpace permission +// Call this through Delete(Space) api to make sure the caller has DeleteSpace permission. func (c *Controller) deleteRepositoriesNoAuth(ctx context.Context, session *auth.Session, spaceID int64) error { filter := &types.RepoFilter{ Page: 1, diff --git a/internal/api/controller/space/list_repositories.go b/internal/api/controller/space/list_repositories.go index ba63f546d..9311ca501 100644 --- a/internal/api/controller/space/list_repositories.go +++ b/internal/api/controller/space/list_repositories.go @@ -26,11 +26,14 @@ func (c *Controller) ListRepositories(ctx context.Context, session *auth.Session return nil, 0, err } return c.ListRepositoriesNoAuth(ctx, space.ID, filter) - } // ListRepositoriesNoAuth list repositories WITHOUT checking for PermissionRepoView. -func (c *Controller) ListRepositoriesNoAuth(ctx context.Context, spaceID int64, filter *types.RepoFilter) ([]*types.Repository, int64, error) { +func (c *Controller) ListRepositoriesNoAuth( + ctx context.Context, + spaceID int64, + filter *types.RepoFilter, +) ([]*types.Repository, int64, error) { count, err := c.repoStore.Count(ctx, spaceID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to count child repos: %w", err) diff --git a/internal/api/controller/space/list_spaces.go b/internal/api/controller/space/list_spaces.go index 97e4b7220..2e2d7db83 100644 --- a/internal/api/controller/space/list_spaces.go +++ b/internal/api/controller/space/list_spaces.go @@ -29,7 +29,11 @@ func (c *Controller) ListSpaces(ctx context.Context, session *auth.Session, } // List spaces WITHOUT checking PermissionSpaceView. -func (c *Controller) ListSpacesNoAuth(ctx context.Context, spaceID int64, filter *types.SpaceFilter) ([]*types.Space, int64, error) { +func (c *Controller) ListSpacesNoAuth( + ctx context.Context, + spaceID int64, + filter *types.SpaceFilter, +) ([]*types.Space, int64, error) { count, err := c.spaceStore.Count(ctx, spaceID, filter) if err != nil { return nil, 0, fmt.Errorf("failed to count child spaces: %w", err) diff --git a/internal/api/controller/tx.go b/internal/api/controller/tx.go index b97e56063..38f2509d2 100644 --- a/internal/api/controller/tx.go +++ b/internal/api/controller/tx.go @@ -7,8 +7,10 @@ package controller import ( "context" "errors" + "github.com/harness/gitness/internal/store" "github.com/harness/gitness/internal/store/database/dbtx" + "github.com/jmoiron/sqlx" ) @@ -16,7 +18,7 @@ type TxOptionRetryCount int // TxOptLock runs the provided function inside a database transaction. If optimistic lock error occurs // during the operation, the function will retry the whole transaction again (to the maximum of 5 times, -// but this can be overridden by providing an additional TxOptionRetryCount option) +// but this can be overridden by providing an additional TxOptionRetryCount option). func TxOptLock(ctx context.Context, db *sqlx.DB, txFn func(ctx context.Context) error, diff --git a/internal/api/openapi/pullreq.go b/internal/api/openapi/pullreq.go index 14eff0e04..0b9817847 100644 --- a/internal/api/openapi/pullreq.go +++ b/internal/api/openapi/pullreq.go @@ -384,7 +384,7 @@ func pullReqOperations(reflector *openapi3.Reflector) { reviewerAdd.WithTags("pullreq") reviewerAdd.WithMapOfAnything(map[string]interface{}{"operationId": "reviewerAddPullReq"}) _ = reflector.SetRequest(&reviewerAdd, new(reviewerAddPullReqRequest), http.MethodPut) - _ = reflector.SetJSONResponse(&reviewerAdd, nil, http.StatusNoContent) + _ = reflector.SetJSONResponse(&reviewerAdd, new(types.PullReqReviewer), http.StatusOK) _ = reflector.SetJSONResponse(&reviewerAdd, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&reviewerAdd, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&reviewerAdd, new(usererror.Error), http.StatusUnauthorized) @@ -396,7 +396,7 @@ func pullReqOperations(reflector *openapi3.Reflector) { reviewerList.WithTags("pullreq") reviewerList.WithMapOfAnything(map[string]interface{}{"operationId": "reviewerListPullReq"}) _ = reflector.SetRequest(&reviewerList, new(reviewerListPullReqRequest), http.MethodGet) - _ = reflector.SetJSONResponse(&reviewerList, nil, http.StatusNoContent) + _ = reflector.SetJSONResponse(&reviewerList, new([]*types.PullReqReviewer), http.StatusOK) _ = reflector.SetJSONResponse(&reviewerList, new(usererror.Error), http.StatusBadRequest) _ = reflector.SetJSONResponse(&reviewerList, new(usererror.Error), http.StatusInternalServerError) _ = reflector.SetJSONResponse(&reviewerList, new(usererror.Error), http.StatusUnauthorized) diff --git a/internal/api/render/header.go b/internal/api/render/header.go index d0e300be0..319e45cc3 100644 --- a/internal/api/render/header.go +++ b/internal/api/render/header.go @@ -23,7 +23,7 @@ func Pagination(r *http.Request, w http.ResponseWriter, page, size, total int) { // Add information that doesn't require total PaginationNoTotal(r, w, page, size, page >= last) - // add information that requries total + // add information that requires total uri := getPaginationBaseURL(r, page, size) params := uri.Query() diff --git a/internal/api/usererror/usererror.go b/internal/api/usererror/usererror.go index 5b51cd83f..dc3026aa6 100644 --- a/internal/api/usererror/usererror.go +++ b/internal/api/usererror/usererror.go @@ -11,7 +11,7 @@ import ( var ( // ErrInternal is returned when an internal error occurred. - ErrInternal = New(http.StatusInternalServerError, "Internal error occured") + ErrInternal = New(http.StatusInternalServerError, "Internal error occurred") // ErrInvalidToken is returned when the api request token is invalid. ErrInvalidToken = New(http.StatusUnauthorized, "Invalid or missing token") diff --git a/internal/auth/authz/authz.go b/internal/auth/authz/authz.go index fb4409910..9695c4d17 100644 --- a/internal/auth/authz/authz.go +++ b/internal/auth/authz/authz.go @@ -26,7 +26,7 @@ type Authorizer interface { * Returns * (true, nil) - the action is permitted * (false, nil) - the action is not permitted - * (false, err) - an error occured while performing the permission check and the action should be denied + * (false, err) - an error occurred while performing the permission check and the action should be denied */ Check(ctx context.Context, session *auth.Session, @@ -40,7 +40,7 @@ type Authorizer interface { * Returns * (true, nil) - all requested actions are permitted * (false, nil) - at least one requested action is not permitted - * (false, err) - an error occured while performing the permission check and all actions should be denied + * (false, err) - an error occurred while performing the permission check and all actions should be denied */ CheckAll(ctx context.Context, session *auth.Session, diff --git a/internal/githook/cli.go b/internal/githook/cli.go index 7eeea5737..86b6cd72c 100644 --- a/internal/githook/cli.go +++ b/internal/githook/cli.go @@ -38,7 +38,7 @@ var ( ExecutionTimeout = 3 * time.Minute ) -// SanitizeArgsForGit sanitizes the command line arguments (os.Args) if the command indicates they are comming from git. +// SanitizeArgsForGit sanitizes the command line arguments (os.Args) if the command indicates they are coming from git. // Returns the santized args and true if the call comes from git, otherwise the original args are returned with false. func SanitizeArgsForGit(command string, args []string) ([]string, bool) { switch command { diff --git a/internal/githook/githook.go b/internal/githook/githook.go index 58d3d3990..fcff5187f 100644 --- a/internal/githook/githook.go +++ b/internal/githook/githook.go @@ -105,7 +105,7 @@ func (c *GitHook) PostReceive(ctx context.Context) error { func handleServerHookOutput(out *types.ServerHookOutput, err error) error { if err != nil { - return fmt.Errorf("an error occured when calling the server: %w", err) + return fmt.Errorf("an error occurred when calling the server: %w", err) } if out == nil { diff --git a/internal/router/api.go b/internal/router/api.go index 453736788..9747989cd 100644 --- a/internal/router/api.go +++ b/internal/router/api.go @@ -314,7 +314,7 @@ func SetupWebhook(r chi.Router, webhookCtrl *webhook.Controller) { func setupUser(r chi.Router, userCtrl *user.Controller) { r.Route("/user", func(r chi.Router) { - // enforce principial authenticated and it's a user + // enforce principal authenticated and it's a user r.Use(middlewareprincipal.RestrictTo(enum.PrincipalTypeUser)) r.Get("/", handleruser.HandleFind(userCtrl)) diff --git a/internal/services/webhook/trigger.go b/internal/services/webhook/trigger.go index 06ec33f3a..271c089fd 100644 --- a/internal/services/webhook/trigger.go +++ b/internal/services/webhook/trigger.go @@ -178,7 +178,7 @@ func (s *Service) executeWebhook(ctx context.Context, webhook *types.Webhook, tr TriggerType: triggerType, // for unexpected errors we don't retry - protect the system. User can retrigger manually (if body was set) Result: enum.WebhookExecutionResultFatalError, - Error: "An unknown error occured", + Error: "An unknown error occurred", } defer func(oCtx context.Context, start time.Time) { // set total execution time @@ -253,7 +253,7 @@ func (s *Service) executeWebhook(ctx context.Context, webhook *types.Webhook, tr case err != nil: // for all other errors we don't retry - protect the system. User can retrigger manually (if body was set) - tErr := fmt.Errorf("an error occured while sending the request: %w", err) + tErr := fmt.Errorf("an error occurred while sending the request: %w", err) execution.Error = tErr.Error() execution.Result = enum.WebhookExecutionResultFatalError return &execution, tErr @@ -298,7 +298,7 @@ func (s *Service) prepareHTTPRequest(ctx context.Context, execution *types.Webho err := json.NewEncoder(bBuff).Encode(body) if err != nil { // this is an internal issue, nothing the user can do - don't expose error details - execution.Error = "an error occured preparing the request body" + execution.Error = "an error occurred preparing the request body" execution.Result = enum.WebhookExecutionResultFatalError return nil, fmt.Errorf("failed to serialize body to json: %w", err) } @@ -380,7 +380,7 @@ func handleWebhookResponse(execution *types.WebhookExecution, resp *http.Respons var bodyRaw []byte bodyRaw, err = io.ReadAll(io.LimitReader(resp.Body, responseBodyBytesLimit)) if err != nil { - tErr := fmt.Errorf("an error occured while reading the response body: %w", err) + tErr := fmt.Errorf("an error occurred while reading the response body: %w", err) execution.Error = tErr.Error() execution.Result = enum.WebhookExecutionResultRetriableError return tErr diff --git a/internal/store/transformation.go b/internal/store/transformation.go index 43ecc6b87..9311dc95e 100644 --- a/internal/store/transformation.go +++ b/internal/store/transformation.go @@ -9,7 +9,7 @@ import ( ) // PrincipalUIDTransformation transforms a principalUID to a value that should be duplicate free. -// This allows us to simply switch between principalUIDs being case sensitive, insensitive or anything inbetween. +// This allows us to simply switch between principalUIDs being case sensitive, insensitive or anything in between. type PrincipalUIDTransformation func(uid string) (string, error) func ToLowerPrincipalUIDTransformation(uid string) (string, error) { @@ -17,7 +17,7 @@ func ToLowerPrincipalUIDTransformation(uid string) (string, error) { } // PathTransformation transforms a path to a value that should be duplicate free. -// This allows us to simply switch between paths being case sensitive, insensitive or anything inbetween. +// This allows us to simply switch between paths being case sensitive, insensitive or anything in between. type PathTransformation func(string) (string, error) func ToLowerPathTransformation(original string) (string, error) { diff --git a/mocks/gomock_reflect_975878678/prog.bin b/mocks/gomock_reflect_975878678/prog.bin deleted file mode 100755 index bc9e1b518..000000000 Binary files a/mocks/gomock_reflect_975878678/prog.bin and /dev/null differ diff --git a/mocks/gomock_reflect_975878678/prog.go b/mocks/gomock_reflect_975878678/prog.go deleted file mode 100644 index 5a6b6261a..000000000 --- a/mocks/gomock_reflect_975878678/prog.go +++ /dev/null @@ -1,70 +0,0 @@ - -package main - -import ( - "encoding/gob" - "flag" - "fmt" - "os" - "path" - "reflect" - - "github.com/golang/mock/mockgen/model" - - pkg_ "github.com/harness/gitness/internal/store" -) - -var output = flag.String("output", "", "The output file name, or empty to use stdout.") - -func main() { - flag.Parse() - - its := []struct{ - sym string - typ reflect.Type - }{ - - { "PrincipalStore", reflect.TypeOf((*pkg_.PrincipalStore)(nil)).Elem()}, - - { "SpaceStore", reflect.TypeOf((*pkg_.SpaceStore)(nil)).Elem()}, - - { "RepoStore", reflect.TypeOf((*pkg_.RepoStore)(nil)).Elem()}, - - } - pkg := &model.Package{ - // NOTE: This behaves contrary to documented behaviour if the - // package name is not the final component of the import path. - // The reflect package doesn't expose the package name, though. - Name: path.Base("github.com/harness/gitness/internal/store"), - } - - for _, it := range its { - intf, err := model.InterfaceFromInterfaceType(it.typ) - if err != nil { - fmt.Fprintf(os.Stderr, "Reflection: %v\n", err) - os.Exit(1) - } - intf.Name = it.sym - pkg.Interfaces = append(pkg.Interfaces, intf) - } - - outfile := os.Stdout - if len(*output) != 0 { - var err error - outfile, err = os.Create(*output) - if err != nil { - fmt.Fprintf(os.Stderr, "failed to open output file %q", *output) - } - defer func() { - if err := outfile.Close(); err != nil { - fmt.Fprintf(os.Stderr, "failed to close output file %q", *output) - os.Exit(1) - } - }() - } - - if err := gob.NewEncoder(outfile).Encode(pkg); err != nil { - fmt.Fprintf(os.Stderr, "gob encode: %v\n", err) - os.Exit(1) - } -} diff --git a/mocks/mock_client.go b/mocks/mock_client.go index 3216e04cb..fbd985bd4 100644 --- a/mocks/mock_client.go +++ b/mocks/mock_client.go @@ -8,9 +8,10 @@ import ( context "context" reflect "reflect" - gomock "github.com/golang/mock/gomock" user "github.com/harness/gitness/internal/api/controller/user" types "github.com/harness/gitness/types" + + gomock "github.com/golang/mock/gomock" ) // MockClient is a mock of Client interface. diff --git a/mocks/mock_store.go b/mocks/mock_store.go index 30b7ec550..8ad9973bf 100644 --- a/mocks/mock_store.go +++ b/mocks/mock_store.go @@ -8,9 +8,10 @@ import ( context "context" reflect "reflect" - gomock "github.com/golang/mock/gomock" types "github.com/harness/gitness/types" enum "github.com/harness/gitness/types/enum" + + gomock "github.com/golang/mock/gomock" ) // MockPrincipalStore is a mock of PrincipalStore interface. diff --git a/stream/options.go b/stream/options.go index 3a041f1c3..5b9b13d56 100644 --- a/stream/options.go +++ b/stream/options.go @@ -16,7 +16,7 @@ const ( // MaxMaxRetries is the max number of retries of a message for a single consumer group. MaxMaxRetries = 64 - // MinIdleTimeout is the minumum time that can be configured as idle timeout for a stream consumer. + // MinIdleTimeout is the minimum time that can be configured as idle timeout for a stream consumer. MinIdleTimeout = 5 * time.Second )