mirror of
https://github.com/harness/drone.git
synced 2025-05-05 15:32:56 +00:00
[maint] gitrpc package removed (#726)
This commit is contained in:
parent
bd5437515c
commit
67f560874d
@ -75,7 +75,7 @@ WORKDIR /app
|
||||
VOLUME /data
|
||||
|
||||
ENV XDG_CACHE_HOME /data
|
||||
ENV GITRPC_SERVER_GIT_ROOT /data
|
||||
ENV GITNESS_GIT_ROOT /data
|
||||
ENV GITNESS_DATABASE_DRIVER sqlite3
|
||||
ENV GITNESS_DATABASE_DATASOURCE /data/database.sqlite
|
||||
ENV GITNESS_METRIC_ENABLED=true
|
||||
|
11
Makefile
11
Makefile
@ -74,7 +74,7 @@ lint: tools generate # lint the golang code
|
||||
# the source file has changed.
|
||||
###############################################################################
|
||||
|
||||
generate: wire proto
|
||||
generate: wire
|
||||
@echo "Generated Code"
|
||||
|
||||
wire: cmd/gitness/wire_gen.go
|
||||
@ -85,15 +85,6 @@ force-wire: ## Force wire code generation
|
||||
cmd/gitness/wire_gen.go: cmd/gitness/wire.go
|
||||
@sh ./scripts/wire/gitness.sh
|
||||
|
||||
proto: ## generate proto files for gitrpc integration (and format, as we can't exclude it from being formatted easily)
|
||||
@protoc --proto_path=./gitrpc/proto \
|
||||
--go_out=./gitrpc/rpc \
|
||||
--go_opt=paths=source_relative \
|
||||
--go-grpc_out=./gitrpc/rpc \
|
||||
--go-grpc_opt=paths=source_relative \
|
||||
./gitrpc/proto/*.proto
|
||||
@goimports -w ./gitrpc/rpc
|
||||
|
||||
###############################################################################
|
||||
# Install Tools and deps
|
||||
#
|
||||
|
@ -24,7 +24,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -140,12 +140,12 @@ func (c *Controller) Report(
|
||||
return nil, errValidate
|
||||
}
|
||||
|
||||
if !gitrpc.ValidateCommitSHA(commitSHA) {
|
||||
if !git.ValidateCommitSHA(commitSHA) {
|
||||
return nil, usererror.BadRequest("invalid commit SHA provided")
|
||||
}
|
||||
|
||||
_, err = c.gitRPCClient.GetCommit(ctx, &gitrpc.GetCommitParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: repo.GitUID},
|
||||
_, err = c.git.GetCommit(ctx, &git.GetCommitParams{
|
||||
ReadParams: git.ReadParams{RepoUID: repo.GitUID},
|
||||
SHA: commitSHA,
|
||||
})
|
||||
if err != nil {
|
||||
|
@ -23,18 +23,18 @@ import (
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/auth/authz"
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
type Controller struct {
|
||||
tx dbtx.Transactor
|
||||
authorizer authz.Authorizer
|
||||
repoStore store.RepoStore
|
||||
checkStore store.CheckStore
|
||||
gitRPCClient gitrpc.Interface
|
||||
tx dbtx.Transactor
|
||||
authorizer authz.Authorizer
|
||||
repoStore store.RepoStore
|
||||
checkStore store.CheckStore
|
||||
git git.Interface
|
||||
}
|
||||
|
||||
func NewController(
|
||||
@ -42,14 +42,14 @@ func NewController(
|
||||
authorizer authz.Authorizer,
|
||||
repoStore store.RepoStore,
|
||||
checkStore store.CheckStore,
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
) *Controller {
|
||||
return &Controller{
|
||||
tx: tx,
|
||||
authorizer: authorizer,
|
||||
repoStore: repoStore,
|
||||
checkStore: checkStore,
|
||||
gitRPCClient: gitRPCClient,
|
||||
tx: tx,
|
||||
authorizer: authorizer,
|
||||
repoStore: repoStore,
|
||||
checkStore: checkStore,
|
||||
git: git,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -17,7 +17,7 @@ package check
|
||||
import (
|
||||
"github.com/harness/gitness/app/auth/authz"
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
|
||||
"github.com/google/wire"
|
||||
@ -33,7 +33,7 @@ func ProvideController(
|
||||
authorizer authz.Authorizer,
|
||||
repoStore store.RepoStore,
|
||||
checkStore store.CheckStore,
|
||||
rpcClient gitrpc.Interface,
|
||||
rpcClient git.Interface,
|
||||
) *Controller {
|
||||
return NewController(
|
||||
tx,
|
||||
|
@ -16,14 +16,14 @@ package pullreq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
events "github.com/harness/gitness/app/events/pullreq"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/store"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
@ -108,10 +108,8 @@ func (c *Controller) CommentCreate(
|
||||
|
||||
switch {
|
||||
case in.IsCodeComment():
|
||||
var cut gitrpc.DiffCutOutput
|
||||
|
||||
cut, err = c.gitRPCClient.DiffCut(ctx, &gitrpc.DiffCutParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: repo.GitUID},
|
||||
cut, err := c.git.DiffCut(ctx, &git.DiffCutParams{
|
||||
ReadParams: git.ReadParams{RepoUID: repo.GitUID},
|
||||
SourceCommitSHA: in.SourceCommitSHA,
|
||||
SourceBranch: pr.SourceBranch,
|
||||
TargetCommitSHA: in.TargetCommitSHA,
|
||||
@ -122,8 +120,8 @@ func (c *Controller) CommentCreate(
|
||||
LineEnd: in.LineEnd,
|
||||
LineEndNew: in.LineEndNew,
|
||||
})
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusNotFound || gitrpc.ErrorStatus(err) == gitrpc.StatusPathNotFound {
|
||||
return nil, usererror.BadRequest(gitrpc.ErrorMessage(err))
|
||||
if errors.AsStatus(err) == errors.StatusNotFound || errors.AsStatus(err) == errors.StatusPathNotFound {
|
||||
return nil, usererror.BadRequest(errors.Message(err))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -306,7 +304,7 @@ func getCommentActivity(session *auth.Session, pr *types.PullReq, in *CommentCre
|
||||
return act
|
||||
}
|
||||
|
||||
func setAsCodeComment(a *types.PullReqActivity, cut gitrpc.DiffCutOutput, path, sourceCommitSHA string) {
|
||||
func setAsCodeComment(a *types.PullReqActivity, cut git.DiffCutOutput, path, sourceCommitSHA string) {
|
||||
var falseBool bool
|
||||
a.Type = enum.PullReqActivityTypeCodeComment
|
||||
a.Kind = enum.PullReqActivityKindChangeComment
|
||||
|
@ -30,8 +30,9 @@ import (
|
||||
"github.com/harness/gitness/app/sse"
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
gitrpcenum "github.com/harness/gitness/gitrpc/enum"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
gitenum "github.com/harness/gitness/git/enum"
|
||||
"github.com/harness/gitness/lock"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
"github.com/harness/gitness/types"
|
||||
@ -52,7 +53,7 @@ type Controller struct {
|
||||
fileViewStore store.PullReqFileViewStore
|
||||
membershipStore store.MembershipStore
|
||||
checkStore store.CheckStore
|
||||
gitRPCClient gitrpc.Interface
|
||||
git git.Interface
|
||||
eventReporter *pullreqevents.Reporter
|
||||
mtxManager lock.MutexManager
|
||||
codeCommentMigrator *codecomments.Migrator
|
||||
@ -76,7 +77,7 @@ func NewController(
|
||||
fileViewStore store.PullReqFileViewStore,
|
||||
membershipStore store.MembershipStore,
|
||||
checkStore store.CheckStore,
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
eventReporter *pullreqevents.Reporter,
|
||||
mtxManager lock.MutexManager,
|
||||
codeCommentMigrator *codecomments.Migrator,
|
||||
@ -99,7 +100,7 @@ func NewController(
|
||||
fileViewStore: fileViewStore,
|
||||
membershipStore: membershipStore,
|
||||
checkStore: checkStore,
|
||||
gitRPCClient: gitRPCClient,
|
||||
git: git,
|
||||
codeCommentMigrator: codeCommentMigrator,
|
||||
eventReporter: eventReporter,
|
||||
mtxManager: mtxManager,
|
||||
@ -117,13 +118,13 @@ func (c *Controller) verifyBranchExistence(ctx context.Context,
|
||||
return "", usererror.BadRequest("branch name can't be empty")
|
||||
}
|
||||
|
||||
ref, err := c.gitRPCClient.GetRef(ctx,
|
||||
gitrpc.GetRefParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: repo.GitUID},
|
||||
ref, err := c.git.GetRef(ctx,
|
||||
git.GetRefParams{
|
||||
ReadParams: git.ReadParams{RepoUID: repo.GitUID},
|
||||
Name: branch,
|
||||
Type: gitrpcenum.RefTypeBranch,
|
||||
Type: gitenum.RefTypeBranch,
|
||||
})
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusNotFound {
|
||||
if errors.AsStatus(err) == errors.StatusNotFound {
|
||||
return "", usererror.BadRequest(
|
||||
fmt.Sprintf("branch %s does not exist in the repository %s", branch, repo.UID))
|
||||
}
|
||||
|
@ -21,7 +21,8 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -35,7 +36,7 @@ func (f *FileViewAddInput) Validate() error {
|
||||
if f.Path == "" {
|
||||
return usererror.BadRequest("path can't be empty")
|
||||
}
|
||||
if !gitrpc.ValidateCommitSHA(f.CommitSHA) {
|
||||
if !git.ValidateCommitSHA(f.CommitSHA) {
|
||||
return usererror.BadRequest("commit_sha is invalid")
|
||||
}
|
||||
|
||||
@ -72,17 +73,16 @@ func (c *Controller) FileViewAdd(
|
||||
}
|
||||
|
||||
// retrieve file from both provided SHA and mergeBaseSHA to validate user input
|
||||
// TODO: Add GITRPC call to get multiple tree nodes at once
|
||||
|
||||
inNode, err := c.gitRPCClient.GetTreeNode(ctx, &gitrpc.GetTreeNodeParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
inNode, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
GitREF: in.CommitSHA,
|
||||
Path: in.Path,
|
||||
IncludeLatestCommit: false,
|
||||
})
|
||||
if err != nil && gitrpc.ErrorStatus(err) != gitrpc.StatusPathNotFound {
|
||||
if err != nil && errors.AsStatus(err) != errors.StatusPathNotFound {
|
||||
return nil, fmt.Errorf(
|
||||
"failed to get tree node '%s' for provided sha '%s' from gitrpc: %w",
|
||||
"failed to get tree node '%s' for provided sha '%s': %w",
|
||||
in.Path,
|
||||
in.CommitSHA,
|
||||
err,
|
||||
@ -91,20 +91,20 @@ func (c *Controller) FileViewAdd(
|
||||
|
||||
// ensure provided path actually points to a blob or commit (submodule)
|
||||
if inNode != nil &&
|
||||
inNode.Node.Type != gitrpc.TreeNodeTypeBlob &&
|
||||
inNode.Node.Type != gitrpc.TreeNodeTypeCommit {
|
||||
inNode.Node.Type != git.TreeNodeTypeBlob &&
|
||||
inNode.Node.Type != git.TreeNodeTypeCommit {
|
||||
return nil, usererror.BadRequestf("Provided path '%s' doesn't point to a file.", in.Path)
|
||||
}
|
||||
|
||||
mergeBaseNode, err := c.gitRPCClient.GetTreeNode(ctx, &gitrpc.GetTreeNodeParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
mergeBaseNode, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
GitREF: pr.MergeBaseSHA,
|
||||
Path: in.Path,
|
||||
IncludeLatestCommit: false,
|
||||
})
|
||||
if err != nil && gitrpc.ErrorStatus(err) != gitrpc.StatusPathNotFound {
|
||||
if err != nil && errors.AsStatus(err) != errors.StatusPathNotFound {
|
||||
return nil, fmt.Errorf(
|
||||
"failed to get tree node '%s' for MergeBaseSHA '%s' from gitrpc: %w",
|
||||
"failed to get tree node '%s' for MergeBaseSHA '%s': %w",
|
||||
in.Path,
|
||||
pr.MergeBaseSHA,
|
||||
err,
|
||||
|
@ -15,12 +15,12 @@
|
||||
package pullreq
|
||||
|
||||
import (
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
)
|
||||
|
||||
func rpcIdentityFromPrincipal(p types.Principal) *gitrpc.Identity {
|
||||
return &gitrpc.Identity{
|
||||
func identityFromPrincipal(p types.Principal) *git.Identity {
|
||||
return &git.Identity{
|
||||
Name: p.DisplayName,
|
||||
Email: p.Email,
|
||||
}
|
||||
|
@ -16,7 +16,6 @@ package pullreq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@ -26,10 +25,11 @@ import (
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/bootstrap"
|
||||
pullreqevents "github.com/harness/gitness/app/events/pullreq"
|
||||
"github.com/harness/gitness/app/services/codeowners"
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
gitrpcenum "github.com/harness/gitness/gitrpc/enum"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
gitenum "github.com/harness/gitness/git/enum"
|
||||
gittypes "github.com/harness/gitness/git/types"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
|
||||
@ -172,7 +172,7 @@ func (c *Controller) Merge(
|
||||
|
||||
codeOwnerWithApproval, err := c.codeOwners.Evaluate(ctx, sourceRepo, pr, reviewers)
|
||||
// check for error and ignore if it is codeowners file not found else throw error
|
||||
if err != nil && !errors.Is(err, codeowners.ErrNotFound) {
|
||||
if err != nil && errors.AsStatus(err) != errors.StatusNotFound {
|
||||
return nil, nil, fmt.Errorf("CODEOWNERS evaluation failed: %w", err)
|
||||
}
|
||||
|
||||
@ -203,20 +203,20 @@ func (c *Controller) Merge(
|
||||
}
|
||||
|
||||
// TODO: This is a temporary solution. The changes needed for the proper implementation:
|
||||
// 1) GitRPC: Change the merge method to return SHAs (source/target/merge base) even in case of conflicts.
|
||||
// 1) Git: Change the merge method to return SHAs (source/target/merge base) even in case of conflicts.
|
||||
// 2) Event handler: Update target and merge base SHA in the event handler even in case of merge conflicts.
|
||||
// 3) Here: Update the pull request target and merge base SHA in the DB if merge check status is unchecked.
|
||||
// 4) Remove the recheck API.
|
||||
if pr.MergeCheckStatus == enum.MergeCheckStatusUnchecked {
|
||||
_, err = c.gitRPCClient.Merge(ctx, &gitrpc.MergeParams{
|
||||
_, err = c.git.Merge(ctx, &git.MergeParams{
|
||||
WriteParams: targetWriteParams,
|
||||
BaseBranch: pr.TargetBranch,
|
||||
HeadRepoUID: sourceRepo.GitUID,
|
||||
HeadBranch: pr.SourceBranch,
|
||||
HeadExpectedSHA: in.SourceSHA,
|
||||
})
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusNotMergeable {
|
||||
out.ConflictFiles = gitrpc.AsConflictFilesError(err)
|
||||
if cferr := gittypes.AsMergeConflictsError(err); cferr != nil {
|
||||
out.ConflictFiles = cferr.Files
|
||||
} else if err != nil {
|
||||
return nil, nil, fmt.Errorf("merge check execution failed: %w", err)
|
||||
}
|
||||
@ -231,34 +231,34 @@ func (c *Controller) Merge(
|
||||
|
||||
// TODO: for forking merge title might be different?
|
||||
var mergeTitle string
|
||||
if in.Method == enum.MergeMethod(gitrpcenum.MergeMethodSquash) {
|
||||
if in.Method == enum.MergeMethod(gitenum.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)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
var mergeOutput gitrpc.MergeOutput
|
||||
mergeOutput, err = c.gitRPCClient.Merge(ctx, &gitrpc.MergeParams{
|
||||
mergeOutput, err := c.git.Merge(ctx, &git.MergeParams{
|
||||
WriteParams: targetWriteParams,
|
||||
BaseBranch: pr.TargetBranch,
|
||||
HeadRepoUID: sourceRepo.GitUID,
|
||||
HeadBranch: pr.SourceBranch,
|
||||
Title: mergeTitle,
|
||||
Message: "",
|
||||
Committer: rpcIdentityFromPrincipal(bootstrap.NewSystemServiceSession().Principal),
|
||||
Committer: identityFromPrincipal(bootstrap.NewSystemServiceSession().Principal),
|
||||
CommitterDate: &now,
|
||||
Author: rpcIdentityFromPrincipal(session.Principal),
|
||||
Author: identityFromPrincipal(session.Principal),
|
||||
AuthorDate: &now,
|
||||
RefType: gitrpcenum.RefTypeBranch,
|
||||
RefType: gitenum.RefTypeBranch,
|
||||
RefName: pr.TargetBranch,
|
||||
HeadExpectedSHA: in.SourceSHA,
|
||||
Method: gitrpcenum.MergeMethod(in.Method),
|
||||
Method: gitenum.MergeMethod(in.Method),
|
||||
})
|
||||
if err != nil {
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusNotMergeable {
|
||||
if cf := gittypes.AsMergeConflictsError(err); cf != nil {
|
||||
//nolint: nilerr
|
||||
return nil, &types.MergeViolations{
|
||||
ConflictFiles: gitrpc.AsConflictFilesError(err),
|
||||
ConflictFiles: cf.Files,
|
||||
RuleViolations: violations,
|
||||
}, nil
|
||||
}
|
||||
@ -318,7 +318,7 @@ func (c *Controller) Merge(
|
||||
|
||||
var branchDeleted bool
|
||||
if ruleOut.DeleteSourceBranch {
|
||||
errDelete := c.gitRPCClient.DeleteBranch(ctx, &gitrpc.DeleteBranchParams{
|
||||
errDelete := c.git.DeleteBranch(ctx, &git.DeleteBranchParams{
|
||||
WriteParams: sourceWriteParams,
|
||||
BranchName: pr.SourceBranch,
|
||||
})
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -46,8 +46,8 @@ func (c *Controller) Commits(
|
||||
gitRef := pr.SourceSHA
|
||||
afterRef := pr.MergeBaseSHA
|
||||
|
||||
rpcOut, err := c.gitRPCClient.ListCommits(ctx, &gitrpc.ListCommitsParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
output, err := c.git.ListCommits(ctx, &git.ListCommitsParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
GitREF: gitRef,
|
||||
After: afterRef,
|
||||
Page: int32(filter.Page),
|
||||
@ -57,10 +57,10 @@ func (c *Controller) Commits(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
commits := make([]types.Commit, len(rpcOut.Commits))
|
||||
for i := range rpcOut.Commits {
|
||||
commits := make([]types.Commit, len(output.Commits))
|
||||
for i := range output.Commits {
|
||||
var commit *types.Commit
|
||||
commit, err = controller.MapCommit(&rpcOut.Commits[i])
|
||||
commit, err = controller.MapCommit(&output.Commits[i])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to map commit: %w", err)
|
||||
}
|
||||
|
@ -23,7 +23,7 @@ import (
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
pullreqevents "github.com/harness/gitness/app/events/pullreq"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
|
||||
@ -84,8 +84,8 @@ func (c *Controller) Create(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mergeBaseResult, err := c.gitRPCClient.MergeBase(ctx, gitrpc.MergeBaseParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: sourceRepo.GitUID},
|
||||
mergeBaseResult, err := c.git.MergeBase(ctx, git.MergeBaseParams{
|
||||
ReadParams: git.ReadParams{RepoUID: sourceRepo.GitUID},
|
||||
Ref1: in.SourceBranch,
|
||||
Ref2: in.TargetBranch,
|
||||
})
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -49,8 +49,8 @@ func (c *Controller) Find(
|
||||
headRef := pr.SourceSHA
|
||||
baseRef := pr.MergeBaseSHA
|
||||
|
||||
output, err := c.gitRPCClient.DiffStats(ctx, &gitrpc.DiffParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
output, err := c.git.DiffStats(ctx, &git.DiffParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
BaseRef: baseRef,
|
||||
HeadRef: headRef,
|
||||
})
|
||||
|
@ -23,7 +23,7 @@ import (
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
pullreqevents "github.com/harness/gitness/app/events/pullreq"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
|
||||
@ -120,10 +120,8 @@ func (c *Controller) State(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var mergeBaseResult gitrpc.MergeBaseOutput
|
||||
|
||||
mergeBaseResult, err = c.gitRPCClient.MergeBase(ctx, gitrpc.MergeBaseParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: sourceRepo.GitUID},
|
||||
mergeBaseResult, err := c.git.MergeBase(ctx, git.MergeBaseParams{
|
||||
ReadParams: git.ReadParams{RepoUID: sourceRepo.GitUID},
|
||||
Ref1: pr.SourceBranch,
|
||||
Ref2: pr.TargetBranch,
|
||||
})
|
||||
|
@ -22,7 +22,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/store"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
@ -79,8 +79,8 @@ func (c *Controller) ReviewSubmit(
|
||||
return nil, usererror.BadRequest("Can't submit review to own pull requests.")
|
||||
}
|
||||
|
||||
commit, err := c.gitRPCClient.GetCommit(ctx, &gitrpc.GetCommitParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: repo.GitUID},
|
||||
commit, err := c.git.GetCommit(ctx, &git.GetCommitParams{
|
||||
ReadParams: git.ReadParams{RepoUID: repo.GitUID},
|
||||
SHA: in.CommitSHA,
|
||||
})
|
||||
if err != nil {
|
||||
|
@ -24,7 +24,7 @@ import (
|
||||
"github.com/harness/gitness/app/sse"
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/lock"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
|
||||
@ -43,7 +43,7 @@ func ProvideController(tx dbtx.Transactor, urlProvider url.Provider, authorizer
|
||||
repoStore store.RepoStore, principalStore store.PrincipalStore,
|
||||
fileViewStore store.PullReqFileViewStore, membershipStore store.MembershipStore,
|
||||
checkStore store.CheckStore,
|
||||
rpcClient gitrpc.Interface, eventReporter *pullreqevents.Reporter,
|
||||
rpcClient git.Interface, eventReporter *pullreqevents.Reporter,
|
||||
mtxManager lock.MutexManager, codeCommentMigrator *codecomments.Migrator,
|
||||
pullreqService *pullreq.Service, ruleManager *protection.Manager, sseStreamer sse.Streamer,
|
||||
codeOwners *codeowners.Service,
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -29,7 +29,7 @@ func (c *Controller) Blame(ctx context.Context,
|
||||
session *auth.Session,
|
||||
repoRef, gitRef, path string,
|
||||
lineFrom, lineTo int,
|
||||
) (types.Stream[*gitrpc.BlamePart], error) {
|
||||
) (types.Stream[*git.BlamePart], error) {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return nil, usererror.BadRequest("File path needs to specified.")
|
||||
@ -48,9 +48,9 @@ func (c *Controller) Blame(ctx context.Context,
|
||||
gitRef = repo.DefaultBranch
|
||||
}
|
||||
|
||||
reader := gitrpc.NewStreamReader(
|
||||
c.gitRPCClient.Blame(ctx, &gitrpc.BlameParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
reader := git.NewStreamReader(
|
||||
c.git.Blame(ctx, &git.BlameParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
GitRef: gitRef,
|
||||
Path: path,
|
||||
LineFrom: lineFrom,
|
||||
|
@ -24,14 +24,15 @@ import (
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/bootstrap"
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
// CommitFileAction holds file operation data.
|
||||
type CommitFileAction struct {
|
||||
Action gitrpc.FileAction `json:"action"`
|
||||
Action git.FileAction `json:"action"`
|
||||
Path string `json:"path"`
|
||||
Payload string `json:"payload"`
|
||||
Encoding enum.ContentEncodingType `json:"encoding"`
|
||||
@ -94,14 +95,14 @@ func (c *Controller) CommitFiles(ctx context.Context,
|
||||
return types.CommitFilesResponse{}, violations, nil
|
||||
}
|
||||
|
||||
actions := make([]gitrpc.CommitFileAction, len(in.Actions))
|
||||
actions := make([]git.CommitFileAction, len(in.Actions))
|
||||
for i, action := range in.Actions {
|
||||
var rawPayload []byte
|
||||
switch action.Encoding {
|
||||
case enum.ContentEncodingTypeBase64:
|
||||
rawPayload, err = base64.StdEncoding.DecodeString(action.Payload)
|
||||
if err != nil {
|
||||
return types.CommitFilesResponse{}, nil, fmt.Errorf("failed to decode base64 payload: %w", err)
|
||||
return types.CommitFilesResponse{}, nil, errors.InvalidArgument("failed to decode base64 payload", err)
|
||||
}
|
||||
case enum.ContentEncodingTypeUTF8:
|
||||
fallthrough
|
||||
@ -110,7 +111,7 @@ func (c *Controller) CommitFiles(ctx context.Context,
|
||||
rawPayload = []byte(action.Payload)
|
||||
}
|
||||
|
||||
actions[i] = gitrpc.CommitFileAction{
|
||||
actions[i] = git.CommitFileAction{
|
||||
Action: action.Action,
|
||||
Path: action.Path,
|
||||
Payload: rawPayload,
|
||||
@ -125,16 +126,16 @@ func (c *Controller) CommitFiles(ctx context.Context,
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
commit, err := c.gitRPCClient.CommitFiles(ctx, &gitrpc.CommitFilesParams{
|
||||
commit, err := c.git.CommitFiles(ctx, &git.CommitFilesParams{
|
||||
WriteParams: writeParams,
|
||||
Title: in.Title,
|
||||
Message: in.Message,
|
||||
Branch: in.Branch,
|
||||
NewBranch: in.NewBranch,
|
||||
Actions: actions,
|
||||
Committer: rpcIdentityFromPrincipal(bootstrap.NewSystemServiceSession().Principal),
|
||||
Committer: identityFromPrincipal(bootstrap.NewSystemServiceSession().Principal),
|
||||
CommitterDate: &now,
|
||||
Author: rpcIdentityFromPrincipal(session.Principal),
|
||||
Author: identityFromPrincipal(session.Principal),
|
||||
AuthorDate: &now,
|
||||
})
|
||||
if err != nil {
|
||||
|
@ -22,7 +22,8 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -109,9 +110,9 @@ func (c *Controller) GetContent(ctx context.Context,
|
||||
}
|
||||
|
||||
// create read params once
|
||||
readParams := gitrpc.CreateRPCReadParams(repo)
|
||||
readParams := git.CreateReadParams(repo)
|
||||
|
||||
treeNodeOutput, err := c.gitRPCClient.GetTreeNode(ctx, &gitrpc.GetTreeNodeParams{
|
||||
treeNodeOutput, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
|
||||
ReadParams: readParams,
|
||||
GitREF: gitRef,
|
||||
Path: repoPath,
|
||||
@ -151,19 +152,18 @@ func (c *Controller) GetContent(ctx context.Context,
|
||||
}
|
||||
|
||||
func (c *Controller) getSubmoduleContent(ctx context.Context,
|
||||
readParams gitrpc.ReadParams,
|
||||
readParams git.ReadParams,
|
||||
gitRef string,
|
||||
repoPath string,
|
||||
commitSHA string,
|
||||
) (*SubmoduleContent, error) {
|
||||
output, err := c.gitRPCClient.GetSubmodule(ctx, &gitrpc.GetSubmoduleParams{
|
||||
output, err := c.git.GetSubmodule(ctx, &git.GetSubmoduleParams{
|
||||
ReadParams: readParams,
|
||||
GitREF: gitRef,
|
||||
Path: repoPath,
|
||||
})
|
||||
if err != nil {
|
||||
// TODO: handle not found error
|
||||
// This requires gitrpc to also return notfound though!
|
||||
return nil, fmt.Errorf("failed to get submodule: %w", err)
|
||||
}
|
||||
|
||||
@ -174,10 +174,10 @@ func (c *Controller) getSubmoduleContent(ctx context.Context,
|
||||
}
|
||||
|
||||
func (c *Controller) getFileContent(ctx context.Context,
|
||||
readParams gitrpc.ReadParams,
|
||||
readParams git.ReadParams,
|
||||
blobSHA string,
|
||||
) (*FileContent, error) {
|
||||
output, err := c.gitRPCClient.GetBlob(ctx, &gitrpc.GetBlobParams{
|
||||
output, err := c.git.GetBlob(ctx, &git.GetBlobParams{
|
||||
ReadParams: readParams,
|
||||
SHA: blobSHA,
|
||||
SizeLimit: maxGetContentFileSize,
|
||||
@ -200,17 +200,16 @@ func (c *Controller) getFileContent(ctx context.Context,
|
||||
}
|
||||
|
||||
func (c *Controller) getSymlinkContent(ctx context.Context,
|
||||
readParams gitrpc.ReadParams,
|
||||
readParams git.ReadParams,
|
||||
blobSHA string,
|
||||
) (*SymlinkContent, error) {
|
||||
output, err := c.gitRPCClient.GetBlob(ctx, &gitrpc.GetBlobParams{
|
||||
output, err := c.git.GetBlob(ctx, &git.GetBlobParams{
|
||||
ReadParams: readParams,
|
||||
SHA: blobSHA,
|
||||
SizeLimit: maxGetContentFileSize, // TODO: do we need to guard against too big symlinks?
|
||||
})
|
||||
if err != nil {
|
||||
// TODO: handle not found error
|
||||
// This requires gitrpc to also return notfound though!
|
||||
return nil, fmt.Errorf("failed to get symlink: %w", err)
|
||||
}
|
||||
|
||||
@ -226,12 +225,12 @@ func (c *Controller) getSymlinkContent(ctx context.Context,
|
||||
}
|
||||
|
||||
func (c *Controller) getDirContent(ctx context.Context,
|
||||
readParams gitrpc.ReadParams,
|
||||
readParams git.ReadParams,
|
||||
gitRef string,
|
||||
repoPath string,
|
||||
includeLatestCommit bool,
|
||||
) (*DirContent, error) {
|
||||
output, err := c.gitRPCClient.ListTreeNodes(ctx, &gitrpc.ListTreeNodeParams{
|
||||
output, err := c.git.ListTreeNodes(ctx, &git.ListTreeNodeParams{
|
||||
ReadParams: readParams,
|
||||
GitREF: gitRef,
|
||||
Path: repoPath,
|
||||
@ -239,7 +238,6 @@ func (c *Controller) getDirContent(ctx context.Context,
|
||||
})
|
||||
if err != nil {
|
||||
// TODO: handle not found error
|
||||
// This requires gitrpc to also return notfound though!
|
||||
return nil, fmt.Errorf("failed to get content of dir: %w", err)
|
||||
}
|
||||
|
||||
@ -256,7 +254,7 @@ func (c *Controller) getDirContent(ctx context.Context,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func mapToContentInfo(node gitrpc.TreeNode, commit *gitrpc.Commit, includeLatestCommit bool) (ContentInfo, error) {
|
||||
func mapToContentInfo(node git.TreeNode, commit *git.Commit, includeLatestCommit bool) (ContentInfo, error) {
|
||||
typ, err := mapNodeModeToContentType(node.Mode)
|
||||
if err != nil {
|
||||
return ContentInfo{}, err
|
||||
@ -280,17 +278,17 @@ func mapToContentInfo(node gitrpc.TreeNode, commit *gitrpc.Commit, includeLatest
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func mapNodeModeToContentType(m gitrpc.TreeNodeMode) (ContentType, error) {
|
||||
func mapNodeModeToContentType(m git.TreeNodeMode) (ContentType, error) {
|
||||
switch m {
|
||||
case gitrpc.TreeNodeModeFile, gitrpc.TreeNodeModeExec:
|
||||
case git.TreeNodeModeFile, git.TreeNodeModeExec:
|
||||
return ContentTypeFile, nil
|
||||
case gitrpc.TreeNodeModeSymlink:
|
||||
case git.TreeNodeModeSymlink:
|
||||
return ContentTypeSymlink, nil
|
||||
case gitrpc.TreeNodeModeCommit:
|
||||
case git.TreeNodeModeCommit:
|
||||
return ContentTypeSubmodule, nil
|
||||
case gitrpc.TreeNodeModeTree:
|
||||
case git.TreeNodeModeTree:
|
||||
return ContentTypeDir, nil
|
||||
default:
|
||||
return ContentTypeFile, fmt.Errorf("unsupported tree node mode '%s'", m)
|
||||
return ContentTypeFile, errors.Internal("unsupported tree node mode '%s'", m)
|
||||
}
|
||||
}
|
||||
|
@ -19,7 +19,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
@ -28,7 +28,7 @@ type PathsDetailsInput struct {
|
||||
}
|
||||
|
||||
type PathsDetailsOutput struct {
|
||||
Details []gitrpc.PathDetails `json:"details"`
|
||||
Details []git.PathDetails `json:"details"`
|
||||
}
|
||||
|
||||
// PathsDetails finds the additional info about the provided paths of the repo.
|
||||
@ -59,8 +59,8 @@ func (c *Controller) PathsDetails(ctx context.Context,
|
||||
gitRef = repo.DefaultBranch
|
||||
}
|
||||
|
||||
result, err := c.gitRPCClient.PathsDetails(ctx, gitrpc.PathsDetailsParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
result, err := c.git.PathsDetails(ctx, git.PathsDetailsParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
GitREF: gitRef,
|
||||
Paths: input.Paths,
|
||||
})
|
||||
|
@ -30,7 +30,7 @@ import (
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/check"
|
||||
@ -49,7 +49,7 @@ type Controller struct {
|
||||
principalStore store.PrincipalStore
|
||||
ruleStore store.RuleStore
|
||||
protectionManager *protection.Manager
|
||||
gitRPCClient gitrpc.Interface
|
||||
git git.Interface
|
||||
importer *importer.Repository
|
||||
codeOwners *codeowners.Service
|
||||
eventReporter *repoevents.Reporter
|
||||
@ -67,7 +67,7 @@ func NewController(
|
||||
principalStore store.PrincipalStore,
|
||||
ruleStore store.RuleStore,
|
||||
protectionManager *protection.Manager,
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
importer *importer.Repository,
|
||||
codeOwners *codeowners.Service,
|
||||
eventReporter *repoevents.Reporter,
|
||||
@ -84,7 +84,7 @@ func NewController(
|
||||
principalStore: principalStore,
|
||||
ruleStore: ruleStore,
|
||||
protectionManager: protectionManager,
|
||||
gitRPCClient: gitRPCClient,
|
||||
git: git,
|
||||
importer: importer,
|
||||
codeOwners: codeOwners,
|
||||
eventReporter: eventReporter,
|
||||
|
@ -26,7 +26,7 @@ import (
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/bootstrap"
|
||||
"github.com/harness/gitness/app/githook"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/resources"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/check"
|
||||
@ -64,9 +64,9 @@ func (c *Controller) Create(ctx context.Context, session *auth.Session, in *Crea
|
||||
return nil, fmt.Errorf("failed to sanitize input: %w", err)
|
||||
}
|
||||
|
||||
gitRPCResp, err := c.createGitRPCRepository(ctx, session, in)
|
||||
gitResp, err := c.createGitRepository(ctx, session, in)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creating repository on GitRPC: %w", err)
|
||||
return nil, fmt.Errorf("error creating repository on git: %w", err)
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
@ -74,7 +74,7 @@ func (c *Controller) Create(ctx context.Context, session *auth.Session, in *Crea
|
||||
Version: 0,
|
||||
ParentID: parentSpace.ID,
|
||||
UID: in.UID,
|
||||
GitUID: gitRPCResp.UID,
|
||||
GitUID: gitResp.UID,
|
||||
Description: in.Description,
|
||||
IsPublic: in.IsPublic,
|
||||
CreatedBy: session.Principal.ID,
|
||||
@ -85,8 +85,8 @@ func (c *Controller) Create(ctx context.Context, session *auth.Session, in *Crea
|
||||
}
|
||||
err = c.repoStore.Create(ctx, repo)
|
||||
if err != nil {
|
||||
if dErr := c.deleteGitRPCRepository(ctx, session, repo); dErr != nil {
|
||||
log.Ctx(ctx).Warn().Err(dErr).Msg("gitrpc failed to delete repo for cleanup")
|
||||
if dErr := c.deleteGitRepository(ctx, session, repo); dErr != nil {
|
||||
log.Ctx(ctx).Warn().Err(dErr).Msg("failed to delete repo for cleanup")
|
||||
}
|
||||
return nil, fmt.Errorf("failed to create repository in storage: %w", err)
|
||||
}
|
||||
@ -143,16 +143,16 @@ func (c *Controller) sanitizeCreateInput(in *CreateInput) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) createGitRPCRepository(ctx context.Context, session *auth.Session,
|
||||
in *CreateInput) (*gitrpc.CreateRepositoryOutput, error) {
|
||||
func (c *Controller) createGitRepository(ctx context.Context, session *auth.Session,
|
||||
in *CreateInput) (*git.CreateRepositoryOutput, error) {
|
||||
var (
|
||||
err error
|
||||
content []byte
|
||||
)
|
||||
files := make([]gitrpc.File, 0, 3) // readme, gitignore, licence
|
||||
files := make([]git.File, 0, 3) // readme, gitignore, licence
|
||||
if in.Readme {
|
||||
content = createReadme(in.UID, in.Description)
|
||||
files = append(files, gitrpc.File{
|
||||
files = append(files, git.File{
|
||||
Path: "README.md",
|
||||
Content: content,
|
||||
})
|
||||
@ -162,7 +162,7 @@ func (c *Controller) createGitRPCRepository(ctx context.Context, session *auth.S
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read license '%s': %w", in.License, err)
|
||||
}
|
||||
files = append(files, gitrpc.File{
|
||||
files = append(files, git.File{
|
||||
Path: "LICENSE",
|
||||
Content: content,
|
||||
})
|
||||
@ -172,7 +172,7 @@ func (c *Controller) createGitRPCRepository(ctx context.Context, session *auth.S
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read git ignore '%s': %w", in.GitIgnore, err)
|
||||
}
|
||||
files = append(files, gitrpc.File{
|
||||
files = append(files, git.File{
|
||||
Path: ".gitignore",
|
||||
Content: content,
|
||||
})
|
||||
@ -191,10 +191,10 @@ func (c *Controller) createGitRPCRepository(ctx context.Context, session *auth.S
|
||||
return nil, fmt.Errorf("failed to generate git hook environment variables: %w", err)
|
||||
}
|
||||
|
||||
actor := rpcIdentityFromPrincipal(session.Principal)
|
||||
committer := rpcIdentityFromPrincipal(bootstrap.NewSystemServiceSession().Principal)
|
||||
actor := identityFromPrincipal(session.Principal)
|
||||
committer := identityFromPrincipal(bootstrap.NewSystemServiceSession().Principal)
|
||||
now := time.Now()
|
||||
resp, err := c.gitRPCClient.CreateRepository(ctx, &gitrpc.CreateRepositoryParams{
|
||||
resp, err := c.git.CreateRepository(ctx, &git.CreateRepositoryParams{
|
||||
Actor: *actor,
|
||||
EnvVars: envVars,
|
||||
DefaultBranch: in.DefaultBranch,
|
||||
@ -205,7 +205,7 @@ func (c *Controller) createGitRPCRepository(ctx context.Context, session *auth.S
|
||||
CommitterDate: &now,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create repo on gitrpc: %w", err)
|
||||
return nil, fmt.Errorf("failed to create repo on: %w", err)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
@ -220,8 +220,8 @@ func createReadme(name, description string) []byte {
|
||||
return content.Bytes()
|
||||
}
|
||||
|
||||
func rpcIdentityFromPrincipal(p types.Principal) *gitrpc.Identity {
|
||||
return &gitrpc.Identity{
|
||||
func identityFromPrincipal(p types.Principal) *git.Identity {
|
||||
return &git.Identity{
|
||||
Name: p.DisplayName,
|
||||
Email: p.Email,
|
||||
}
|
||||
|
@ -21,7 +21,7 @@ import (
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -77,7 +77,7 @@ func (c *Controller) CreateBranch(ctx context.Context,
|
||||
return nil, nil, fmt.Errorf("failed to create RPC write params: %w", err)
|
||||
}
|
||||
|
||||
rpcOut, err := c.gitRPCClient.CreateBranch(ctx, &gitrpc.CreateBranchParams{
|
||||
rpcOut, err := c.git.CreateBranch(ctx, &git.CreateBranchParams{
|
||||
WriteParams: writeParams,
|
||||
BranchName: in.Name,
|
||||
Target: in.Target,
|
||||
|
@ -22,7 +22,7 @@ import (
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -82,12 +82,12 @@ func (c *Controller) CreateCommitTag(ctx context.Context,
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
rpcOut, err := c.gitRPCClient.CreateCommitTag(ctx, &gitrpc.CreateCommitTagParams{
|
||||
rpcOut, err := c.git.CreateCommitTag(ctx, &git.CreateCommitTagParams{
|
||||
WriteParams: writeParams,
|
||||
Name: in.Name,
|
||||
Target: in.Target,
|
||||
Message: in.Message,
|
||||
Tagger: rpcIdentityFromPrincipal(session.Principal),
|
||||
Tagger: identityFromPrincipal(session.Principal),
|
||||
TaggerDate: &now,
|
||||
})
|
||||
if err != nil {
|
||||
|
@ -22,7 +22,8 @@ import (
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
repoevents "github.com/harness/gitness/app/events/repo"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
|
||||
@ -56,7 +57,7 @@ func (c *Controller) Delete(ctx context.Context, session *auth.Session, repoRef
|
||||
}
|
||||
|
||||
func (c *Controller) DeleteNoAuth(ctx context.Context, session *auth.Session, repo *types.Repository) error {
|
||||
if err := c.deleteGitRPCRepository(ctx, session, repo); err != nil {
|
||||
if err := c.deleteGitRepository(ctx, session, repo); err != nil {
|
||||
return fmt.Errorf("failed to delete git repository: %w", err)
|
||||
}
|
||||
|
||||
@ -73,7 +74,7 @@ func (c *Controller) DeleteNoAuth(ctx context.Context, session *auth.Session, re
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) deleteGitRPCRepository(
|
||||
func (c *Controller) deleteGitRepository(
|
||||
ctx context.Context,
|
||||
session *auth.Session,
|
||||
repo *types.Repository,
|
||||
@ -83,16 +84,16 @@ func (c *Controller) deleteGitRPCRepository(
|
||||
return fmt.Errorf("failed to create RPC write params: %w", err)
|
||||
}
|
||||
|
||||
err = c.gitRPCClient.DeleteRepository(ctx, &gitrpc.DeleteRepositoryParams{
|
||||
err = c.git.DeleteRepository(ctx, &git.DeleteRepositoryParams{
|
||||
WriteParams: writeParams,
|
||||
})
|
||||
|
||||
// deletion should not fail if dir does not exist in repos dir
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusNotFound {
|
||||
log.Ctx(ctx).Warn().Msgf("gitrpc repo %s does not exist", repo.GitUID)
|
||||
if errors.AsStatus(err) == errors.StatusNotFound {
|
||||
log.Ctx(ctx).Warn().Msgf("repo %s does not exist", repo.GitUID)
|
||||
} else if err != nil {
|
||||
// deletion has failed before removing(rename) the repo dir
|
||||
return fmt.Errorf("gitrpc failed to delete repo %s: %w", repo.GitUID, err)
|
||||
return fmt.Errorf("failed to delete repo %s: %w", repo.GitUID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -22,7 +22,7 @@ import (
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -72,7 +72,7 @@ func (c *Controller) DeleteBranch(ctx context.Context,
|
||||
return nil, fmt.Errorf("failed to create RPC write params: %w", err)
|
||||
}
|
||||
|
||||
err = c.gitRPCClient.DeleteBranch(ctx, &gitrpc.DeleteBranchParams{
|
||||
err = c.git.DeleteBranch(ctx, &git.DeleteBranchParams{
|
||||
WriteParams: writeParams,
|
||||
BranchName: branchName,
|
||||
})
|
||||
|
@ -21,7 +21,7 @@ import (
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -63,7 +63,7 @@ func (c *Controller) DeleteTag(ctx context.Context,
|
||||
return nil, fmt.Errorf("failed to create RPC write params: %w", err)
|
||||
}
|
||||
|
||||
err = c.gitRPCClient.DeleteTag(ctx, &gitrpc.DeleteTagParams{
|
||||
err = c.git.DeleteTag(ctx, &git.DeleteTagParams{
|
||||
Name: tagName,
|
||||
WriteParams: writeParams,
|
||||
})
|
||||
|
@ -22,7 +22,7 @@ import (
|
||||
apiauth "github.com/harness/gitness/app/api/auth"
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -44,8 +44,8 @@ func (c *Controller) RawDiff(
|
||||
return err
|
||||
}
|
||||
|
||||
return c.gitRPCClient.RawDiff(ctx, &gitrpc.DiffParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
return c.git.RawDiff(ctx, &git.DiffParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
BaseRef: info.BaseRef,
|
||||
HeadRef: info.HeadRef,
|
||||
MergeBase: info.MergeBase,
|
||||
@ -64,8 +64,8 @@ func (c *Controller) CommitDiff(
|
||||
return err
|
||||
}
|
||||
|
||||
return c.gitRPCClient.CommitDiff(ctx, &gitrpc.GetCommitParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
return c.git.CommitDiff(ctx, &git.GetCommitParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
SHA: sha,
|
||||
}, w)
|
||||
}
|
||||
@ -111,8 +111,8 @@ func (c *Controller) DiffStats(
|
||||
return types.DiffStats{}, err
|
||||
}
|
||||
|
||||
output, err := c.gitRPCClient.DiffStats(ctx, &gitrpc.DiffParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
output, err := c.git.DiffStats(ctx, &git.DiffParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
BaseRef: info.BaseRef,
|
||||
HeadRef: info.HeadRef,
|
||||
MergeBase: info.MergeBase,
|
||||
@ -133,7 +133,7 @@ func (c *Controller) Diff(
|
||||
repoRef string,
|
||||
path string,
|
||||
includePatch bool,
|
||||
) (types.Stream[*gitrpc.FileDiff], error) {
|
||||
) (types.Stream[*git.FileDiff], error) {
|
||||
repo, err := c.repoStore.FindByRef(ctx, repoRef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -148,8 +148,8 @@ func (c *Controller) Diff(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reader := gitrpc.NewStreamReader(c.gitRPCClient.Diff(ctx, &gitrpc.DiffParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
reader := git.NewStreamReader(c.git.Diff(ctx, &git.DiffParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
BaseRef: info.BaseRef,
|
||||
HeadRef: info.HeadRef,
|
||||
MergeBase: info.MergeBase,
|
||||
|
@ -19,7 +19,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
@ -34,12 +34,12 @@ func (c *Controller) GetBranch(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rpcOut, err := c.gitRPCClient.GetBranch(ctx, &gitrpc.GetBranchParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
rpcOut, err := c.git.GetBranch(ctx, &git.GetBranchParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
BranchName: branchName,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get branch from gitrpc: %w", err)
|
||||
return nil, fmt.Errorf("failed to get branch: %w", err)
|
||||
}
|
||||
|
||||
branch, err := mapBranch(rpcOut.Branch)
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -36,12 +36,12 @@ func (c *Controller) GetCommit(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rpcOut, err := c.gitRPCClient.GetCommit(ctx, &gitrpc.GetCommitParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
rpcOut, err := c.git.GetCommit(ctx, &git.GetCommitParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
SHA: sha,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get commit from gitrpc: %w", err)
|
||||
return nil, fmt.Errorf("failed to get commit: %w", err)
|
||||
}
|
||||
|
||||
rpcCommit := rpcOut.Commit
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
"github.com/harness/gitness/app/api/request"
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
@ -70,10 +70,10 @@ func (c *Controller) GetCommitDivergences(ctx context.Context,
|
||||
}
|
||||
|
||||
// map to rpc params
|
||||
options := &gitrpc.GetCommitDivergencesParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
options := &git.GetCommitDivergencesParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
MaxCount: in.MaxCount,
|
||||
Requests: make([]gitrpc.CommitDivergenceRequest, len(in.Requests)),
|
||||
Requests: make([]git.CommitDivergenceRequest, len(in.Requests)),
|
||||
}
|
||||
for i := range in.Requests {
|
||||
options.Requests[i].From = in.Requests[i].From
|
||||
@ -85,7 +85,7 @@ func (c *Controller) GetCommitDivergences(ctx context.Context,
|
||||
}
|
||||
|
||||
// TODO: We should cache the responses as times can reach multiple seconds
|
||||
rpcOutput, err := c.gitRPCClient.GetCommitDivergences(ctx, options)
|
||||
rpcOutput, err := c.git.GetCommitDivergences(ctx, options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
"io"
|
||||
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
@ -38,14 +38,14 @@ func (c *Controller) GitInfoRefs(
|
||||
return fmt.Errorf("failed to verify repo access: %w", err)
|
||||
}
|
||||
|
||||
if err = c.gitRPCClient.GetInfoRefs(ctx, w, &gitrpc.InfoRefsParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
// TODO: gitrpc shouldn't take a random string here, but instead have accepted enum values.
|
||||
if err = c.git.GetInfoRefs(ctx, w, &git.InfoRefsParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
// TODO: git shouldn't take a random string here, but instead have accepted enum values.
|
||||
Service: string(service),
|
||||
Options: nil,
|
||||
GitProtocol: gitProtocol,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("failed GetInfoRefs on gitrpc: %w", err)
|
||||
return fmt.Errorf("failed GetInfoRefs on git: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
@ -21,7 +21,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
@ -48,8 +48,8 @@ func (c *Controller) GitServicePack(
|
||||
return fmt.Errorf("failed to verify repo access: %w", err)
|
||||
}
|
||||
|
||||
params := &gitrpc.ServicePackParams{
|
||||
// TODO: gitrpc shouldn't take a random string here, but instead have accepted enum values.
|
||||
params := &git.ServicePackParams{
|
||||
// TODO: git shouldn't take a random string here, but instead have accepted enum values.
|
||||
Service: string(service),
|
||||
Data: r,
|
||||
Options: nil,
|
||||
@ -58,19 +58,19 @@ func (c *Controller) GitServicePack(
|
||||
|
||||
// setup read/writeparams depending on whether it's a write operation
|
||||
if isWriteOperation {
|
||||
var writeParams gitrpc.WriteParams
|
||||
var writeParams git.WriteParams
|
||||
writeParams, err = controller.CreateRPCExternalWriteParams(ctx, c.urlProvider, session, repo)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create RPC write params: %w", err)
|
||||
}
|
||||
params.WriteParams = &writeParams
|
||||
} else {
|
||||
readParams := gitrpc.CreateRPCReadParams(repo)
|
||||
readParams := git.CreateReadParams(repo)
|
||||
params.ReadParams = &readParams
|
||||
}
|
||||
|
||||
if err = c.gitRPCClient.ServicePack(ctx, w, params); err != nil {
|
||||
return fmt.Errorf("failed service pack operation %q on gitrpc: %w", service, err)
|
||||
if err = c.git.ServicePack(ctx, w, params); err != nil {
|
||||
return fmt.Errorf("failed service pack operation %q on git: %w", service, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -43,8 +43,8 @@ func (c *Controller) ListBranches(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rpcOut, err := c.gitRPCClient.ListBranches(ctx, &gitrpc.ListBranchesParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
rpcOut, err := c.git.ListBranches(ctx, &git.ListBranchesParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
IncludeCommit: includeCommit,
|
||||
Query: filter.Query,
|
||||
Sort: mapToRPCBranchSortOption(filter.Sort),
|
||||
@ -67,35 +67,35 @@ func (c *Controller) ListBranches(ctx context.Context,
|
||||
return branches, nil
|
||||
}
|
||||
|
||||
func mapToRPCBranchSortOption(o enum.BranchSortOption) gitrpc.BranchSortOption {
|
||||
func mapToRPCBranchSortOption(o enum.BranchSortOption) git.BranchSortOption {
|
||||
switch o {
|
||||
case enum.BranchSortOptionDate:
|
||||
return gitrpc.BranchSortOptionDate
|
||||
return git.BranchSortOptionDate
|
||||
case enum.BranchSortOptionName:
|
||||
return gitrpc.BranchSortOptionName
|
||||
return git.BranchSortOptionName
|
||||
case enum.BranchSortOptionDefault:
|
||||
return gitrpc.BranchSortOptionDefault
|
||||
return git.BranchSortOptionDefault
|
||||
default:
|
||||
// no need to error out - just use default for sorting
|
||||
return gitrpc.BranchSortOptionDefault
|
||||
return git.BranchSortOptionDefault
|
||||
}
|
||||
}
|
||||
|
||||
func mapToRPCSortOrder(o enum.Order) gitrpc.SortOrder {
|
||||
func mapToRPCSortOrder(o enum.Order) git.SortOrder {
|
||||
switch o {
|
||||
case enum.OrderAsc:
|
||||
return gitrpc.SortOrderAsc
|
||||
return git.SortOrderAsc
|
||||
case enum.OrderDesc:
|
||||
return gitrpc.SortOrderDesc
|
||||
return git.SortOrderDesc
|
||||
case enum.OrderDefault:
|
||||
return gitrpc.SortOrderDefault
|
||||
return git.SortOrderDefault
|
||||
default:
|
||||
// no need to error out - just use default for sorting
|
||||
return gitrpc.SortOrderDefault
|
||||
return git.SortOrderDefault
|
||||
}
|
||||
}
|
||||
|
||||
func mapBranch(b gitrpc.Branch) (Branch, error) {
|
||||
func mapBranch(b git.Branch) (Branch, error) {
|
||||
var commit *types.Commit
|
||||
if b.Commit != nil {
|
||||
var err error
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -47,8 +47,8 @@ func (c *Controller) ListCommitTags(ctx context.Context,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rpcOut, err := c.gitRPCClient.ListCommitTags(ctx, &gitrpc.ListCommitTagsParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
rpcOut, err := c.git.ListCommitTags(ctx, &git.ListCommitTagsParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
IncludeCommit: includeCommit,
|
||||
Query: filter.Query,
|
||||
Sort: mapToRPCTagSortOption(filter.Sort),
|
||||
@ -71,21 +71,21 @@ func (c *Controller) ListCommitTags(ctx context.Context,
|
||||
return tags, nil
|
||||
}
|
||||
|
||||
func mapToRPCTagSortOption(o enum.TagSortOption) gitrpc.TagSortOption {
|
||||
func mapToRPCTagSortOption(o enum.TagSortOption) git.TagSortOption {
|
||||
switch o {
|
||||
case enum.TagSortOptionDate:
|
||||
return gitrpc.TagSortOptionDate
|
||||
return git.TagSortOptionDate
|
||||
case enum.TagSortOptionName:
|
||||
return gitrpc.TagSortOptionName
|
||||
return git.TagSortOptionName
|
||||
case enum.TagSortOptionDefault:
|
||||
return gitrpc.TagSortOptionDefault
|
||||
return git.TagSortOptionDefault
|
||||
default:
|
||||
// no need to error out - just use default for sorting
|
||||
return gitrpc.TagSortOptionDefault
|
||||
return git.TagSortOptionDefault
|
||||
}
|
||||
}
|
||||
|
||||
func mapCommitTag(t gitrpc.CommitTag) (CommitTag, error) {
|
||||
func mapCommitTag(t git.CommitTag) (CommitTag, error) {
|
||||
var commit *types.Commit
|
||||
if t.Commit != nil {
|
||||
var err error
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -42,8 +42,8 @@ func (c *Controller) ListCommits(ctx context.Context,
|
||||
gitRef = repo.DefaultBranch
|
||||
}
|
||||
|
||||
rpcOut, err := c.gitRPCClient.ListCommits(ctx, &gitrpc.ListCommitsParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
rpcOut, err := c.git.ListCommits(ctx, &git.ListCommitsParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
GitREF: gitRef,
|
||||
After: filter.After,
|
||||
Page: int32(filter.Page),
|
||||
|
@ -16,11 +16,13 @@ package repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
gittypes "github.com/harness/gitness/git/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
@ -50,17 +52,18 @@ func (c *Controller) MergeCheck(
|
||||
return MergeCheck{}, fmt.Errorf("failed to create rpc write params: %w", err)
|
||||
}
|
||||
|
||||
_, err = c.gitRPCClient.Merge(ctx, &gitrpc.MergeParams{
|
||||
_, err = c.git.Merge(ctx, &git.MergeParams{
|
||||
WriteParams: writeParams,
|
||||
BaseBranch: info.BaseRef,
|
||||
HeadRepoUID: writeParams.RepoUID, // forks are not supported for now
|
||||
HeadBranch: info.HeadRef,
|
||||
})
|
||||
if err != nil {
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusNotMergeable {
|
||||
var cferr *gittypes.MergeConflictsError
|
||||
if errors.As(err, &cferr) {
|
||||
return MergeCheck{
|
||||
Mergeable: false,
|
||||
ConflictFiles: gitrpc.AsConflictFilesError(err),
|
||||
ConflictFiles: cferr.Files,
|
||||
}, nil
|
||||
}
|
||||
return MergeCheck{}, fmt.Errorf("merge check execution failed: %w", err)
|
||||
|
@ -19,7 +19,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
@ -34,8 +34,8 @@ func (c *Controller) PipelineGenerate(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err := c.gitRPCClient.GeneratePipeline(ctx, &gitrpc.GeneratePipelineParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
result, err := c.git.GeneratePipeline(ctx, &git.GeneratePipelineParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate pipeline: %w", err)
|
||||
|
@ -21,7 +21,7 @@ import (
|
||||
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
|
||||
@ -44,9 +44,8 @@ func (c *Controller) Raw(ctx context.Context,
|
||||
}
|
||||
|
||||
// create read params once
|
||||
readParams := gitrpc.CreateRPCReadParams(repo)
|
||||
|
||||
treeNodeOutput, err := c.gitRPCClient.GetTreeNode(ctx, &gitrpc.GetTreeNodeParams{
|
||||
readParams := git.CreateReadParams(repo)
|
||||
treeNodeOutput, err := c.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
|
||||
ReadParams: readParams,
|
||||
GitREF: gitRef,
|
||||
Path: repoPath,
|
||||
@ -57,19 +56,19 @@ func (c *Controller) Raw(ctx context.Context,
|
||||
}
|
||||
|
||||
// viewing Raw content is only supported for blob content
|
||||
if treeNodeOutput.Node.Type != gitrpc.TreeNodeTypeBlob {
|
||||
if treeNodeOutput.Node.Type != git.TreeNodeTypeBlob {
|
||||
return nil, 0, usererror.BadRequestf(
|
||||
"Object in '%s' at '/%s' is of type '%s'. Only objects of type %s support raw viewing.",
|
||||
gitRef, repoPath, treeNodeOutput.Node.Type, gitrpc.TreeNodeTypeBlob)
|
||||
gitRef, repoPath, treeNodeOutput.Node.Type, git.TreeNodeTypeBlob)
|
||||
}
|
||||
|
||||
blobReader, err := c.gitRPCClient.GetBlob(ctx, &gitrpc.GetBlobParams{
|
||||
blobReader, err := c.git.GetBlob(ctx, &git.GetBlobParams{
|
||||
ReadParams: readParams,
|
||||
SHA: treeNodeOutput.Node.SHA,
|
||||
SizeLimit: 0, // no size limit, we stream whatever data there is
|
||||
})
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to read blob from gitrpc: %w", err)
|
||||
return nil, 0, fmt.Errorf("failed to read blob: %w", err)
|
||||
}
|
||||
|
||||
return blobReader.Content, blobReader.ContentSize, nil
|
||||
|
@ -22,7 +22,7 @@ import (
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/check"
|
||||
@ -47,7 +47,7 @@ func ProvideController(
|
||||
principalStore store.PrincipalStore,
|
||||
ruleStore store.RuleStore,
|
||||
protectionManager *protection.Manager,
|
||||
rpcClient gitrpc.Interface,
|
||||
rpcClient git.Interface,
|
||||
importer *importer.Repository,
|
||||
codeOwners *codeowners.Service,
|
||||
reporeporter *repoevents.Reporter,
|
||||
|
@ -21,19 +21,19 @@ import (
|
||||
"github.com/harness/gitness/app/auth"
|
||||
"github.com/harness/gitness/app/githook"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
)
|
||||
|
||||
// createRPCWriteParams creates base write parameters for gitrpc write operations.
|
||||
// TODO: this function should be in gitrpc package and should accept params as interface (contract)
|
||||
// createRPCWriteParams creates base write parameters for git write operations.
|
||||
// TODO: this function should be in git package and should accept params as interface (contract)
|
||||
func createRPCWriteParams(
|
||||
ctx context.Context,
|
||||
urlProvider url.Provider,
|
||||
session *auth.Session,
|
||||
repo *types.Repository,
|
||||
isInternal bool,
|
||||
) (gitrpc.WriteParams, error) {
|
||||
) (git.WriteParams, error) {
|
||||
// generate envars (add everything githook CLI needs for execution)
|
||||
envVars, err := githook.GenerateEnvironmentVariables(
|
||||
ctx,
|
||||
@ -44,11 +44,11 @@ func createRPCWriteParams(
|
||||
isInternal,
|
||||
)
|
||||
if err != nil {
|
||||
return gitrpc.WriteParams{}, fmt.Errorf("failed to generate git hook environment variables: %w", err)
|
||||
return git.WriteParams{}, fmt.Errorf("failed to generate git hook environment variables: %w", err)
|
||||
}
|
||||
|
||||
return gitrpc.WriteParams{
|
||||
Actor: gitrpc.Identity{
|
||||
return git.WriteParams{
|
||||
Actor: git.Identity{
|
||||
Name: session.Principal.DisplayName,
|
||||
Email: session.Principal.Email,
|
||||
},
|
||||
@ -57,29 +57,29 @@ func createRPCWriteParams(
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateRPCExternalWriteParams creates base write parameters for gitrpc external write operations.
|
||||
// CreateRPCExternalWriteParams creates base write parameters for git external write operations.
|
||||
// External write operations are direct git pushes.
|
||||
func CreateRPCExternalWriteParams(
|
||||
ctx context.Context,
|
||||
urlProvider url.Provider,
|
||||
session *auth.Session,
|
||||
repo *types.Repository,
|
||||
) (gitrpc.WriteParams, error) {
|
||||
) (git.WriteParams, error) {
|
||||
return createRPCWriteParams(ctx, urlProvider, session, repo, false)
|
||||
}
|
||||
|
||||
// CreateRPCInternalWriteParams creates base write parameters for gitrpc internal write operations.
|
||||
// CreateRPCInternalWriteParams creates base write parameters for git internal write operations.
|
||||
// Internal write operations are git pushes that originate from the Gitness server.
|
||||
func CreateRPCInternalWriteParams(
|
||||
ctx context.Context,
|
||||
urlProvider url.Provider,
|
||||
session *auth.Session,
|
||||
repo *types.Repository,
|
||||
) (gitrpc.WriteParams, error) {
|
||||
) (git.WriteParams, error) {
|
||||
return createRPCWriteParams(ctx, urlProvider, session, repo, true)
|
||||
}
|
||||
|
||||
func MapCommit(c *gitrpc.Commit) (*types.Commit, error) {
|
||||
func MapCommit(c *git.Commit) (*types.Commit, error) {
|
||||
if c == nil {
|
||||
return nil, fmt.Errorf("commit is nil")
|
||||
}
|
||||
@ -103,7 +103,7 @@ func MapCommit(c *gitrpc.Commit) (*types.Commit, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func MapRenameDetails(c *gitrpc.RenameDetails) *types.RenameDetails {
|
||||
func MapRenameDetails(c *git.RenameDetails) *types.RenameDetails {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
@ -115,7 +115,7 @@ func MapRenameDetails(c *gitrpc.RenameDetails) *types.RenameDetails {
|
||||
}
|
||||
}
|
||||
|
||||
func MapSignature(s *gitrpc.Signature) (*types.Signature, error) {
|
||||
func MapSignature(s *git.Signature) (*types.Signature, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("signature is nil")
|
||||
}
|
||||
|
@ -19,7 +19,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/app/api/request"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
|
||||
"github.com/rs/xid"
|
||||
"github.com/rs/zerolog"
|
||||
@ -46,9 +46,9 @@ func HLogRequestIDHandler() func(http.Handler) http.Handler {
|
||||
reqID = xid.New().String()
|
||||
}
|
||||
|
||||
// add requestID to context for internal usage + gitrpc client!
|
||||
// add requestID to context for internal usage client!
|
||||
ctx = request.WithRequestID(ctx, reqID)
|
||||
ctx = gitrpc.WithRequestID(ctx, reqID)
|
||||
ctx = git.WithRequestID(ctx, reqID)
|
||||
|
||||
// update logging context with request ID
|
||||
log := zerolog.Ctx(ctx)
|
||||
|
@ -21,7 +21,7 @@ import (
|
||||
"github.com/harness/gitness/app/api/request"
|
||||
"github.com/harness/gitness/app/api/usererror"
|
||||
"github.com/harness/gitness/app/services/protection"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
|
||||
@ -555,7 +555,7 @@ func repoOperations(reflector *openapi3.Reflector) {
|
||||
opGetBlame.WithParameters(queryParameterGitRef,
|
||||
queryParameterLineFrom, queryParameterLineTo)
|
||||
_ = reflector.SetRequest(&opGetBlame, new(getBlameRequest), http.MethodGet)
|
||||
_ = reflector.SetJSONResponse(&opGetBlame, []gitrpc.BlamePart{}, http.StatusOK)
|
||||
_ = reflector.SetJSONResponse(&opGetBlame, []git.BlamePart{}, http.StatusOK)
|
||||
_ = reflector.SetJSONResponse(&opGetBlame, new(usererror.Error), http.StatusInternalServerError)
|
||||
_ = reflector.SetJSONResponse(&opGetBlame, new(usererror.Error), http.StatusUnauthorized)
|
||||
_ = reflector.SetJSONResponse(&opGetBlame, new(usererror.Error), http.StatusForbidden)
|
||||
@ -705,7 +705,7 @@ func repoOperations(reflector *openapi3.Reflector) {
|
||||
opDiff.WithMapOfAnything(map[string]interface{}{"operationId": "rawDiff"})
|
||||
_ = reflector.SetRequest(&opDiff, new(getRawDiffRequest), http.MethodGet)
|
||||
_ = reflector.SetStringResponse(&opDiff, http.StatusOK, "text/plain")
|
||||
_ = reflector.SetJSONResponse(&opDiff, []gitrpc.FileDiff{}, http.StatusOK)
|
||||
_ = reflector.SetJSONResponse(&opDiff, []git.FileDiff{}, http.StatusOK)
|
||||
_ = reflector.SetJSONResponse(&opDiff, new(usererror.Error), http.StatusInternalServerError)
|
||||
_ = reflector.SetJSONResponse(&opDiff, new(usererror.Error), http.StatusUnauthorized)
|
||||
_ = reflector.SetJSONResponse(&opDiff, new(usererror.Error), http.StatusForbidden)
|
||||
|
@ -15,14 +15,13 @@
|
||||
package usererror
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
apiauth "github.com/harness/gitness/app/api/auth"
|
||||
"github.com/harness/gitness/app/services/codeowners"
|
||||
"github.com/harness/gitness/app/services/webhook"
|
||||
"github.com/harness/gitness/blob"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/lock"
|
||||
"github.com/harness/gitness/store"
|
||||
"github.com/harness/gitness/types/check"
|
||||
@ -34,7 +33,7 @@ func Translate(err error) *Error {
|
||||
var (
|
||||
rError *Error
|
||||
checkError *check.ValidationError
|
||||
gitrpcError *gitrpc.Error
|
||||
appError *errors.Error
|
||||
maxBytesErr *http.MaxBytesError
|
||||
codeOwnersTooLargeError *codeowners.TooLargeError
|
||||
lockError *lock.Error
|
||||
@ -79,12 +78,12 @@ func Translate(err error) *Error {
|
||||
case errors.As(err, &maxBytesErr):
|
||||
return RequestTooLargef("The request is too large. maximum allowed size is %d bytes", maxBytesErr.Limit)
|
||||
|
||||
// gitrpc errors
|
||||
case errors.As(err, &gitrpcError):
|
||||
// git errors
|
||||
case errors.As(err, &appError):
|
||||
return NewWithPayload(httpStatusCode(
|
||||
gitrpcError.Status),
|
||||
gitrpcError.Message,
|
||||
gitrpcError.Details,
|
||||
appError.Status),
|
||||
appError.Message,
|
||||
appError.Details,
|
||||
)
|
||||
|
||||
// webhook errors
|
||||
@ -120,21 +119,20 @@ func errorFromLockError(err *lock.Error) *Error {
|
||||
return ErrInternal
|
||||
}
|
||||
|
||||
// lookup of gitrpc error codes to HTTP status codes.
|
||||
var codes = map[gitrpc.Status]int{
|
||||
gitrpc.StatusConflict: http.StatusConflict,
|
||||
gitrpc.StatusInvalidArgument: http.StatusBadRequest,
|
||||
gitrpc.StatusNotFound: http.StatusNotFound,
|
||||
gitrpc.StatusPathNotFound: http.StatusNotFound,
|
||||
gitrpc.StatusNotImplemented: http.StatusNotImplemented,
|
||||
gitrpc.StatusPreconditionFailed: http.StatusPreconditionFailed,
|
||||
gitrpc.StatusUnauthorized: http.StatusUnauthorized,
|
||||
gitrpc.StatusInternal: http.StatusInternalServerError,
|
||||
gitrpc.StatusNotMergeable: http.StatusPreconditionFailed,
|
||||
// lookup of git error codes to HTTP status codes.
|
||||
var codes = map[errors.Status]int{
|
||||
errors.StatusConflict: http.StatusConflict,
|
||||
errors.StatusInvalidArgument: http.StatusBadRequest,
|
||||
errors.StatusNotFound: http.StatusNotFound,
|
||||
errors.StatusPathNotFound: http.StatusNotFound,
|
||||
errors.StatusNotImplemented: http.StatusNotImplemented,
|
||||
errors.StatusPreconditionFailed: http.StatusPreconditionFailed,
|
||||
errors.StatusUnauthorized: http.StatusUnauthorized,
|
||||
errors.StatusInternal: http.StatusInternalServerError,
|
||||
}
|
||||
|
||||
// httpStatusCode returns the associated HTTP status code for a gitrpc error code.
|
||||
func httpStatusCode(code gitrpc.Status) int {
|
||||
// httpStatusCode returns the associated HTTP status code for a git error code.
|
||||
func httpStatusCode(code errors.Status) int {
|
||||
if v, ok := codes[code]; ok {
|
||||
return v
|
||||
}
|
||||
|
@ -18,16 +18,16 @@ import (
|
||||
"context"
|
||||
|
||||
"github.com/harness/gitness/app/api/controller"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
)
|
||||
|
||||
type service struct {
|
||||
gitRPCClient gitrpc.Interface
|
||||
git git.Interface
|
||||
}
|
||||
|
||||
func newService(gitRPCClient gitrpc.Interface) Service {
|
||||
return &service{gitRPCClient: gitRPCClient}
|
||||
func newService(git git.Interface) Service {
|
||||
return &service{git: git}
|
||||
}
|
||||
|
||||
// FindRef finds information about a commit in gitness for the git ref.
|
||||
@ -38,10 +38,10 @@ func (f *service) FindRef(
|
||||
repo *types.Repository,
|
||||
branch string,
|
||||
) (*types.Commit, error) {
|
||||
readParams := gitrpc.ReadParams{
|
||||
readParams := git.ReadParams{
|
||||
RepoUID: repo.GitUID,
|
||||
}
|
||||
branchOutput, err := f.gitRPCClient.GetBranch(ctx, &gitrpc.GetBranchParams{
|
||||
branchOutput, err := f.git.GetBranch(ctx, &git.GetBranchParams{
|
||||
ReadParams: readParams,
|
||||
BranchName: branch,
|
||||
})
|
||||
@ -59,10 +59,10 @@ func (f *service) FindCommit(
|
||||
repo *types.Repository,
|
||||
sha string,
|
||||
) (*types.Commit, error) {
|
||||
readParams := gitrpc.ReadParams{
|
||||
readParams := git.ReadParams{
|
||||
RepoUID: repo.GitUID,
|
||||
}
|
||||
commitOutput, err := f.gitRPCClient.GetCommit(ctx, &gitrpc.GetCommitParams{
|
||||
commitOutput, err := f.git.GetCommit(ctx, &git.GetCommitParams{
|
||||
ReadParams: readParams,
|
||||
SHA: sha,
|
||||
})
|
||||
|
@ -15,7 +15,7 @@
|
||||
package commit
|
||||
|
||||
import (
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
|
||||
"github.com/google/wire"
|
||||
)
|
||||
@ -27,6 +27,6 @@ var WireSet = wire.NewSet(
|
||||
|
||||
// ProvideService provides a service which can fetch commit
|
||||
// information about a repository.
|
||||
func ProvideService(gitRPCClient gitrpc.Interface) Service {
|
||||
return newService(gitRPCClient)
|
||||
func ProvideService(git git.Interface) Service {
|
||||
return newService(git)
|
||||
}
|
||||
|
@ -19,16 +19,16 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
)
|
||||
|
||||
type service struct {
|
||||
gitRPCClient gitrpc.Interface
|
||||
git git.Interface
|
||||
}
|
||||
|
||||
func newService(gitRPCClient gitrpc.Interface) Service {
|
||||
return &service{gitRPCClient: gitRPCClient}
|
||||
func newService(git git.Interface) Service {
|
||||
return &service{git: git}
|
||||
}
|
||||
|
||||
func (f *service) Get(
|
||||
@ -37,10 +37,10 @@ func (f *service) Get(
|
||||
path string,
|
||||
ref string,
|
||||
) (*File, error) {
|
||||
readParams := gitrpc.ReadParams{
|
||||
readParams := git.ReadParams{
|
||||
RepoUID: repo.GitUID,
|
||||
}
|
||||
treeNodeOutput, err := f.gitRPCClient.GetTreeNode(ctx, &gitrpc.GetTreeNodeParams{
|
||||
treeNodeOutput, err := f.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
|
||||
ReadParams: readParams,
|
||||
GitREF: ref,
|
||||
Path: path,
|
||||
@ -50,17 +50,17 @@ func (f *service) Get(
|
||||
return nil, fmt.Errorf("failed to read tree node: %w", err)
|
||||
}
|
||||
// viewing Raw content is only supported for blob content
|
||||
if treeNodeOutput.Node.Type != gitrpc.TreeNodeTypeBlob {
|
||||
if treeNodeOutput.Node.Type != git.TreeNodeTypeBlob {
|
||||
return nil, fmt.Errorf("path content is not of blob type: %s", treeNodeOutput.Node.Type)
|
||||
}
|
||||
|
||||
blobReader, err := f.gitRPCClient.GetBlob(ctx, &gitrpc.GetBlobParams{
|
||||
blobReader, err := f.git.GetBlob(ctx, &git.GetBlobParams{
|
||||
ReadParams: readParams,
|
||||
SHA: treeNodeOutput.Node.SHA,
|
||||
SizeLimit: 0, // no size limit, we stream whatever data there is
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read blob from gitrpc: %w", err)
|
||||
return nil, fmt.Errorf("failed to read blob: %w", err)
|
||||
}
|
||||
|
||||
buf, err := io.ReadAll(blobReader.Content)
|
||||
|
@ -15,7 +15,7 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
|
||||
"github.com/google/wire"
|
||||
)
|
||||
@ -27,6 +27,6 @@ var WireSet = wire.NewSet(
|
||||
|
||||
// ProvideService provides a service which can read file contents
|
||||
// from a repository.
|
||||
func ProvideService(gitRPCClient gitrpc.Interface) Service {
|
||||
return newService(gitRPCClient)
|
||||
func ProvideService(git git.Interface) Service {
|
||||
return newService(git)
|
||||
}
|
||||
|
@ -17,8 +17,9 @@ package codecomments
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
gitrpcenum "github.com/harness/gitness/gitrpc/enum"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
gitenum "github.com/harness/gitness/git/enum"
|
||||
"github.com/harness/gitness/types"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
@ -30,7 +31,7 @@ type Migrator struct {
|
||||
}
|
||||
|
||||
type hunkHeaderFetcher interface {
|
||||
GetDiffHunkHeaders(context.Context, gitrpc.GetDiffHunkHeadersParams) (gitrpc.GetDiffHunkHeadersOutput, error)
|
||||
GetDiffHunkHeaders(context.Context, git.GetDiffHunkHeadersParams) (git.GetDiffHunkHeadersOutput, error)
|
||||
}
|
||||
|
||||
// MigrateNew updates the "+" (the added lines) part of code comments
|
||||
@ -109,14 +110,14 @@ func (migrator *Migrator) migrate(
|
||||
|
||||
for commentSHA, fileMap := range commitMap {
|
||||
// get all hunk headers for the diff between the SHA that's stored in the comment and the new SHA.
|
||||
diffSummary, errDiff := migrator.hunkHeaderFetcher.GetDiffHunkHeaders(ctx, gitrpc.GetDiffHunkHeadersParams{
|
||||
ReadParams: gitrpc.ReadParams{
|
||||
diffSummary, errDiff := migrator.hunkHeaderFetcher.GetDiffHunkHeaders(ctx, git.GetDiffHunkHeadersParams{
|
||||
ReadParams: git.ReadParams{
|
||||
RepoUID: repoGitUID,
|
||||
},
|
||||
SourceCommitSHA: commentSHA,
|
||||
TargetCommitSHA: newSHA,
|
||||
})
|
||||
if gitrpc.ErrorStatus(errDiff) == gitrpc.StatusNotFound {
|
||||
if errors.AsStatus(errDiff) == errors.StatusNotFound {
|
||||
// Handle the commit SHA not found error and mark all code comments as outdated.
|
||||
for _, codeComments := range fileMap {
|
||||
for _, codeComment := range codeComments {
|
||||
@ -151,7 +152,7 @@ func (migrator *Migrator) migrate(
|
||||
}
|
||||
|
||||
// Handle file delete
|
||||
if _, isDeleted := file.FileHeader.Extensions[gitrpcenum.DiffExtHeaderDeletedFileMode]; isDeleted {
|
||||
if _, isDeleted := file.FileHeader.Extensions[gitenum.DiffExtHeaderDeletedFileMode]; isDeleted {
|
||||
for _, codeComment := range codeComments {
|
||||
codeComment.Outdated = true
|
||||
}
|
||||
@ -159,7 +160,7 @@ func (migrator *Migrator) migrate(
|
||||
}
|
||||
|
||||
// Handle new files - shouldn't happen because no code comments should exist for a non-existing file.
|
||||
if _, isAdded := file.FileHeader.Extensions[gitrpcenum.DiffExtHeaderNewFileMode]; isAdded {
|
||||
if _, isAdded := file.FileHeader.Extensions[gitenum.DiffExtHeaderNewFileMode]; isAdded {
|
||||
for _, codeComment := range codeComments {
|
||||
codeComment.Outdated = true
|
||||
}
|
||||
@ -227,7 +228,7 @@ func mapCodeComments(
|
||||
return commitMap, originalComments
|
||||
}
|
||||
|
||||
func processCodeComment(ccStart, ccEnd int, h gitrpc.HunkHeader) (outdated bool, moveDelta int) {
|
||||
func processCodeComment(ccStart, ccEnd int, h git.HunkHeader) (outdated bool, moveDelta int) {
|
||||
// A code comment is marked as outdated if:
|
||||
// * The code lines covered by the code comment are changed
|
||||
// (the range given by the OldLine/OldSpan overlaps the code comment's code range)
|
||||
|
@ -18,7 +18,7 @@ import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
)
|
||||
|
||||
@ -41,7 +41,7 @@ func TestMigrator(t *testing.T) {
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
headers []gitrpc.HunkHeader
|
||||
headers []git.HunkHeader
|
||||
rebase bool
|
||||
positions []position
|
||||
expected []position
|
||||
@ -60,7 +60,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "source:lines-added-before-two-comments",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 0, OldSpan: 0, NewLine: 10, NewSpan: 10},
|
||||
},
|
||||
positions: []position{
|
||||
@ -74,7 +74,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "source:lines-added-between-two-comments",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 40, OldSpan: 0, NewLine: 40, NewSpan: 40},
|
||||
},
|
||||
positions: []position{
|
||||
@ -88,7 +88,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "source:lines-added-after-two-comments",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 60, OldSpan: 0, NewLine: 60, NewSpan: 200},
|
||||
},
|
||||
positions: []position{
|
||||
@ -102,7 +102,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "source:modified-second-comment",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 50, OldSpan: 1, NewLine: 50, NewSpan: 1},
|
||||
},
|
||||
positions: []position{
|
||||
@ -119,7 +119,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "source:modified-second-comment;also-removed-10-lines-at-1",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 1, OldSpan: 10, NewLine: 0, NewSpan: 0},
|
||||
{OldLine: 50, OldSpan: 1, NewLine: 40, NewSpan: 1},
|
||||
},
|
||||
@ -137,7 +137,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "source:modified-second-comment;also-added-10-lines-at-1",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 0, OldSpan: 0, NewLine: 1, NewSpan: 10},
|
||||
{OldLine: 50, OldSpan: 1, NewLine: 60, NewSpan: 1},
|
||||
},
|
||||
@ -168,7 +168,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "merge-base:lines-added-before-two-comments",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 0, OldSpan: 0, NewLine: 10, NewSpan: 10},
|
||||
},
|
||||
rebase: true,
|
||||
@ -183,7 +183,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "merge-base:lines-added-between-two-comments",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 40, OldSpan: 0, NewLine: 40, NewSpan: 40},
|
||||
},
|
||||
rebase: true,
|
||||
@ -198,7 +198,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "merge-base:lines-added-after-two-comments",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 60, OldSpan: 0, NewLine: 60, NewSpan: 200},
|
||||
},
|
||||
rebase: true,
|
||||
@ -213,7 +213,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "merge-base:modified-second-comment",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 50, OldSpan: 1, NewLine: 50, NewSpan: 1},
|
||||
},
|
||||
rebase: true,
|
||||
@ -231,7 +231,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "merge-base:modified-second-comment;also-removed-10-lines-at-1",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 1, OldSpan: 10, NewLine: 0, NewSpan: 0},
|
||||
{OldLine: 50, OldSpan: 1, NewLine: 40, NewSpan: 1},
|
||||
},
|
||||
@ -250,7 +250,7 @@ func TestMigrator(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "merge-base:modified-second-comment;also-added-10-lines-at-1",
|
||||
headers: []gitrpc.HunkHeader{
|
||||
headers: []git.HunkHeader{
|
||||
{OldLine: 0, OldSpan: 0, NewLine: 1, NewSpan: 10},
|
||||
{OldLine: 50, OldSpan: 1, NewLine: 60, NewSpan: 1},
|
||||
},
|
||||
@ -334,17 +334,17 @@ func TestMigrator(t *testing.T) {
|
||||
|
||||
type testHunkHeaderFetcher struct {
|
||||
fileName string
|
||||
headers []gitrpc.HunkHeader
|
||||
headers []git.HunkHeader
|
||||
}
|
||||
|
||||
func (f testHunkHeaderFetcher) GetDiffHunkHeaders(
|
||||
_ context.Context,
|
||||
_ gitrpc.GetDiffHunkHeadersParams,
|
||||
) (gitrpc.GetDiffHunkHeadersOutput, error) {
|
||||
return gitrpc.GetDiffHunkHeadersOutput{
|
||||
Files: []gitrpc.DiffFileHunkHeaders{
|
||||
_ git.GetDiffHunkHeadersParams,
|
||||
) (git.GetDiffHunkHeadersOutput, error) {
|
||||
return git.GetDiffHunkHeadersOutput{
|
||||
Files: []git.DiffFileHunkHeaders{
|
||||
{
|
||||
FileHeader: gitrpc.DiffFileHeader{
|
||||
FileHeader: git.DiffFileHeader{
|
||||
OldName: f.fileName,
|
||||
NewName: f.fileName,
|
||||
Extensions: nil,
|
||||
@ -361,132 +361,132 @@ func TestProcessCodeComment(t *testing.T) {
|
||||
const ccEnd = 24
|
||||
tests := []struct {
|
||||
name string
|
||||
hunk gitrpc.HunkHeader
|
||||
hunk git.HunkHeader
|
||||
expOutdated bool
|
||||
expMoveDelta int
|
||||
}{
|
||||
// only added lines
|
||||
{
|
||||
name: "three-lines-added-before-far",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 10, OldSpan: 0, NewLine: 11, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 10, OldSpan: 0, NewLine: 11, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 3,
|
||||
},
|
||||
{
|
||||
name: "three-lines-added-before-but-touching",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 19, OldSpan: 0, NewLine: 20, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 19, OldSpan: 0, NewLine: 20, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 3,
|
||||
},
|
||||
{
|
||||
name: "three-lines-added-overlap-at-start",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 20, OldSpan: 0, NewLine: 21, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 20, OldSpan: 0, NewLine: 21, NewSpan: 3},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-added-inside",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 21, OldSpan: 0, NewLine: 22, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 21, OldSpan: 0, NewLine: 22, NewSpan: 3},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-added-overlap-at-end",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 23, OldSpan: 0, NewLine: 24, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 23, OldSpan: 0, NewLine: 24, NewSpan: 3},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-added-after-but-touching",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 24, OldSpan: 0, NewLine: 25, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 24, OldSpan: 0, NewLine: 25, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-added-after-far",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 30, OldSpan: 0, NewLine: 31, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 30, OldSpan: 0, NewLine: 31, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
// only removed lines
|
||||
{
|
||||
name: "three-lines-removed-before-far",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 10, OldSpan: 3, NewLine: 9, NewSpan: 0},
|
||||
hunk: git.HunkHeader{OldLine: 10, OldSpan: 3, NewLine: 9, NewSpan: 0},
|
||||
expOutdated: false, expMoveDelta: -3,
|
||||
},
|
||||
{
|
||||
name: "three-lines-removed-before-but-touching",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 17, OldSpan: 3, NewLine: 16, NewSpan: 0},
|
||||
hunk: git.HunkHeader{OldLine: 17, OldSpan: 3, NewLine: 16, NewSpan: 0},
|
||||
expOutdated: false, expMoveDelta: -3,
|
||||
},
|
||||
{
|
||||
name: "three-lines-removed-overlap-at-start",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 18, OldSpan: 3, NewLine: 17, NewSpan: 0},
|
||||
hunk: git.HunkHeader{OldLine: 18, OldSpan: 3, NewLine: 17, NewSpan: 0},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-removed-inside",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 21, OldSpan: 3, NewLine: 20, NewSpan: 0},
|
||||
hunk: git.HunkHeader{OldLine: 21, OldSpan: 3, NewLine: 20, NewSpan: 0},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-removed-overlap-at-end",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 24, OldSpan: 3, NewLine: 23, NewSpan: 0},
|
||||
hunk: git.HunkHeader{OldLine: 24, OldSpan: 3, NewLine: 23, NewSpan: 0},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-removed-after-but-touching",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 25, OldSpan: 3, NewLine: 24, NewSpan: 0},
|
||||
hunk: git.HunkHeader{OldLine: 25, OldSpan: 3, NewLine: 24, NewSpan: 0},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-removed-after-far",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 30, OldSpan: 3, NewLine: 29, NewSpan: 0},
|
||||
hunk: git.HunkHeader{OldLine: 30, OldSpan: 3, NewLine: 29, NewSpan: 0},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
// only changed lines
|
||||
{
|
||||
name: "three-lines-changed-before-far",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 10, OldSpan: 3, NewLine: 10, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 10, OldSpan: 3, NewLine: 10, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-changed-before-but-touching",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 17, OldSpan: 3, NewLine: 17, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 17, OldSpan: 3, NewLine: 17, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-changed-overlap-at-start",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 18, OldSpan: 3, NewLine: 18, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 18, OldSpan: 3, NewLine: 18, NewSpan: 3},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-changed-inside",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 21, OldSpan: 3, NewLine: 21, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 21, OldSpan: 3, NewLine: 21, NewSpan: 3},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-changed-overlap-at-end",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 24, OldSpan: 3, NewLine: 24, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 24, OldSpan: 3, NewLine: 24, NewSpan: 3},
|
||||
expOutdated: true, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-changed-after-but-touching",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 25, OldSpan: 3, NewLine: 25, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 25, OldSpan: 3, NewLine: 25, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "three-lines-changed-after-far",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 30, OldSpan: 3, NewLine: 30, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 30, OldSpan: 3, NewLine: 30, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
// mixed tests
|
||||
{
|
||||
name: "two-lines-added-one-changed-just-before",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 19, OldSpan: 1, NewLine: 19, NewSpan: 3},
|
||||
hunk: git.HunkHeader{OldLine: 19, OldSpan: 1, NewLine: 19, NewSpan: 3},
|
||||
expOutdated: false, expMoveDelta: 2,
|
||||
},
|
||||
{
|
||||
name: "two-lines-removed-one-added-just-after",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 25, OldSpan: 2, NewLine: 25, NewSpan: 1},
|
||||
hunk: git.HunkHeader{OldLine: 25, OldSpan: 2, NewLine: 25, NewSpan: 1},
|
||||
expOutdated: false, expMoveDelta: 0,
|
||||
},
|
||||
{
|
||||
name: "twenty-lines-added-at-line-15",
|
||||
hunk: gitrpc.HunkHeader{OldLine: 14, OldSpan: 0, NewLine: 15, NewSpan: 20},
|
||||
hunk: git.HunkHeader{OldLine: 14, OldSpan: 0, NewLine: 15, NewSpan: 20},
|
||||
expOutdated: false, expMoveDelta: 20,
|
||||
},
|
||||
}
|
||||
|
@ -15,7 +15,7 @@
|
||||
package codecomments
|
||||
|
||||
import (
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
|
||||
"github.com/google/wire"
|
||||
)
|
||||
@ -25,9 +25,9 @@ var WireSet = wire.NewSet(
|
||||
)
|
||||
|
||||
func ProvideMigrator(
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
) *Migrator {
|
||||
return &Migrator{
|
||||
hunkHeaderFetcher: gitRPCClient,
|
||||
hunkHeaderFetcher: git,
|
||||
}
|
||||
}
|
||||
|
@ -17,13 +17,13 @@ package codeowners
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git"
|
||||
gitness_store "github.com/harness/gitness/store"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
@ -72,7 +72,7 @@ type Config struct {
|
||||
|
||||
type Service struct {
|
||||
repoStore store.RepoStore
|
||||
git gitrpc.Interface
|
||||
git git.Interface
|
||||
principalStore store.PrincipalStore
|
||||
config Config
|
||||
}
|
||||
@ -111,7 +111,7 @@ type OwnerEvaluation struct {
|
||||
|
||||
func New(
|
||||
repoStore store.RepoStore,
|
||||
git gitrpc.Interface,
|
||||
git git.Interface,
|
||||
config Config,
|
||||
principalStore store.PrincipalStore,
|
||||
) *Service {
|
||||
@ -185,7 +185,7 @@ func (s *Service) getCodeOwnerFile(
|
||||
repo *types.Repository,
|
||||
ref string,
|
||||
) (*File, error) {
|
||||
params := gitrpc.CreateRPCReadParams(repo)
|
||||
params := git.CreateReadParams(repo)
|
||||
if ref == "" {
|
||||
ref = "refs/heads/" + repo.DefaultBranch
|
||||
}
|
||||
@ -193,15 +193,15 @@ func (s *Service) getCodeOwnerFile(
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot get codeowner file : %w", err)
|
||||
}
|
||||
if node.Node.Mode != gitrpc.TreeNodeModeFile {
|
||||
if node.Node.Mode != git.TreeNodeModeFile {
|
||||
return nil, fmt.Errorf(
|
||||
"codeowner file is of format '%s' but expected to be of format '%s'",
|
||||
node.Node.Mode,
|
||||
gitrpc.TreeNodeModeFile,
|
||||
git.TreeNodeModeFile,
|
||||
)
|
||||
}
|
||||
|
||||
output, err := s.git.GetBlob(ctx, &gitrpc.GetBlobParams{
|
||||
output, err := s.git.GetBlob(ctx, &git.GetBlobParams{
|
||||
ReadParams: params,
|
||||
SHA: node.Node.SHA,
|
||||
SizeLimit: maxGetContentFileSize,
|
||||
@ -224,19 +224,19 @@ func (s *Service) getCodeOwnerFile(
|
||||
|
||||
func (s *Service) getCodeOwnerFileNode(
|
||||
ctx context.Context,
|
||||
params gitrpc.ReadParams,
|
||||
params git.ReadParams,
|
||||
ref string,
|
||||
) (*gitrpc.GetTreeNodeOutput, error) {
|
||||
) (*git.GetTreeNodeOutput, error) {
|
||||
// iterating over multiple possible codeowner file path to get the file
|
||||
// todo: once we have api to get multi file we can simplify
|
||||
for _, path := range s.config.FilePaths {
|
||||
node, err := s.git.GetTreeNode(ctx, &gitrpc.GetTreeNodeParams{
|
||||
node, err := s.git.GetTreeNode(ctx, &git.GetTreeNodeParams{
|
||||
ReadParams: params,
|
||||
GitREF: ref,
|
||||
Path: path,
|
||||
})
|
||||
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusPathNotFound {
|
||||
if errors.AsStatus(err) == errors.StatusPathNotFound {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
@ -260,8 +260,8 @@ func (s *Service) getApplicableCodeOwnersForPR(
|
||||
}
|
||||
|
||||
var filteredEntries []Entry
|
||||
diffFileStats, err := s.git.DiffFileNames(ctx, &gitrpc.DiffParams{
|
||||
ReadParams: gitrpc.CreateRPCReadParams(repo),
|
||||
diffFileStats, err := s.git.DiffFileNames(ctx, &git.DiffParams{
|
||||
ReadParams: git.CreateReadParams(repo),
|
||||
BaseRef: pr.MergeBaseSHA,
|
||||
HeadRef: pr.SourceSHA,
|
||||
})
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
)
|
||||
|
||||
func TestService_ParseCodeOwner(t *testing.T) {
|
||||
@ -31,7 +31,7 @@ func TestService_ParseCodeOwner(t *testing.T) {
|
||||
"#\n/scripts/api mankrit.singh@harness.io ashish.sanodia@harness.io"
|
||||
type fields struct {
|
||||
repoStore store.RepoStore
|
||||
git gitrpc.Interface
|
||||
git git.Interface
|
||||
Config Config
|
||||
}
|
||||
type args struct {
|
||||
|
@ -16,7 +16,7 @@ package codeowners
|
||||
|
||||
import (
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
|
||||
"github.com/google/wire"
|
||||
)
|
||||
@ -26,10 +26,10 @@ var WireSet = wire.NewSet(
|
||||
)
|
||||
|
||||
func ProvideCodeOwners(
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
repoStore store.RepoStore,
|
||||
config Config,
|
||||
principalStore store.PrincipalStore,
|
||||
) *Service {
|
||||
return New(repoStore, gitRPCClient, config, principalStore)
|
||||
return New(repoStore, git, config, principalStore)
|
||||
}
|
||||
|
@ -30,7 +30,7 @@ import (
|
||||
"github.com/harness/gitness/app/store"
|
||||
gitnessurl "github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/encrypt"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
|
||||
@ -49,7 +49,7 @@ var (
|
||||
|
||||
type Repository struct {
|
||||
urlProvider gitnessurl.Provider
|
||||
git gitrpc.Interface
|
||||
git git.Interface
|
||||
repoStore store.RepoStore
|
||||
scheduler *job.Scheduler
|
||||
encrypter encrypt.Encrypter
|
||||
@ -203,8 +203,8 @@ func (r *Repository) Handle(ctx context.Context, data string, _ job.ProgressRepo
|
||||
return "", err
|
||||
}
|
||||
|
||||
err = r.git.PushRemote(ctx, &gitrpc.PushRemoteParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: repository.GitUID},
|
||||
err = r.git.PushRemote(ctx, &git.PushRemoteParams{
|
||||
ReadParams: git.ReadParams{RepoUID: repository.GitUID},
|
||||
RemoteURL: urlWithToken,
|
||||
})
|
||||
if err != nil && !strings.Contains(err.Error(), "empty") {
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/encrypt"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
|
||||
"github.com/google/wire"
|
||||
)
|
||||
@ -31,7 +31,7 @@ var WireSet = wire.NewSet(
|
||||
|
||||
func ProvideSpaceExporter(
|
||||
urlProvider url.Provider,
|
||||
git gitrpc.Interface,
|
||||
git git.Interface,
|
||||
repoStore store.RepoStore,
|
||||
scheduler *job.Scheduler,
|
||||
executor *job.Executor,
|
||||
|
@ -21,7 +21,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
@ -56,10 +56,10 @@ func (r *Repository) processPipelines(ctx context.Context,
|
||||
return nil
|
||||
}
|
||||
|
||||
actions := make([]gitrpc.CommitFileAction, len(pipelineFiles))
|
||||
actions := make([]git.CommitFileAction, len(pipelineFiles))
|
||||
for i, file := range pipelineFiles {
|
||||
actions[i] = gitrpc.CommitFileAction{
|
||||
Action: gitrpc.CreateAction,
|
||||
actions[i] = git.CommitFileAction{
|
||||
Action: git.CreateAction,
|
||||
Path: file.ConvertedPath,
|
||||
Payload: file.Content,
|
||||
SHA: "",
|
||||
@ -67,12 +67,12 @@ func (r *Repository) processPipelines(ctx context.Context,
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
identity := &gitrpc.Identity{
|
||||
identity := &git.Identity{
|
||||
Name: principal.DisplayName,
|
||||
Email: principal.Email,
|
||||
}
|
||||
|
||||
_, err = r.git.CommitFiles(ctx, &gitrpc.CommitFilesParams{
|
||||
_, err = r.git.CommitFiles(ctx, &git.CommitFilesParams{
|
||||
WriteParams: writeParams,
|
||||
Title: commitMessage,
|
||||
Message: "",
|
||||
|
@ -31,7 +31,7 @@ import (
|
||||
"github.com/harness/gitness/app/store"
|
||||
gitnessurl "github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/encrypt"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
gitness_store "github.com/harness/gitness/store"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
"github.com/harness/gitness/types"
|
||||
@ -53,7 +53,7 @@ var (
|
||||
type Repository struct {
|
||||
defaultBranch string
|
||||
urlProvider gitnessurl.Provider
|
||||
git gitrpc.Interface
|
||||
git git.Interface
|
||||
tx dbtx.Transactor
|
||||
repoStore store.RepoStore
|
||||
pipelineStore store.PipelineStore
|
||||
@ -352,20 +352,20 @@ func (r *Repository) createGitRepository(ctx context.Context,
|
||||
return "", err
|
||||
}
|
||||
|
||||
resp, err := r.git.CreateRepository(ctx, &gitrpc.CreateRepositoryParams{
|
||||
Actor: gitrpc.Identity{
|
||||
resp, err := r.git.CreateRepository(ctx, &git.CreateRepositoryParams{
|
||||
Actor: git.Identity{
|
||||
Name: principal.DisplayName,
|
||||
Email: principal.Email,
|
||||
},
|
||||
EnvVars: envVars,
|
||||
DefaultBranch: r.defaultBranch,
|
||||
Files: nil,
|
||||
Author: &gitrpc.Identity{
|
||||
Author: &git.Identity{
|
||||
Name: principal.DisplayName,
|
||||
Email: principal.Email,
|
||||
},
|
||||
AuthorDate: &now,
|
||||
Committer: &gitrpc.Identity{
|
||||
Committer: &git.Identity{
|
||||
Name: principal.DisplayName,
|
||||
Email: principal.Email,
|
||||
},
|
||||
@ -388,7 +388,7 @@ func (r *Repository) syncGitRepository(ctx context.Context,
|
||||
return "", err
|
||||
}
|
||||
|
||||
syncOut, err := r.git.SyncRepository(ctx, &gitrpc.SyncRepositoryParams{
|
||||
syncOut, err := r.git.SyncRepository(ctx, &git.SyncRepositoryParams{
|
||||
WriteParams: writeParams,
|
||||
Source: sourceCloneURL,
|
||||
CreateIfNotExists: false,
|
||||
@ -410,7 +410,7 @@ func (r *Repository) deleteGitRepository(ctx context.Context,
|
||||
return err
|
||||
}
|
||||
|
||||
err = r.git.DeleteRepository(ctx, &gitrpc.DeleteRepositoryParams{
|
||||
err = r.git.DeleteRepository(ctx, &git.DeleteRepositoryParams{
|
||||
WriteParams: writeParams,
|
||||
})
|
||||
if err != nil {
|
||||
@ -427,8 +427,8 @@ func (r *Repository) matchFiles(ctx context.Context,
|
||||
pattern string,
|
||||
maxSize int,
|
||||
) ([]pipelineFile, error) {
|
||||
resp, err := r.git.MatchFiles(ctx, &gitrpc.MatchFilesParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: repo.GitUID},
|
||||
resp, err := r.git.MatchFiles(ctx, &git.MatchFilesParams{
|
||||
ReadParams: git.ReadParams{RepoUID: repo.GitUID},
|
||||
Ref: ref,
|
||||
DirPath: dirPath,
|
||||
Pattern: pattern,
|
||||
@ -454,14 +454,14 @@ func (r *Repository) matchFiles(ctx context.Context,
|
||||
func (r *Repository) createRPCWriteParams(ctx context.Context,
|
||||
principal *types.Principal,
|
||||
repo *types.Repository,
|
||||
) (gitrpc.WriteParams, error) {
|
||||
) (git.WriteParams, error) {
|
||||
envVars, err := r.createEnvVars(ctx, principal, repo.ID)
|
||||
if err != nil {
|
||||
return gitrpc.WriteParams{}, err
|
||||
return git.WriteParams{}, err
|
||||
}
|
||||
|
||||
return gitrpc.WriteParams{
|
||||
Actor: gitrpc.Identity{
|
||||
return git.WriteParams{
|
||||
Actor: git.Identity{
|
||||
Name: principal.DisplayName,
|
||||
Email: principal.Email,
|
||||
},
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/encrypt"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/store/database/dbtx"
|
||||
"github.com/harness/gitness/types"
|
||||
|
||||
@ -34,7 +34,7 @@ var WireSet = wire.NewSet(
|
||||
func ProvideRepoImporter(
|
||||
config *types.Config,
|
||||
urlProvider url.Provider,
|
||||
git gitrpc.Interface,
|
||||
git git.Interface,
|
||||
tx dbtx.Transactor,
|
||||
repoStore store.RepoStore,
|
||||
pipelineStore store.PipelineStore,
|
||||
|
@ -24,7 +24,7 @@ import (
|
||||
gitevents "github.com/harness/gitness/app/events/git"
|
||||
pullreqevents "github.com/harness/gitness/app/events/pullreq"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
|
||||
@ -68,8 +68,8 @@ func (s *Service) triggerPREventOnBranchUpdate(ctx context.Context,
|
||||
return fmt.Errorf("failed to get repo git info: %w", err)
|
||||
}
|
||||
|
||||
mergeBaseInfo, err := s.gitRPCClient.MergeBase(ctx, gitrpc.MergeBaseParams{
|
||||
ReadParams: gitrpc.ReadParams{RepoUID: targetRepo.GitUID},
|
||||
mergeBaseInfo, err := s.git.MergeBase(ctx, git.MergeBaseParams{
|
||||
ReadParams: git.ReadParams{RepoUID: targetRepo.GitUID},
|
||||
Ref1: event.Payload.NewSHA,
|
||||
Ref2: pr.TargetBranch,
|
||||
})
|
||||
|
@ -22,7 +22,7 @@ import (
|
||||
|
||||
pullreqevents "github.com/harness/gitness/app/events/pullreq"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
)
|
||||
|
||||
// handleFileViewedOnBranchUpdate handles pull request Branch Updated events.
|
||||
@ -37,8 +37,8 @@ func (s *Service) handleFileViewedOnBranchUpdate(ctx context.Context,
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get repo git info: %w", err)
|
||||
}
|
||||
reader := gitrpc.NewStreamReader(s.gitRPCClient.Diff(ctx, &gitrpc.DiffParams{
|
||||
ReadParams: gitrpc.ReadParams{
|
||||
reader := git.NewStreamReader(s.git.Diff(ctx, &git.DiffParams{
|
||||
ReadParams: git.ReadParams{
|
||||
RepoUID: repoGit.GitUID,
|
||||
},
|
||||
BaseRef: event.Payload.OldSHA,
|
||||
@ -63,15 +63,15 @@ func (s *Service) handleFileViewedOnBranchUpdate(ctx context.Context,
|
||||
// UPDATED: mark as obsolete - in case pr is closed file SHA is handling it
|
||||
// This strategy leads to a behavior very similar to what github is doing
|
||||
switch fileDiff.Status {
|
||||
case gitrpc.FileDiffStatusAdded:
|
||||
case git.FileDiffStatusAdded:
|
||||
obsoletePaths = append(obsoletePaths, fileDiff.Path)
|
||||
case gitrpc.FileDiffStatusDeleted:
|
||||
case git.FileDiffStatusDeleted:
|
||||
obsoletePaths = append(obsoletePaths, fileDiff.OldPath)
|
||||
case gitrpc.FileDiffStatusRenamed:
|
||||
case git.FileDiffStatusRenamed:
|
||||
obsoletePaths = append(obsoletePaths, fileDiff.OldPath, fileDiff.Path)
|
||||
case gitrpc.FileDiffStatusModified:
|
||||
case git.FileDiffStatusModified:
|
||||
obsoletePaths = append(obsoletePaths, fileDiff.Path)
|
||||
case gitrpc.FileDiffStatusUndefined:
|
||||
case git.FileDiffStatusUndefined:
|
||||
// other cases we don't care
|
||||
}
|
||||
}
|
||||
|
@ -21,8 +21,8 @@ import (
|
||||
|
||||
pullreqevents "github.com/harness/gitness/app/events/pullreq"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
gitrpcenum "github.com/harness/gitness/gitrpc/enum"
|
||||
"github.com/harness/gitness/git"
|
||||
gitenum "github.com/harness/gitness/git/enum"
|
||||
)
|
||||
|
||||
// createHeadRefOnCreated handles pull request Created events.
|
||||
@ -42,10 +42,10 @@ func (s *Service) createHeadRefOnCreated(ctx context.Context,
|
||||
|
||||
// TODO: This doesn't work for forked repos (only works when sourceRepo==targetRepo).
|
||||
// This is because commits from the source repository must be first pulled into the target repository.
|
||||
err = s.gitRPCClient.UpdateRef(ctx, gitrpc.UpdateRefParams{
|
||||
err = s.git.UpdateRef(ctx, git.UpdateRefParams{
|
||||
WriteParams: writeParams,
|
||||
Name: strconv.Itoa(int(event.Payload.Number)),
|
||||
Type: gitrpcenum.RefTypePullReqHead,
|
||||
Type: gitenum.RefTypePullReqHead,
|
||||
NewValue: event.Payload.SourceSHA,
|
||||
OldValue: "", // this is a new pull request, so we expect that the ref doesn't exist
|
||||
})
|
||||
@ -73,10 +73,10 @@ func (s *Service) updateHeadRefOnBranchUpdate(ctx context.Context,
|
||||
|
||||
// TODO: This doesn't work for forked repos (only works when sourceRepo==targetRepo)
|
||||
// This is because commits from the source repository must be first pulled into the target repository.
|
||||
err = s.gitRPCClient.UpdateRef(ctx, gitrpc.UpdateRefParams{
|
||||
err = s.git.UpdateRef(ctx, git.UpdateRefParams{
|
||||
WriteParams: writeParams,
|
||||
Name: strconv.Itoa(int(event.Payload.Number)),
|
||||
Type: gitrpcenum.RefTypePullReqHead,
|
||||
Type: gitenum.RefTypePullReqHead,
|
||||
NewValue: event.Payload.NewSHA,
|
||||
OldValue: event.Payload.OldSHA,
|
||||
})
|
||||
@ -104,10 +104,10 @@ func (s *Service) updateHeadRefOnReopen(ctx context.Context,
|
||||
|
||||
// TODO: This doesn't work for forked repos (only works when sourceRepo==targetRepo)
|
||||
// This is because commits from the source repository must be first pulled into the target repository.
|
||||
err = s.gitRPCClient.UpdateRef(ctx, gitrpc.UpdateRefParams{
|
||||
err = s.git.UpdateRef(ctx, git.UpdateRefParams{
|
||||
WriteParams: writeParams,
|
||||
Name: strconv.Itoa(int(event.Payload.Number)),
|
||||
Type: gitrpcenum.RefTypePullReqHead,
|
||||
Type: gitenum.RefTypePullReqHead,
|
||||
NewValue: event.Payload.SourceSHA,
|
||||
OldValue: "", // the request is re-opened, so anything can be the old value
|
||||
})
|
||||
|
@ -21,9 +21,11 @@ import (
|
||||
"time"
|
||||
|
||||
pullreqevents "github.com/harness/gitness/app/events/pullreq"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
gitrpcenum "github.com/harness/gitness/gitrpc/enum"
|
||||
"github.com/harness/gitness/git"
|
||||
gitenum "github.com/harness/gitness/git/enum"
|
||||
gittypes "github.com/harness/gitness/git/types"
|
||||
"github.com/harness/gitness/pubsub"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
@ -104,11 +106,11 @@ func (s *Service) deleteMergeRef(ctx context.Context, repoID int64, prNum int64)
|
||||
}
|
||||
|
||||
// TODO: This doesn't work for forked repos
|
||||
err = s.gitRPCClient.UpdateRef(ctx, gitrpc.UpdateRefParams{
|
||||
err = s.git.UpdateRef(ctx, git.UpdateRefParams{
|
||||
WriteParams: writeParams,
|
||||
Name: strconv.Itoa(int(prNum)),
|
||||
Type: gitrpcenum.RefTypePullReqMerge,
|
||||
NewValue: "", // when NewValue is empty gitrpc will delete the ref.
|
||||
Type: gitenum.RefTypePullReqMerge,
|
||||
NewValue: "", // when NewValue is empty will delete the ref.
|
||||
OldValue: "", // we don't care about the old value
|
||||
})
|
||||
if err != nil {
|
||||
@ -219,13 +221,13 @@ func (s *Service) updateMergeDataInner(
|
||||
|
||||
// call merge and store output in pr merge reference.
|
||||
now := time.Now()
|
||||
var output gitrpc.MergeOutput
|
||||
output, err = s.gitRPCClient.Merge(ctx, &gitrpc.MergeParams{
|
||||
var output git.MergeOutput
|
||||
output, err = s.git.Merge(ctx, &git.MergeParams{
|
||||
WriteParams: writeParams,
|
||||
BaseBranch: pr.TargetBranch,
|
||||
HeadRepoUID: sourceRepo.GitUID,
|
||||
HeadBranch: pr.SourceBranch,
|
||||
RefType: gitrpcenum.RefTypePullReqMerge,
|
||||
RefType: gitenum.RefTypePullReqMerge,
|
||||
RefName: strconv.Itoa(int(pr.Number)),
|
||||
HeadExpectedSHA: newSHA,
|
||||
Force: true,
|
||||
@ -233,14 +235,14 @@ func (s *Service) updateMergeDataInner(
|
||||
// set committer date to ensure repeatability of merge commit across replicas
|
||||
CommitterDate: &now,
|
||||
})
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusPreconditionFailed {
|
||||
if errors.AsStatus(err) == errors.StatusPreconditionFailed {
|
||||
return events.NewDiscardEventErrorf("Source branch '%s' is not on SHA '%s' anymore.",
|
||||
pr.SourceBranch, newSHA)
|
||||
}
|
||||
|
||||
conflicts := gitrpc.AsConflictFilesError(err)
|
||||
var cferr *gittypes.MergeConflictsError
|
||||
|
||||
isNotMergeableError := gitrpc.ErrorStatus(err) == gitrpc.StatusNotMergeable
|
||||
isNotMergeableError := errors.As(err, &cferr)
|
||||
if err != nil && !isNotMergeableError {
|
||||
return fmt.Errorf("merge check failed for %d:%s and %d:%s with err: %w",
|
||||
targetRepo.ID, pr.TargetBranch,
|
||||
@ -255,11 +257,11 @@ func (s *Service) updateMergeDataInner(
|
||||
}
|
||||
|
||||
if isNotMergeableError {
|
||||
// TODO: gitrpc should return sha's either way, and also conflicting files!
|
||||
// TODO: should return sha's either way, and also conflicting files!
|
||||
pr.MergeCheckStatus = enum.MergeCheckStatusConflict
|
||||
// pr.MergeTargetSHA = &output.BaseSHA // TODO: Merge API doesn't return this when there are conflicts
|
||||
pr.MergeSHA = nil
|
||||
pr.MergeConflicts = conflicts
|
||||
pr.MergeConflicts = cferr.Files
|
||||
} else {
|
||||
pr.MergeCheckStatus = enum.MergeCheckStatusMergeable
|
||||
pr.MergeTargetSHA = &output.BaseSHA
|
||||
|
@ -29,7 +29,7 @@ import (
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/pubsub"
|
||||
"github.com/harness/gitness/stream"
|
||||
"github.com/harness/gitness/types"
|
||||
@ -37,7 +37,7 @@ import (
|
||||
|
||||
type Service struct {
|
||||
pullreqEvReporter *pullreqevents.Reporter
|
||||
gitRPCClient gitrpc.Interface
|
||||
git git.Interface
|
||||
repoGitInfoCache store.RepoGitInfoCache
|
||||
repoStore store.RepoStore
|
||||
pullreqStore store.PullReqStore
|
||||
@ -60,7 +60,7 @@ func New(ctx context.Context,
|
||||
gitReaderFactory *events.ReaderFactory[*gitevents.Reader],
|
||||
pullreqEvReaderFactory *events.ReaderFactory[*pullreqevents.Reader],
|
||||
pullreqEvReporter *pullreqevents.Reporter,
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
repoGitInfoCache store.RepoGitInfoCache,
|
||||
repoStore store.RepoStore,
|
||||
pullreqStore store.PullReqStore,
|
||||
@ -74,7 +74,7 @@ func New(ctx context.Context,
|
||||
) (*Service, error) {
|
||||
service := &Service{
|
||||
pullreqEvReporter: pullreqEvReporter,
|
||||
gitRPCClient: gitRPCClient,
|
||||
git: git,
|
||||
repoGitInfoCache: repoGitInfoCache,
|
||||
repoStore: repoStore,
|
||||
pullreqStore: pullreqStore,
|
||||
@ -247,13 +247,13 @@ func New(ctx context.Context,
|
||||
return service, nil
|
||||
}
|
||||
|
||||
// createSystemRPCWriteParams creates base write parameters for gitrpc write operations.
|
||||
// createSystemRPCWriteParams creates base write parameters for write operations.
|
||||
func createSystemRPCWriteParams(
|
||||
ctx context.Context,
|
||||
urlProvider url.Provider,
|
||||
repoID int64,
|
||||
repoGITUID string,
|
||||
) (gitrpc.WriteParams, error) {
|
||||
) (git.WriteParams, error) {
|
||||
principal := bootstrap.NewSystemServiceSession().Principal
|
||||
|
||||
// generate envars (add everything githook CLI needs for execution)
|
||||
@ -266,11 +266,11 @@ func createSystemRPCWriteParams(
|
||||
true,
|
||||
)
|
||||
if err != nil {
|
||||
return gitrpc.WriteParams{}, fmt.Errorf("failed to generate git hook environment variables: %w", err)
|
||||
return git.WriteParams{}, fmt.Errorf("failed to generate git hook environment variables: %w", err)
|
||||
}
|
||||
|
||||
return gitrpc.WriteParams{
|
||||
Actor: gitrpc.Identity{
|
||||
return git.WriteParams{
|
||||
Actor: git.Identity{
|
||||
Name: principal.DisplayName,
|
||||
Email: principal.Email,
|
||||
},
|
||||
|
@ -24,7 +24,7 @@ import (
|
||||
"github.com/harness/gitness/app/store"
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/pubsub"
|
||||
"github.com/harness/gitness/types"
|
||||
|
||||
@ -40,7 +40,7 @@ func ProvideService(ctx context.Context,
|
||||
gitReaderFactory *events.ReaderFactory[*gitevents.Reader],
|
||||
pullReqEvFactory *events.ReaderFactory[*pullreqevents.Reader],
|
||||
pullReqEvReporter *pullreqevents.Reporter,
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
repoGitInfoCache store.RepoGitInfoCache,
|
||||
repoStore store.RepoStore,
|
||||
pullreqStore store.PullReqStore,
|
||||
@ -52,7 +52,7 @@ func ProvideService(ctx context.Context,
|
||||
urlProvider url.Provider,
|
||||
sseStreamer sse.Streamer,
|
||||
) (*Service, error) {
|
||||
return New(ctx, config, gitReaderFactory, pullReqEvFactory, pullReqEvReporter, gitRPCClient,
|
||||
return New(ctx, config, gitReaderFactory, pullReqEvFactory, pullReqEvReporter, git,
|
||||
repoGitInfoCache, repoStore, pullreqStore, activityStore,
|
||||
codeCommentView, codeCommentMigrator, fileViewStore, pubsub, urlProvider, sseStreamer)
|
||||
}
|
||||
|
@ -19,8 +19,9 @@ import (
|
||||
"fmt"
|
||||
|
||||
gitevents "github.com/harness/gitness/app/events/git"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -142,14 +143,14 @@ func (s *Service) handleEventBranchDeleted(ctx context.Context,
|
||||
}
|
||||
|
||||
func (s *Service) fetchCommitInfoForEvent(ctx context.Context, repoUID string, sha string) (CommitInfo, error) {
|
||||
out, err := s.gitRPCClient.GetCommit(ctx, &gitrpc.GetCommitParams{
|
||||
ReadParams: gitrpc.ReadParams{
|
||||
out, err := s.git.GetCommit(ctx, &git.GetCommitParams{
|
||||
ReadParams: git.ReadParams{
|
||||
RepoUID: repoUID,
|
||||
},
|
||||
SHA: sha,
|
||||
})
|
||||
|
||||
if gitrpc.ErrorStatus(err) == gitrpc.StatusNotFound {
|
||||
if errors.AsStatus(err) == errors.StatusNotFound {
|
||||
// this could happen if the commit has been deleted and garbage collected by now
|
||||
// or if the sha doesn't point to an event - either way discard the event.
|
||||
return CommitInfo{}, events.NewDiscardEventErrorf("commit with sha '%s' doesn't exist", sha)
|
||||
|
@ -27,7 +27,7 @@ import (
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/encrypt"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/stream"
|
||||
)
|
||||
|
||||
@ -82,7 +82,7 @@ type Service struct {
|
||||
repoStore store.RepoStore
|
||||
pullreqStore store.PullReqStore
|
||||
principalStore store.PrincipalStore
|
||||
gitRPCClient gitrpc.Interface
|
||||
git git.Interface
|
||||
activityStore store.PullReqActivityStore
|
||||
encrypter encrypt.Encrypter
|
||||
|
||||
@ -107,7 +107,7 @@ func NewService(
|
||||
activityStore store.PullReqActivityStore,
|
||||
urlProvider url.Provider,
|
||||
principalStore store.PrincipalStore,
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
encrypter encrypt.Encrypter,
|
||||
) (*Service, error) {
|
||||
if err := config.Prepare(); err != nil {
|
||||
@ -121,7 +121,7 @@ func NewService(
|
||||
activityStore: activityStore,
|
||||
urlProvider: urlProvider,
|
||||
principalStore: principalStore,
|
||||
gitRPCClient: gitRPCClient,
|
||||
git: git,
|
||||
encrypter: encrypter,
|
||||
|
||||
secureHTTPClient: newHTTPClient(config.AllowLoopback, config.AllowPrivateNetwork, false),
|
||||
|
@ -18,7 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/types"
|
||||
"github.com/harness/gitness/types/enum"
|
||||
)
|
||||
@ -154,8 +154,8 @@ type CommitInfo struct {
|
||||
Committer SignatureInfo `json:"committer"`
|
||||
}
|
||||
|
||||
// commitInfoFrom gets the CommitInfo from a gitrpc.Commit.
|
||||
func commitInfoFrom(commit gitrpc.Commit) CommitInfo {
|
||||
// commitInfoFrom gets the CommitInfo from a git.Commit.
|
||||
func commitInfoFrom(commit git.Commit) CommitInfo {
|
||||
return CommitInfo{
|
||||
SHA: commit.SHA,
|
||||
Message: commit.Message,
|
||||
@ -171,8 +171,8 @@ type SignatureInfo struct {
|
||||
When time.Time `json:"when"`
|
||||
}
|
||||
|
||||
// signatureInfoFrom gets the SignatureInfo from a gitrpc.Signature.
|
||||
func signatureInfoFrom(signature gitrpc.Signature) SignatureInfo {
|
||||
// signatureInfoFrom gets the SignatureInfo from a git.Signature.
|
||||
func signatureInfoFrom(signature git.Signature) SignatureInfo {
|
||||
return SignatureInfo{
|
||||
Identity: identityInfoFrom(signature.Identity),
|
||||
When: signature.When,
|
||||
@ -186,8 +186,8 @@ type IdentityInfo struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// identityInfoFrom gets the IdentityInfo from a gitrpc.Identity.
|
||||
func identityInfoFrom(identity gitrpc.Identity) IdentityInfo {
|
||||
// identityInfoFrom gets the IdentityInfo from a git.Identity.
|
||||
func identityInfoFrom(identity git.Identity) IdentityInfo {
|
||||
return IdentityInfo{
|
||||
Name: identity.Name,
|
||||
Email: identity.Email,
|
||||
|
@ -23,7 +23,7 @@ import (
|
||||
"github.com/harness/gitness/app/url"
|
||||
"github.com/harness/gitness/encrypt"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/git"
|
||||
|
||||
"github.com/google/wire"
|
||||
)
|
||||
@ -44,10 +44,10 @@ func ProvideService(ctx context.Context,
|
||||
activityStore store.PullReqActivityStore,
|
||||
urlProvider url.Provider,
|
||||
principalStore store.PrincipalStore,
|
||||
gitRPCClient gitrpc.Interface,
|
||||
git git.Interface,
|
||||
encrypter encrypt.Encrypter,
|
||||
) (*Service, error) {
|
||||
return NewService(ctx, config, gitReaderFactory, prReaderFactory,
|
||||
webhookStore, webhookExecutionStore, repoStore, pullreqStore, activityStore,
|
||||
urlProvider, principalStore, gitRPCClient, encrypter)
|
||||
urlProvider, principalStore, git, encrypter)
|
||||
}
|
||||
|
@ -28,8 +28,6 @@ import (
|
||||
"github.com/harness/gitness/app/services/webhook"
|
||||
"github.com/harness/gitness/blob"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
"github.com/harness/gitness/gitrpc/server"
|
||||
"github.com/harness/gitness/lock"
|
||||
"github.com/harness/gitness/pubsub"
|
||||
"github.com/harness/gitness/store/database"
|
||||
@ -67,6 +65,31 @@ func LoadConfig() (*types.Config, error) {
|
||||
return nil, fmt.Errorf("failed to backfil urls: %w", err)
|
||||
}
|
||||
|
||||
if config.Git.HookPath == "" {
|
||||
executablePath, err := os.Executable()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get path of current executable: %w", err)
|
||||
}
|
||||
|
||||
config.Git.HookPath = executablePath
|
||||
}
|
||||
if config.Git.Root == "" {
|
||||
homedir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newPath := filepath.Join(homedir, gitnessHomeDir)
|
||||
config.Git.Root = newPath
|
||||
|
||||
oldPath := filepath.Join(homedir, ".gitrpc")
|
||||
if _, err := os.Stat(oldPath); err == nil {
|
||||
if err := os.Rename(oldPath, newPath); err != nil {
|
||||
config.Git.Root = oldPath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@ -230,47 +253,6 @@ func ProvideBlobStoreConfig(config *types.Config) (blob.Config, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ProvideGitRPCServerConfig loads the gitrpc server config from the environment.
|
||||
// It backfills certain config elements to work with cmdone.
|
||||
func ProvideGitRPCServerConfig() (server.Config, error) {
|
||||
config := server.Config{}
|
||||
err := envconfig.Process("", &config)
|
||||
if err != nil {
|
||||
return server.Config{}, fmt.Errorf("failed to load gitrpc server config: %w", err)
|
||||
}
|
||||
if config.GitHookPath == "" {
|
||||
var executablePath string
|
||||
executablePath, err = os.Executable()
|
||||
if err != nil {
|
||||
return server.Config{}, fmt.Errorf("failed to get path of current executable: %w", err)
|
||||
}
|
||||
|
||||
config.GitHookPath = executablePath
|
||||
}
|
||||
if config.GitRoot == "" {
|
||||
var homedir string
|
||||
homedir, err = os.UserHomeDir()
|
||||
if err != nil {
|
||||
return server.Config{}, err
|
||||
}
|
||||
|
||||
config.GitRoot = filepath.Join(homedir, ".gitrpc")
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// ProvideGitRPCClientConfig loads the gitrpc client config from the environment.
|
||||
func ProvideGitRPCClientConfig() (gitrpc.Config, error) {
|
||||
config := gitrpc.Config{}
|
||||
err := envconfig.Process("", &config)
|
||||
if err != nil {
|
||||
return gitrpc.Config{}, fmt.Errorf("failed to load gitrpc client config: %w", err)
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// ProvideEventsConfig loads the events config from the main config.
|
||||
func ProvideEventsConfig(config *types.Config) events.Config {
|
||||
return events.Config{
|
||||
|
@ -36,10 +36,9 @@ import (
|
||||
)
|
||||
|
||||
type command struct {
|
||||
envfile string
|
||||
enableGitRPC bool
|
||||
enableCI bool
|
||||
initializer func(context.Context, *types.Config) (*System, error)
|
||||
envfile string
|
||||
enableCI bool
|
||||
initializer func(context.Context, *types.Config) (*System, error)
|
||||
}
|
||||
|
||||
func (c *command) run(*kingpin.ParseContext) error {
|
||||
@ -131,18 +130,6 @@ func (c *command) run(*kingpin.ParseContext) error {
|
||||
Stringer("version", version.Version).
|
||||
Msg("server started")
|
||||
|
||||
if c.enableGitRPC {
|
||||
// start grpc server
|
||||
g.Go(system.gitRPCServer.Start)
|
||||
log.Info().Msg("gitrpc server started")
|
||||
|
||||
// run the gitrpc cron jobs
|
||||
g.Go(func() error {
|
||||
return system.gitRPCCronMngr.Run(ctx)
|
||||
})
|
||||
log.Info().Msg("gitrpc cron manager subroutine started")
|
||||
}
|
||||
|
||||
// wait until the error group context is done
|
||||
<-gCtx.Done()
|
||||
|
||||
@ -158,12 +145,6 @@ func (c *command) run(*kingpin.ParseContext) error {
|
||||
log.Err(sErr).Msg("failed to shutdown http server gracefully")
|
||||
}
|
||||
|
||||
if c.enableGitRPC {
|
||||
if rpcErr := system.gitRPCServer.Stop(); rpcErr != nil {
|
||||
log.Err(rpcErr).Msg("failed to shutdown grpc server gracefully")
|
||||
}
|
||||
}
|
||||
|
||||
system.services.JobScheduler.WaitJobsDone(shutdownCtx)
|
||||
|
||||
log.Info().Msg("wait for subroutines to complete")
|
||||
@ -223,11 +204,6 @@ func Register(app *kingpin.Application, initializer func(context.Context, *types
|
||||
Default("").
|
||||
StringVar(&c.envfile)
|
||||
|
||||
cmd.Flag("enable-gitrpc", "start the gitrpc server").
|
||||
Default("true").
|
||||
Envar("ENABLE_GITRPC").
|
||||
BoolVar(&c.enableGitRPC)
|
||||
|
||||
cmd.Flag("enable-ci", "start ci runners for build executions").
|
||||
Default("true").
|
||||
Envar("ENABLE_CI").
|
||||
|
@ -19,34 +19,27 @@ import (
|
||||
"github.com/harness/gitness/app/pipeline/plugin"
|
||||
"github.com/harness/gitness/app/server"
|
||||
"github.com/harness/gitness/app/services"
|
||||
gitrpcserver "github.com/harness/gitness/gitrpc/server"
|
||||
gitrpccron "github.com/harness/gitness/gitrpc/server/cron"
|
||||
|
||||
"github.com/drone/runner-go/poller"
|
||||
)
|
||||
|
||||
// System stores high level System sub-routines.
|
||||
type System struct {
|
||||
bootstrap bootstrap.Bootstrap
|
||||
server *server.Server
|
||||
gitRPCServer *gitrpcserver.GRPCServer
|
||||
pluginManager *plugin.Manager
|
||||
poller *poller.Poller
|
||||
services services.Services
|
||||
gitRPCCronMngr *gitrpccron.Manager
|
||||
bootstrap bootstrap.Bootstrap
|
||||
server *server.Server
|
||||
pluginManager *plugin.Manager
|
||||
poller *poller.Poller
|
||||
services services.Services
|
||||
}
|
||||
|
||||
// NewSystem returns a new system structure.
|
||||
func NewSystem(bootstrap bootstrap.Bootstrap, server *server.Server, poller *poller.Poller,
|
||||
gitRPCServer *gitrpcserver.GRPCServer, pluginManager *plugin.Manager,
|
||||
gitrpccron *gitrpccron.Manager, services services.Services) *System {
|
||||
pluginManager *plugin.Manager, services services.Services) *System {
|
||||
return &System{
|
||||
bootstrap: bootstrap,
|
||||
server: server,
|
||||
poller: poller,
|
||||
gitRPCServer: gitRPCServer,
|
||||
pluginManager: pluginManager,
|
||||
services: services,
|
||||
gitRPCCronMngr: gitrpccron,
|
||||
bootstrap: bootstrap,
|
||||
server: server,
|
||||
poller: poller,
|
||||
pluginManager: pluginManager,
|
||||
services: services,
|
||||
}
|
||||
}
|
||||
|
@ -68,9 +68,9 @@ import (
|
||||
cliserver "github.com/harness/gitness/cli/server"
|
||||
"github.com/harness/gitness/encrypt"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
gitrpcserver "github.com/harness/gitness/gitrpc/server"
|
||||
gitrpccron "github.com/harness/gitness/gitrpc/server/cron"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/git/adapter"
|
||||
"github.com/harness/gitness/git/storage"
|
||||
"github.com/harness/gitness/livelog"
|
||||
"github.com/harness/gitness/lock"
|
||||
"github.com/harness/gitness/pubsub"
|
||||
@ -112,10 +112,9 @@ func initSystem(ctx context.Context, config *types.Config) (*cliserver.System, e
|
||||
gitevents.WireSet,
|
||||
pullreqevents.WireSet,
|
||||
repoevents.WireSet,
|
||||
cliserver.ProvideGitRPCServerConfig,
|
||||
gitrpcserver.WireSet,
|
||||
cliserver.ProvideGitRPCClientConfig,
|
||||
gitrpc.WireSet,
|
||||
storage.WireSet,
|
||||
adapter.WireSet,
|
||||
git.WireSet,
|
||||
store.WireSet,
|
||||
check.WireSet,
|
||||
encrypt.WireSet,
|
||||
@ -135,7 +134,6 @@ func initSystem(ctx context.Context, config *types.Config) (*cliserver.System, e
|
||||
codecomments.WireSet,
|
||||
job.WireSet,
|
||||
protection.WireSet,
|
||||
gitrpccron.WireSet,
|
||||
checkcontroller.WireSet,
|
||||
execution.WireSet,
|
||||
pipeline.WireSet,
|
||||
|
@ -67,9 +67,9 @@ import (
|
||||
"github.com/harness/gitness/cli/server"
|
||||
"github.com/harness/gitness/encrypt"
|
||||
"github.com/harness/gitness/events"
|
||||
"github.com/harness/gitness/gitrpc"
|
||||
server3 "github.com/harness/gitness/gitrpc/server"
|
||||
"github.com/harness/gitness/gitrpc/server/cron"
|
||||
"github.com/harness/gitness/git"
|
||||
"github.com/harness/gitness/git/adapter"
|
||||
"github.com/harness/gitness/git/storage"
|
||||
"github.com/harness/gitness/livelog"
|
||||
"github.com/harness/gitness/lock"
|
||||
"github.com/harness/gitness/pubsub"
|
||||
@ -121,11 +121,18 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gitrpcConfig, err := server.ProvideGitRPCClientConfig()
|
||||
goGitRepoProvider := adapter.ProvideGoGitRepoProvider()
|
||||
universalClient, err := server.ProvideRedis(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gitrpcInterface, err := gitrpc.ProvideClient(gitrpcConfig)
|
||||
cacheCache := adapter.ProvideLastCommitCache(config, universalClient, goGitRepoProvider)
|
||||
gitAdapter, err := git.ProvideGITAdapter(goGitRepoProvider, cacheCache)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storageStore := storage.ProvideLocalStore()
|
||||
gitInterface, err := git.ProvideService(config, gitAdapter, storageStore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -136,10 +143,6 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
}
|
||||
jobStore := database.ProvideJobStore(db)
|
||||
pubsubConfig := server.ProvidePubsubConfig(config)
|
||||
universalClient, err := server.ProvideRedis(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pubSub := pubsub.ProvidePubSub(pubsubConfig, universalClient)
|
||||
executor := job.ProvideExecutor(jobStore, pubSub)
|
||||
lockConfig := server.ProvideLockConfig(config)
|
||||
@ -149,12 +152,12 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
return nil, err
|
||||
}
|
||||
streamer := sse.ProvideEventsStreaming(pubSub)
|
||||
repository, err := importer.ProvideRepoImporter(config, provider, gitrpcInterface, transactor, repoStore, pipelineStore, triggerStore, encrypter, jobScheduler, executor, streamer)
|
||||
repository, err := importer.ProvideRepoImporter(config, provider, gitInterface, transactor, repoStore, pipelineStore, triggerStore, encrypter, jobScheduler, executor, streamer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
codeownersConfig := server.ProvideCodeOwnerConfig(config)
|
||||
codeownersService := codeowners.ProvideCodeOwners(gitrpcInterface, repoStore, codeownersConfig, principalStore)
|
||||
codeownersService := codeowners.ProvideCodeOwners(gitInterface, repoStore, codeownersConfig, principalStore)
|
||||
eventsConfig := server.ProvideEventsConfig(config)
|
||||
eventsSystem, err := events.ProvideSystem(eventsConfig, universalClient)
|
||||
if err != nil {
|
||||
@ -164,7 +167,7 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repoController := repo.ProvideController(config, transactor, provider, pathUID, authorizer, repoStore, spaceStore, pipelineStore, principalStore, ruleStore, protectionManager, gitrpcInterface, repository, codeownersService, reporter)
|
||||
repoController := repo.ProvideController(config, transactor, provider, pathUID, authorizer, repoStore, spaceStore, pipelineStore, principalStore, ruleStore, protectionManager, gitInterface, repository, codeownersService, reporter)
|
||||
executionStore := database.ProvideExecutionStore(db)
|
||||
checkStore := database.ProvideCheckStore(db, principalInfoCache)
|
||||
stageStore := database.ProvideStageStore(db)
|
||||
@ -174,8 +177,8 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
}
|
||||
stepStore := database.ProvideStepStore(db)
|
||||
cancelerCanceler := canceler.ProvideCanceler(executionStore, streamer, repoStore, schedulerScheduler, stageStore, stepStore)
|
||||
commitService := commit.ProvideService(gitrpcInterface)
|
||||
fileService := file.ProvideService(gitrpcInterface)
|
||||
commitService := commit.ProvideService(gitInterface)
|
||||
fileService := file.ProvideService(gitInterface)
|
||||
triggererTriggerer := triggerer.ProvideTriggerer(executionStore, checkStore, stageStore, transactor, pipelineStore, fileService, schedulerScheduler, repoStore, provider)
|
||||
executionController := execution.ProvideController(transactor, authorizer, executionStore, checkStore, cancelerCanceler, commitService, triggererTriggerer, repoStore, stageStore, pipelineStore)
|
||||
logStore := logs.ProvideLogStore(db, config)
|
||||
@ -184,7 +187,7 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
secretStore := database.ProvideSecretStore(db)
|
||||
connectorStore := database.ProvideConnectorStore(db)
|
||||
templateStore := database.ProvideTemplateStore(db)
|
||||
exporterRepository, err := exporter.ProvideSpaceExporter(provider, gitrpcInterface, repoStore, jobScheduler, executor, encrypter, streamer)
|
||||
exporterRepository, err := exporter.ProvideSpaceExporter(provider, gitInterface, repoStore, jobScheduler, executor, encrypter, streamer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -206,7 +209,7 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
migrator := codecomments.ProvideMigrator(gitrpcInterface)
|
||||
migrator := codecomments.ProvideMigrator(gitInterface)
|
||||
readerFactory, err := events4.ProvideReaderFactory(eventsSystem)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -217,15 +220,15 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
}
|
||||
repoGitInfoView := database.ProvideRepoGitInfoView(db)
|
||||
repoGitInfoCache := cache.ProvideRepoGitInfoCache(repoGitInfoView)
|
||||
pullreqService, err := pullreq.ProvideService(ctx, config, readerFactory, eventsReaderFactory, eventsReporter, gitrpcInterface, repoGitInfoCache, repoStore, pullReqStore, pullReqActivityStore, codeCommentView, migrator, pullReqFileViewStore, pubSub, provider, streamer)
|
||||
pullreqService, err := pullreq.ProvideService(ctx, config, readerFactory, eventsReaderFactory, eventsReporter, gitInterface, repoGitInfoCache, repoStore, pullReqStore, pullReqActivityStore, codeCommentView, migrator, pullReqFileViewStore, pubSub, provider, streamer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pullreqController := pullreq2.ProvideController(transactor, provider, authorizer, pullReqStore, pullReqActivityStore, codeCommentView, pullReqReviewStore, pullReqReviewerStore, repoStore, principalStore, pullReqFileViewStore, membershipStore, checkStore, gitrpcInterface, eventsReporter, mutexManager, migrator, pullreqService, protectionManager, streamer, codeownersService)
|
||||
pullreqController := pullreq2.ProvideController(transactor, provider, authorizer, pullReqStore, pullReqActivityStore, codeCommentView, pullReqReviewStore, pullReqReviewerStore, repoStore, principalStore, pullReqFileViewStore, membershipStore, checkStore, gitInterface, eventsReporter, mutexManager, migrator, pullreqService, protectionManager, streamer, codeownersService)
|
||||
webhookConfig := server.ProvideWebhookConfig(config)
|
||||
webhookStore := database.ProvideWebhookStore(db)
|
||||
webhookExecutionStore := database.ProvideWebhookExecutionStore(db)
|
||||
webhookService, err := webhook.ProvideService(ctx, webhookConfig, readerFactory, eventsReaderFactory, webhookStore, webhookExecutionStore, repoStore, pullReqStore, pullReqActivityStore, provider, principalStore, gitrpcInterface, encrypter)
|
||||
webhookService, err := webhook.ProvideService(ctx, webhookConfig, readerFactory, eventsReaderFactory, webhookStore, webhookExecutionStore, repoStore, pullReqStore, pullReqActivityStore, provider, principalStore, gitInterface, encrypter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -237,7 +240,7 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
githookController := githook.ProvideController(authorizer, principalStore, repoStore, reporter2, pullReqStore, provider, protectionManager)
|
||||
serviceaccountController := serviceaccount.NewController(principalUID, authorizer, principalStore, spaceStore, repoStore, tokenStore)
|
||||
principalController := principal.ProvideController(principalStore)
|
||||
checkController := check2.ProvideController(transactor, authorizer, repoStore, checkStore, gitrpcInterface)
|
||||
checkController := check2.ProvideController(transactor, authorizer, repoStore, checkStore, gitInterface)
|
||||
systemController := system.NewController(principalStore, config)
|
||||
blobConfig, err := server.ProvideBlobStoreConfig(config)
|
||||
if err != nil {
|
||||
@ -261,21 +264,6 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
return nil, err
|
||||
}
|
||||
poller := runner.ProvideExecutionPoller(runtimeRunner, client)
|
||||
serverConfig, err := server.ProvideGitRPCServerConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
goGitRepoProvider := server3.ProvideGoGitRepoProvider()
|
||||
cacheCache := server3.ProvideLastCommitCache(serverConfig, universalClient, goGitRepoProvider)
|
||||
gitAdapter, err := server3.ProvideGITAdapter(goGitRepoProvider, cacheCache)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
grpcServer, err := server3.ProvideServer(serverConfig, gitAdapter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cronManager := cron.ProvideManager(serverConfig)
|
||||
triggerConfig := server.ProvideTriggerConfig(config)
|
||||
triggerService, err := trigger2.ProvideService(ctx, triggerConfig, triggerStore, commitService, pullReqStore, repoStore, pipelineStore, triggererTriggerer, readerFactory, eventsReaderFactory)
|
||||
if err != nil {
|
||||
@ -291,6 +279,6 @@ func initSystem(ctx context.Context, config *types.Config) (*server.System, erro
|
||||
return nil, err
|
||||
}
|
||||
servicesServices := services.ProvideServices(webhookService, pullreqService, triggerService, jobScheduler, collector, cleanupService)
|
||||
serverSystem := server.NewSystem(bootstrapBootstrap, serverServer, poller, grpcServer, pluginManager, cronManager, servicesServices)
|
||||
serverSystem := server.NewSystem(bootstrapBootstrap, serverServer, poller, pluginManager, servicesServices)
|
||||
return serverSystem, nil
|
||||
}
|
||||
|
216
errors/status.go
Normal file
216
errors/status.go
Normal file
@ -0,0 +1,216 @@
|
||||
// Copyright 2023 Harness, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package errors
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusConflict Status = "conflict"
|
||||
StatusInternal Status = "internal"
|
||||
StatusInvalidArgument Status = "invalid"
|
||||
StatusNotFound Status = "not_found"
|
||||
StatusPathNotFound Status = "path_not_found"
|
||||
StatusNotImplemented Status = "not_implemented"
|
||||
StatusUnauthorized Status = "unauthorized"
|
||||
StatusFailed Status = "failed"
|
||||
StatusPreconditionFailed Status = "precondition_failed"
|
||||
StatusAborted Status = "aborted"
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
// Source error
|
||||
Err error
|
||||
|
||||
// Machine-readable status code.
|
||||
Status Status
|
||||
|
||||
// Human-readable error message.
|
||||
Message string
|
||||
|
||||
// Details
|
||||
Details map[string]any
|
||||
}
|
||||
|
||||
func (e *Error) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *Error) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
// AsStatus unwraps an error and returns its code.
|
||||
// Non-application errors always return StatusInternal.
|
||||
func AsStatus(err error) Status {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
e := AsError(err)
|
||||
if e != nil {
|
||||
return e.Status
|
||||
}
|
||||
return StatusInternal
|
||||
}
|
||||
|
||||
// Message unwraps an error and returns its message.
|
||||
func Message(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
e := AsError(err)
|
||||
if e != nil {
|
||||
return e.Message
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
// Details unwraps an error and returns its details.
|
||||
func Details(err error) map[string]any {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
e := AsError(err)
|
||||
if e != nil {
|
||||
return e.Details
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AsError return err as Error.
|
||||
func AsError(err error) (e *Error) {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.As(err, &e) {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type Arg struct {
|
||||
Key string
|
||||
Value any
|
||||
}
|
||||
|
||||
// Format is a helper function to return an Error with a given status and formatted message.
|
||||
func Format(code Status, format string, args ...interface{}) *Error {
|
||||
var (
|
||||
err error
|
||||
details []Arg
|
||||
newArgs []any
|
||||
)
|
||||
|
||||
for _, arg := range args {
|
||||
if arg == nil {
|
||||
continue
|
||||
}
|
||||
switch obj := arg.(type) {
|
||||
case error:
|
||||
err = obj
|
||||
case Arg:
|
||||
details = append(details, obj)
|
||||
case []Arg:
|
||||
details = append(details, obj...)
|
||||
default:
|
||||
newArgs = append(newArgs, obj)
|
||||
}
|
||||
}
|
||||
|
||||
msg := fmt.Sprintf(format, newArgs...)
|
||||
newErr := &Error{
|
||||
Status: code,
|
||||
Message: msg,
|
||||
Err: err,
|
||||
}
|
||||
if len(details) > 0 {
|
||||
newErr.Details = make(map[string]any)
|
||||
for _, arg := range details {
|
||||
newErr.Details[arg.Key] = arg.Value
|
||||
}
|
||||
}
|
||||
return newErr
|
||||
}
|
||||
|
||||
// NotFound is a helper function to return an not found Error.
|
||||
func NotFound(format string, args ...interface{}) *Error {
|
||||
return Format(StatusNotFound, format, args...)
|
||||
}
|
||||
|
||||
// InvalidArgument is a helper function to return an invalid argument Error.
|
||||
func InvalidArgument(format string, args ...interface{}) *Error {
|
||||
return Format(StatusInvalidArgument, format, args...)
|
||||
}
|
||||
|
||||
// Internal is a helper function to return an internal Error.
|
||||
func Internal(format string, args ...interface{}) *Error {
|
||||
return Format(StatusInternal, format, args...)
|
||||
}
|
||||
|
||||
// Conflict is a helper function to return an conflict Error.
|
||||
func Conflict(format string, args ...interface{}) *Error {
|
||||
return Format(StatusConflict, format, args...)
|
||||
}
|
||||
|
||||
// PreconditionFailed is a helper function to return an precondition
|
||||
// failed error.
|
||||
func PreconditionFailed(format string, args ...interface{}) *Error {
|
||||
return Format(StatusPreconditionFailed, format, args...)
|
||||
}
|
||||
|
||||
// Failed is a helper function to return failed error status.
|
||||
func Failed(format string, args ...interface{}) *Error {
|
||||
return Format(StatusFailed, format, args...)
|
||||
}
|
||||
|
||||
// Aborted is a helper function to return aborted error status.
|
||||
func Aborted(format string, args ...interface{}) *Error {
|
||||
return Format(StatusAborted, format, args...)
|
||||
}
|
||||
|
||||
// IsNotFound checks if err is not found error.
|
||||
func IsNotFound(err error) bool {
|
||||
return AsStatus(err) == StatusNotFound
|
||||
}
|
||||
|
||||
// IsConflict checks if err is conflict error.
|
||||
func IsConflict(err error) bool {
|
||||
return AsStatus(err) == StatusConflict
|
||||
}
|
||||
|
||||
// IsInvalidArgument checks if err is invalid argument error.
|
||||
func IsInvalidArgument(err error) bool {
|
||||
return AsStatus(err) == StatusInvalidArgument
|
||||
}
|
||||
|
||||
// IsInternal checks if err is internal error.
|
||||
func IsInternal(err error) bool {
|
||||
return AsStatus(err) == StatusInternal
|
||||
}
|
||||
|
||||
// IsPreconditionFailed checks if err is precondition failed error.
|
||||
func IsPreconditionFailed(err error) bool {
|
||||
return AsStatus(err) == StatusPreconditionFailed
|
||||
}
|
||||
|
||||
// IsAborted checks if err is aborted error.
|
||||
func IsAborted(err error) bool {
|
||||
return AsStatus(err) == StatusAborted
|
||||
}
|
@ -12,19 +12,18 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cron
|
||||
package errors
|
||||
|
||||
import (
|
||||
"github.com/harness/gitness/gitrpc/server"
|
||||
import "errors"
|
||||
|
||||
"github.com/google/wire"
|
||||
)
|
||||
|
||||
// WireSet provides a wire set for this package.
|
||||
var WireSet = wire.NewSet(ProvideManager)
|
||||
|
||||
func ProvideManager(gitrpcconfig server.Config) *Manager {
|
||||
cmngr := NewManager()
|
||||
_ = AddAllGitRPCCronJobs(cmngr, gitrpcconfig)
|
||||
return cmngr
|
||||
func New(text string) error {
|
||||
return errors.New(text)
|
||||
}
|
||||
|
||||
func Is(err error, target error) bool {
|
||||
return errors.Is(err, target)
|
||||
}
|
||||
|
||||
func As(err error, target any) bool {
|
||||
return errors.As(err, target)
|
||||
}
|
@ -12,23 +12,35 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package service
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/enum"
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/adapter"
|
||||
"github.com/harness/gitness/git/enum"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
)
|
||||
|
||||
// GitAdapter for accessing git commands from gitea.
|
||||
type GitAdapter interface {
|
||||
var _ Adapter = (*adapter.Adapter)(nil)
|
||||
|
||||
// Adapter for accessing git commands from gitea.
|
||||
type Adapter interface {
|
||||
InitRepository(ctx context.Context, path string, bare bool) error
|
||||
OpenRepository(ctx context.Context, path string) (*git.Repository, error)
|
||||
SharedRepository(tmp string, repoUID string, remotePath string) (*adapter.SharedRepo, error)
|
||||
Config(ctx context.Context, repoPath, key, value string) error
|
||||
SetDefaultBranch(ctx context.Context, repoPath string, defaultBranch string, allowEmpty bool) error
|
||||
|
||||
SetDefaultBranch(ctx context.Context, repoPath string,
|
||||
defaultBranch string, allowEmpty bool) error
|
||||
GetDefaultBranch(ctx context.Context, repoPath string) (string, error)
|
||||
GetRemoteDefaultBranch(ctx context.Context, remoteURL string) (string, error)
|
||||
GetRemoteDefaultBranch(ctx context.Context,
|
||||
remoteURL string) (string, error)
|
||||
HasBranches(ctx context.Context, repoPath string) (bool, error)
|
||||
|
||||
Clone(ctx context.Context, from, to string, opts types.CloneRepoOptions) error
|
||||
AddFiles(repoPath string, all bool, files ...string) error
|
||||
Commit(ctx context.Context, repoPath string, opts types.CommitChangesOptions) error
|
||||
@ -60,7 +72,7 @@ type GitAdapter interface {
|
||||
CreateTemporaryRepoForPR(ctx context.Context, reposTempPath string, pr *types.PullRequest,
|
||||
baseBranch, trackingBranch string) (types.TempRepository, error)
|
||||
Merge(ctx context.Context, pr *types.PullRequest, mergeMethod enum.MergeMethod, baseBranch, trackingBranch string,
|
||||
tmpBasePath string, mergeMsg string, env []string, identity *types.Identity) error
|
||||
tmpBasePath string, mergeMsg string, identity *types.Identity, env ...string) error
|
||||
GetMergeBase(ctx context.Context, repoPath, remote, base, head string) (string, string, error)
|
||||
Blame(ctx context.Context, repoPath, rev, file string, lineFrom, lineTo int) types.BlameReader
|
||||
Sync(ctx context.Context, repoPath string, source string, refSpecs []string) error
|
||||
@ -111,6 +123,22 @@ type GitAdapter interface {
|
||||
regExpDef string,
|
||||
maxSize int) ([]types.FileContent, error)
|
||||
|
||||
// http
|
||||
InfoRefs(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
service string,
|
||||
w io.Writer,
|
||||
env ...string,
|
||||
) error
|
||||
ServicePack(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
service string,
|
||||
stdin io.Reader,
|
||||
stdout io.Writer,
|
||||
env ...string,
|
||||
) error
|
||||
DiffFileName(ctx context.Context,
|
||||
repoPath string,
|
||||
baseRef string,
|
@ -12,13 +12,13 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/harness/gitness/cache"
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/setting"
|
@ -12,14 +12,14 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
@ -12,29 +12,38 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func (g Adapter) Blame(ctx context.Context,
|
||||
repoPath, rev, file string,
|
||||
lineFrom, lineTo int,
|
||||
var (
|
||||
// blamePorcelainHeadRE is used to detect line header start in git blame porcelain output.
|
||||
// It is explained here: https://www.git-scm.com/docs/git-blame#_the_porcelain_format
|
||||
blamePorcelainHeadRE = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64}) (\d+) (\d+)( (\d+))?$`)
|
||||
blamePorcelainOutOfRangeErrorRE = regexp.MustCompile(`has only \d+ lines$`)
|
||||
)
|
||||
|
||||
func (a Adapter) Blame(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
rev string,
|
||||
file string,
|
||||
lineFrom int,
|
||||
lineTo int,
|
||||
) types.BlameReader {
|
||||
// prepare the git command line arguments
|
||||
args := make([]string, 0, 8)
|
||||
@ -77,12 +86,6 @@ func (g Adapter) Blame(ctx context.Context,
|
||||
}
|
||||
}
|
||||
|
||||
// blamePorcelainHeadRE is used to detect line header start in git blame porcelain output.
|
||||
// It is explained here: https://www.git-scm.com/docs/git-blame#_the_porcelain_format
|
||||
var blamePorcelainHeadRE = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64}) (\d+) (\d+)( (\d+))?$`)
|
||||
|
||||
var blamePorcelainOutOfRangeErrorRE = regexp.MustCompile(`has only \d+ lines$`)
|
||||
|
||||
type BlameReader struct {
|
||||
scanner *bufio.Scanner
|
||||
lastLine string
|
||||
@ -114,7 +117,7 @@ func (r *BlameReader) unreadLine(line string) {
|
||||
r.lastLine = line
|
||||
}
|
||||
|
||||
//nolint:gocognit,nestif // it's ok
|
||||
//nolint:complexity,gocognit,nestif // it's ok
|
||||
func (r *BlameReader) NextPart() (*types.BlamePart, error) {
|
||||
var commit *types.Commit
|
||||
var lines []string
|
||||
@ -152,7 +155,7 @@ func (r *BlameReader) NextPart() (*types.BlamePart, error) {
|
||||
r.commitCache[commit.SHA] = commit
|
||||
|
||||
return &types.BlamePart{
|
||||
Commit: *commit,
|
||||
Commit: commit,
|
||||
Lines: lines,
|
||||
}, nil
|
||||
}
|
||||
@ -189,26 +192,26 @@ func (r *BlameReader) NextPart() (*types.BlamePart, error) {
|
||||
|
||||
switch {
|
||||
case strings.Contains(line, "no such path"):
|
||||
return nil, status.Error(codes.NotFound, line)
|
||||
return nil, errors.NotFound(line)
|
||||
case strings.Contains(line, "bad revision"):
|
||||
return nil, status.Error(codes.NotFound, line)
|
||||
return nil, errors.NotFound(line)
|
||||
case blamePorcelainOutOfRangeErrorRE.MatchString(line):
|
||||
return nil, status.Error(codes.InvalidArgument, line)
|
||||
return nil, errors.InvalidArgument(line)
|
||||
default:
|
||||
return nil, status.Error(codes.Unknown, line)
|
||||
return nil, errors.Internal(line)
|
||||
}
|
||||
}
|
||||
|
||||
// This error can happen if the command git failed to start. Triggered by pipe writer's CloseWithError call.
|
||||
if !errors.Is(err, io.EOF) {
|
||||
return nil, status.Error(codes.Internal, err.Error())
|
||||
return nil, errors.Internal(err.Error())
|
||||
}
|
||||
|
||||
var part *types.BlamePart
|
||||
|
||||
if commit != nil && len(lines) > 0 {
|
||||
part = &types.BlamePart{
|
||||
Commit: *commit,
|
||||
Commit: commit,
|
||||
Lines: lines,
|
||||
}
|
||||
}
|
@ -12,22 +12,20 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/iotest"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestBlameReader_NextPart(t *testing.T) {
|
||||
@ -75,7 +73,7 @@ filename file_name.go
|
||||
Email: "noreply@harness.io",
|
||||
}
|
||||
|
||||
commit1 := types.Commit{
|
||||
commit1 := &types.Commit{
|
||||
SHA: "16f267ad4f731af1b2e36f42e170ed8921377398",
|
||||
Title: "Pull request 1",
|
||||
Message: "",
|
||||
@ -89,7 +87,7 @@ filename file_name.go
|
||||
},
|
||||
}
|
||||
|
||||
commit2 := types.Commit{
|
||||
commit2 := &types.Commit{
|
||||
SHA: "dcb4b6b63e86f06ed4e4c52fbc825545dc0b6200",
|
||||
Title: "Pull request 2",
|
||||
Message: "",
|
||||
@ -152,7 +150,7 @@ func TestBlameReader_NextPart_UserError(t *testing.T) {
|
||||
}
|
||||
|
||||
_, err := reader.NextPart()
|
||||
if s, ok := status.FromError(err); !ok || s.Code() != codes.NotFound {
|
||||
if s := errors.AsStatus(err); s != errors.StatusNotFound {
|
||||
t.Errorf("expected NotFound error but got: %v", err)
|
||||
}
|
||||
}
|
||||
@ -165,7 +163,7 @@ func TestBlameReader_NextPart_CmdError(t *testing.T) {
|
||||
}
|
||||
|
||||
_, err := reader.NextPart()
|
||||
if s, ok := status.FromError(err); !ok || s.Code() != codes.Internal || s.Message() != "dummy error" {
|
||||
if s := errors.AsError(err); s.Status != errors.StatusInternal || s.Message != "dummy error" {
|
||||
t.Errorf("expected Internal error but got: %v", err)
|
||||
}
|
||||
}
|
@ -12,32 +12,39 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gogitplumbing "github.com/go-git/go-git/v5/plumbing"
|
||||
)
|
||||
|
||||
// GetBlob returns the blob for the given object sha.
|
||||
func (g Adapter) GetBlob(ctx context.Context, repoPath string, sha string, sizeLimit int64) (*types.BlobReader, error) {
|
||||
repo, err := g.repoProvider.Get(ctx, repoPath)
|
||||
func (a Adapter) GetBlob(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
sha string,
|
||||
sizeLimit int64,
|
||||
) (*types.BlobReader, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
repo, err := a.repoProvider.Get(ctx, repoPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open repository: %w", err)
|
||||
return nil, errors.Internal("failed to open repository", err)
|
||||
}
|
||||
|
||||
blob, err := repo.BlobObject(gogitplumbing.NewHash(sha))
|
||||
if err != nil {
|
||||
if errors.Is(err, gogitplumbing.ErrObjectNotFound) {
|
||||
return nil, types.ErrNotFound
|
||||
return nil, errors.NotFound("blob sha %s not found", sha)
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get blob object: %w", err)
|
||||
return nil, errors.Internal("failed to get blob object for sha '%s'", sha, err)
|
||||
}
|
||||
|
||||
objectSize := blob.Size
|
||||
@ -48,7 +55,7 @@ func (g Adapter) GetBlob(ctx context.Context, repoPath string, sha string, sizeL
|
||||
|
||||
reader, err := blob.Reader()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open blob object: %w", err)
|
||||
return nil, errors.Internal("failed to open blob object for sha '%s'", sha, err)
|
||||
}
|
||||
|
||||
return &types.BlobReader{
|
@ -12,20 +12,31 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
)
|
||||
|
||||
// GetBranch gets an existing branch.
|
||||
func (g Adapter) GetBranch(ctx context.Context, repoPath string,
|
||||
branchName string) (*types.Branch, error) {
|
||||
func (a Adapter) GetBranch(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
branchName string,
|
||||
) (*types.Branch, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
if branchName == "" {
|
||||
return nil, ErrBranchNameEmpty
|
||||
}
|
||||
|
||||
giteaRepo, err := gitea.OpenRepository(ctx, repoPath)
|
||||
if err != nil {
|
||||
return nil, processGiteaErrorf(err, "failed to open repository")
|
||||
@ -44,7 +55,7 @@ func (g Adapter) GetBranch(ctx context.Context, repoPath string,
|
||||
|
||||
commit, err := mapGiteaCommit(giteaCommit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to map gitea commit: %w", err)
|
||||
return nil, errors.Internal("failed to map gitea commit", err)
|
||||
}
|
||||
|
||||
return &types.Branch{
|
||||
@ -53,3 +64,24 @@ func (g Adapter) GetBranch(ctx context.Context, repoPath string,
|
||||
Commit: commit,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// HasBranches returns true iff there's at least one branch in the repo (any branch)
|
||||
// NOTE: This is different from repo.Empty(),
|
||||
// as it doesn't care whether the existing branch is the default branch or not.
|
||||
func (a Adapter) HasBranches(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
) (bool, error) {
|
||||
if repoPath == "" {
|
||||
return false, ErrRepositoryPathEmpty
|
||||
}
|
||||
// repo has branches IFF there's at least one commit that is reachable via a branch
|
||||
// (every existing branch points to a commit)
|
||||
stdout, _, runErr := gitea.NewCommand(ctx, "rev-list", "--max-count", "1", "--branches").
|
||||
RunStdBytes(&gitea.RunOpts{Dir: repoPath})
|
||||
if runErr != nil {
|
||||
return false, processGiteaErrorf(runErr, "failed to trigger rev-list command")
|
||||
}
|
||||
|
||||
return strings.TrimSpace(string(stdout)) == "", nil
|
||||
}
|
@ -12,17 +12,17 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
)
|
||||
@ -33,8 +33,15 @@ const (
|
||||
|
||||
// GetLatestCommit gets the latest commit of a path relative from the provided reference.
|
||||
// Note: ref can be Branch / Tag / CommitSHA.
|
||||
func (g Adapter) GetLatestCommit(ctx context.Context, repoPath string,
|
||||
ref string, treePath string) (*types.Commit, error) {
|
||||
func (a Adapter) GetLatestCommit(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
ref string,
|
||||
treePath string,
|
||||
) (*types.Commit, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
treePath = cleanTreePath(treePath)
|
||||
|
||||
giteaRepo, err := gitea.OpenRepository(ctx, repoPath)
|
||||
@ -52,7 +59,11 @@ func (g Adapter) GetLatestCommit(ctx context.Context, repoPath string,
|
||||
}
|
||||
|
||||
// giteaGetCommitByPath returns the latest commit per specific branch.
|
||||
func giteaGetCommitByPath(giteaRepo *gitea.Repository, ref string, treePath string) (*gitea.Commit, error) {
|
||||
func giteaGetCommitByPath(
|
||||
giteaRepo *gitea.Repository,
|
||||
ref string,
|
||||
treePath string,
|
||||
) (*gitea.Commit, error) {
|
||||
if treePath == "" {
|
||||
treePath = "."
|
||||
}
|
||||
@ -61,20 +72,23 @@ func giteaGetCommitByPath(giteaRepo *gitea.Repository, ref string, treePath stri
|
||||
stdout, _, runErr := gitea.NewCommand(giteaRepo.Ctx, "log", ref, "-1", giteaPrettyLogFormat, "--", treePath).
|
||||
RunStdBytes(&gitea.RunOpts{Dir: giteaRepo.Path})
|
||||
if runErr != nil {
|
||||
return nil, fmt.Errorf("failed to trigger log command: %w", runErr)
|
||||
return nil, fmt.Errorf("in giteaGetCommitByPath: failed to trigger log command: %w", runErr)
|
||||
}
|
||||
|
||||
lines := parseLinesToSlice(stdout)
|
||||
|
||||
giteaCommits, err := getGiteaCommits(giteaRepo, lines)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("in giteaGetCommitByPath: failed to get commits: %w", err)
|
||||
}
|
||||
|
||||
return giteaCommits[0], nil
|
||||
}
|
||||
|
||||
func getGiteaCommits(giteaRepo *gitea.Repository, commitIDs []string) ([]*gitea.Commit, error) {
|
||||
func getGiteaCommits(
|
||||
giteaRepo *gitea.Repository,
|
||||
commitIDs []string,
|
||||
) ([]*gitea.Commit, error) {
|
||||
var giteaCommits []*gitea.Commit
|
||||
if len(commitIDs) == 0 {
|
||||
return giteaCommits, nil
|
||||
@ -91,7 +105,7 @@ func getGiteaCommits(giteaRepo *gitea.Repository, commitIDs []string) ([]*gitea.
|
||||
return giteaCommits, nil
|
||||
}
|
||||
|
||||
func (g Adapter) listCommitSHAs(
|
||||
func (a Adapter) listCommitSHAs(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
ref string,
|
||||
@ -115,7 +129,7 @@ func (g Adapter) listCommitSHAs(
|
||||
}
|
||||
|
||||
// add pagination if requested
|
||||
// TODO: we should add absolut limits to protect gitrpc (return error)
|
||||
// TODO: we should add absolut limits to protect git (return error)
|
||||
if limit > 0 {
|
||||
args = append(args, "--max-count", fmt.Sprint(limit))
|
||||
|
||||
@ -149,7 +163,7 @@ func (g Adapter) listCommitSHAs(
|
||||
// ListCommitSHAs lists the commits reachable from ref.
|
||||
// Note: ref & afterRef can be Branch / Tag / CommitSHA.
|
||||
// Note: commits returned are [ref->...->afterRef).
|
||||
func (g Adapter) ListCommitSHAs(
|
||||
func (a Adapter) ListCommitSHAs(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
ref string,
|
||||
@ -157,24 +171,29 @@ func (g Adapter) ListCommitSHAs(
|
||||
limit int,
|
||||
filter types.CommitFilter,
|
||||
) ([]string, error) {
|
||||
return g.listCommitSHAs(ctx, repoPath, ref, page, limit, filter)
|
||||
return a.listCommitSHAs(ctx, repoPath, ref, page, limit, filter)
|
||||
}
|
||||
|
||||
// ListCommits lists the commits reachable from ref.
|
||||
// Note: ref & afterRef can be Branch / Tag / CommitSHA.
|
||||
// Note: commits returned are [ref->...->afterRef).
|
||||
func (g Adapter) ListCommits(ctx context.Context,
|
||||
func (a Adapter) ListCommits(ctx context.Context,
|
||||
repoPath string,
|
||||
ref string,
|
||||
page int, limit int, filter types.CommitFilter,
|
||||
page int,
|
||||
limit int,
|
||||
filter types.CommitFilter,
|
||||
) ([]types.Commit, []types.PathRenameDetails, error) {
|
||||
if repoPath == "" {
|
||||
return nil, nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
giteaRepo, err := gitea.OpenRepository(ctx, repoPath)
|
||||
if err != nil {
|
||||
return nil, nil, processGiteaErrorf(err, "failed to open repository")
|
||||
}
|
||||
defer giteaRepo.Close()
|
||||
|
||||
commitSHAs, err := g.listCommitSHAs(ctx, repoPath, ref, page, limit, filter)
|
||||
commitSHAs, err := a.listCommitSHAs(ctx, repoPath, ref, page, limit, filter)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@ -228,7 +247,8 @@ func cleanupCommitsForRename(
|
||||
func getRenameDetails(
|
||||
giteaRepo *gitea.Repository,
|
||||
commits []types.Commit,
|
||||
path string) ([]types.PathRenameDetails, error) {
|
||||
path string,
|
||||
) ([]types.PathRenameDetails, error) {
|
||||
if len(commits) == 0 {
|
||||
return []types.PathRenameDetails{}, nil
|
||||
}
|
||||
@ -260,7 +280,11 @@ func getRenameDetails(
|
||||
return renameDetailsList, nil
|
||||
}
|
||||
|
||||
func giteaGetRenameDetails(giteaRepo *gitea.Repository, ref string, path string) (*types.PathRenameDetails, error) {
|
||||
func giteaGetRenameDetails(
|
||||
giteaRepo *gitea.Repository,
|
||||
ref string,
|
||||
path string,
|
||||
) (*types.PathRenameDetails, error) {
|
||||
stdout, _, runErr := gitea.NewCommand(giteaRepo.Ctx, "log", ref, "--name-status", "--pretty=format:", "-1").
|
||||
RunStdBytes(&gitea.RunOpts{Dir: giteaRepo.Path})
|
||||
if runErr != nil {
|
||||
@ -284,7 +308,10 @@ func giteaGetRenameDetails(giteaRepo *gitea.Repository, ref string, path string)
|
||||
return &types.PathRenameDetails{}, nil
|
||||
}
|
||||
|
||||
func getFileChangeTypeFromLog(changeStrings []string, filePath string) (*string, *string, *string, error) {
|
||||
func getFileChangeTypeFromLog(
|
||||
changeStrings []string,
|
||||
filePath string,
|
||||
) (*string, *string, *string, error) {
|
||||
for _, changeString := range changeStrings {
|
||||
if strings.Contains(changeString, filePath) {
|
||||
changeInfo := strings.Split(changeString, "\t")
|
||||
@ -294,12 +321,19 @@ func getFileChangeTypeFromLog(changeStrings []string, filePath string) (*string,
|
||||
return &changeInfo[0], &changeInfo[1], &changeInfo[2], nil
|
||||
}
|
||||
}
|
||||
return nil, nil, nil, fmt.Errorf("could not parse change for the file")
|
||||
return nil, nil, nil, fmt.Errorf("could not parse change for the file '%s'", filePath)
|
||||
}
|
||||
|
||||
// GetCommit returns the (latest) commit for a specific ref.
|
||||
// Note: ref can be Branch / Tag / CommitSHA.
|
||||
func (g Adapter) GetCommit(ctx context.Context, repoPath string, ref string) (*types.Commit, error) {
|
||||
func (a Adapter) GetCommit(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
ref string,
|
||||
) (*types.Commit, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
giteaRepo, err := gitea.OpenRepository(ctx, repoPath)
|
||||
if err != nil {
|
||||
return nil, processGiteaErrorf(err, "failed to open repository")
|
||||
@ -314,13 +348,27 @@ func (g Adapter) GetCommit(ctx context.Context, repoPath string, ref string) (*t
|
||||
return mapGiteaCommit(commit)
|
||||
}
|
||||
|
||||
func (g Adapter) GetFullCommitID(ctx context.Context, repoPath, shortID string) (string, error) {
|
||||
func (a Adapter) GetFullCommitID(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
shortID string,
|
||||
) (string, error) {
|
||||
if repoPath == "" {
|
||||
return "", ErrRepositoryPathEmpty
|
||||
}
|
||||
return gitea.GetFullCommitID(ctx, repoPath, shortID)
|
||||
}
|
||||
|
||||
// GetCommits returns the (latest) commits for a specific list of refs.
|
||||
// Note: ref can be Branch / Tag / CommitSHA.
|
||||
func (g Adapter) GetCommits(ctx context.Context, repoPath string, refs []string) ([]types.Commit, error) {
|
||||
func (a Adapter) GetCommits(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
refs []string,
|
||||
) ([]types.Commit, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
giteaRepo, err := gitea.OpenRepository(ctx, repoPath)
|
||||
if err != nil {
|
||||
return nil, processGiteaErrorf(err, "failed to open repository")
|
||||
@ -349,13 +397,20 @@ func (g Adapter) GetCommits(ctx context.Context, repoPath string, refs []string)
|
||||
// GetCommitDivergences returns the count of the diverging commits for all branch pairs.
|
||||
// IMPORTANT: If a max is provided it limits the overal count of diverging commits
|
||||
// (max 10 could lead to (0, 10) while it's actually (2, 12)).
|
||||
func (g Adapter) GetCommitDivergences(ctx context.Context, repoPath string,
|
||||
requests []types.CommitDivergenceRequest, max int32) ([]types.CommitDivergence, error) {
|
||||
func (a Adapter) GetCommitDivergences(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
requests []types.CommitDivergenceRequest,
|
||||
max int32,
|
||||
) ([]types.CommitDivergence, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
var err error
|
||||
res := make([]types.CommitDivergence, len(requests))
|
||||
for i, req := range requests {
|
||||
res[i], err = g.getCommitDivergence(ctx, repoPath, req, max)
|
||||
if errors.Is(err, types.ErrNotFound) {
|
||||
res[i], err = a.getCommitDivergence(ctx, repoPath, req, max)
|
||||
if errors.Is(err, &types.NotFoundError{}) {
|
||||
res[i] = types.CommitDivergence{Ahead: -1, Behind: -1}
|
||||
continue
|
||||
}
|
||||
@ -372,8 +427,12 @@ func (g Adapter) GetCommitDivergences(ctx context.Context, repoPath string,
|
||||
// (max 10 could lead to (0, 10) while it's actually (2, 12)).
|
||||
// NOTE: Gitea implementation makes two git cli calls, but it can be done with one
|
||||
// (downside is the max behavior explained above).
|
||||
func (g Adapter) getCommitDivergence(ctx context.Context, repoPath string,
|
||||
req types.CommitDivergenceRequest, max int32) (types.CommitDivergence, error) {
|
||||
func (a Adapter) getCommitDivergence(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
req types.CommitDivergenceRequest,
|
||||
max int32,
|
||||
) (types.CommitDivergence, error) {
|
||||
// prepare args
|
||||
args := []string{
|
||||
"rev-list",
|
@ -12,18 +12,31 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/errors"
|
||||
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
)
|
||||
|
||||
// Config set local git key and value configuration.
|
||||
func (g Adapter) Config(ctx context.Context, repoPath, key, value string) error {
|
||||
func (a Adapter) Config(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
key string,
|
||||
value string,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
if key == "" {
|
||||
return errors.InvalidArgument("key cannot be empty")
|
||||
}
|
||||
var outbuf, errbuf strings.Builder
|
||||
if err := git.NewCommand(ctx, "config", "--local").AddArguments(key, value).
|
||||
Run(&git.RunOpts{
|
@ -12,23 +12,23 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/parser"
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git/parser"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
)
|
||||
|
||||
func (g Adapter) RawDiff(
|
||||
func (a Adapter) RawDiff(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
baseRef string,
|
||||
@ -36,6 +36,9 @@ func (g Adapter) RawDiff(
|
||||
mergeBase bool,
|
||||
w io.Writer,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
args := make([]string, 0, 8)
|
||||
args = append(args, "diff", "-M", "--full-index")
|
||||
if mergeBase {
|
||||
@ -60,7 +63,18 @@ func (g Adapter) RawDiff(
|
||||
}
|
||||
|
||||
// CommitDiff will stream diff for provided ref.
|
||||
func (g Adapter) CommitDiff(ctx context.Context, repoPath, sha string, w io.Writer) error {
|
||||
func (a Adapter) CommitDiff(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
sha string,
|
||||
w io.Writer,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
if sha == "" {
|
||||
return errors.InvalidArgument("commit sha cannot be empty")
|
||||
}
|
||||
args := make([]string, 0, 8)
|
||||
args = append(args, "show", "--full-index", "--pretty=format:%b", sha)
|
||||
|
||||
@ -76,13 +90,16 @@ func (g Adapter) CommitDiff(ctx context.Context, repoPath, sha string, w io.Writ
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g Adapter) DiffShortStat(
|
||||
func (a Adapter) DiffShortStat(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
baseRef string,
|
||||
headRef string,
|
||||
useMergeBase bool,
|
||||
) (types.DiffShortStat, error) {
|
||||
if repoPath == "" {
|
||||
return types.DiffShortStat{}, ErrRepositoryPathEmpty
|
||||
}
|
||||
separator := ".."
|
||||
if useMergeBase {
|
||||
separator = "..."
|
||||
@ -108,10 +125,15 @@ func (g Adapter) DiffShortStat(
|
||||
// and all hunk headers. The diffs are generated with unified=0 parameter to create minimum sized hunks.
|
||||
// Hunks' body is ignored.
|
||||
// The purpose of this function is to get data based on which code comments could be repositioned.
|
||||
func (g Adapter) GetDiffHunkHeaders(
|
||||
func (a Adapter) GetDiffHunkHeaders(
|
||||
ctx context.Context,
|
||||
repoPath, targetRef, sourceRef string,
|
||||
repoPath string,
|
||||
targetRef string,
|
||||
sourceRef string,
|
||||
) ([]*types.DiffFileHunkHeaders, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
pipeRead, pipeWrite := io.Pipe()
|
||||
stderr := &bytes.Buffer{}
|
||||
go func() {
|
||||
@ -148,11 +170,17 @@ func (g Adapter) GetDiffHunkHeaders(
|
||||
|
||||
// DiffCut parses full file git diff output and returns lines specified with the parameters.
|
||||
// The purpose of this function is to get diff data with which code comments could be generated.
|
||||
func (g Adapter) DiffCut(
|
||||
func (a Adapter) DiffCut(
|
||||
ctx context.Context,
|
||||
repoPath, targetRef, sourceRef, path string,
|
||||
repoPath string,
|
||||
targetRef string,
|
||||
sourceRef string,
|
||||
path string,
|
||||
params types.DiffCutParams,
|
||||
) (types.HunkHeader, types.Hunk, error) {
|
||||
if repoPath == "" {
|
||||
return types.HunkHeader{}, types.Hunk{}, ErrRepositoryPathEmpty
|
||||
}
|
||||
pipeRead, pipeWrite := io.Pipe()
|
||||
stderr := &bytes.Buffer{}
|
||||
go func() {
|
||||
@ -188,7 +216,7 @@ func (g Adapter) DiffCut(
|
||||
return diffCutHeader, linesHunk, nil
|
||||
}
|
||||
|
||||
func (g Adapter) DiffFileName(ctx context.Context,
|
||||
func (a Adapter) DiffFileName(ctx context.Context,
|
||||
repoPath string,
|
||||
baseRef string,
|
||||
headRef string,
|
@ -12,11 +12,10 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package service
|
||||
package adapter
|
||||
|
||||
const (
|
||||
EnvActorName = "GITRPC_ACTOR_NAME"
|
||||
EnvActorEmail = "GITRPC_ACTOR_EMAIL"
|
||||
EnvRepoUID = "GITRPC_REPO_UID"
|
||||
EnvRequestID = "GITRPC_REQUEST_ID"
|
||||
gitCommitterEmail = "GIT_COMMITTER_EMAIL"
|
||||
gitCommitterName = "GIT_COMMITTER_NAME"
|
||||
gitCommitterDate = "GIT_COMMITTER_DATE"
|
||||
)
|
@ -12,25 +12,58 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/errors"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
gogitfilemode "github.com/go-git/go-git/v5/plumbing/filemode"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrRepositoryPathEmpty = errors.InvalidArgument("repository path cannot be empty")
|
||||
ErrBranchNameEmpty = errors.InvalidArgument("branch name cannot be empty")
|
||||
)
|
||||
|
||||
type runStdError struct {
|
||||
err error
|
||||
stderr string
|
||||
errMsg string
|
||||
}
|
||||
|
||||
func (r *runStdError) Error() string {
|
||||
// the stderr must be in the returned error text, some code only checks `strings.Contains(err.Error(), "git error")`
|
||||
if r.errMsg == "" {
|
||||
r.errMsg = gitea.ConcatenateError(r.err, r.stderr).Error()
|
||||
}
|
||||
return r.errMsg
|
||||
}
|
||||
|
||||
func (r *runStdError) Unwrap() error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
func (r *runStdError) Stderr() string {
|
||||
return r.stderr
|
||||
}
|
||||
|
||||
func (r *runStdError) IsExitCode(code int) bool {
|
||||
var exitError *exec.ExitError
|
||||
if errors.As(r.err, &exitError) {
|
||||
return exitError.ExitCode() == code
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Logs the error and message, returns either the provided message or a git equivalent if possible.
|
||||
// Always logs the full message with error as warning.
|
||||
func processGiteaErrorf(err error, format string, args ...interface{}) error {
|
||||
// create fallback error returned if we can't map it
|
||||
fallbackErr := fmt.Errorf(format, args...)
|
||||
fallbackErr := errors.Internal(format, args...)
|
||||
|
||||
// always log internal error together with message.
|
||||
log.Warn().Msgf("%v: [GITEA] %v", fallbackErr, err)
|
||||
@ -44,11 +77,11 @@ func processGiteaErrorf(err error, format string, args ...interface{}) error {
|
||||
switch {
|
||||
// gitea is using errors.New(no such file or directory") exclusively for OpenRepository ... (at least as of now)
|
||||
case err.Error() == "no such file or directory":
|
||||
return fmt.Errorf("repository not found: %w", types.ErrNotFound)
|
||||
return errors.NotFound("repository not found")
|
||||
case gitea.IsErrNotExist(err):
|
||||
return types.ErrNotFound
|
||||
return errors.NotFound(format, args, err)
|
||||
case gitea.IsErrBranchNotExist(err):
|
||||
return types.ErrNotFound
|
||||
return errors.NotFound(format, args, err)
|
||||
default:
|
||||
return fallbackErr
|
||||
}
|
||||
@ -61,15 +94,15 @@ func mapGiteaRunStdError(err gitea.RunStdError, fallback error) error {
|
||||
// exit status 128 - fatal: A branch named 'mybranch' already exists.
|
||||
// exit status 128 - fatal: cannot lock ref 'refs/heads/a': 'refs/heads/a/b' exists; cannot create 'refs/heads/a'
|
||||
case err.IsExitCode(128) && strings.Contains(err.Stderr(), "exists"):
|
||||
return types.ErrAlreadyExists
|
||||
return errors.Conflict(err.Stderr())
|
||||
|
||||
// exit status 128 - fatal: 'a/bc/d/' is not a valid branch name.
|
||||
case err.IsExitCode(128) && strings.Contains(err.Stderr(), "not a valid"):
|
||||
return types.ErrInvalidArgument
|
||||
return errors.InvalidArgument(err.Stderr())
|
||||
|
||||
// exit status 1 - error: branch 'mybranch' not found.
|
||||
case err.IsExitCode(1) && strings.Contains(err.Stderr(), "not found"):
|
||||
return types.ErrNotFound
|
||||
return errors.NotFound(err.Stderr())
|
||||
|
||||
// exit status 128 - fatal: ambiguous argument 'branch1...branch2': unknown revision or path not in the working tree.
|
||||
case err.IsExitCode(128) && strings.Contains(err.Stderr(), "unknown revision"):
|
||||
@ -82,107 +115,18 @@ func mapGiteaRunStdError(err gitea.RunStdError, fallback error) error {
|
||||
msg = cols[1] + ", " + cols[2]
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%v err: %w", msg, types.ErrNotFound)
|
||||
return errors.NotFound(msg)
|
||||
|
||||
// exit status 128 - fatal: couldn't find remote ref v1.
|
||||
case err.IsExitCode(128) && strings.Contains(err.Stderr(), "couldn't find"):
|
||||
return types.ErrNotFound
|
||||
return errors.NotFound(err.Stderr())
|
||||
|
||||
// exit status 128 - fatal: unable to access 'http://127.0.0.1:4101/hvfl1xj5fojwlrw77xjflw80uxjous254jrr967rvj/':
|
||||
// Failed to connect to 127.0.0.1 port 4101 after 4 ms: Connection refused
|
||||
case err.IsExitCode(128) && strings.Contains(err.Stderr(), "Failed to connect"):
|
||||
return types.ErrFailedToConnect
|
||||
return errors.Internal("failed to connect")
|
||||
|
||||
default:
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
func mapGiteaRawRef(raw map[string]string) (map[types.GitReferenceField]string, error) {
|
||||
res := make(map[types.GitReferenceField]string, len(raw))
|
||||
for k, v := range raw {
|
||||
gitRefField, err := types.ParseGitReferenceField(k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res[gitRefField] = v
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func mapToGiteaReferenceSortingArgument(s types.GitReferenceField, o types.SortOrder) string {
|
||||
sortBy := string(types.GitReferenceFieldRefName)
|
||||
desc := o == types.SortOrderDesc
|
||||
|
||||
if s == types.GitReferenceFieldCreatorDate {
|
||||
sortBy = string(types.GitReferenceFieldCreatorDate)
|
||||
if o == types.SortOrderDefault {
|
||||
desc = true
|
||||
}
|
||||
}
|
||||
|
||||
if desc {
|
||||
return "-" + sortBy
|
||||
}
|
||||
|
||||
return sortBy
|
||||
}
|
||||
|
||||
func mapGiteaCommit(giteaCommit *gitea.Commit) (*types.Commit, error) {
|
||||
if giteaCommit == nil {
|
||||
return nil, fmt.Errorf("gitea commit is nil")
|
||||
}
|
||||
|
||||
author, err := mapGiteaSignature(giteaCommit.Author)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to map gitea author: %w", err)
|
||||
}
|
||||
committer, err := mapGiteaSignature(giteaCommit.Committer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to map gitea commiter: %w", err)
|
||||
}
|
||||
return &types.Commit{
|
||||
SHA: giteaCommit.ID.String(),
|
||||
Title: giteaCommit.Summary(),
|
||||
// remove potential tailing newlines from message
|
||||
Message: strings.TrimRight(giteaCommit.Message(), "\n"),
|
||||
Author: author,
|
||||
Committer: committer,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func mapGogitNodeToTreeNodeModeAndType(
|
||||
gogitMode gogitfilemode.FileMode,
|
||||
) (types.TreeNodeType, types.TreeNodeMode, error) {
|
||||
//nolint:exhaustive
|
||||
switch gogitMode {
|
||||
case gogitfilemode.Regular, gogitfilemode.Deprecated:
|
||||
return types.TreeNodeTypeBlob, types.TreeNodeModeFile, nil
|
||||
case gogitfilemode.Symlink:
|
||||
return types.TreeNodeTypeBlob, types.TreeNodeModeSymlink, nil
|
||||
case gogitfilemode.Executable:
|
||||
return types.TreeNodeTypeBlob, types.TreeNodeModeExec, nil
|
||||
case gogitfilemode.Submodule:
|
||||
return types.TreeNodeTypeCommit, types.TreeNodeModeCommit, nil
|
||||
case gogitfilemode.Dir:
|
||||
return types.TreeNodeTypeTree, types.TreeNodeModeTree, nil
|
||||
default:
|
||||
return types.TreeNodeTypeBlob, types.TreeNodeModeFile,
|
||||
fmt.Errorf("received unknown tree node mode from gogit: '%s'", gogitMode.String())
|
||||
}
|
||||
}
|
||||
|
||||
func mapGiteaSignature(giteaSignature *gitea.Signature) (types.Signature, error) {
|
||||
if giteaSignature == nil {
|
||||
return types.Signature{}, fmt.Errorf("gitea signature is nil")
|
||||
}
|
||||
|
||||
return types.Signature{
|
||||
Identity: types.Identity{
|
||||
Name: giteaSignature.Name,
|
||||
Email: giteaSignature.Email,
|
||||
},
|
||||
When: giteaSignature.When,
|
||||
}, nil
|
||||
}
|
@ -12,17 +12,17 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/cache"
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gogitosfs "github.com/go-git/go-billy/v5/osfs"
|
||||
gogit "github.com/go-git/go-git/v5"
|
||||
@ -36,7 +36,10 @@ type GoGitRepoProvider struct {
|
||||
gitObjectCache cache.Cache[string, *gogitcache.ObjectLRU]
|
||||
}
|
||||
|
||||
func NewGoGitRepoProvider(objectCacheMax int, cacheDuration time.Duration) *GoGitRepoProvider {
|
||||
func NewGoGitRepoProvider(
|
||||
objectCacheMax int,
|
||||
cacheDuration time.Duration,
|
||||
) *GoGitRepoProvider {
|
||||
c := cache.New[string, *gogitcache.ObjectLRU](gitObjectCacheGetter{
|
||||
maxSize: objectCacheMax,
|
||||
}, cacheDuration)
|
||||
@ -45,7 +48,10 @@ func NewGoGitRepoProvider(objectCacheMax int, cacheDuration time.Duration) *GoGi
|
||||
}
|
||||
}
|
||||
|
||||
func (gr *GoGitRepoProvider) Get(ctx context.Context, path string) (*gogit.Repository, error) {
|
||||
func (gr *GoGitRepoProvider) Get(
|
||||
ctx context.Context,
|
||||
path string,
|
||||
) (*gogit.Repository, error) {
|
||||
fs := gogitosfs.New(path)
|
||||
stat, err := fs.Stat("")
|
||||
if err != nil {
|
||||
@ -78,15 +84,22 @@ type gitObjectCacheGetter struct {
|
||||
maxSize int
|
||||
}
|
||||
|
||||
func (r gitObjectCacheGetter) Find(_ context.Context, _ string) (*gogitcache.ObjectLRU, error) {
|
||||
func (r gitObjectCacheGetter) Find(
|
||||
_ context.Context,
|
||||
_ string,
|
||||
) (*gogitcache.ObjectLRU, error) {
|
||||
return gogitcache.NewObjectLRU(gogitcache.FileSize(r.maxSize)), nil
|
||||
}
|
||||
|
||||
func (g Adapter) getGoGitCommit(ctx context.Context,
|
||||
func (a Adapter) getGoGitCommit(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
rev string,
|
||||
) (*gogit.Repository, *gogitobject.Commit, error) {
|
||||
repo, err := g.repoProvider.Get(ctx, repoPath)
|
||||
if repoPath == "" {
|
||||
return nil, nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
repo, err := a.repoProvider.Get(ctx, repoPath)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to open repository: %w", err)
|
||||
}
|
||||
@ -96,7 +109,7 @@ func (g Adapter) getGoGitCommit(ctx context.Context,
|
||||
var head *gogitplumbing.Reference
|
||||
head, err = repo.Head()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to get head: %w", err)
|
||||
return nil, nil, errors.Internal("failed to get head: %w", err)
|
||||
}
|
||||
|
||||
headHash := head.Hash()
|
||||
@ -104,9 +117,9 @@ func (g Adapter) getGoGitCommit(ctx context.Context,
|
||||
} else {
|
||||
refSHA, err = repo.ResolveRevision(gogitplumbing.Revision(rev))
|
||||
if errors.Is(err, gogitplumbing.ErrReferenceNotFound) {
|
||||
return nil, nil, types.ErrNotFound
|
||||
return nil, nil, errors.NotFound("reference not found '%s'", rev)
|
||||
} else if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to resolve revision %s: %w", rev, err)
|
||||
return nil, nil, errors.Internal("failed to resolve revision '%s'", rev, err)
|
||||
}
|
||||
}
|
||||
|
97
git/adapter/http.go
Normal file
97
git/adapter/http.go
Normal file
@ -0,0 +1,97 @@
|
||||
// Copyright 2023 Harness, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/errors"
|
||||
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (a Adapter) InfoRefs(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
service string,
|
||||
w io.Writer,
|
||||
env ...string,
|
||||
) error {
|
||||
cmd := &bytes.Buffer{}
|
||||
if err := git.NewCommand(ctx, service, "--stateless-rpc", "--advertise-refs", ".").
|
||||
Run(&git.RunOpts{
|
||||
Env: env,
|
||||
Dir: repoPath,
|
||||
Stdout: cmd,
|
||||
}); err != nil {
|
||||
return errors.Internal("InfoRefsUploadPack: cmd: %v", err)
|
||||
}
|
||||
if _, err := w.Write(packetWrite("# service=git-" + service + "\n")); err != nil {
|
||||
return errors.Internal("InfoRefsUploadPack: pktLine: %v", err)
|
||||
}
|
||||
|
||||
if _, err := w.Write([]byte("0000")); err != nil {
|
||||
return errors.Internal("InfoRefsUploadPack: flush: %v", err)
|
||||
}
|
||||
|
||||
if _, err := io.Copy(w, cmd); err != nil {
|
||||
return errors.Internal("InfoRefsUploadPack: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a Adapter) ServicePack(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
service string,
|
||||
stdin io.Reader,
|
||||
stdout io.Writer,
|
||||
env ...string,
|
||||
) error {
|
||||
// set this for allow pre-receive and post-receive execute
|
||||
env = append(env, "SSH_ORIGINAL_COMMAND="+service)
|
||||
|
||||
var (
|
||||
stderr bytes.Buffer
|
||||
)
|
||||
cmd := git.NewCommand(ctx, service, "--stateless-rpc", repoPath)
|
||||
cmd.SetDescription(fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", repoPath))
|
||||
err := cmd.Run(&git.RunOpts{
|
||||
Dir: repoPath,
|
||||
Env: env,
|
||||
Stdout: stdout,
|
||||
Stdin: stdin,
|
||||
Stderr: &stderr,
|
||||
UseContextTimeout: true,
|
||||
})
|
||||
if err != nil && err.Error() != "signal: killed" {
|
||||
log.Ctx(ctx).Err(err).Msgf("Fail to serve RPC(%s) in %s: %v - %s", service, repoPath, err, stderr.String())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func packetWrite(str string) []byte {
|
||||
s := strconv.FormatInt(int64(len(str)+4), 16)
|
||||
if len(s)%4 != 0 {
|
||||
s = strings.Repeat("0", 4-len(s)%4) + s
|
||||
}
|
||||
return []byte(s + str)
|
||||
}
|
@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
@ -24,7 +24,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/cache"
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
gogitplumbing "github.com/go-git/go-git/v5/plumbing"
|
||||
@ -55,7 +55,7 @@ func NewRedisLastCommitCache(
|
||||
func(key CommitEntryKey) string {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(key))
|
||||
return "gitrpc:last_commit:" + hex.EncodeToString(h.Sum(nil))
|
||||
return "last_commit:" + hex.EncodeToString(h.Sum(nil))
|
||||
},
|
||||
commitValueCodec{},
|
||||
cacheDuration)
|
||||
@ -71,11 +71,19 @@ type CommitEntryKey string
|
||||
|
||||
const commitEntryKeySeparator = "\x00"
|
||||
|
||||
func makeCommitEntryKey(repoPath, commitSHA, path string) CommitEntryKey {
|
||||
func makeCommitEntryKey(
|
||||
repoPath string,
|
||||
commitSHA string,
|
||||
path string,
|
||||
) CommitEntryKey {
|
||||
return CommitEntryKey(repoPath + commitEntryKeySeparator + commitSHA + commitEntryKeySeparator + path)
|
||||
}
|
||||
|
||||
func (c CommitEntryKey) Split() (repoPath, commitSHA, path string) {
|
||||
func (c CommitEntryKey) Split() (
|
||||
repoPath string,
|
||||
commitSHA string,
|
||||
path string,
|
||||
) {
|
||||
parts := strings.Split(string(c), commitEntryKeySeparator)
|
||||
if len(parts) != 3 {
|
||||
return
|
||||
@ -110,7 +118,10 @@ type commitEntryGetter struct {
|
||||
}
|
||||
|
||||
// Find implements the cache.Getter interface.
|
||||
func (c commitEntryGetter) Find(ctx context.Context, key CommitEntryKey) (*types.Commit, error) {
|
||||
func (c commitEntryGetter) Find(
|
||||
ctx context.Context,
|
||||
key CommitEntryKey,
|
||||
) (*types.Commit, error) {
|
||||
repoPath, rev, path := key.Split()
|
||||
|
||||
if path == "" {
|
||||
@ -126,7 +137,7 @@ func (c commitEntryGetter) Find(ctx context.Context, key CommitEntryKey) (*types
|
||||
commitSHA = strings.TrimSpace(commitSHA)
|
||||
|
||||
if commitSHA == "" {
|
||||
return nil, types.ErrNotFound
|
||||
return nil, types.ErrNotFound("revision '%s' not found", rev)
|
||||
}
|
||||
|
||||
repo, err := c.repoProvider.Get(ctx, repoPath)
|
121
git/adapter/mapping.go
Normal file
121
git/adapter/mapping.go
Normal file
@ -0,0 +1,121 @@
|
||||
// Copyright 2023 Harness, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
gogitfilemode "github.com/go-git/go-git/v5/plumbing/filemode"
|
||||
)
|
||||
|
||||
func mapGiteaRawRef(
|
||||
raw map[string]string,
|
||||
) (map[types.GitReferenceField]string, error) {
|
||||
res := make(map[types.GitReferenceField]string, len(raw))
|
||||
for k, v := range raw {
|
||||
gitRefField, err := types.ParseGitReferenceField(k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res[gitRefField] = v
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func mapToGiteaReferenceSortingArgument(
|
||||
s types.GitReferenceField,
|
||||
o types.SortOrder,
|
||||
) string {
|
||||
sortBy := string(types.GitReferenceFieldRefName)
|
||||
desc := o == types.SortOrderDesc
|
||||
|
||||
if s == types.GitReferenceFieldCreatorDate {
|
||||
sortBy = string(types.GitReferenceFieldCreatorDate)
|
||||
if o == types.SortOrderDefault {
|
||||
desc = true
|
||||
}
|
||||
}
|
||||
|
||||
if desc {
|
||||
return "-" + sortBy
|
||||
}
|
||||
|
||||
return sortBy
|
||||
}
|
||||
|
||||
func mapGiteaCommit(giteaCommit *gitea.Commit) (*types.Commit, error) {
|
||||
if giteaCommit == nil {
|
||||
return nil, fmt.Errorf("gitea commit is nil")
|
||||
}
|
||||
|
||||
author, err := mapGiteaSignature(giteaCommit.Author)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to map gitea author: %w", err)
|
||||
}
|
||||
committer, err := mapGiteaSignature(giteaCommit.Committer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to map gitea commiter: %w", err)
|
||||
}
|
||||
return &types.Commit{
|
||||
SHA: giteaCommit.ID.String(),
|
||||
Title: giteaCommit.Summary(),
|
||||
// remove potential tailing newlines from message
|
||||
Message: strings.TrimRight(giteaCommit.Message(), "\n"),
|
||||
Author: author,
|
||||
Committer: committer,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func mapGogitNodeToTreeNodeModeAndType(
|
||||
gogitMode gogitfilemode.FileMode,
|
||||
) (types.TreeNodeType, types.TreeNodeMode, error) {
|
||||
//nolint:exhaustive
|
||||
switch gogitMode {
|
||||
case gogitfilemode.Regular, gogitfilemode.Deprecated:
|
||||
return types.TreeNodeTypeBlob, types.TreeNodeModeFile, nil
|
||||
case gogitfilemode.Symlink:
|
||||
return types.TreeNodeTypeBlob, types.TreeNodeModeSymlink, nil
|
||||
case gogitfilemode.Executable:
|
||||
return types.TreeNodeTypeBlob, types.TreeNodeModeExec, nil
|
||||
case gogitfilemode.Submodule:
|
||||
return types.TreeNodeTypeCommit, types.TreeNodeModeCommit, nil
|
||||
case gogitfilemode.Dir:
|
||||
return types.TreeNodeTypeTree, types.TreeNodeModeTree, nil
|
||||
default:
|
||||
return types.TreeNodeTypeBlob, types.TreeNodeModeFile,
|
||||
fmt.Errorf("received unknown tree node mode from gogit: '%s'", gogitMode.String())
|
||||
}
|
||||
}
|
||||
|
||||
func mapGiteaSignature(
|
||||
giteaSignature *gitea.Signature,
|
||||
) (types.Signature, error) {
|
||||
if giteaSignature == nil {
|
||||
return types.Signature{}, fmt.Errorf("gitea signature is nil")
|
||||
}
|
||||
|
||||
return types.Signature{
|
||||
Identity: types.Identity{
|
||||
Name: giteaSignature.Name,
|
||||
Email: giteaSignature.Email,
|
||||
},
|
||||
When: giteaSignature.When,
|
||||
}, nil
|
||||
}
|
@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
@ -21,19 +21,24 @@ import (
|
||||
"io"
|
||||
"path"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gogitobject "github.com/go-git/go-git/v5/plumbing/object"
|
||||
)
|
||||
|
||||
func (g Adapter) MatchFiles(ctx context.Context,
|
||||
// nolint:gocognit
|
||||
func (a Adapter) MatchFiles(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
ref string,
|
||||
dirPath string,
|
||||
pattern string,
|
||||
maxSize int,
|
||||
) ([]types.FileContent, error) {
|
||||
_, refCommit, err := g.getGoGitCommit(ctx, repoPath, ref)
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
_, refCommit, err := a.getGoGitCommit(ctx, repoPath, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -56,7 +61,6 @@ func (g Adapter) MatchFiles(ctx context.Context,
|
||||
var files []types.FileContent
|
||||
for i := range tree.Entries {
|
||||
fileEntry := tree.Entries[i]
|
||||
|
||||
ok, err := path.Match(pattern, fileEntry.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
@ -25,9 +25,9 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/enum"
|
||||
"github.com/harness/gitness/gitrpc/internal/tempdir"
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/enum"
|
||||
"github.com/harness/gitness/git/tempdir"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"github.com/rs/zerolog/log"
|
||||
@ -37,7 +37,7 @@ import (
|
||||
// it also create a second base branch called "original_base".
|
||||
//
|
||||
//nolint:funlen,gocognit // need refactor
|
||||
func (g Adapter) CreateTemporaryRepoForPR(
|
||||
func (a Adapter) CreateTemporaryRepoForPR(
|
||||
ctx context.Context,
|
||||
reposTempPath string,
|
||||
pr *types.PullRequest,
|
||||
@ -69,7 +69,7 @@ func (g Adapter) CreateTemporaryRepoForPR(
|
||||
return types.TempRepository{}, err
|
||||
}
|
||||
|
||||
if err = g.InitRepository(ctx, tmpBasePath, false); err != nil {
|
||||
if err = a.InitRepository(ctx, tmpBasePath, false); err != nil {
|
||||
_ = tempdir.RemoveTemporaryPath(tmpBasePath)
|
||||
return types.TempRepository{}, err
|
||||
}
|
||||
@ -114,7 +114,7 @@ func (g Adapter) CreateTemporaryRepoForPR(
|
||||
errbuf.Reset()
|
||||
|
||||
// Fetch base branch
|
||||
baseCommit, err := g.GetCommit(ctx, pr.BaseRepoPath, pr.BaseBranch)
|
||||
baseCommit, err := a.GetCommit(ctx, pr.BaseRepoPath, pr.BaseBranch)
|
||||
if err != nil {
|
||||
return types.TempRepository{}, fmt.Errorf("failed to get commit of base branch '%s', error: %w", pr.BaseBranch, err)
|
||||
}
|
||||
@ -170,7 +170,7 @@ func (g Adapter) CreateTemporaryRepoForPR(
|
||||
outbuf.Reset()
|
||||
errbuf.Reset()
|
||||
|
||||
headCommit, err := g.GetCommit(ctx, pr.HeadRepoPath, pr.HeadBranch)
|
||||
headCommit, err := a.GetCommit(ctx, pr.HeadRepoPath, pr.HeadBranch)
|
||||
if err != nil {
|
||||
return types.TempRepository{}, fmt.Errorf("failed to get commit of head branch '%s', error: %w", pr.HeadBranch, err)
|
||||
}
|
||||
@ -215,14 +215,16 @@ func runMergeCommand(
|
||||
// Merge will leave a MERGE_HEAD file in the .git folder if there is a conflict
|
||||
if _, statErr := os.Stat(filepath.Join(tmpBasePath, ".git", "MERGE_HEAD")); statErr == nil {
|
||||
// We have a merge conflict error
|
||||
if err = conflictFiles(ctx, pr, env, tmpBasePath, &outbuf); err != nil {
|
||||
return err
|
||||
files, cferr := conflictFiles(ctx, pr, env, tmpBasePath)
|
||||
if cferr != nil {
|
||||
return cferr
|
||||
}
|
||||
return &types.MergeConflictsError{
|
||||
Method: mergeMethod,
|
||||
StdOut: outbuf.String(),
|
||||
StdErr: errbuf.String(),
|
||||
Err: err,
|
||||
Files: files,
|
||||
}
|
||||
} else if strings.Contains(errbuf.String(), "refusing to merge unrelated histories") {
|
||||
return &types.MergeUnrelatedHistoriesError{
|
||||
@ -278,7 +280,7 @@ func commitAndSignNoAuthor(
|
||||
// Merge merges changes between 2 refs (branch, commits or tags).
|
||||
//
|
||||
//nolint:gocognit,nestif
|
||||
func (g Adapter) Merge(
|
||||
func (a Adapter) Merge(
|
||||
ctx context.Context,
|
||||
pr *types.PullRequest,
|
||||
mergeMethod enum.MergeMethod,
|
||||
@ -286,8 +288,8 @@ func (g Adapter) Merge(
|
||||
trackingBranch string,
|
||||
tmpBasePath string,
|
||||
mergeMsg string,
|
||||
env []string,
|
||||
identity *types.Identity,
|
||||
env ...string,
|
||||
) error {
|
||||
var (
|
||||
outbuf, errbuf strings.Builder
|
||||
@ -440,30 +442,37 @@ func (g Adapter) Merge(
|
||||
return nil
|
||||
}
|
||||
|
||||
func conflictFiles(ctx context.Context,
|
||||
func conflictFiles(
|
||||
ctx context.Context,
|
||||
pr *types.PullRequest,
|
||||
env []string,
|
||||
repoPath string,
|
||||
buf *strings.Builder,
|
||||
) error {
|
||||
stdout, stderr, cferr := git.NewCommand(
|
||||
) (files []string, err error) {
|
||||
stdout, stderr, err := git.NewCommand(
|
||||
ctx, "diff", "--name-only", "--diff-filter=U", "--relative",
|
||||
).RunStdString(&git.RunOpts{
|
||||
Env: env,
|
||||
Dir: repoPath,
|
||||
})
|
||||
if cferr != nil {
|
||||
return processGiteaErrorf(cferr, "failed to list conflict files [%s -> %s], stderr: %v, err: %v",
|
||||
pr.HeadBranch, pr.BaseBranch, stderr, cferr)
|
||||
if err != nil {
|
||||
return nil, processGiteaErrorf(err, "failed to list conflict files [%s -> %s], stderr: %v, err: %v",
|
||||
pr.HeadBranch, pr.BaseBranch, stderr, err)
|
||||
}
|
||||
if len(stdout) > 0 {
|
||||
buf.Reset()
|
||||
buf.WriteString(stdout)
|
||||
files = strings.Split(stdout[:len(stdout)-1], "\n")
|
||||
}
|
||||
return nil
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (g Adapter) GetDiffTree(ctx context.Context, repoPath, baseBranch, headBranch string) (string, error) {
|
||||
func (a Adapter) GetDiffTree(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
baseBranch string,
|
||||
headBranch string,
|
||||
) (string, error) {
|
||||
if repoPath == "" {
|
||||
return "", ErrRepositoryPathEmpty
|
||||
}
|
||||
getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) {
|
||||
var outbuf, errbuf strings.Builder
|
||||
if err := git.NewCommand(ctx, "diff-tree", "--no-commit-id",
|
||||
@ -514,7 +523,16 @@ func (g Adapter) GetDiffTree(ctx context.Context, repoPath, baseBranch, headBran
|
||||
}
|
||||
|
||||
// GetMergeBase checks and returns merge base of two branches and the reference used as base.
|
||||
func (g Adapter) GetMergeBase(ctx context.Context, repoPath, remote, base, head string) (string, string, error) {
|
||||
func (a Adapter) GetMergeBase(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
remote string,
|
||||
base string,
|
||||
head string,
|
||||
) (string, string, error) {
|
||||
if repoPath == "" {
|
||||
return "", "", ErrRepositoryPathEmpty
|
||||
}
|
||||
if remote == "" {
|
||||
remote = "origin"
|
||||
}
|
||||
@ -539,7 +557,6 @@ func (g Adapter) GetMergeBase(ctx context.Context, repoPath, remote, base, head
|
||||
|
||||
// giteaRunStdError is an implementation of the RunStdError interface in the gitea codebase.
|
||||
// It allows us to process gitea errors even when using cmd.Run() instead of cmd.RunStdString() or run.StdBytes().
|
||||
// TODO: solve this nicer once we have proper gitrpc error handling.
|
||||
type giteaRunStdError struct {
|
||||
err error
|
||||
stderr string
|
@ -12,14 +12,14 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gogitplumbing "github.com/go-git/go-git/v5/plumbing"
|
||||
gogitfilemode "github.com/go-git/go-git/v5/plumbing/filemode"
|
||||
@ -28,13 +28,13 @@ import (
|
||||
|
||||
// PathsDetails returns additional details about provided the paths.
|
||||
//
|
||||
//nolint:gocognit // refactor if needed
|
||||
func (g Adapter) PathsDetails(ctx context.Context,
|
||||
//nolint:gocognit
|
||||
func (a Adapter) PathsDetails(ctx context.Context,
|
||||
repoPath string,
|
||||
ref string,
|
||||
paths []string,
|
||||
) ([]types.PathDetails, error) {
|
||||
repo, refCommit, err := g.getGoGitCommit(ctx, repoPath, ref)
|
||||
repo, refCommit, err := a.getGoGitCommit(ctx, repoPath, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -49,7 +49,6 @@ func (g Adapter) PathsDetails(ctx context.Context,
|
||||
results := make([]types.PathDetails, len(paths))
|
||||
|
||||
for i, path := range paths {
|
||||
// store original path in output in case caller is doing exact matching
|
||||
results[i].Path = path
|
||||
|
||||
// use cleaned-up path for calculations to avoid not-founds.
|
||||
@ -76,7 +75,7 @@ func (g Adapter) PathsDetails(ctx context.Context,
|
||||
}
|
||||
}
|
||||
|
||||
commitEntry, err := g.lastCommitCache.Get(ctx, makeCommitEntryKey(repoPath, refSHA, path))
|
||||
commitEntry, err := a.lastCommitCache.Get(ctx, makeCommitEntryKey(repoPath, refSHA, path))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to find last commit for path %s: %w", path, err)
|
||||
}
|
@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
@ -21,13 +21,15 @@ import (
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
gitearef "code.gitea.io/gitea/modules/git/foreachref"
|
||||
)
|
||||
|
||||
func DefaultInstructor(_ types.WalkReferencesEntry) (types.WalkInstruction, error) {
|
||||
func DefaultInstructor(
|
||||
_ types.WalkReferencesEntry,
|
||||
) (types.WalkInstruction, error) {
|
||||
return types.WalkInstructionHandle, nil
|
||||
}
|
||||
|
||||
@ -35,8 +37,15 @@ func DefaultInstructor(_ types.WalkReferencesEntry) (types.WalkInstruction, erro
|
||||
// and calls the handle function for every matching node.
|
||||
// The instructor & handler are called with a map that contains the matching value for every field provided in fields.
|
||||
// TODO: walkGiteaReferences related code should be moved to separate file.
|
||||
func (g Adapter) WalkReferences(ctx context.Context,
|
||||
repoPath string, handler types.WalkReferencesHandler, opts *types.WalkReferencesOptions) error {
|
||||
func (a Adapter) WalkReferences(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
handler types.WalkReferencesHandler,
|
||||
opts *types.WalkReferencesOptions,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
// backfil optional options
|
||||
if opts.Instructor == nil {
|
||||
opts.Instructor = DefaultInstructor
|
||||
@ -79,7 +88,7 @@ func (g Adapter) WalkReferences(ctx context.Context,
|
||||
sortArg,
|
||||
"--count",
|
||||
fmt.Sprint(opts.MaxWalkDistance),
|
||||
// "--ignore-case" // slows down performance drastically
|
||||
"--ignore-case",
|
||||
}
|
||||
args = append(args, opts.Patterns...)
|
||||
err := gitea.NewCommand(ctx, args...).Run(rc)
|
||||
@ -96,8 +105,11 @@ func (g Adapter) WalkReferences(ctx context.Context,
|
||||
return walkGiteaReferenceParser(parser, handler, opts)
|
||||
}
|
||||
|
||||
func walkGiteaReferenceParser(parser *gitearef.Parser, handler types.WalkReferencesHandler,
|
||||
opts *types.WalkReferencesOptions) error {
|
||||
func walkGiteaReferenceParser(
|
||||
parser *gitearef.Parser,
|
||||
handler types.WalkReferencesHandler,
|
||||
opts *types.WalkReferencesOptions,
|
||||
) error {
|
||||
for i := int32(0); i < opts.MaxWalkDistance; i++ {
|
||||
// parse next line - nil if end of output reached or an error occurred.
|
||||
rawRef := parser.Next()
|
||||
@ -141,14 +153,21 @@ func walkGiteaReferenceParser(parser *gitearef.Parser, handler types.WalkReferen
|
||||
// GetRef get's the target of a reference
|
||||
// IMPORTANT provide full reference name to limit risk of collisions across reference types
|
||||
// (e.g `refs/heads/main` instead of `main`).
|
||||
func (g Adapter) GetRef(ctx context.Context, repoPath, reference string) (string, error) {
|
||||
func (a Adapter) GetRef(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
reference string,
|
||||
) (string, error) {
|
||||
if repoPath == "" {
|
||||
return "", ErrRepositoryPathEmpty
|
||||
}
|
||||
cmd := gitea.NewCommand(ctx, "show-ref", "--verify", "-s", "--", reference)
|
||||
stdout, _, err := cmd.RunStdString(&gitea.RunOpts{
|
||||
Dir: repoPath,
|
||||
})
|
||||
if err != nil {
|
||||
if err.IsExitCode(128) && strings.Contains(err.Stderr(), "not a valid ref") {
|
||||
return "", types.ErrNotFound
|
||||
return "", types.ErrNotFound("reference '%s' not found", reference)
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
@ -159,9 +178,16 @@ func (g Adapter) GetRef(ctx context.Context, repoPath, reference string) (string
|
||||
// UpdateRef allows to update / create / delete references
|
||||
// IMPORTANT provide full reference name to limit risk of collisions across reference types
|
||||
// (e.g `refs/heads/main` instead of `main`).
|
||||
func (g Adapter) UpdateRef(ctx context.Context,
|
||||
repoPath, reference, newValue, oldValue string,
|
||||
func (a Adapter) UpdateRef(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
reference string,
|
||||
newValue string,
|
||||
oldValue string,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
args := make([]string, 0, 4)
|
||||
args = append(args, "update-ref")
|
||||
if newValue == "" {
|
@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
@ -21,22 +21,52 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
)
|
||||
|
||||
const (
|
||||
gitReferenceNamePrefixBranch = "refs/heads/"
|
||||
gitReferenceNamePrefixTag = "refs/tags/"
|
||||
)
|
||||
|
||||
var lsRemoteHeadRegexp = regexp.MustCompile(`ref: refs/heads/([^\s]+)\s+HEAD`)
|
||||
|
||||
// InitRepository initializes a new Git repository.
|
||||
func (g Adapter) InitRepository(ctx context.Context, repoPath string, bare bool) error {
|
||||
func (a Adapter) InitRepository(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
bare bool,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
return gitea.InitRepository(ctx, repoPath, bare)
|
||||
}
|
||||
|
||||
func (a Adapter) OpenRepository(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
) (*gitea.Repository, error) {
|
||||
repo, err := gitea.OpenRepository(ctx, repoPath)
|
||||
if err != nil {
|
||||
return nil, processGiteaErrorf(err, "failed to open repository")
|
||||
}
|
||||
return repo, nil
|
||||
}
|
||||
|
||||
// SetDefaultBranch sets the default branch of a repo.
|
||||
func (g Adapter) SetDefaultBranch(ctx context.Context, repoPath string,
|
||||
defaultBranch string, allowEmpty bool) error {
|
||||
func (a Adapter) SetDefaultBranch(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
defaultBranch string,
|
||||
allowEmpty bool,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
giteaRepo, err := gitea.OpenRepository(ctx, repoPath)
|
||||
if err != nil {
|
||||
return processGiteaErrorf(err, "failed to open repository")
|
||||
@ -59,7 +89,13 @@ func (g Adapter) SetDefaultBranch(ctx context.Context, repoPath string,
|
||||
}
|
||||
|
||||
// GetDefaultBranch gets the default branch of a repo.
|
||||
func (g Adapter) GetDefaultBranch(ctx context.Context, repoPath string) (string, error) {
|
||||
func (a Adapter) GetDefaultBranch(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
) (string, error) {
|
||||
if repoPath == "" {
|
||||
return "", ErrRepositoryPathEmpty
|
||||
}
|
||||
giteaRepo, err := gitea.OpenRepository(ctx, repoPath)
|
||||
if err != nil {
|
||||
return "", processGiteaErrorf(err, "failed to open gitea repo")
|
||||
@ -77,7 +113,10 @@ func (g Adapter) GetDefaultBranch(ctx context.Context, repoPath string) (string,
|
||||
|
||||
// GetRemoteDefaultBranch retrieves the default branch of a remote repository.
|
||||
// If the repo doesn't have a default branch, types.ErrNoDefaultBranch is returned.
|
||||
func (g Adapter) GetRemoteDefaultBranch(ctx context.Context, remoteURL string) (string, error) {
|
||||
func (a Adapter) GetRemoteDefaultBranch(
|
||||
ctx context.Context,
|
||||
remoteURL string,
|
||||
) (string, error) {
|
||||
args := []string{
|
||||
"-c", "credential.helper=",
|
||||
"ls-remote",
|
||||
@ -104,7 +143,12 @@ func (g Adapter) GetRemoteDefaultBranch(ctx context.Context, remoteURL string) (
|
||||
return match[1], nil
|
||||
}
|
||||
|
||||
func (g Adapter) Clone(ctx context.Context, from, to string, opts types.CloneRepoOptions) error {
|
||||
func (a Adapter) Clone(
|
||||
ctx context.Context,
|
||||
from string,
|
||||
to string,
|
||||
opts types.CloneRepoOptions,
|
||||
) error {
|
||||
err := gitea.Clone(ctx, from, to, gitea.CloneRepoOptions{
|
||||
Timeout: opts.Timeout,
|
||||
Mirror: opts.Mirror,
|
||||
@ -126,7 +170,15 @@ func (g Adapter) Clone(ctx context.Context, from, to string, opts types.CloneRep
|
||||
|
||||
// Sync synchronizes the repository to match the provided source.
|
||||
// NOTE: This is a read operation and doesn't trigger any server side hooks.
|
||||
func (g Adapter) Sync(ctx context.Context, repoPath string, source string, refSpecs []string) error {
|
||||
func (a Adapter) Sync(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
source string,
|
||||
refSpecs []string,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
if len(refSpecs) == 0 {
|
||||
refSpecs = []string{"+refs/*:refs/*"}
|
||||
}
|
||||
@ -156,7 +208,14 @@ func (g Adapter) Sync(ctx context.Context, repoPath string, source string, refSp
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g Adapter) AddFiles(repoPath string, all bool, files ...string) error {
|
||||
func (a Adapter) AddFiles(
|
||||
repoPath string,
|
||||
all bool,
|
||||
files ...string,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
err := gitea.AddChanges(repoPath, all, files...)
|
||||
if err != nil {
|
||||
return processGiteaErrorf(err, "failed to add changes")
|
||||
@ -167,16 +226,23 @@ func (g Adapter) AddFiles(repoPath string, all bool, files ...string) error {
|
||||
|
||||
// Commit commits the changes of the repository.
|
||||
// NOTE: Modification of gitea implementation that supports commiter_date + author_date.
|
||||
func (g Adapter) Commit(ctx context.Context, repoPath string, opts types.CommitChangesOptions) error {
|
||||
func (a Adapter) Commit(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
opts types.CommitChangesOptions,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
// setup environment variables used by git-commit
|
||||
// See https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables
|
||||
env := []string{
|
||||
"GIT_AUTHOR_NAME=" + opts.Author.Identity.Name,
|
||||
"GIT_AUTHOR_EMAIL=" + opts.Author.Identity.Email,
|
||||
"GIT_AUTHOR_DATE=" + opts.Author.When.Format(time.RFC3339),
|
||||
"GIT_COMMITTER_NAME=" + opts.Committer.Identity.Name,
|
||||
"GIT_COMMITTER_EMAIL=" + opts.Committer.Identity.Email,
|
||||
"GIT_COMMITTER_DATE=" + opts.Committer.When.Format(time.RFC3339),
|
||||
gitCommitterName + "=" + opts.Committer.Identity.Name,
|
||||
gitCommitterEmail + "=" + opts.Committer.Identity.Email,
|
||||
gitCommitterDate + "=" + opts.Committer.When.Format(time.RFC3339),
|
||||
}
|
||||
|
||||
args := []string{
|
||||
@ -193,7 +259,14 @@ func (g Adapter) Commit(ctx context.Context, repoPath string, opts types.CommitC
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g Adapter) Push(ctx context.Context, repoPath string, opts types.PushOptions) error {
|
||||
func (a Adapter) Push(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
opts types.PushOptions,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
err := Push(ctx, repoPath, opts)
|
||||
if err != nil {
|
||||
return processGiteaErrorf(err, "failed to push changes")
|
||||
@ -205,7 +278,14 @@ func (g Adapter) Push(ctx context.Context, repoPath string, opts types.PushOptio
|
||||
// Push pushs local commits to given remote branch.
|
||||
// NOTE: Modification of gitea implementation that supports --force-with-lease.
|
||||
// TODOD: return our own error types and move to above adapter.Push method
|
||||
func Push(ctx context.Context, repoPath string, opts types.PushOptions) error {
|
||||
func Push(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
opts types.PushOptions,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
cmd := gitea.NewCommand(ctx,
|
||||
"-c", "credential.helper=",
|
||||
"push",
|
@ -12,40 +12,40 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package service
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/gitea"
|
||||
"github.com/harness/gitness/gitrpc/internal/middleware"
|
||||
"github.com/harness/gitness/gitrpc/internal/tempdir"
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/gitrpc/rpc"
|
||||
"github.com/harness/gitness/errors"
|
||||
"github.com/harness/gitness/git/tempdir"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
"github.com/rs/zerolog/log"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// SharedRepo is a type to wrap our upload repositories as a shallow clone.
|
||||
type SharedRepo struct {
|
||||
repoUID string
|
||||
repo *git.Repository
|
||||
repo *gitea.Repository
|
||||
remoteRepoPath string
|
||||
tmpPath string
|
||||
}
|
||||
|
||||
// NewSharedRepo creates a new temporary upload repository.
|
||||
func NewSharedRepo(baseTmpDir, repoUID string, remoteRepoPath string) (*SharedRepo, error) {
|
||||
tmpPath, err := tempdir.CreateTemporaryPath(baseTmpDir, repoUID)
|
||||
func NewSharedRepo(
|
||||
baseTmpDir string,
|
||||
repoUID string,
|
||||
remoteRepoPath string,
|
||||
) (*SharedRepo, error) {
|
||||
tmpPath, err := tempdir.CreateTemporaryPath(baseTmpDir, repoUID) // Need better solution
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -57,6 +57,14 @@ func NewSharedRepo(baseTmpDir, repoUID string, remoteRepoPath string) (*SharedRe
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (r *SharedRepo) Path() string {
|
||||
return r.repo.Path
|
||||
}
|
||||
|
||||
func (r *SharedRepo) RemotePath() string {
|
||||
return r.remoteRepoPath
|
||||
}
|
||||
|
||||
// Close the repository cleaning up all files.
|
||||
func (r *SharedRepo) Close(ctx context.Context) {
|
||||
defer r.repo.Close()
|
||||
@ -73,20 +81,18 @@ func (r *SharedRepo) Clone(ctx context.Context, branchName string) error {
|
||||
}
|
||||
args = append(args, r.remoteRepoPath, r.tmpPath)
|
||||
|
||||
if _, _, err := git.NewCommand(ctx, args...).RunStdString(nil); err != nil {
|
||||
if _, _, err := gitea.NewCommand(ctx, args...).RunStdString(nil); err != nil {
|
||||
stderr := err.Error()
|
||||
if matched, _ := regexp.MatchString(".*Remote branch .* not found in upstream origin.*", stderr); matched {
|
||||
return git.ErrBranchNotExist{
|
||||
Name: branchName,
|
||||
}
|
||||
return errors.NotFound("branch '%s' does not exist", branchName)
|
||||
} else if matched, _ = regexp.MatchString(".* repository .* does not exist.*", stderr); matched {
|
||||
return fmt.Errorf("%s %w", r.repoUID, types.ErrNotFound)
|
||||
return errors.NotFound("repository '%s' does not exist", r.repoUID)
|
||||
}
|
||||
return fmt.Errorf("Clone: %w %s", err, stderr)
|
||||
return errors.Internal("error while cloning repository: %s", stderr)
|
||||
}
|
||||
gitRepo, err := git.OpenRepository(ctx, r.tmpPath)
|
||||
gitRepo, err := gitea.OpenRepository(ctx, r.tmpPath)
|
||||
if err != nil {
|
||||
return processGitErrorf(err, "failed to open repo")
|
||||
return processGiteaErrorf(err, "failed to open repo")
|
||||
}
|
||||
r.repo = gitRepo
|
||||
return nil
|
||||
@ -94,12 +100,12 @@ func (r *SharedRepo) Clone(ctx context.Context, branchName string) error {
|
||||
|
||||
// Init the repository.
|
||||
func (r *SharedRepo) Init(ctx context.Context) error {
|
||||
if err := git.InitRepository(ctx, r.tmpPath, false); err != nil {
|
||||
if err := gitea.InitRepository(ctx, r.tmpPath, false); err != nil {
|
||||
return err
|
||||
}
|
||||
gitRepo, err := git.OpenRepository(ctx, r.tmpPath)
|
||||
gitRepo, err := gitea.OpenRepository(ctx, r.tmpPath)
|
||||
if err != nil {
|
||||
return processGitErrorf(err, "failed to open repo")
|
||||
return processGiteaErrorf(err, "failed to open repo")
|
||||
}
|
||||
r.repo = gitRepo
|
||||
return nil
|
||||
@ -107,14 +113,17 @@ func (r *SharedRepo) Init(ctx context.Context) error {
|
||||
|
||||
// SetDefaultIndex sets the git index to our HEAD.
|
||||
func (r *SharedRepo) SetDefaultIndex(ctx context.Context) error {
|
||||
if _, _, err := git.NewCommand(ctx, "read-tree", "HEAD").RunStdString(&git.RunOpts{Dir: r.tmpPath}); err != nil {
|
||||
if _, _, err := gitea.NewCommand(ctx, "read-tree", "HEAD").RunStdString(&gitea.RunOpts{Dir: r.tmpPath}); err != nil {
|
||||
return fmt.Errorf("SetDefaultIndex: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LsFiles checks if the given filename arguments are in the index.
|
||||
func (r *SharedRepo) LsFiles(ctx context.Context, filenames ...string) ([]string, error) {
|
||||
func (r *SharedRepo) LsFiles(
|
||||
ctx context.Context,
|
||||
filenames ...string,
|
||||
) ([]string, error) {
|
||||
stdOut := new(bytes.Buffer)
|
||||
stdErr := new(bytes.Buffer)
|
||||
|
||||
@ -125,8 +134,8 @@ func (r *SharedRepo) LsFiles(ctx context.Context, filenames ...string) ([]string
|
||||
}
|
||||
}
|
||||
|
||||
if err := git.NewCommand(ctx, cmdArgs...).
|
||||
Run(&git.RunOpts{
|
||||
if err := gitea.NewCommand(ctx, cmdArgs...).
|
||||
Run(&gitea.RunOpts{
|
||||
Dir: r.tmpPath,
|
||||
Stdout: stdOut,
|
||||
Stderr: stdErr,
|
||||
@ -145,7 +154,10 @@ func (r *SharedRepo) LsFiles(ctx context.Context, filenames ...string) ([]string
|
||||
}
|
||||
|
||||
// RemoveFilesFromIndex removes the given files from the index.
|
||||
func (r *SharedRepo) RemoveFilesFromIndex(ctx context.Context, filenames ...string) error {
|
||||
func (r *SharedRepo) RemoveFilesFromIndex(
|
||||
ctx context.Context,
|
||||
filenames ...string,
|
||||
) error {
|
||||
stdOut := new(bytes.Buffer)
|
||||
stdErr := new(bytes.Buffer)
|
||||
stdIn := new(bytes.Buffer)
|
||||
@ -157,8 +169,8 @@ func (r *SharedRepo) RemoveFilesFromIndex(ctx context.Context, filenames ...stri
|
||||
}
|
||||
}
|
||||
|
||||
if err := git.NewCommand(ctx, "update-index", "--remove", "-z", "--index-info").
|
||||
Run(&git.RunOpts{
|
||||
if err := gitea.NewCommand(ctx, "update-index", "--remove", "-z", "--index-info").
|
||||
Run(&gitea.RunOpts{
|
||||
Dir: r.tmpPath,
|
||||
Stdin: stdIn,
|
||||
Stdout: stdOut,
|
||||
@ -171,12 +183,15 @@ func (r *SharedRepo) RemoveFilesFromIndex(ctx context.Context, filenames ...stri
|
||||
}
|
||||
|
||||
// WriteGitObject writes the provided content to the object db and returns its hash.
|
||||
func (r *SharedRepo) WriteGitObject(ctx context.Context, content io.Reader) (string, error) {
|
||||
func (r *SharedRepo) WriteGitObject(
|
||||
ctx context.Context,
|
||||
content io.Reader,
|
||||
) (string, error) {
|
||||
stdOut := new(bytes.Buffer)
|
||||
stdErr := new(bytes.Buffer)
|
||||
|
||||
if err := git.NewCommand(ctx, "hash-object", "-w", "--stdin").
|
||||
Run(&git.RunOpts{
|
||||
if err := gitea.NewCommand(ctx, "hash-object", "-w", "--stdin").
|
||||
Run(&gitea.RunOpts{
|
||||
Dir: r.tmpPath,
|
||||
Stdin: content,
|
||||
Stdout: stdOut,
|
||||
@ -190,11 +205,16 @@ func (r *SharedRepo) WriteGitObject(ctx context.Context, content io.Reader) (str
|
||||
}
|
||||
|
||||
// ShowFile dumps show file and write to io.Writer.
|
||||
func (r *SharedRepo) ShowFile(ctx context.Context, filePath, commitHash string, writer io.Writer) error {
|
||||
func (r *SharedRepo) ShowFile(
|
||||
ctx context.Context,
|
||||
filePath string,
|
||||
commitHash string,
|
||||
writer io.Writer,
|
||||
) error {
|
||||
stderr := new(bytes.Buffer)
|
||||
file := strings.TrimSpace(commitHash) + ":" + strings.TrimSpace(filePath)
|
||||
cmd := git.NewCommand(ctx, "show", file)
|
||||
if err := cmd.Run(&git.RunOpts{
|
||||
cmd := gitea.NewCommand(ctx, "show", file)
|
||||
if err := cmd.Run(&gitea.RunOpts{
|
||||
Dir: r.repo.Path,
|
||||
Stdout: writer,
|
||||
Stderr: stderr,
|
||||
@ -205,13 +225,18 @@ func (r *SharedRepo) ShowFile(ctx context.Context, filePath, commitHash string,
|
||||
}
|
||||
|
||||
// AddObjectToIndex adds the provided object hash to the index with the provided mode and path.
|
||||
func (r *SharedRepo) AddObjectToIndex(ctx context.Context, mode, objectHash, objectPath string) error {
|
||||
if _, _, err := git.NewCommand(ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, objectHash,
|
||||
objectPath).RunStdString(&git.RunOpts{Dir: r.tmpPath}); err != nil {
|
||||
func (r *SharedRepo) AddObjectToIndex(
|
||||
ctx context.Context,
|
||||
mode string,
|
||||
objectHash string,
|
||||
objectPath string,
|
||||
) error {
|
||||
if _, _, err := gitea.NewCommand(ctx, "update-index", "--add", "--replace", "--cacheinfo", mode, objectHash,
|
||||
objectPath).RunStdString(&gitea.RunOpts{Dir: r.tmpPath}); err != nil {
|
||||
if matched, _ := regexp.MatchString(".*Invalid path '.*", err.Error()); matched {
|
||||
return types.ErrInvalidPath
|
||||
return errors.InvalidArgument("invalid path '%s'", objectPath)
|
||||
}
|
||||
return fmt.Errorf("unable to add object to index at %s in temporary repo %s Error: %w",
|
||||
return fmt.Errorf("unable to add object to index at %s in temporary repo path %s Error: %w",
|
||||
objectPath, r.repoUID, err)
|
||||
}
|
||||
return nil
|
||||
@ -219,9 +244,9 @@ func (r *SharedRepo) AddObjectToIndex(ctx context.Context, mode, objectHash, obj
|
||||
|
||||
// WriteTree writes the current index as a tree to the object db and returns its hash.
|
||||
func (r *SharedRepo) WriteTree(ctx context.Context) (string, error) {
|
||||
stdout, _, err := git.NewCommand(ctx, "write-tree").RunStdString(&git.RunOpts{Dir: r.tmpPath})
|
||||
stdout, _, err := gitea.NewCommand(ctx, "write-tree").RunStdString(&gitea.RunOpts{Dir: r.tmpPath})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("unable to write-tree in temporary repo for: %s Error: %w",
|
||||
return "", fmt.Errorf("unable to write-tree in temporary repo path for: %s Error: %w",
|
||||
r.repoUID, err)
|
||||
}
|
||||
return strings.TrimSpace(stdout), nil
|
||||
@ -233,14 +258,17 @@ func (r *SharedRepo) GetLastCommit(ctx context.Context) (string, error) {
|
||||
}
|
||||
|
||||
// GetLastCommitByRef gets the last commit ID SHA of the repo by ref.
|
||||
func (r *SharedRepo) GetLastCommitByRef(ctx context.Context, ref string) (string, error) {
|
||||
func (r *SharedRepo) GetLastCommitByRef(
|
||||
ctx context.Context,
|
||||
ref string,
|
||||
) (string, error) {
|
||||
if ref == "" {
|
||||
ref = "HEAD"
|
||||
}
|
||||
stdout, _, err := git.NewCommand(ctx, "rev-parse", ref).RunStdString(&git.RunOpts{Dir: r.tmpPath})
|
||||
stdout, _, err := gitea.NewCommand(ctx, "rev-parse", ref).RunStdString(&gitea.RunOpts{Dir: r.tmpPath})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("unable to rev-parse %s in temporary repo for: %s Error: %w",
|
||||
ref, r.repoUID, err)
|
||||
return "", processGiteaErrorf(err, "unable to rev-parse %s in temporary repo for: %s",
|
||||
ref, r.repoUID)
|
||||
}
|
||||
return strings.TrimSpace(stdout), nil
|
||||
}
|
||||
@ -249,7 +277,7 @@ func (r *SharedRepo) GetLastCommitByRef(ctx context.Context, ref string) (string
|
||||
func (r *SharedRepo) CommitTreeWithDate(
|
||||
ctx context.Context,
|
||||
parent string,
|
||||
author, committer *rpc.Identity,
|
||||
author, committer *types.Identity,
|
||||
treeHash, message string,
|
||||
signoff bool,
|
||||
authorDate, committerDate time.Time,
|
||||
@ -279,7 +307,7 @@ func (r *SharedRepo) CommitTreeWithDate(
|
||||
args = append(args, "--no-gpg-sign")
|
||||
|
||||
if signoff {
|
||||
giteaSignature := &git.Signature{
|
||||
giteaSignature := &gitea.Signature{
|
||||
Name: committer.Name,
|
||||
Email: committer.Email,
|
||||
When: committerDate,
|
||||
@ -292,75 +320,112 @@ func (r *SharedRepo) CommitTreeWithDate(
|
||||
|
||||
stdout := new(bytes.Buffer)
|
||||
stderr := new(bytes.Buffer)
|
||||
if err := git.NewCommand(ctx, args...).
|
||||
Run(&git.RunOpts{
|
||||
if err := gitea.NewCommand(ctx, args...).
|
||||
Run(&gitea.RunOpts{
|
||||
Env: env,
|
||||
Dir: r.tmpPath,
|
||||
Stdin: messageBytes,
|
||||
Stdout: stdout,
|
||||
Stderr: stderr,
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("unable to commit-tree in temporary repo: %s Error: %w\nStdout: %s\nStderr: %s",
|
||||
return "", processGiteaErrorf(err, "unable to commit-tree in temporary repo: %s Error: %v\nStdout: %s\nStderr: %s",
|
||||
r.repoUID, err, stdout, stderr)
|
||||
}
|
||||
return strings.TrimSpace(stdout.String()), nil
|
||||
}
|
||||
|
||||
func (r *SharedRepo) PushDeleteBranch(ctx context.Context, writeRequest *rpc.WriteRequest,
|
||||
branch string) error {
|
||||
return r.push(ctx, writeRequest, "", GetReferenceFromBranchName(branch))
|
||||
func (r *SharedRepo) PushDeleteBranch(
|
||||
ctx context.Context,
|
||||
branch string,
|
||||
force bool,
|
||||
env ...string,
|
||||
) error {
|
||||
return r.push(ctx, "", GetReferenceFromBranchName(branch), force, env...)
|
||||
}
|
||||
|
||||
func (r *SharedRepo) PushCommitToBranch(ctx context.Context, writeRequest *rpc.WriteRequest,
|
||||
commitSHA string, branch string) error {
|
||||
return r.push(ctx, writeRequest, commitSHA, GetReferenceFromBranchName(branch))
|
||||
func (r *SharedRepo) PushCommitToBranch(
|
||||
ctx context.Context,
|
||||
commitSHA string,
|
||||
branch string,
|
||||
force bool,
|
||||
env ...string,
|
||||
) error {
|
||||
return r.push(ctx,
|
||||
commitSHA,
|
||||
GetReferenceFromBranchName(branch),
|
||||
force,
|
||||
env...,
|
||||
)
|
||||
}
|
||||
|
||||
func (r *SharedRepo) PushBranch(ctx context.Context, writeRequest *rpc.WriteRequest,
|
||||
sourceBranch string, branch string) error {
|
||||
return r.push(ctx, writeRequest, GetReferenceFromBranchName(sourceBranch), GetReferenceFromBranchName(branch))
|
||||
func (r *SharedRepo) PushBranch(
|
||||
ctx context.Context,
|
||||
sourceBranch string,
|
||||
branch string,
|
||||
force bool,
|
||||
env ...string,
|
||||
) error {
|
||||
return r.push(ctx,
|
||||
GetReferenceFromBranchName(sourceBranch),
|
||||
GetReferenceFromBranchName(branch),
|
||||
force,
|
||||
env...,
|
||||
)
|
||||
}
|
||||
func (r *SharedRepo) PushTag(ctx context.Context, writeRequest *rpc.WriteRequest,
|
||||
tagName string) error {
|
||||
func (r *SharedRepo) PushTag(
|
||||
ctx context.Context,
|
||||
tagName string,
|
||||
force bool,
|
||||
env ...string,
|
||||
) error {
|
||||
refTag := GetReferenceFromTagName(tagName)
|
||||
return r.push(ctx, writeRequest, refTag, refTag)
|
||||
return r.push(ctx, refTag, refTag, force, env...)
|
||||
}
|
||||
|
||||
func (r *SharedRepo) PushDeleteTag(ctx context.Context, writeRequest *rpc.WriteRequest,
|
||||
tagName string) error {
|
||||
func (r *SharedRepo) PushDeleteTag(
|
||||
ctx context.Context,
|
||||
tagName string,
|
||||
force bool,
|
||||
env ...string,
|
||||
) error {
|
||||
refTag := GetReferenceFromTagName(tagName)
|
||||
return r.push(ctx, writeRequest, "", refTag)
|
||||
return r.push(ctx, "", refTag, force, env...)
|
||||
}
|
||||
|
||||
// push pushes the provided references to the provided branch in the original repository.
|
||||
func (r *SharedRepo) push(ctx context.Context, writeRequest *rpc.WriteRequest,
|
||||
sourceRef, destinationRef string) error {
|
||||
func (r *SharedRepo) push(
|
||||
ctx context.Context,
|
||||
sourceRef string,
|
||||
destinationRef string,
|
||||
force bool,
|
||||
env ...string,
|
||||
) error {
|
||||
// Because calls hooks we need to pass in the environment
|
||||
env := CreateEnvironmentForPush(ctx, writeRequest)
|
||||
if err := gitea.Push(ctx, r.tmpPath, types.PushOptions{
|
||||
if err := gitea.Push(ctx, r.tmpPath, gitea.PushOptions{
|
||||
Remote: r.remoteRepoPath,
|
||||
Branch: sourceRef + ":" + destinationRef,
|
||||
Env: env,
|
||||
Force: force,
|
||||
}); err != nil {
|
||||
if git.IsErrPushOutOfDate(err) {
|
||||
if gitea.IsErrPushOutOfDate(err) {
|
||||
return err
|
||||
} else if git.IsErrPushRejected(err) {
|
||||
rejectErr := new(git.ErrPushRejected)
|
||||
} else if gitea.IsErrPushRejected(err) {
|
||||
rejectErr := new(gitea.ErrPushRejected)
|
||||
if errors.As(err, &rejectErr) {
|
||||
log.Ctx(ctx).Info().Msgf("Unable to push back to repo from temporary repo due to rejection:"+
|
||||
" %s (%s)\nStdout: %s\nStderr: %s\nError: %v",
|
||||
r.repoUID, r.tmpPath, rejectErr.StdOut, rejectErr.StdErr, rejectErr.Err)
|
||||
" %s \nStdout: %s\nStderr: %s\nError: %v",
|
||||
r.repoUID, rejectErr.StdOut, rejectErr.StdErr, rejectErr.Err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("unable to push back to repo from temporary repo: %s (%s) Error: %w",
|
||||
r.repoUID, r.tmpPath, err)
|
||||
return processGiteaErrorf(err, "unable to push back to repo from temporary repo: %s Error: %v",
|
||||
r.repoUID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBranchCommit Gets the commit object of the given branch.
|
||||
func (r *SharedRepo) GetBranchCommit(branch string) (*git.Commit, error) {
|
||||
func (r *SharedRepo) GetBranchCommit(branch string) (*gitea.Commit, error) {
|
||||
if r.repo == nil {
|
||||
return nil, fmt.Errorf("repository has not been cloned")
|
||||
}
|
||||
@ -368,44 +433,22 @@ func (r *SharedRepo) GetBranchCommit(branch string) (*git.Commit, error) {
|
||||
return r.repo.GetBranchCommit(strings.TrimPrefix(branch, gitReferenceNamePrefixBranch))
|
||||
}
|
||||
|
||||
// GetBranch gets the branch object of the given ref.
|
||||
func (r *SharedRepo) GetBranch(rev string) (*gitea.Branch, error) {
|
||||
if r.repo == nil {
|
||||
return nil, fmt.Errorf("repository has not been cloned")
|
||||
}
|
||||
return r.repo.GetBranch(rev)
|
||||
}
|
||||
|
||||
// GetCommit Gets the commit object of the given commit ID.
|
||||
func (r *SharedRepo) GetCommit(commitID string) (*git.Commit, error) {
|
||||
func (r *SharedRepo) GetCommit(commitID string) (*gitea.Commit, error) {
|
||||
if r.repo == nil {
|
||||
return nil, fmt.Errorf("repository has not been cloned")
|
||||
}
|
||||
return r.repo.GetCommit(commitID)
|
||||
}
|
||||
|
||||
// ASSUMPTION: writeRequst and writeRequst.Actor is never nil.
|
||||
func CreateEnvironmentForPush(ctx context.Context, writeRequest *rpc.WriteRequest) []string {
|
||||
// don't send existing environment variables (os.Environ()), only send what's explicitly necessary.
|
||||
// Otherwise we create implicit dependencies that are easy to break.
|
||||
environ := []string{
|
||||
// request id to use for hooks
|
||||
EnvRequestID + "=" + middleware.RequestIDFrom(ctx),
|
||||
// repo related info
|
||||
EnvRepoUID + "=" + writeRequest.RepoUid,
|
||||
// actor related info
|
||||
EnvActorName + "=" + writeRequest.Actor.Name,
|
||||
EnvActorEmail + "=" + writeRequest.Actor.Email,
|
||||
}
|
||||
|
||||
// add all environment variables coming from client request
|
||||
for _, envVar := range writeRequest.EnvVars {
|
||||
environ = append(environ, fmt.Sprintf("%s=%s", envVar.Name, envVar.Value))
|
||||
}
|
||||
|
||||
// add all environment variables from the metadata
|
||||
if metadata, mOK := metadata.FromIncomingContext(ctx); mOK {
|
||||
if envVars, eOK := metadata[rpc.MetadataKeyEnvironmentVariables]; eOK {
|
||||
// TODO: should we do a sanity check?
|
||||
environ = append(environ, envVars...)
|
||||
}
|
||||
}
|
||||
|
||||
return environ
|
||||
}
|
||||
|
||||
// GetReferenceFromBranchName assumes the provided value is the branch name (not the ref!)
|
||||
// and first sanitizes the branch name (remove any spaces or 'refs/heads/' prefix)
|
||||
// It then returns the full form of the branch reference.
|
||||
@ -432,3 +475,12 @@ func GetReferenceFromTagName(tagName string) string {
|
||||
// return reference
|
||||
return gitReferenceNamePrefixTag + tagName
|
||||
}
|
||||
|
||||
// SharedRepository creates new instance of SharedRepo.
|
||||
func (a Adapter) SharedRepository(
|
||||
tmpDir string,
|
||||
repoUID string,
|
||||
remotePath string,
|
||||
) (*SharedRepo, error) {
|
||||
return NewSharedRepo(tmpDir, repoUID, remotePath)
|
||||
}
|
@ -12,20 +12,27 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
)
|
||||
|
||||
// GetSubmodule returns the submodule at the given path reachable from ref.
|
||||
// Note: ref can be Branch / Tag / CommitSHA.
|
||||
func (g Adapter) GetSubmodule(ctx context.Context, repoPath string,
|
||||
ref string, treePath string) (*types.Submodule, error) {
|
||||
func (a Adapter) GetSubmodule(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
ref string,
|
||||
treePath string,
|
||||
) (*types.Submodule, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
treePath = cleanTreePath(treePath)
|
||||
|
||||
giteaRepo, err := gitea.OpenRepository(ctx, repoPath)
|
@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package gitea
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@ -24,7 +24,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/harness/gitness/gitrpc/internal/types"
|
||||
"github.com/harness/gitness/git/types"
|
||||
|
||||
gitea "code.gitea.io/gitea/modules/git"
|
||||
)
|
||||
@ -35,7 +35,14 @@ const (
|
||||
)
|
||||
|
||||
// GetAnnotatedTag returns the tag for a specific tag sha.
|
||||
func (g Adapter) GetAnnotatedTag(ctx context.Context, repoPath string, sha string) (*types.Tag, error) {
|
||||
func (a Adapter) GetAnnotatedTag(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
sha string,
|
||||
) (*types.Tag, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
tags, err := giteaGetAnnotatedTags(ctx, repoPath, []string{sha})
|
||||
if err != nil || len(tags) == 0 {
|
||||
return nil, processGiteaErrorf(err, "failed to get annotated tag with sha '%s'", sha)
|
||||
@ -45,18 +52,28 @@ func (g Adapter) GetAnnotatedTag(ctx context.Context, repoPath string, sha strin
|
||||
}
|
||||
|
||||
// GetAnnotatedTags returns the tags for a specific list of tag sha.
|
||||
func (g Adapter) GetAnnotatedTags(ctx context.Context, repoPath string, shas []string) ([]types.Tag, error) {
|
||||
func (a Adapter) GetAnnotatedTags(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
shas []string,
|
||||
) ([]types.Tag, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
return giteaGetAnnotatedTags(ctx, repoPath, shas)
|
||||
}
|
||||
|
||||
// CreateTag creates the tag pointing at the provided SHA (could be any type, e.g. commit, tag, blob, ...)
|
||||
func (g Adapter) CreateTag(
|
||||
func (a Adapter) CreateTag(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
name string,
|
||||
targetSHA string,
|
||||
opts *types.CreateTagOptions,
|
||||
) error {
|
||||
if repoPath == "" {
|
||||
return ErrRepositoryPathEmpty
|
||||
}
|
||||
args := []string{
|
||||
"tag",
|
||||
}
|
||||
@ -90,7 +107,14 @@ func (g Adapter) CreateTag(
|
||||
|
||||
// giteaGetAnnotatedTag is a custom implementation to retrieve an annotated tag from a sha.
|
||||
// The code is following parts of the gitea implementation.
|
||||
func giteaGetAnnotatedTags(ctx context.Context, repoPath string, shas []string) ([]types.Tag, error) {
|
||||
func giteaGetAnnotatedTags(
|
||||
ctx context.Context,
|
||||
repoPath string,
|
||||
shas []string,
|
||||
) ([]types.Tag, error) {
|
||||
if repoPath == "" {
|
||||
return nil, ErrRepositoryPathEmpty
|
||||
}
|
||||
// The tag is an annotated tag with a message.
|
||||
writer, reader, cancel := gitea.CatFileBatch(ctx, repoPath)
|
||||
defer func() {
|
||||
@ -140,43 +164,40 @@ func giteaGetAnnotatedTags(ctx context.Context, repoPath string, shas []string)
|
||||
}
|
||||
|
||||
// parseTagDataFromCatFile parses a tag from a cat-file output.
|
||||
func parseTagDataFromCatFile(data []byte) (types.Tag, error) {
|
||||
func parseTagDataFromCatFile(data []byte) (tag types.Tag, err error) {
|
||||
p := 0
|
||||
|
||||
var err error
|
||||
var tag types.Tag
|
||||
|
||||
// parse object Id
|
||||
tag.TargetSha, p, err = giteaParseCatFileLine(data, p, "object")
|
||||
if err != nil {
|
||||
return types.Tag{}, fmt.Errorf("failed to parse cat file 'object' line: %w", err)
|
||||
return tag, err
|
||||
}
|
||||
|
||||
// parse object type
|
||||
rawType, p, err := giteaParseCatFileLine(data, p, "type")
|
||||
if err != nil {
|
||||
return types.Tag{}, fmt.Errorf("failed to parse cat file 'type' line: %w", err)
|
||||
return tag, err
|
||||
}
|
||||
|
||||
tag.TargetType, err = types.ParseGitObjectType(rawType)
|
||||
if err != nil {
|
||||
return types.Tag{}, fmt.Errorf("failed to parse raw git object type: %w", err)
|
||||
return tag, err
|
||||
}
|
||||
|
||||
// parse tag name
|
||||
tag.Name, p, err = giteaParseCatFileLine(data, p, "tag")
|
||||
if err != nil {
|
||||
return types.Tag{}, fmt.Errorf("failed to parse cat file 'tag' line: %w", err)
|
||||
return tag, err
|
||||
}
|
||||
|
||||
// parse tagger
|
||||
rawTaggerInfo, p, err := giteaParseCatFileLine(data, p, "tagger")
|
||||
if err != nil {
|
||||
return types.Tag{}, fmt.Errorf("failed to parse cat file 'tagger' line: %w", err)
|
||||
return tag, err
|
||||
}
|
||||
tag.Tagger, err = parseSignatureFromCatFileLine(rawTaggerInfo)
|
||||
if err != nil {
|
||||
return types.Tag{}, fmt.Errorf("failed to parse tagger signature: %w", err)
|
||||
return tag, err
|
||||
}
|
||||
|
||||
// remainder is message and gpg (remove leading and tailing new lines)
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user