All files / modules/35-connectors/components/CreateConnector/commonSteps GitDetailsStep.tsx

79.55% Statements 70/88
66.87% Branches 111/166
100% Functions 11/11
79.31% Lines 69/87

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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363              222x 222x 222x                         222x 222x 222x     222x             222x 222x 222x   222x 222x 222x                                     222x 40x   40x 6x 34x 14x 20x 10x 10x 10x         222x 40x 40x 40x 40x 40x 40x 40x   40x                     40x                     40x 120x   16x       42x       31x       31x               40x 120x     58x       31x       31x               40x 8x 8x   8x 8x                                                                         40x 40x 24x                     16x               40x                       8x         34x 31x 31x     31x 10x   21x 21x 19x   2x                                 120x       120x                                                               3x                                                                                           4x                                           222x  
/*
 * 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, { useRef, useState } from 'react'
import cx from 'classnames'
import {
  Layout,
  Button,
  Formik,
  StepProps,
  ModalErrorHandlerBinding,
  ModalErrorHandler,
  FormikForm,
  Container,
  FormInput,
  Text,
  ButtonVariation
} from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import { FontVariation } from '@harness/design-system'
import * as Yup from 'yup'
import type { IOptionProps } from '@blueprintjs/core'
import type { FormikProps } from 'formik'
import {
  ConnectorConfigDTO,
  ConnectorInfoDTO,
  ResponseBoolean,
  validateTheIdentifierIsUniquePromise,
  Failure
} from 'services/cd-ng'
import { GitAuthTypes } from '@connectors/pages/connectors/utils/ConnectorHelper'
import { String, useStrings } from 'framework/strings'
import { GitUrlType, GitConnectionType, saveCurrentStepData } from '@connectors/pages/connectors/utils/ConnectorUtils'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { Connectors } from '@connectors/constants'
import css from './ConnectorDetailsStep.module.scss'
import commonCss from './ConnectorCommonStyles.module.scss'
 
interface ConnectorDetailsStepProps extends StepProps<ConnectorInfoDTO> {
  type: ConnectorInfoDTO['type']
  name: string
  setFormData?: (formData: ConnectorConfigDTO) => void
  formData?: ConnectorConfigDTO
  isEditMode?: boolean
  connectorInfo: ConnectorInfoDTO | void
  mock?: ResponseBoolean
}
 
interface DetailsStepInterface {
  urlType: string
  connectionType: string
  url: string
  validationRepo?: string
}
 
const getTooltipAnchorForHeading = (connectorType: ConnectorInfoDTO['type']): string => {
  Iif (connectorType === 'Aws') {
    return 'awsCCDetailsTooltip'
  } else if (connectorType === 'Git') {
    return 'gitConnectorDetailsTooltip'
  } else if (connectorType === 'Github') {
    return 'githubConnectorDetailsTooltip'
  } else if (connectorType === 'Bitbucket') {
    return 'bitbucketConnectorDetailsTooltip'
  } else Eif (connectorType === 'Gitlab') {
    return 'gitlabConnectorDetailsTooltip'
  }
  return 'connectorDetailsTooltip'
}
 
const GitDetailsStep: React.FC<StepProps<ConnectorConfigDTO> & ConnectorDetailsStepProps> = props => {
  const { prevStepData, nextStep } = props
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
  const mounted = useRef(false)
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const [loading, setLoading] = useState(false)
  const isEdit = props.isEditMode || prevStepData?.isEdit
  const { getString } = useStrings()
 
  const urlTypeOptions: IOptionProps[] = [
    {
      label: getString('account'),
      value: GitUrlType.ACCOUNT
    },
    {
      label: getString('repository'),
      value: GitUrlType.REPO
    }
  ]
 
  const connectionTypeOptions: IOptionProps[] = [
    {
      label: getString('HTTP'),
      value: GitConnectionType.HTTP
    },
    {
      label: getString('SSH'),
      value: GitConnectionType.SSH
    }
  ]
 
  const getUrlLabel = (connectorType: ConnectorInfoDTO['type'], urlType: string): string => {
    switch (connectorType) {
      case Connectors.GIT:
        return urlType === GitUrlType.ACCOUNT
          ? getString('common.git.gitAccountUrl')
          : getString('common.git.gitRepoUrl')
      case Connectors.GITHUB:
        return urlType === GitUrlType.ACCOUNT
          ? getString('common.git.gitHubAccountUrl')
          : getString('common.git.gitHubRepoUrl')
      case Connectors.GITLAB:
        return urlType === GitUrlType.ACCOUNT
          ? getString('common.git.gitLabAccountUrl')
          : getString('common.git.gitLabRepoUrl')
      case Connectors.BITBUCKET:
        return urlType === GitUrlType.ACCOUNT
          ? getString('common.git.bitbucketAccountUrl')
          : getString('common.git.bitbucketRepoUrl')
      default:
        return ''
    }
  }
 
  const getUrlLabelPlaceholder = (connectorType: ConnectorInfoDTO['type'], connectionType: string): string => {
    switch (connectorType) {
      case Connectors.GIT:
      case Connectors.GITHUB:
        return connectionType === GitConnectionType.HTTP
          ? getString('common.git.gitHubUrlPlaceholder')
          : getString('common.git.gitHubUrlPlaceholderSSH')
      case Connectors.GITLAB:
        return connectionType === GitConnectionType.HTTP
          ? getString('common.git.gitLabUrlPlaceholder')
          : getString('common.git.gitLabUrlPlaceholderSSH')
      case Connectors.BITBUCKET:
        return connectionType === GitConnectionType.HTTP
          ? getString('common.git.bitbucketUrlPlaceholder')
          : getString('common.git.bitbucketPlaceholderSSH')
      default:
        return ''
    }
  }
 
  const handleSubmit = async (formData: ConnectorConfigDTO): Promise<void> => {
    mounted.current = true
    Eif (isEdit) {
      //In edit mode validateTheIdentifierIsUnique API not required
      props.setFormData?.(formData)
      nextStep?.({ ...props.connectorInfo, ...prevStepData, ...formData })
    } else {
      setLoading(true)
      try {
        const response = await validateTheIdentifierIsUniquePromise({
          queryParams: {
            identifier: formData.identifier,
            accountIdentifier: accountId,
            orgIdentifier: orgIdentifier,
            projectIdentifier: projectIdentifier
          },
          mock: props.mock
        })
        setLoading(false)
 
        if ('SUCCESS' === response.status) {
          if (response.data) {
            props.setFormData?.(formData)
            nextStep?.({ ...props.connectorInfo, ...prevStepData, ...formData })
          } else {
            modalErrorHandler?.showDanger(
              getString('validation.duplicateIdError', {
                connectorName: formData.name,
                connectorIdentifier: formData.identifier
              })
            )
          }
        } else {
          throw response as Failure
        }
      } catch (error) {
        setLoading(false)
        modalErrorHandler?.showDanger(error.message)
      }
    }
  }
 
  const getInitialValues = (): DetailsStepInterface => {
    if (isEdit && props.connectorInfo) {
      return {
        urlType:
          props.type === Connectors.GIT ? props.connectorInfo?.spec?.connectionType : props.connectorInfo?.spec?.type,
        url: props.connectorInfo?.spec?.url,
        validationRepo: props.connectorInfo?.spec?.validationRepo,
        connectionType:
          props.type === Connectors.GIT
            ? props.connectorInfo?.spec?.type
            : props.connectorInfo?.spec?.authentication?.type
      }
    } else {
      return {
        urlType: GitUrlType.ACCOUNT,
        connectionType: GitConnectionType.HTTP,
        url: ''
      }
    }
  }
 
  return (
    <Layout.Vertical className={cx(css.gitDetails, css.firstep, commonCss.stepContainer)}>
      <ModalErrorHandler bind={setModalErrorHandler} />
      <Text
        font={{ variation: FontVariation.H3 }}
        tooltipProps={{ dataTooltipId: getTooltipAnchorForHeading(props.type) }}
      >
        {getString('details')}
      </Text>
 
      <Formik
        onSubmit={formData => {
          handleSubmit(formData)
        }}
        formName="gitDetailsStepForm"
        validationSchema={Yup.object().shape({
          url: Yup.string().test('isValidUrl', getString('validation.urlIsNotValid'), function (_url) {
            if (!_url) return false
            const trimmedUrl = _url?.trim() || ''
            Iif (trimmedUrl.includes(' ')) {
              return false
            }
            if (this.parent.connectionType === GitConnectionType.SSH) {
              return trimmedUrl.startsWith('git@') || trimmedUrl.startsWith('ssh://') ? true : false
            }
            try {
              const url = new URL(_url)
              return url.protocol === 'http:' || url.protocol === 'https:'
            } catch (_) {
              return false
            }
          }),
          validationRepo: Yup.string()
            .nullable()
            .when('urlType', {
              is: 'Account',
              then: Yup.string().required(getString('common.validation.testRepoIsRequired'))
            })
        })}
        initialValues={{
          ...getInitialValues(),
          ...prevStepData,
          ...props.formData
        }}
      >
        {(formikProps: FormikProps<DetailsStepInterface>) => {
          saveCurrentStepData<ConnectorInfoDTO>(
            props.getCurrentStepData,
            formikProps.values as unknown as ConnectorInfoDTO
          )
          return (
            <FormikForm className={cx(css.connectorForm, commonCss.fullHeight, commonCss.fullHeightDivsWithFlex)}>
              <Layout.Vertical className={commonCss.paddingTop8}>
                <Container className={commonCss.bottomPadding1}>
                  <Layout.Vertical spacing="xsmall">
                    <Text
                      tooltipProps={{ dataTooltipId: `${props.type.toLocaleLowerCase()}URLType` }}
                      font={{ variation: FontVariation.FORM_LABEL }}
                    >
                      {getString('common.git.urlType')}
                    </Text>
                    <FormInput.RadioGroup
                      style={{ fontSize: 'normal' }}
                      radioGroup={{ inline: true }}
                      name="urlType"
                      items={urlTypeOptions}
                    />
                  </Layout.Vertical>
                  <Layout.Vertical spacing="xsmall">
                    <Text
                      tooltipProps={{ dataTooltipId: `${props.type.toLocaleLowerCase()}ConnectionType` }}
                      font={{ variation: FontVariation.FORM_LABEL }}
                    >
                      {getString('common.git.connectionType')}
                    </Text>
                    <FormInput.RadioGroup
                      style={{ fontSize: 'normal' }}
                      name="connectionType"
                      radioGroup={{ inline: true }}
                      items={connectionTypeOptions}
                      onChange={val => {
                        // initialize authType for only 1 option
                        Iif (val.currentTarget.value === GitConnectionType.HTTP && props.type === Connectors.BITBUCKET) {
                          formikProps.setFieldValue('authType', GitAuthTypes.USER_PASSWORD)
                        }
                      }}
                    />
                  </Layout.Vertical>
                </Container>
                <FormInput.Text
                  name="url"
                  className={css.formElm}
                  label={
                    <Text font={{ variation: FontVariation.FORM_LABEL }}>
                      {getUrlLabel(props.type, formikProps.values.urlType)}
                    </Text>
                  }
                  placeholder={getUrlLabelPlaceholder(props.type, formikProps.values.connectionType)}
                  tooltipProps={{ dataTooltipId: `${props.type.toLocaleLowerCase()}DetailsStepForm_url` }}
                />
                {formikProps.values.urlType === 'Account' && (
                  <Container>
                    <Text
                      font={{ variation: FontVariation.BODY }}
                      className={cx(commonCss.bottomMargin5, commonCss.topMargin1)}
                    >
                      {getString('common.git.testRepositoryDescription')}
                    </Text>
                    <FormInput.Text
                      name="validationRepo"
                      className={css.formElm}
                      label={
                        <Text font={{ variation: FontVariation.FORM_LABEL }}>
                          {getString('common.git.testRepository')}
                        </Text>
                      }
                      placeholder={getString('common.git.selectRepoLabel')}
                      tooltipProps={{
                        dataTooltipId: `${props.type.toLocaleLowerCase()}DetailsStepForm_validationRepo`
                      }}
                    />
                  </Container>
                )}
              </Layout.Vertical>
              <Layout.Horizontal spacing="medium">
                <Button
                  text={getString('back')}
                  icon="chevron-left"
                  onClick={() => props?.previousStep?.(props?.prevStepData)}
                  data-name="commonGitBackButton"
                  variation={ButtonVariation.SECONDARY}
                />
                <Button
                  type="submit"
                  intent="primary"
                  rightIcon="chevron-right"
                  disabled={loading}
                  variation={ButtonVariation.PRIMARY}
                >
                  <String stringID="continue" />
                </Button>
              </Layout.Horizontal>
            </FormikForm>
          )
        }}
      </Formik>
    </Layout.Vertical>
  )
}
 
export default GitDetailsStep