All files / modules/10-common/modals/SaveToGitDialog useSaveToGitDialog.tsx

74.75% Statements 74/99
44.44% Branches 68/153
54.55% Functions 12/22
74.49% Lines 73/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332              273x 273x 273x 273x 273x 273x 273x 273x       273x 273x   273x 273x 273x 273x 273x                                                           273x     895x 895x 895x         895x 895x                       895x     895x   895x 895x   895x 895x 895x     895x                     895x 895x 895x                       895x                       895x                             895x           895x 6x 6x 6x     6x                               895x                           895x 1x                                                     895x 35x                                               895x                                 895x             895x 8x 8x     8x   8x           895x 18x 18x 18x 1x 1x   17x   18x     8x     6x       895x 23x       23x                   18x 18x                   895x   23x 23x 23x 23x 23x          
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useState } from 'react'
import { Button, getErrorInfoFromErrorObject } from '@wings-software/uicore'
import { Classes, Dialog, IDialogProps } from '@blueprintjs/core'
import { useParams } from 'react-router-dom'
import { defaultTo, noop } from 'lodash-es'
import { useModalHook } from '@harness/use-modal'
import { Entities } from '@common/interfaces/GitSyncInterface'
import SaveToGitForm, {
  GitResourceInterface,
  SaveToGitFormInterface
} from '@common/components/SaveToGitForm/SaveToGitForm'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import { getEntityNameFromType } from '@common/utils/StringUtils'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { EntityGitDetails, ResponseMessage, useCreatePR } from 'services/cd-ng'
import { String, useStrings } from 'framework/strings'
import { ProgressOverlay, StepStatus } from '../ProgressOverlay/ProgressOverlay'
import { useGitDiffEditorDialog } from '../GitDiffEditor/useGitDiffEditorDialog'
import css from './useSaveToGitDialog.module.scss'
 
export interface UseSaveSuccessResponse {
  status?: 'SUCCESS' | 'FAILURE' | 'ERROR'
  nextCallback?: () => void
}
 
export interface UseSaveToGitDialogProps<T> {
  onSuccess?: (
    data: SaveToGitFormInterface,
    payload?: T,
    objectId?: EntityGitDetails['objectId'],
    isEdit?: boolean
  ) => Promise<UseSaveSuccessResponse>
  onClose?: () => void
  onProgessOverlayClose?: () => void
}
 
export interface OpenSaveToGitDialogValue<T> {
  isEditing: boolean
  resource: GitResourceInterface
  payload: T
  _modalProps?: IDialogProps
}
 
export interface UseSaveToGitDialogReturn<T> {
  openSaveToGitDialog: (args: OpenSaveToGitDialogValue<T>) => void
  hideSaveToGitDialog: () => void
}
 
export function useSaveToGitDialog<T = Record<string, string>>(
  props: UseSaveToGitDialogProps<T>
): UseSaveToGitDialogReturn<T> {
  const [isEditMode, setIsEditMode] = useState(false)
  const [payloadData, setPayloadData] = useState<T>()
  const [resource, setResource] = useState<GitResourceInterface>({
    type: Entities.CONNECTORS,
    name: '',
    identifier: ''
  })
  const { getString } = useStrings()
  const [modalProps, setModalProps] = useState<IDialogProps>({
    isOpen: true,
    enforceFocus: false,
    style: {
      width: 720,
      minHeight: 540,
      borderLeft: 0,
      paddingBottom: 0,
      position: 'relative',
      overflow: 'hidden'
    }
  })
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
 
  /* Progress dialog states */
  const [prCreateStatus, setPRCreateStatus] = useState<StepStatus>()
  const [prMetaData, setPRMetaData] =
    useState<Pick<SaveToGitFormInterface, 'branch' | 'targetBranch' | 'isNewBranch'>>()
  const [nextCallback, setNextCallback] = useState<UseSaveSuccessResponse['nextCallback']>()
  /* TODO Don't see proper types for this new errors format, replace Record<string, any> with more stricter type when available */
  const [error, setError] = useState<Record<string, any>>({})
  const [createUpdateStatus, setCreateUpdateStatus] = useState<StepStatus>()
  const { mutate: createPullRequest, loading: creatingPR } = useCreatePR({})
 
  /* Stages for an entity updated/created and/or saved to git */
  const entityCreateUpdateStage = {
    status: createUpdateStatus,
    intermediateLabel: (
      <String
        stringID={isEditMode ? 'common.updating' : 'common.creating'}
        vars={{ name: resource.name, entity: getEntityNameFromType(resource.type) }}
      />
    ),
    finalLabel: getErrorInfoFromErrorObject(error),
    error: error?.data
  }
  const fromBranch = defaultTo(prMetaData?.branch, '')
  const toBranch = defaultTo(prMetaData?.targetBranch, '')
  const setupBranchStage = {
    status: createUpdateStatus,
    intermediateLabel: (
      <String
        stringID="common.gitSync.settingUpNewBranch"
        vars={{
          branch: fromBranch
        }}
        useRichText
      />
    )
  }
  const pushingChangesToBranch = {
    status: createUpdateStatus,
    intermediateLabel: (
      <String
        stringID="common.gitSync.pushingChangestoBranch"
        vars={{
          branch: fromBranch
        }}
        useRichText
      />
    )
  }
  const createPRStage = {
    status: prCreateStatus,
    intermediateLabel: (
      <String
        stringID="common.gitSync.creatingPR"
        vars={{
          fromBranch,
          toBranch
        }}
        useRichText
      />
    ),
    finalLabel: getString('common.gitSync.unableToCreatePR')
  }
 
  const handleCreateUpdateSuccess = (status?: string): void => {
    if (status === 'SUCCESS') {
      nextCallback?.()
    }
  }
 
  const handleCreateUpdateError = (e: any, data: SaveToGitFormInterface): void => {
    setError(e)
    setCreateUpdateStatus('ERROR')
    Iif (data?.createPr) {
      setPRCreateStatus('ABORTED')
    }
    Iif (
      ((e?.responseMessages as ResponseMessage[]) || (e.data?.responseMessages as ResponseMessage[]) || [])?.findIndex(
        (mssg: ResponseMessage) => mssg.code === 'SCM_CONFLICT_ERROR'
      ) !== -1
    ) {
      const conflictCommitId = defaultTo(e?.metadata?.conflictCommitId, e?.data?.metadata?.conflictCommitId)
 
      openGitDiffDialog(payloadData, {
        ...data,
        resolvedConflictCommitId: defaultTo(conflictCommitId, '')
      })
    }
  }
 
  // Dialogs
  // Modal to show when a git conflict occurs
  const { openGitDiffDialog } = useGitDiffEditorDialog({
    onSuccess: (payload, objectId: EntityGitDetails['objectId'], gitData?: SaveToGitFormInterface): void => {
      try {
        if (gitData) {
          handleSuccess(gitData, payload as T, objectId)
        }
      } catch (e) {
        //ignore error
      }
    },
    onClose: noop
  })
 
  // Modal to show while creating/updating an entity and creating a PR
  const [showCreateUpdateWithPRCreationModal, hideCreateUpdateWithPRCreationModal] = useModalHook(() => {
    return (
      <Dialog
        isOpen={true}
        className={Classes.DIALOG}
        style={{
          minWidth: 600,
          paddingBottom: 0,
          maxHeight: 500
        }}
        enforceFocus={false}
      >
        <ProgressOverlay
          preFirstStage={prMetaData?.isNewBranch ? setupBranchStage : undefined}
          firstStage={entityCreateUpdateStage}
          postFirstStage={pushingChangesToBranch}
          secondStage={createPRStage}
          onClose={() => {
            hideCreateUpdateWithPRCreationModal()
            handleCreateUpdateSuccess(createUpdateStatus)
            props.onProgessOverlayClose?.()
          }}
        />
      </Dialog>
    )
  }, [creatingPR, createUpdateStatus, error, prCreateStatus, prMetaData])
 
  // Modal to show while only creating/updating an entity
  const [showCreateUpdateModal, hideCreateUpdateModal] = useModalHook(() => {
    return (
      <Dialog
        isOpen={true}
        enforceFocus={false}
        className={Classes.DIALOG}
        style={{
          minWidth: 600,
          paddingBottom: 0,
          maxHeight: 500
        }}
      >
        <ProgressOverlay
          firstStage={entityCreateUpdateStage}
          postFirstStage={pushingChangesToBranch}
          onClose={() => {
            hideCreateUpdateModal()
            handleCreateUpdateSuccess(createUpdateStatus)
            props.onProgessOverlayClose?.()
          }}
        />
      </Dialog>
    )
  }, [createUpdateStatus, error])
 
  const createPR = (data: SaveToGitFormInterface): void => {
    createPullRequest({
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      sourceBranch: defaultTo(data?.branch, ''),
      targetBranch: defaultTo(data?.targetBranch, ''),
      title: defaultTo(data?.commitMsg, ''),
      useUserFromToken: true,
      yamlGitConfigRef: defaultTo(data?.repoIdentifier, '')
    })
      .then(_response => {
        setPRCreateStatus(_response?.status)
      })
      .catch(() => setPRCreateStatus('ERROR'))
  }
 
  const abortPR = (errorResponse: UseSaveSuccessResponse, data: SaveToGitFormInterface): void => {
    if (data?.createPr) {
      setPRCreateStatus('ABORTED')
    }
    throw errorResponse
  }
 
  const createPRHandler = async (data: SaveToGitFormInterface, response: UseSaveSuccessResponse): Promise<void> => {
    setNextCallback(() => response?.nextCallback)
    setCreateUpdateStatus(response.status)
 
    // if entity creation/update succeeds, raise a PR, if specified
    Iif (response.status === 'SUCCESS' && data?.createPr) {
      createPR(data)
    } else Iif (data?.createPr) {
      // if entity creation/update fails, abort PR creation
      abortPR(response, data)
    }
  }
 
  const handleSuccess = (data: SaveToGitFormInterface, diffData?: T, objectId?: EntityGitDetails['objectId']): void => {
    setPRMetaData({ branch: data?.branch, targetBranch: data?.targetBranch, isNewBranch: data?.isNewBranch })
    setCreateUpdateStatus('IN_PROGRESS')
    if (data?.createPr) {
      setPRCreateStatus('IN_PROGRESS')
      showCreateUpdateWithPRCreationModal()
    } else {
      showCreateUpdateModal()
    }
    props
      .onSuccess?.(data, diffData, objectId, isEditMode)
      .then(async response => {
        createPRHandler(data, response)
      })
      .catch(e => {
        handleCreateUpdateError(e, data)
      })
  }
 
  const [showModal, hideModal] = useModalHook(() => {
    const closeHandler = (): void => {
      props.onClose?.()
      hideModal()
    }
    return (
      <Dialog className={css.gitDialog} {...modalProps}>
        <GitSyncStoreProvider>
          <SaveToGitForm
            accountId={accountId}
            orgIdentifier={orgIdentifier}
            projectIdentifier={projectIdentifier}
            isEditing={isEditMode}
            resource={resource}
            onSuccess={data => {
              handleSuccess(data, payloadData, resource.gitDetails?.objectId)
              hideModal()
            }}
            onClose={closeHandler}
          />
        </GitSyncStoreProvider>
        <Button minimal icon="cross" iconProps={{ size: 18 }} className={css.crossIcon} onClick={closeHandler} />
      </Dialog>
    )
  }, [isEditMode, resource])
 
  return {
    openSaveToGitDialog: ({ isEditing, resource: resourceData, _modalProps, payload }: OpenSaveToGitDialogValue<T>) => {
      setIsEditMode(isEditing)
      setPayloadData(payload)
      setResource(resourceData)
      setModalProps(defaultTo(_modalProps, modalProps))
      showModal()
    },
    hideSaveToGitDialog: hideModal
  }
}