All files / modules/70-pipeline/components/PipelineInputSetForm CICodebaseInputSetForm.tsx

98.46% Statements 64/65
82.43% Branches 61/74
100% Functions 11/11
98.46% Lines 64/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 228 229 230 231 232 233              66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x                     66x           66x           66x                       50x   50x 50x 50x 50x 50x   50x           50x 50x 50x 50x 50x   50x           50x           50x                   50x         50x 12x 6x 6x                         50x 7x 5x       50x 26x 26x 21x   26x 26x     26x 26x 26x       50x   13x 7x             7x       50x 6x 6x   6x 3x   3x       50x 37x                     6x           50x                               2x               2x                 2x                                     66x  
/*
 * 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, useEffect, useRef } from 'react'
import { useParams } from 'react-router-dom'
import { get, isEmpty, isUndefined } from 'lodash-es'
import { FormInput, MultiTypeInputType, Container, Layout, Text, Radio, Icon } from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import { connect, FormikContext } from 'formik'
import { useStrings } from 'framework/strings'
import { getIdentifierFromValue, getScopeFromValue } from '@common/components/EntityReference/EntityReference'
import { Scope } from '@common/interfaces/SecretsInterface'
import { useVariablesExpression } from '@pipeline/components/PipelineStudio/PiplineHooks/useVariablesExpression'
import { ConnectorInfoDTO, PipelineInfoConfig, useGetConnector } from 'services/cd-ng'
 
export interface CICodebaseInputSetFormProps {
  path: string
  readonly?: boolean
  formik?: FormikContext<any>
  originalPipeline: PipelineInfoConfig
}
 
type CodeBaseType = 'branch' | 'tag' | 'PR'
 
const inputNames = {
  branch: 'branch',
  tag: 'tag',
  PR: 'number'
}
 
const defaultValues = {
  branch: '<+trigger.branch>',
  tag: '<+trigger.tag>',
  PR: '<+trigger.prNumber>'
}
 
const placeholderValues = {
  branch: defaultValues['branch'],
  tag: defaultValues['tag'],
  PR: defaultValues['PR']
}
 
function CICodebaseInputSetFormInternal({
  path,
  readonly,
  formik,
  originalPipeline
}: CICodebaseInputSetFormProps): JSX.Element {
  const { triggerIdentifier, accountId, projectIdentifier, orgIdentifier } = useParams<Record<string, string>>()
 
  const [isInputTouched, setIsInputTouched] = useState(false)
  const [connectorType, setConnectorType] = useState<ConnectorInfoDTO['type']>()
  const [connectorId, setConnectorId] = useState<string>('')
  const [connectorRef, setConnectorRef] = useState<string>('')
  const [codeBaseType, setCodeBaseType] = useState<CodeBaseType>()
 
  const savedValues = useRef<Record<string, string>>({
    branch: '',
    tag: '',
    PR: ''
  })
 
  const { getString } = useStrings()
  const { expressions } = useVariablesExpression()
  const formattedPath = isEmpty(path) ? '' : `${path}.`
  const codeBaseTypePath = `${formattedPath}properties.ci.codebase.build.type`
  const buildSpecPath = `${formattedPath}properties.ci.codebase.build.spec`
 
  const radioLabels = {
    branch: getString('gitBranch'),
    tag: getString('gitTag'),
    PR: getString('pipeline.gitPullRequest')
  }
 
  const inputLabels = {
    branch: getString('common.branchName'),
    tag: getString('common.tagName'),
    PR: getString('pipeline.ciCodebase.pullRequestNumber')
  }
 
  const codeBaseInputFieldFormName = {
    branch: `${formattedPath}properties.ci.codebase.build.spec.branch`,
    tag: `${formattedPath}properties.ci.codebase.build.spec.tag`,
    PR: `${formattedPath}properties.ci.codebase.build.spec.number`
  }
 
  const {
    data: connectorDetails,
    loading: loadingConnectorDetails,
    refetch: getConnectorDetails
  } = useGetConnector({
    identifier: connectorId,
    lazy: true
  })
 
  useEffect(() => {
    if (connectorId) {
      const connectorScope = getScopeFromValue(connectorRef)
      getConnectorDetails({
        pathParams: {
          identifier: connectorId
        },
        queryParams: {
          accountIdentifier: accountId,
          orgIdentifier: connectorScope === Scope.ORG || connectorScope === Scope.PROJECT ? orgIdentifier : undefined,
          projectIdentifier: connectorScope === Scope.PROJECT ? projectIdentifier : undefined
        }
      })
    }
  }, [connectorId])
 
  useEffect(() => {
    if (!loadingConnectorDetails && !isUndefined(connectorDetails)) {
      setConnectorType(get(connectorDetails, 'data.connector.type', '') as ConnectorInfoDTO['type'])
    }
  }, [loadingConnectorDetails, connectorDetails])
 
  useEffect(() => {
    const type = get(formik?.values, codeBaseTypePath) as CodeBaseType
    if (type) {
      setCodeBaseType(type)
    }
    const typeOfConnector = get(formik?.values, 'connectorRef.connector.type', '') as ConnectorInfoDTO['type']
    Iif (typeOfConnector) {
      setConnectorType(typeOfConnector)
    } else {
      const ctrRef = get(originalPipeline, 'properties.ci.codebase.connectorRef') as string
      setConnectorRef(ctrRef)
      setConnectorId(getIdentifierFromValue(ctrRef))
    }
  }, [formik?.values])
 
  useEffect(() => {
    // OnEdit Case, persists saved ciCodebase build spec
    if (codeBaseType) {
      savedValues.current = Object.assign(savedValues.current, {
        [codeBaseType]: get(
          formik?.values,
          `${formattedPath}properties.ci.codebase.build.spec.${inputNames[codeBaseType]}`,
          ''
        )
      })
      formik?.setFieldValue(buildSpecPath, { [inputNames[codeBaseType]]: savedValues.current[codeBaseType] })
    }
  }, [codeBaseType])
 
  const handleTypeChange = (newType: CodeBaseType): void => {
    formik?.setFieldValue(`${formattedPath}properties.ci.codebase.build`, '')
    formik?.setFieldValue(codeBaseTypePath, newType)
 
    if (!isInputTouched && triggerIdentifier) {
      formik?.setFieldValue(buildSpecPath, { [inputNames[newType]]: defaultValues[newType] })
    } else {
      formik?.setFieldValue(buildSpecPath, { [inputNames[newType]]: savedValues.current[newType] })
    }
  }
 
  const renderCodeBaseTypeInput = (type: CodeBaseType): JSX.Element => {
    return (
      <Container>
        <FormInput.MultiTextInput
          label={<Text font={{ variation: FontVariation.FORM_LABEL }}>{inputLabels[type]}</Text>}
          name={codeBaseInputFieldFormName[type]}
          multiTextInputProps={{
            expressions,
            allowableTypes: [MultiTypeInputType.EXPRESSION, MultiTypeInputType.FIXED]
          }}
          placeholder={triggerIdentifier ? placeholderValues[type] : ''}
          disabled={readonly}
          onChange={() => setIsInputTouched(true)}
        />
      </Container>
    )
  }
 
  return (
    <Layout.Vertical spacing="small">
      {loadingConnectorDetails ? (
        <Container flex={{ justifyContent: 'center' }}>
          <Icon name="steps-spinner" size={25} />
        </Container>
      ) : (
        <>
          <Layout.Horizontal
            flex={{ justifyContent: 'start' }}
            padding={{ top: 'small', left: 'xsmall', bottom: 'xsmall' }}
            margin={{ left: 'large' }}
            spacing="huge"
          >
            <Radio
              label={radioLabels['branch']}
              onClick={() => handleTypeChange('branch')}
              checked={codeBaseType === 'branch'}
              disabled={readonly}
              font={{ variation: FontVariation.FORM_LABEL }}
              key="branch-radio-option"
            />
            <Radio
              label={radioLabels['tag']}
              onClick={() => handleTypeChange('tag')}
              checked={codeBaseType === 'tag'}
              disabled={readonly}
              font={{ variation: FontVariation.FORM_LABEL }}
              key="tag-radio-option"
            />
            {connectorType && connectorType !== 'Codecommit' ? (
              <Radio
                label={radioLabels['PR']}
                onClick={() => handleTypeChange('PR')}
                checked={codeBaseType === 'PR'}
                disabled={readonly}
                font={{ variation: FontVariation.FORM_LABEL }}
                key="pr-radio-option"
              />
            ) : null}
          </Layout.Horizontal>
          <Container width={'50%'}>
            {codeBaseType === 'branch' ? renderCodeBaseTypeInput('branch') : null}
            {codeBaseType === 'tag' ? renderCodeBaseTypeInput('tag') : null}
            {codeBaseType === 'PR' ? renderCodeBaseTypeInput('PR') : null}
          </Container>
        </>
      )}
    </Layout.Vertical>
  )
}
 
export const CICodebaseInputSetForm = connect(CICodebaseInputSetFormInternal)