Skip to content

Commit

Permalink
feat: [pipe-20916]: fix types and code
Browse files Browse the repository at this point in the history
Signed-off-by: Calvin Lee <[email protected]>
  • Loading branch information
cjlee1 committed Nov 16, 2024
1 parent 6595afe commit af3b443
Show file tree
Hide file tree
Showing 3 changed files with 142 additions and 88 deletions.
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import React, { useEffect } from 'react'
import { useCallback, useEffect } from 'react'
import { usePullRequestDataStore } from '../stores/pull-request-store'
import { useGetSpaceURLParam } from '../../../framework/hooks/useGetSpaceParam'
import { useGetRepoRef } from '../../../framework/hooks/useGetRepoPath'
import { useParams } from 'react-router-dom'
import { PathParams } from '../../../RouteDefinitions'
import useGetPullRequestTab, { PullRequestTab } from '../../../hooks/useGetPullRequestTab'
import {
TypesPullReq,
useFindRepositoryQuery,
useGetPullReqQuery,
useListCommitsQuery,
Expand All @@ -17,12 +18,7 @@ import { SSEEvent } from '../../../types'
import useSpaceSSE from '../../../framework/hooks/useSpaceSSE'
import { extractSpecificViolations } from '../utils'
import { isEqual } from 'lodash-es'
export const codeOwnersNotFoundMessage = 'CODEOWNERS file not found'
export const codeOwnersNotFoundMessage2 = `path "CODEOWNERS" not found`
export const codeOwnersNotFoundMessage3 = `failed to find node 'CODEOWNERS' in 'main': failed to get tree node: failed to ls file: path "CODEOWNERS" not found`
export const oldCommitRefetchRequired = 'A newer commit is available. Only the latest commit can be merged.'
export const prMergedRefetchRequired = 'Pull request already merged'
export const POLLING_INTERVAL = 10000

const PullRequestDataProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const space = useGetSpaceURLParam() ?? ''
const repoRef = useGetRepoRef()
Expand All @@ -38,8 +34,7 @@ const PullRequestDataProvider: React.FC<{ children: React.ReactNode }> = ({ chil
prPanelData,
setResolvedCommentArr,
setPullReqMetadata,
setPullReqStats,
pullReqStats,

setRepoMetadata
} = store

Expand All @@ -53,6 +48,7 @@ const PullRequestDataProvider: React.FC<{ children: React.ReactNode }> = ({ chil
pullreq_number: Number(pullRequestId),
queryParams: {}
})

const {
data: { body: activities } = {},
isFetching: activitiesLoading,
Expand All @@ -76,22 +72,33 @@ const PullRequestDataProvider: React.FC<{ children: React.ReactNode }> = ({ chil
repo_ref: repoRef
})
const pullReqChecksDecision = usePRChecksDecision({ repoMetadata, pullReqMetadata: pullReqData })
useSpaceSSE({
space,
events: [SSEEvent.PULLREQ_UPDATED],
onEvent: data => {
const handleEvent = useCallback(
(data: TypesPullReq) => {
if (data && String(data?.number) === pullRequestId) {
refetchPullReq()
}
}
},
[pullRequestId, refetchPullReq]
)
useSpaceSSE({
space,
events: [SSEEvent.PULLREQ_UPDATED],
onEvent: handleEvent,
shouldRun: !!(space && pullRequestId) // Ensure shouldRun is true only when space and pullRequestId are valid
})
useEffect(() => {
if (repoMetadata) {
setRepoMetadata(repoMetadata)
}
}, [repoMetadata, setRepoMetadata])
useEffect(
() => {
useEffect(() => {
const hasChanges =
!isEqual(store.pullReqMetadata, pullReqData) ||
!isEqual(store.pullReqStats, pullReqData?.stats) ||
!isEqual(store.pullReqCommits, commits) ||
!isEqual(store.pullReqActivities, activities)

if (hasChanges) {
store.updateState({
repoMetadata,
setPullReqMetadata,
Expand Down Expand Up @@ -134,30 +141,28 @@ const PullRequestDataProvider: React.FC<{ children: React.ReactNode }> = ({ chil
ruleViolationArr: undefined
}
})
},
[
// repoMetadata,
// pullReqData,
// commits,
// activities,
// pullReqLoading,
// activitiesLoading,
// pullReqError,
// activitiesError,
// commitsError,
// pullReqChecksDecision,
// refetchActivities,
// refetchCommits,
// refetchPullReq
]
)
}
}, [
repoMetadata,
pullReqData,
commits,
activities,
pullReqLoading,
activitiesLoading,
pullReqError,
activitiesError,
commitsError,
pullReqChecksDecision,
refetchActivities,
refetchCommits,
refetchPullReq
])

useEffect(() => {
const intervalId = setInterval(() => {
console.log(pullReqMetadata, pullRequestTab, repoRef)
if (pullReqMetadata?.source_sha && pullRequestTab === PullRequestTab.CONVERSATION && repoRef) {
console.log('dryMerge', pullReqMetadata)
dryMerge()
console.log(prPanelData, 22222)
}
}, 10000) // Poll every 10 seconds

Expand Down Expand Up @@ -186,7 +191,6 @@ const PullRequestDataProvider: React.FC<{ children: React.ReactNode }> = ({ chil

useEffect(() => {
const ruleViolationArr = prPanelData.ruleViolationArr
console.log('ruleViolationArr', ruleViolationArr, prPanelData)
if (ruleViolationArr) {
const requireResCommentRule = extractSpecificViolations(ruleViolationArr, 'pullreq.comments.require_resolve_all')
if (requireResCommentRule) {
Expand All @@ -195,26 +199,6 @@ const PullRequestDataProvider: React.FC<{ children: React.ReactNode }> = ({ chil
}
}, [prPanelData.ruleViolationArr])

useEffect(() => {
if (pullReqData && !isEqual(pullReqMetadata, pullReqData)) {
if (
!pullReqMetadata ||
(pullReqMetadata &&
(pullReqMetadata.merge_base_sha !== pullReqData.merge_base_sha ||
pullReqMetadata.source_sha !== pullReqData.source_sha))
) {
refetchCommits()
}

setPullReqMetadata(pullReqData)

if (!isEqual(pullReqStats, pullReqData.stats)) {
setPullReqStats(pullReqData.stats)
refetchActivities()
}
}
}, [pullReqData, pullReqMetadata, pullReqStats, refetchActivities, refetchCommits])

return <>{children}</>
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ export default function PullRequestConversationPage() {
queryParams: {}
})
const [changesLoading, setChangesLoading] = useState(true)
console.log(reviewers, codeOwners)
const [activities, setActivities] = useState(activityData)
const approvedEvaluations = reviewers?.filter(evaluation => evaluation.review_decision === 'approved')
const latestApprovalArr = approvedEvaluations?.filter(
Expand Down Expand Up @@ -177,22 +176,22 @@ export default function PullRequestConversationPage() {
console.error('Failed to save comment:', error)
})
}
console.log(
'cp',
approvedEvaluations,
prPanelData?.atLeastOneReviewerRule,
prPanelData?.reqCodeOwnerApproval,
prPanelData?.minApproval,
prPanelData?.reqCodeOwnerLatestApproval,
prPanelData?.minReqLatestApproval,
codeOwnerChangeReqEntries,
codeOwnerPendingEntries,
latestCodeOwnerApprovalArr,
latestApprovalArr,
codeOwnerApprovalEntries,
changeReqReviewer,
changeReqEvaluations
)
// console.log(
// 'cp',
// approvedEvaluations,
// prPanelData?.atLeastOneReviewerRule,
// prPanelData?.reqCodeOwnerApproval,
// prPanelData?.minApproval,
// prPanelData?.reqCodeOwnerLatestApproval,
// prPanelData?.minReqLatestApproval,
// codeOwnerChangeReqEntries,
// codeOwnerPendingEntries,
// latestCodeOwnerApprovalArr,
// latestApprovalArr,
// codeOwnerApprovalEntries,
// changeReqReviewer,
// changeReqEvaluations
// )
const changesInfo = extractInfoForCodeOwnerContent({
approvedEvaluations,
reqNoChangeReq: prPanelData?.atLeastOneReviewerRule,
Expand Down Expand Up @@ -306,7 +305,7 @@ export default function PullRequestConversationPage() {
commentsInfo={prPanelData?.commentsInfoData}
ruleViolation={prPanelData.ruleViolation}
checks={pullReqChecksDecision?.data?.checks}
PRStateLoading={prPanelData?.PRStateLoading }
PRStateLoading={prPanelData?.PRStateLoading}
// TODO: TypesPullReq is null for someone: vardan will look into why swagger is doing this
pullReqMetadata={pullReqMetadata ? pullReqMetadata : undefined}
// TODO: add dry merge check into pr context
Expand Down Expand Up @@ -382,7 +381,7 @@ export default function PullRequestConversationPage() {
</SandboxLayout.Content>
</SandboxLayout.Column>
<SandboxLayout.Column>
<SandboxLayout.Content className="pl-0 pr-0">
<SandboxLayout.Content className="px-0">
<PullRequestSideBar
addReviewers={handleAddReviewer}
usersList={principals?.map(user => ({ id: user.id, display_name: user.display_name, uid: user.uid }))}
Expand Down
97 changes: 84 additions & 13 deletions apps/gitness/src/pages/pull-request/stores/pull-request-store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import create from 'zustand'
import { create } from 'zustand'
import {
ChecksPullReqOkResponse,
ListCommitsOkResponse,
Expand All @@ -10,9 +10,15 @@ import {
mergePullReqOp,
commentStatusPullReq as apiCommentStatusPullReq
} from '@harnessio/code-service-client'
import { ExecutionState } from '@harnessio/playground'
import { ExecutionState } from '@harnessio/views'
import { CodeCommentState, PullRequestState } from '../types/types'

export const codeOwnersNotFoundMessage = 'CODEOWNERS file not found'
export const codeOwnersNotFoundMessage2 = `path "CODEOWNERS" not found`
export const codeOwnersNotFoundMessage3 = `failed to find node 'CODEOWNERS' in 'main': failed to get tree node: failed to ls file: path "CODEOWNERS" not found`
export const oldCommitRefetchRequired = 'A newer commit is available. Only the latest commit can be merged.'
export const prMergedRefetchRequired = 'Pull request already merged'
export const POLLING_INTERVAL = 10000
interface PullReqChecksDecisionProps {
overallStatus: ExecutionState | undefined
count: {
Expand Down Expand Up @@ -45,7 +51,8 @@ interface PullRequestDataState {
pullReqStats: TypesPullReqStats | undefined
pullReqCommits: ListCommitsOkResponse | undefined
pullReqActivities: TypesPullReqActivity[] | undefined
loading: boolean // eslint-disable-next-line @typescript-eslint/no-explicit-any
loading: boolean
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error: any
pullReqChecksDecision: PullReqChecksDecisionProps
showEditDescription: boolean
Expand Down Expand Up @@ -145,9 +152,8 @@ export const usePullRequestDataStore = create<PullRequestDataState>((set, get) =
refetchPullReq: () => {},
retryOnErrorFunc: () => {},
dryMerge: () => {
const { repoMetadata, pullReqMetadata, refetchPullReq, setRuleViolationArr } = get()
const { repoMetadata, pullReqMetadata, refetchPullReq } = get()
const isClosed = pullReqMetadata?.state === PullRequestState.CLOSED
console.log('dryMerge2', isClosed, repoMetadata?.path, pullReqMetadata?.state)
if (!isClosed && repoMetadata?.path !== undefined && pullReqMetadata?.state !== PullRequestState.MERGED) {
mergePullReqOp({
repo_ref: `${repoMetadata?.path}/+`,
Expand All @@ -157,22 +163,90 @@ export const usePullRequestDataStore = create<PullRequestDataState>((set, get) =
.then(({ body: res }) => {
if (res?.rule_violations?.length && res?.rule_violations?.length > 0) {
console.log('ruleViolations', res.rule_violations)
const updatedData = {
ruleViolation: res?.rule_violations?.length > 0,
ruleViolationArr:
res?.rule_violations?.length > 0 ? { data: { rule_violations: res.rule_violations } } : undefined,
requiresCommentApproval: res.requires_comment_resolution ?? false,
atLeastOneReviewerRule: res.requires_no_change_requests ?? false,
reqCodeOwnerApproval: res.requires_code_owners_approval ?? false,
minApproval: res.minimum_required_approvals_count ?? 0,
reqCodeOwnerLatestApproval: res.requires_code_owners_approval_latest ?? false,
minReqLatestApproval: res.minimum_required_approvals_count_latest ?? 0,
conflictingFiles: res.conflict_files,
PRStateLoading: false,
commentsLoading: false,
commentsInfoData: {
header: '',
content: undefined,
status: ''
}
}
set({
prPanelData: {
...get().prPanelData,
ruleViolation: true,
ruleViolationArr: { data: { rule_violations: res.rule_violations } }
...updatedData
}
})
} else {
set({ prPanelData: { ...get().prPanelData, ruleViolation: false, ruleViolationArr: undefined } })
const updatedData = {
ruleViolation: false,
ruleViolationArr: undefined,
requiresCommentApproval: res.requires_comment_resolution ?? false,
atLeastOneReviewerRule: res.requires_no_change_requests ?? false,
reqCodeOwnerApproval: res.requires_code_owners_approval ?? false,
minApproval: res.minimum_required_approvals_count ?? 0,
reqCodeOwnerLatestApproval: res.requires_code_owners_approval_latest ?? false,
minReqLatestApproval: res.minimum_required_approvals_count_latest ?? 0,
conflictingFiles: res.conflict_files,
PRStateLoading: false,
commentsLoading: false,
commentsInfoData: {
header: '',
content: undefined,
status: ''
}
}
set({ prPanelData: { ...updatedData } })
}
})
.catch(err => {
if (err.status === 422) {
setRuleViolationArr(err)
const updatedData = {
ruleViolation: true,
ruleViolationArr: err,
requiresCommentApproval: err.requires_comment_resolution ?? false,
atLeastOneReviewerRule: err.requires_no_change_requests ?? false,
reqCodeOwnerApproval: err.requires_code_owners_approval ?? false,
minApproval: err.minimum_required_approvals_count ?? 0,
reqCodeOwnerLatestApproval: err.requires_code_owners_approval_latest ?? false,
minReqLatestApproval: err.minimum_required_approvals_count_latest ?? 0,
conflictingFiles: err.conflict_files,
PRStateLoading: false,
commentsLoading: false,
commentsInfoData: {
header: '',
content: undefined,
status: ''
}
}
set({
prPanelData: {
...updatedData
}
})
} else if (err.status === 400) {
refetchPullReq()
} else if (
err.message === codeOwnersNotFoundMessage ||
err.message === codeOwnersNotFoundMessage2 ||
err.message === codeOwnersNotFoundMessage3 ||
err.status === 423 // resource locked (merge / dry-run already ongoing)
) {
return
// } else if (pullRequestSection !== PullRequestSection.CONVERSATION) {
// return
} else {
// showError(getErrorMessage(err))
}
})
.finally(() => {
Expand Down Expand Up @@ -238,6 +312,3 @@ export const usePullRequestDataStore = create<PullRequestDataState>((set, get) =
setPullReqStats: stats => set({ pullReqStats: stats }),
updateState: newState => set(newState)
}))

// Export the store
export default usePullRequestDataStore

0 comments on commit af3b443

Please sign in to comment.