All files / modules/10-common/components/GitContextForm GitContextForm.tsx

78.79% Statements 52/66
61.98% Branches 150/242
64.29% Functions 9/14
80.65% Lines 50/62

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              261x 261x   261x 261x 261x 261x 261x 261x   261x                                     261x                   261x 107x 107x 107x 107x 107x 107x 107x         107x 107x   107x 24x 42x 24x 3x         107x 20x 4x 7x         4x 4x 4x                 107x         107x 17x                               107x 13x 10x 10x 1x     10x   10x 48x 28x           10x 28x 10x               10x           107x                                                                                                                         261x  
/*
 * 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 { Container, FormInput, Icon, Layout, SelectOption, Text } from '@wings-software/uicore'
import { isEmpty } from 'lodash-es'
import type { FormikContext } from 'formik'
import React from 'react'
import cx from 'classnames'
import { useParams } from 'react-router-dom'
import { GitSyncConfig, EntityGitDetails, useGetListOfBranchesWithStatus, GitBranchDTO } from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import { useGitSyncStore } from 'framework/GitRepoStore/GitSyncStoreContext'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import css from './GitContextForm.module.scss'
 
export interface IGitContextFormProps extends EntityGitDetails {
  getDefaultFromOtherRepo: boolean
}
 
export interface GitContextFormProps<T> {
  formikProps: FormikContext<T>
  gitDetails?: IGitContextFormProps
  className?: string
  onRepoChange?: (gitDetails: EntityGitDetails) => void
  onBranchChange?: (gitDetails: EntityGitDetails) => void
}
 
export interface GitContextProps {
  repo: string
  branch: string
}
 
export const branchSyncStatus: Record<string, GitBranchDTO['branchSyncStatus']> = {
  SYNCED: 'SYNCED',
  SYNCING: 'SYNCING',
  UNSYNCED: 'UNSYNCED'
}
 
/**
 * GitContextForm can be used inside any form as a subForm to set Git context
 * @param gitContextFormProps: GitContextFormProps
 */
const GitContextForm: React.FC<GitContextFormProps<Record<string, any> & GitContextProps>> = gitContextFormProps => {
  const { getString } = useStrings()
  const { gitDetails, formikProps, onRepoChange, onBranchChange } = gitContextFormProps
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
  const { gitSyncRepos, loadingRepos } = useGitSyncStore()
  const [repoSelectOptions, setRepoSelectOptions] = React.useState<SelectOption[]>([])
  const isEditing = !!gitDetails?.objectId
  const defaultBranchSelect: SelectOption = {
    label: gitDetails?.branch ?? (gitSyncRepos[0]?.branch || ''),
    value: gitDetails?.branch ?? (gitSyncRepos[0]?.branch || '')
  }
 
  const [branchSelectOptions, setBranchSelectOptions] = React.useState<SelectOption[]>([defaultBranchSelect])
  const [searchTerm, setSearchTerm] = React.useState<string>('')
 
  React.useEffect(() => {
    const defaultRepoSelect = gitDetails?.repoIdentifier ?? gitSyncRepos[0]?.identifier
    const isSelectedBranchExist = !!branchSelectOptions.filter(item => item.value === defaultBranchSelect.value)[0]
    if (!isSelectedBranchExist && defaultRepoSelect === formikProps?.values?.repo) {
      branchSelectOptions.push(defaultBranchSelect)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [branchSelectOptions, defaultBranchSelect.value])
 
  React.useEffect(() => {
    if (gitSyncRepos?.length && !loadingRepos) {
      const reposAvailable = gitSyncRepos?.map((gitRepo: GitSyncConfig) => {
        return {
          label: gitRepo.name || '',
          value: gitRepo.identifier || ''
        }
      })
      formikProps.setFieldValue('repo', gitDetails?.repoIdentifier ?? gitSyncRepos[0]?.identifier)
      formikProps.setFieldValue('branch', gitDetails?.branch ?? gitSyncRepos[0]?.branch)
      setRepoSelectOptions(reposAvailable)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loadingRepos, gitDetails?.repoIdentifier, gitDetails?.branch])
 
  const {
    data: branchList,
    loading: loadingBranchList,
    refetch: getListOfBranchesWithStatus
  } = useGetListOfBranchesWithStatus({
    lazy: true,
    debounce: 500
  })
 
  React.useEffect(() => {
    !isEditing &&
      !gitDetails?.getDefaultFromOtherRepo &&
      getListOfBranchesWithStatus({
        queryParams: {
          accountIdentifier: accountId,
          orgIdentifier,
          projectIdentifier,
          yamlGitConfigIdentifier: formikProps.values.repo,
          page: 0,
          size: 100,
          searchTerm
        }
      })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchTerm, formikProps.values.repo])
 
  React.useEffect(() => {
    if (!loadingBranchList && branchList?.data?.branches?.content?.length) {
      const defaultBranch = branchList.data.defaultBranch?.branchName as string
      if (isEmpty(gitDetails?.branch) && !formikProps.values.branch) {
        formikProps.setFieldValue('branch', defaultBranch)
      }
 
      const syncedBranchOption: SelectOption[] = []
 
      branchList.data.branches.content.forEach((branch: GitBranchDTO) => {
        if (branch.branchSyncStatus === branchSyncStatus.SYNCED) {
          syncedBranchOption.push({
            label: branch.branchName || '',
            value: branch.branchName || ''
          })
        }
      })
      Eif (!isEmpty(defaultBranch)) {
        const isSelectedBranchExist = !!syncedBranchOption.filter(item => item.value === defaultBranch)[0]
        Iif (!isSelectedBranchExist) {
          syncedBranchOption.push({
            label: defaultBranch,
            value: defaultBranch
          })
        }
      }
 
      setBranchSelectOptions(syncedBranchOption)
    }
 
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loadingBranchList])
 
  return (
    <Container
      border={{ top: true }}
      padding={{ top: 'medium', bottom: 'medium' }}
      className={cx(gitContextFormProps.className)}
      data-testid="GitContextForm"
    >
      <Text margin={{ top: 'small', bottom: 'small' }}>
        {getString('common.gitSync.gitRepositoryDetails').toUpperCase()}
      </Text>
      <FormInput.Select
        name="repo"
        label={getString('common.git.selectRepoLabel')}
        items={repoSelectOptions}
        disabled={loadingRepos || isEditing}
        onChange={(selected: SelectOption) => {
          const selectedRepo = gitSyncRepos.find((repo: GitSyncConfig) => repo.identifier === selected.value)
          // Selecting current context branch if user select current context repo
          if (selectedRepo?.identifier === gitDetails?.repoIdentifier) {
            formikProps.setFieldValue('branch', gitDetails?.branch)
            setBranchSelectOptions([
              {
                label: gitDetails?.branch || '',
                value: gitDetails?.branch || ''
              }
            ])
            onRepoChange?.({ repoIdentifier: selectedRepo?.identifier, branch: gitDetails?.branch })
          } else {
            // Selecting default branch if user select any other repo
            formikProps.setFieldValue('branch', selectedRepo?.branch)
            gitDetails?.getDefaultFromOtherRepo &&
              setBranchSelectOptions([
                {
                  label: selectedRepo?.branch || '',
                  value: selectedRepo?.branch || ''
                }
              ])
            onRepoChange?.({ repoIdentifier: selectedRepo?.identifier, branch: selectedRepo?.branch })
          }
        }}
      />
      <Layout.Horizontal spacing="small" flex={{ alignItems: 'center' }}>
        <FormInput.Select
          name="branch"
          label={getString('common.gitSync.selectBranchLabel')}
          key={formikProps.values.repo}
          items={branchSelectOptions}
          onQueryChange={(query: string) => setSearchTerm(query)}
          disabled={loadingBranchList || isEditing || gitDetails?.getDefaultFromOtherRepo}
          onChange={(selected: SelectOption) => {
            const selectedBranch = branchSelectOptions.find(branchOption => branchOption.value === selected.value)
            onBranchChange?.({ branch: (selectedBranch || '') as string })
          }}
          className={css.selectBranchInput}
        />
        <Container width={16}>{loadingBranchList && <Icon margin={{ top: 'xsmall' }} name="spinner" />}</Container>
      </Layout.Horizontal>
    </Container>
  )
}
 
export default GitContextForm