small fixes (#1232)

This commit is contained in:
Johannes Batzill 2024-04-19 01:36:03 +00:00 committed by Harness
parent 032bbeb066
commit a690fa4ebc
10 changed files with 58 additions and 26 deletions

View File

@ -107,14 +107,14 @@ func (c *Controller) reportBranchEvent(
branchUpdate hook.ReferenceUpdate, branchUpdate hook.ReferenceUpdate,
) { ) {
switch { switch {
case branchUpdate.Old.String() == types.NilSHA: case branchUpdate.Old.IsNil():
c.gitReporter.BranchCreated(ctx, &events.BranchCreatedPayload{ c.gitReporter.BranchCreated(ctx, &events.BranchCreatedPayload{
RepoID: repo.ID, RepoID: repo.ID,
PrincipalID: principalID, PrincipalID: principalID,
Ref: branchUpdate.Ref, Ref: branchUpdate.Ref,
SHA: branchUpdate.New.String(), SHA: branchUpdate.New.String(),
}) })
case branchUpdate.New.String() == types.NilSHA: case branchUpdate.New.IsNil():
c.gitReporter.BranchDeleted(ctx, &events.BranchDeletedPayload{ c.gitReporter.BranchDeleted(ctx, &events.BranchDeletedPayload{
RepoID: repo.ID, RepoID: repo.ID,
PrincipalID: principalID, PrincipalID: principalID,
@ -157,14 +157,14 @@ func (c *Controller) reportTagEvent(
tagUpdate hook.ReferenceUpdate, tagUpdate hook.ReferenceUpdate,
) { ) {
switch { switch {
case tagUpdate.Old.String() == types.NilSHA: case tagUpdate.Old.IsNil():
c.gitReporter.TagCreated(ctx, &events.TagCreatedPayload{ c.gitReporter.TagCreated(ctx, &events.TagCreatedPayload{
RepoID: repo.ID, RepoID: repo.ID,
PrincipalID: principalID, PrincipalID: principalID,
Ref: tagUpdate.Ref, Ref: tagUpdate.Ref,
SHA: tagUpdate.New.String(), SHA: tagUpdate.New.String(),
}) })
case tagUpdate.New.String() == types.NilSHA: case tagUpdate.New.IsNil():
c.gitReporter.TagDeleted(ctx, &events.TagDeletedPayload{ c.gitReporter.TagDeleted(ctx, &events.TagDeletedPayload{
RepoID: repo.ID, RepoID: repo.ID,
PrincipalID: principalID, PrincipalID: principalID,
@ -195,7 +195,7 @@ func (c *Controller) handlePRMessaging(
// skip anything that was a batch push / isn't branch related / isn't updating/creating a branch. // skip anything that was a batch push / isn't branch related / isn't updating/creating a branch.
if len(in.RefUpdates) != 1 || if len(in.RefUpdates) != 1 ||
!strings.HasPrefix(in.RefUpdates[0].Ref, gitReferenceNamePrefixBranch) || !strings.HasPrefix(in.RefUpdates[0].Ref, gitReferenceNamePrefixBranch) ||
in.RefUpdates[0].New.String() == types.NilSHA { in.RefUpdates[0].New.IsNil() {
return return
} }
@ -273,7 +273,7 @@ func (c *Controller) handleEmptyRepoPush(
// we only care about one active branch that was pushed. // we only care about one active branch that was pushed.
for _, refUpdate := range in.RefUpdates { for _, refUpdate := range in.RefUpdates {
if strings.HasPrefix(refUpdate.Ref, gitReferenceNamePrefixBranch) && if strings.HasPrefix(refUpdate.Ref, gitReferenceNamePrefixBranch) &&
refUpdate.New.String() != types.NilSHA { !refUpdate.New.IsNil() {
branchName = refUpdate.Ref[len(gitReferenceNamePrefixBranch):] branchName = refUpdate.Ref[len(gitReferenceNamePrefixBranch):]
break break
} }

View File

@ -186,9 +186,9 @@ type changes struct {
func (c *changes) groupByAction(refUpdate hook.ReferenceUpdate, name string) { func (c *changes) groupByAction(refUpdate hook.ReferenceUpdate, name string) {
switch { switch {
case refUpdate.Old.String() == types.NilSHA: case refUpdate.Old.IsNil():
c.created = append(c.created, name) c.created = append(c.created, name)
case refUpdate.New.String() == types.NilSHA: case refUpdate.New.IsNil():
c.deleted = append(c.deleted, name) c.deleted = append(c.deleted, name)
default: default:
c.updated = append(c.updated, name) c.updated = append(c.updated, name)

View File

@ -92,7 +92,7 @@ func scanSecretsInternal(ctx context.Context,
ctx := logging.NewContext(ctx, loggingWithRefUpdate(refUpdate)) ctx := logging.NewContext(ctx, loggingWithRefUpdate(refUpdate))
log := log.Ctx(ctx) log := log.Ctx(ctx)
if refUpdate.New.String() == types.NilSHA { if refUpdate.New.IsNil() {
log.Debug().Msg("skip deleted reference") log.Debug().Msg("skip deleted reference")
continue continue
} }

View File

@ -424,10 +424,11 @@ func (c *Controller) Merge(
pr.ActivitySeq = activitySeqMerge pr.ActivitySeq = activitySeqMerge
activityPayload := &types.PullRequestActivityPayloadMerge{ activityPayload := &types.PullRequestActivityPayloadMerge{
MergeMethod: in.Method, MergeMethod: in.Method,
MergeSHA: mergeOutput.MergeSHA.String(), MergeSHA: mergeOutput.MergeSHA.String(),
TargetSHA: mergeOutput.BaseSHA.String(), TargetSHA: mergeOutput.BaseSHA.String(),
SourceSHA: mergeOutput.HeadSHA.String(), SourceSHA: mergeOutput.HeadSHA.String(),
RulesBypassed: protection.IsBypassed(violations),
} }
if _, errAct := c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, activityPayload); errAct != nil { if _, errAct := c.activityStore.CreateWithPayload(ctx, pr, session.Principal.ID, activityPayload); errAct != nil {
// non-critical error // non-critical error

View File

@ -69,6 +69,15 @@ func IsCritical(violations []types.RuleViolations) bool {
return false return false
} }
func IsBypassed(violations []types.RuleViolations) bool {
for i := range violations {
if violations[i].IsBypassed() {
return true
}
}
return false
}
// NewManager creates new protection Manager. // NewManager creates new protection Manager.
func NewManager(ruleStore store.RuleStore) *Manager { func NewManager(ruleStore store.RuleStore) *Manager {
return &Manager{ return &Manager{

View File

@ -50,7 +50,7 @@ func (c *CLICore) PreReceive(ctx context.Context) error {
return fmt.Errorf("failed to read updated references from std in: %w", err) return fmt.Errorf("failed to read updated references from std in: %w", err)
} }
alternateObjDirs, err := getAlternateObjectDirsFromEnv() alternateObjDirs, err := getAlternateObjectDirsFromEnv(refUpdates)
if err != nil { if err != nil {
return fmt.Errorf("failed to read alternate object dirs from env: %w", err) return fmt.Errorf("failed to read alternate object dirs from env: %w", err)
} }
@ -68,8 +68,10 @@ func (c *CLICore) PreReceive(ctx context.Context) error {
} }
// Update executes the update git hook. // Update executes the update git hook.
func (c *CLICore) Update(ctx context.Context, ref string, oldSHA string, newSHA string) error { func (c *CLICore) Update(ctx context.Context, ref string, oldSHARaw string, newSHARaw string) error {
alternateObjDirs, err := getAlternateObjectDirsFromEnv() newSHA := sha.Must(newSHARaw)
oldSHA := sha.Must(oldSHARaw)
alternateObjDirs, err := getAlternateObjectDirsFromEnv([]ReferenceUpdate{{Ref: ref, Old: oldSHA, New: newSHA}})
if err != nil { if err != nil {
return fmt.Errorf("failed to read alternate object dirs from env: %w", err) return fmt.Errorf("failed to read alternate object dirs from env: %w", err)
} }
@ -77,8 +79,8 @@ func (c *CLICore) Update(ctx context.Context, ref string, oldSHA string, newSHA
in := UpdateInput{ in := UpdateInput{
RefUpdate: ReferenceUpdate{ RefUpdate: ReferenceUpdate{
Ref: ref, Ref: ref,
Old: sha.Must(oldSHA), Old: oldSHA,
New: sha.Must(newSHA), New: newSHA,
}, },
Environment: Environment{ Environment: Environment{
AlternateObjectDirs: alternateObjDirs, AlternateObjectDirs: alternateObjDirs,
@ -183,7 +185,20 @@ func getUpdatedReferencesFromStdIn() ([]ReferenceUpdate, error) {
// to be able to preemptively access the quarantined objects created by a write operation. // to be able to preemptively access the quarantined objects created by a write operation.
// NOTE: The temp dir of a write operation is it's main object dir, // NOTE: The temp dir of a write operation is it's main object dir,
// which is the one that read operations have to use as alternate object dir. // which is the one that read operations have to use as alternate object dir.
func getAlternateObjectDirsFromEnv() ([]string, error) { func getAlternateObjectDirsFromEnv(refUpdates []ReferenceUpdate) ([]string, error) {
hasCreateOrUpdate := false
for i := range refUpdates {
if !refUpdates[i].New.IsNil() {
hasCreateOrUpdate = true
break
}
}
// git doesn't create an alternate object dir if there's only delete operations
if !hasCreateOrUpdate {
return nil, nil
}
tmpDir, err := getRequiredEnvironmentVariable(command.GitObjectDir) tmpDir, err := getRequiredEnvironmentVariable(command.GitObjectDir)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -220,10 +220,11 @@ func (a *PullRequestActivityPayloadCodeComment) ActivityType() enum.PullReqActiv
} }
type PullRequestActivityPayloadMerge struct { type PullRequestActivityPayloadMerge struct {
MergeMethod enum.MergeMethod `json:"merge_method"` MergeMethod enum.MergeMethod `json:"merge_method"`
MergeSHA string `json:"merge_sha"` MergeSHA string `json:"merge_sha"`
TargetSHA string `json:"target_sha"` TargetSHA string `json:"target_sha"`
SourceSHA string `json:"source_sha"` SourceSHA string `json:"source_sha"`
RulesBypassed bool `json:"rules_bypassed,omitempty"`
} }
func (a *PullRequestActivityPayloadMerge) ActivityType() enum.PullReqActivityType { func (a *PullRequestActivityPayloadMerge) ActivityType() enum.PullReqActivityType {

View File

@ -164,7 +164,11 @@ func (violations *RuleViolations) Addf(code, format string, params ...any) {
} }
func (violations *RuleViolations) IsCritical() bool { func (violations *RuleViolations) IsCritical() bool {
return violations.Rule.State == enum.RuleStateActive && !violations.Bypassed && len(violations.Violations) > 0 return violations.Rule.State == enum.RuleStateActive && len(violations.Violations) > 0 && !violations.Bypassed
}
func (violations *RuleViolations) IsBypassed() bool {
return violations.Rule.State == enum.RuleStateActive && len(violations.Violations) > 0 && violations.Bypassed
} }
// RuleInfo holds basic info about a rule that is used to describe the rule in RuleViolations. // RuleInfo holds basic info about a rule that is used to describe the rule in RuleViolations.

View File

@ -286,8 +286,8 @@ pr:
requestSubmitted: Request for changes submitted. requestSubmitted: Request for changes submitted.
prReviewSubmit: '{user} {state|approved:approved, rejected:rejected,changereq:requested changes to, reviewed} this pull request. {time}' prReviewSubmit: '{user} {state|approved:approved, rejected:rejected,changereq:requested changes to, reviewed} this pull request. {time}'
prMergedBannerInfo: '{user} merged branch {source} into {target} {time}.' prMergedBannerInfo: '{user} merged branch {source} into {target} {time}.'
prMergedInfo: '{user} merged changes from {source} into {target} as {mergeSha} {time}' prMergedInfo: '{user}{bypassed|true: bypassed rules and , }merged changes from {source} into {target} as {mergeSha} {time}'
prRebasedInfo: '{user} rebased changes from branch {source} onto {target}, now at {mergeSha} {time}' prRebasedInfo: '{user}{bypassed|true: bypassed rules and , }rebased changes from branch {source} onto {target}, now at {mergeSha} {time}'
prBranchPushInfo: '{user} pushed a new commit {commit}' prBranchPushInfo: '{user} pushed a new commit {commit}'
prBranchDeleteInfo: '{user} deleted the source branch with latest commit {commit}' prBranchDeleteInfo: '{user} deleted the source branch with latest commit {commit}'
prStateChanged: '{user} changed pull request state from {old} to {new}.' prStateChanged: '{user} changed pull request state from {old} to {new}.'

View File

@ -39,6 +39,7 @@ interface SystemCommentProps extends Pick<GitInfoProps, 'pullReqMetadata'> {
interface MergePayload { interface MergePayload {
merge_sha: string merge_sha: string
merge_method: string merge_method: string
rules_bypassed: boolean
} }
export const SystemComment: React.FC<SystemCommentProps> = ({ pullReqMetadata, commentItems, repoMetadataPath }) => { export const SystemComment: React.FC<SystemCommentProps> = ({ pullReqMetadata, commentItems, repoMetadataPath }) => {
@ -68,6 +69,7 @@ export const SystemComment: React.FC<SystemCommentProps> = ({ pullReqMetadata, c
user: <strong className={css.rightTextPadding}>{pullReqMetadata.merger?.display_name}</strong>, user: <strong className={css.rightTextPadding}>{pullReqMetadata.merger?.display_name}</strong>,
source: <strong className={css.textPadding}>{pullReqMetadata.source_branch}</strong>, source: <strong className={css.textPadding}>{pullReqMetadata.source_branch}</strong>,
target: <strong className={css.textPadding}>{pullReqMetadata.target_branch}</strong>, target: <strong className={css.textPadding}>{pullReqMetadata.target_branch}</strong>,
bypassed: (payload?.payload as MergePayload)?.rules_bypassed,
mergeSha: ( mergeSha: (
<Container className={css.commitContainer} padding={{ left: 'small', right: 'xsmall' }}> <Container className={css.commitContainer} padding={{ left: 'small', right: 'xsmall' }}>
<CommitActions <CommitActions