All files / modules/40-gitsync/components/FullSyncForm FullSyncFormHelper.tsx

77.46% Statements 55/71
60.56% Branches 109/180
92.31% Functions 12/13
75.38% Lines 49/65

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                  7x   7x                                                                                             7x 8x   16x               7x                     7x           8x       8x 8x 8x   8x 8x   8x 8x 8x 8x 8x 8x               8x     8x 8x   16x               7x             4x 4x 4x               7x                 8x 8x   8x       8x     8x           8x 16x       8x     8x         8x 8x     8x 8x               7x               1x 1x   1x 1x       1x     1x                       1x      
/*
 * Copyright 2022 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 type { ModalErrorHandlerBinding, SelectOption } from '@harness/uicore'
import type { FormikProps } from 'formik'
import { isEmpty } from 'lodash-es'
import type { UseStringsReturn } from 'framework/strings/String'
import {
  createGitFullSyncConfigPromise,
  Failure,
  getListOfBranchesByConnectorPromise,
  GetListOfBranchesByConnectorQueryParams,
  GitFullSyncConfigDTO,
  GitFullSyncConfigRequestDTO,
  GitSyncConfig,
  GitSyncFolderConfigDTO,
  ResponseListString,
  ResponseGitFullSyncConfigDTO,
  triggerFullSyncPromise,
  updateGitFullSyncConfigPromise,
  UpdateGitFullSyncConfigQueryParams
} from 'services/cd-ng'
 
export interface FullSyncFormProps {
  isNewUser: boolean
  classname?: string
}
 
export interface ModalConfigureProps {
  onClose?: () => void
  onSuccess?: () => void
}
 
export interface FullSyncCallbacks extends ModalConfigureProps {
  showError: (error?: string) => void
  setDefaultFormData: React.Dispatch<React.SetStateAction<GitFullSyncConfigRequestDTO>>
  setRootFolderSelectOptions: React.Dispatch<React.SetStateAction<SelectOption[]>>
  setRepoSelectOptions: React.Dispatch<React.SetStateAction<SelectOption[]>>
  fetchBranches: (repoIdentifier: string) => void
}
 
export interface FetchBranchCallbacks {
  setDisableCreatePR: React.Dispatch<React.SetStateAction<boolean>>
  setDisableBranchSelection: React.Dispatch<React.SetStateAction<boolean>>
  setBranches: React.Dispatch<React.SetStateAction<SelectOption[] | undefined>>
  getString: UseStringsReturn['getString']
}
 
export interface SubmitCallbacks {
  showSuccess: (msg: string) => void
  onSuccess?: () => void
  getString: UseStringsReturn['getString']
}
 
export const getRootFolderSelectOptions = (folders: GitSyncFolderConfigDTO[] | undefined): SelectOption[] => {
  return folders?.length
    ? folders.map((folder: GitSyncFolderConfigDTO) => {
        return {
          label: folder.rootFolder || '',
          value: folder.rootFolder || ''
        }
      })
    : []
}
 
export const defaultInitialFormData: GitFullSyncConfigRequestDTO = {
  baseBranch: '',
  branch: '',
  createPullRequest: false,
  newBranch: false,
  prTitle: '',
  repoIdentifier: '',
  rootFolder: '',
  targetBranch: ''
}
 
export const initiliazeConfigForm = (
  config: GitFullSyncConfigDTO | undefined,
  gitSyncRepos: GitSyncConfig[],
  formikRef: React.MutableRefObject<FormikProps<GitFullSyncConfigRequestDTO> | undefined>,
  handlers: FullSyncCallbacks
): void => {
  const { setDefaultFormData, setRootFolderSelectOptions, setRepoSelectOptions, fetchBranches } = handlers
  // Setting up default form fields
  // formikRef used for repo change, config used for default while edit, gitSyncRepos[0] is default for new config
  const repoIdentifier =
    formikRef?.current?.values?.repoIdentifier || config?.repoIdentifier || gitSyncRepos[0].identifier || ''
  const selectedRepo = gitSyncRepos.find((repo: GitSyncConfig) => repo.identifier === repoIdentifier)
  const baseBranch = selectedRepo?.branch
 
  const defaultRootFolder = selectedRepo?.gitSyncFolderConfigDTOs?.find(
    (folder: GitSyncFolderConfigDTO) => folder.isDefault
  )
  const rootFolder = config?.rootFolder || defaultRootFolder?.rootFolder || ''
  const branch = config?.branch || ''
  formikRef?.current?.setFieldValue('repoIdentifier', repoIdentifier)
  formikRef?.current?.setFieldValue('branch', branch)
  formikRef?.current?.setFieldValue('rootFolder', rootFolder)
  setDefaultFormData({
    ...defaultInitialFormData,
    repoIdentifier,
    baseBranch,
    branch,
    rootFolder
  })
 
  fetchBranches(repoIdentifier)
 
  // Setting up default repo and rootFolder dropdown options
  setRootFolderSelectOptions(getRootFolderSelectOptions(selectedRepo?.gitSyncFolderConfigDTOs))
  setRepoSelectOptions(
    gitSyncRepos?.map((gitRepo: GitSyncConfig) => {
      return {
        label: gitRepo.name || '',
        value: gitRepo.identifier || ''
      }
    })
  )
}
 
export const handleConfigResponse = (
  configResponse: ResponseGitFullSyncConfigDTO | null,
  configError: Failure,
  gitSyncRepos: GitSyncConfig[],
  formikRef: React.MutableRefObject<FormikProps<GitFullSyncConfigRequestDTO> | undefined>,
  handlers: FullSyncCallbacks
): void => {
  const { showError, onClose } = handlers
  Eif ('SUCCESS' === configResponse?.status || 'RESOURCE_NOT_FOUND' === configError?.code) {
    initiliazeConfigForm(configResponse?.data, gitSyncRepos, formikRef, handlers)
  } else {
    //Closing edit config modal with error toaster if fetch config API has failed
    showError(configError?.message)
    onClose?.()
  }
}
 
export const branchFetchHandler = (
  queryParams: GetListOfBranchesByConnectorQueryParams,
  isNewBranch: boolean,
  currentConfigBranch: string | undefined,
  createPR: boolean,
  handlers: FetchBranchCallbacks,
  modalErrorHandler: ModalErrorHandlerBinding | undefined,
  query?: string
): void => {
  const { setDisableCreatePR, setDisableBranchSelection, setBranches, getString } = handlers
  modalErrorHandler?.hide()
 
  getListOfBranchesByConnectorPromise({
    queryParams
  })
    .then((response: ResponseListString) => {
      const branchesInResponse = response?.data
      /* Show error in case no branches exist on a git repo at all */
      /* A valid git repo should have atleast one branch in it(a.k.a default branch) */
      Iif (!query && isEmpty(branchesInResponse)) {
        setDisableCreatePR(true)
        setDisableBranchSelection(true)
        modalErrorHandler?.showDanger(getString('common.git.noBranchesFound'))
        return
      }
      const branchOptions = branchesInResponse?.map((branch: string) => {
        return { label: branch, value: branch }
      }) as SelectOption[]
 
      // Handling for currentConfigBranch may not be in response
      Iif (
        branchOptions.length &&
        currentConfigBranch &&
        -1 === branchOptions.findIndex(option => option.value === currentConfigBranch)
      ) {
        branchOptions.unshift({ label: currentConfigBranch, value: currentConfigBranch })
      }
 
      setDisableCreatePR(false)
      Iif (!isNewBranch && isEmpty(branchOptions)) {
        setDisableBranchSelection(true)
      } else {
        setBranches(branchOptions)
        setDisableBranchSelection(!createPR)
      }
    })
    .catch(e => {
      modalErrorHandler?.showDanger(e.data?.message || e.message)
    })
}
 
export const saveAndTriggerFullSync = async (
  queryParams: UpdateGitFullSyncConfigQueryParams,
  fullSyncData: GitFullSyncConfigRequestDTO,
  isNewBranch: boolean,
  config: ResponseGitFullSyncConfigDTO | null,
  handlers: SubmitCallbacks,
  modalErrorHandler?: ModalErrorHandlerBinding
): Promise<void> => {
  const { showSuccess, onSuccess, getString } = handlers
  modalErrorHandler?.hide()
 
  try {
    const reqObj = {
      queryParams,
      body: { ...fullSyncData, newBranch: isNewBranch }
    }
    const fullSyncConfigData = config?.data
      ? await updateGitFullSyncConfigPromise(reqObj)
      : await createGitFullSyncConfigPromise(reqObj)
    if (fullSyncConfigData.status !== 'SUCCESS') {
      throw fullSyncConfigData
    } else {
      showSuccess(getString('gitsync.configSaveToaster'))
    }
    const triggerFullSync = await triggerFullSyncPromise({ queryParams, body: {} as unknown as void })
    if (triggerFullSync.status !== 'SUCCESS') {
      throw triggerFullSync
    }
    showSuccess(getString('gitsync.syncSucessToaster'))
    onSuccess?.()
  } catch (err) {
    modalErrorHandler?.showDanger(err.message)
  }
}