All files / modules/75-ci/components/PipelineStudio/BuildStage/EditStageView EditStageView.tsx

84.52% Statements 71/84
60% Branches 174/290
72.73% Functions 8/11
86.25% Lines 69/80

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 364 365 366 367 368 369 370 371 372              2x 2x                     2x 2x 2x 2x   2x 2x   2x 2x 2x 2x       2x 2x         2x 2x 2x   2x 2x     2x 2x 2x 2x 2x                                             2x 4x 4x 4x 4x 4x           4x   4x         4x   4x                         4x   4x 4x           4x                           4x 4x 4x                 4x 4x         4x 2x 2x                                   4x 2x 2x     2x 1x   2x     4x 1x   1x 1x                             1x     1x 1x 1x 1x 1x 1x 1x       4x 4x 4x           4x                       10x                                                                                                                                                                                                                                                                                        
/*
 * 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 React from 'react'
import {
  Text,
  Container,
  Formik,
  FormikForm,
  FormInput,
  Button,
  Switch,
  TextInput,
  RUNTIME_INPUT_VALUE
} from '@wings-software/uicore'
import * as Yup from 'yup'
import { Color } from '@harness/design-system'
import { defaultTo, isEmpty, set } from 'lodash-es'
import { useParams } from 'react-router-dom'
import type { FormikErrors } from 'formik'
import { produce } from 'immer'
import { parse } from 'yaml'
import type { PipelineInfoConfig } from 'services/cd-ng'
import { ConnectorInfoDTO, useGetConnector } from 'services/cd-ng'
import { usePipelineContext } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import { useStrings } from 'framework/strings'
import {
  ConnectorReferenceField,
  ConnectorReferenceFieldProps
} from '@connectors/components/ConnectorReferenceField/ConnectorReferenceField'
import { NameId, NameIdDescriptionTags } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import {
  getIdentifierFromValue,
  getScopeFromDTO,
  getScopeFromValue
} from '@common/components/EntityReference/EntityReference'
import { IdentifierSchemaWithoutHook, NameSchemaWithoutHook } from '@common/utils/Validation'
import { Scope } from '@common/interfaces/SecretsInterface'
import { isDuplicateStageId } from '@pipeline/components/PipelineStudio/StageBuilder/StageBuilderUtil'
import type { GitQueryParams } from '@common/interfaces/RouteInterfaces'
import { useQueryParams } from '@common/hooks'
import { useGitScope } from '@pipeline/utils/CIUtils'
import type { BuildStageElementConfig, StageElementWrapper } from '@pipeline/utils/pipelineTypes'
import type { TemplateSummaryResponse } from 'services/template-ng'
import { createTemplate, getTemplateNameWithLabel } from '@pipeline/utils/templateUtils'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { Category, StageActions } from '@common/constants/TrackingConstants'
import { isContextTypeNotStageTemplate } from '@pipeline/components/PipelineStudio/PipelineUtils'
import css from './EditStageView.module.scss'
 
export interface EditStageView {
  data?: StageElementWrapper<BuildStageElementConfig>
  template?: TemplateSummaryResponse
  onSubmit?: (
    values: StageElementWrapper<BuildStageElementConfig>,
    identifier: string,
    pipeline?: PipelineInfoConfig
  ) => void
  onChange?: (values: Values) => void
}
 
interface Values {
  identifier: string
  name: string
  description?: string
  tags?: { [key: string]: string }
  cloneCodebase?: boolean
  connectorRef?: ConnectorReferenceFieldProps['selected']
  repoName?: string
}
 
export const EditStageView: React.FC<EditStageView> = ({ data, template, onSubmit, onChange }): JSX.Element => {
  const { getString } = useStrings()
  const [connectionType, setConnectionType] = React.useState('')
  const [connectorUrl, setConnectorUrl] = React.useState('')
  const gitScope = useGitScope()
  const repositoryNameLabel = getString('common.repositoryName')
 
  const {
    state: { pipeline },
    contextType,
    isReadonly
  } = usePipelineContext()
 
  const { accountId, projectIdentifier, orgIdentifier } = useParams<{
    projectIdentifier: string
    orgIdentifier: string
    accountId: string
  }>()
  const { repoIdentifier, branch } = useQueryParams<GitQueryParams>()
 
  const initialValues: Values = {
    identifier: data?.stage?.identifier || '',
    name: data?.stage?.name || '',
    description: data?.stage?.description,
    tags: data?.stage?.tags,
    cloneCodebase: defaultTo(
      template
        ? parse(defaultTo(template.yaml, '')).template.spec.spec.cloneCodebase
        : data?.stage?.spec?.cloneCodebase,
      true
    )
  }
 
  const codebase = (pipeline as PipelineInfoConfig)?.properties?.ci?.codebase
 
  const connectorId = getIdentifierFromValue((codebase?.connectorRef as string) || '')
  const initialScope = getScopeFromValue((codebase?.connectorRef as string) || '')
 
  const {
    data: connector,
    loading,
    refetch
  } = useGetConnector({
    identifier: connectorId,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier: initialScope === Scope.ORG || initialScope === Scope.PROJECT ? orgIdentifier : undefined,
      projectIdentifier: initialScope === Scope.PROJECT ? projectIdentifier : undefined,
      ...(gitScope?.repo && gitScope.branch
        ? { repoIdentifier: gitScope.repo, branch: gitScope.branch, getDefaultFromOtherRepo: true }
        : {})
    },
    lazy: true,
    debounce: 300
  })
 
  Eif (connector?.data?.connector) {
    const scope = getScopeFromDTO<ConnectorInfoDTO>(connector?.data?.connector)
    initialValues.connectorRef = {
      label: connector?.data?.connector.name || '',
      value: `${scope !== Scope.PROJECT ? `${scope}.` : ''}${connector?.data?.connector.identifier}`,
      scope: scope,
      live: connector?.data?.status?.status === 'SUCCESS',
      connector: connector?.data?.connector
    }
  }
 
  React.useEffect(() => {
    Iif (!isEmpty(codebase?.connectorRef)) {
      refetch()
    }
  }, [codebase?.connectorRef])
 
  const validationSchema = () =>
    Yup.lazy((values: Values): any =>
      Yup.object().shape({
        ...(isContextTypeNotStageTemplate(contextType) && {
          name: NameSchemaWithoutHook(getString, {
            requiredErrorMsg: getString('fieldRequired', { field: getString('stageNameLabel') })
          }),
          identifier: IdentifierSchemaWithoutHook(getString)
        }),
        ...(!codebase &&
          isContextTypeNotStageTemplate(contextType) &&
          values.cloneCodebase && {
            connectorRef: Yup.mixed().required(getString('fieldRequired', { field: getString('connector') })),
            ...(connectionType === 'Account' && {
              repoName: Yup.string().required(getString('fieldRequired', { field: repositoryNameLabel }))
            })
          })
      })
    )
 
  const handleValidate = (values: Values): FormikErrors<Values> => {
    const errors: { name?: string } = {}
    Iif (isDuplicateStageId(values.identifier, pipeline?.stages || [])) {
      errors.name = getString('validation.identifierDuplicate')
    }
    if (data) {
      onChange?.(values)
    }
    return errors
  }
 
  const handleSubmit = (values: Values): void => {
    Eif (data?.stage) {
      // TODO: Add Codebase verification
      let pipelineData: PipelineInfoConfig | undefined = undefined
      Iif (values.cloneCodebase && values.connectorRef) {
        pipelineData = produce(pipeline, draft => {
          set(draft, 'properties.ci.codebase', {
            connectorRef: typeof values.connectorRef === 'string' ? values.connectorRef : values.connectorRef?.value,
            ...(values.repoName && { repoName: values.repoName }),
            build: RUNTIME_INPUT_VALUE
          })
 
          // Repo level connectors should not have repoName
          if (connectionType === 'Repo' && (draft as PipelineInfoConfig)?.properties?.ci?.codebase?.repoName) {
            delete (draft as PipelineInfoConfig)?.properties?.ci?.codebase?.repoName
          }
        })
      }
 
      Iif (template) {
        onSubmit?.({ stage: createTemplate(values, template) }, values.identifier, pipelineData)
      } else {
        data.stage.identifier = values.identifier
        data.stage.name = values.name
        Eif (values.description) data.stage.description = values.description
        Iif (values.tags) data.stage.tags = values.tags
        Iif (!data.stage.spec) data.stage.spec = {} as any
        set(data, 'stage.spec.cloneCodebase', values.cloneCodebase)
        onSubmit?.(data, values.identifier, pipelineData)
      }
    }
  }
  const { trackEvent } = useTelemetry()
  React.useEffect(() => {
    trackEvent(StageActions.LoadEditStageView, {
      category: Category.STAGE
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  return (
    <div className={css.stageCreate}>
      <Container padding="medium">
        <Formik
          enableReinitialize
          initialValues={initialValues}
          validationSchema={validationSchema}
          validate={handleValidate}
          formName="ciEditStage"
          onSubmit={handleSubmit}
        >
          {formikProps => (
            <FormikForm>
              <Text
                font={{ size: 'medium', weight: 'semi-bold' }}
                icon="ci-main"
                iconProps={{ size: 24, margin: { right: 'xsmall' } }}
                margin={{ bottom: 'medium' }}
                className={css.addStageHeading}
              >
                {getString('pipelineSteps.build.create.aboutYourStage')}
              </Text>
              {isContextTypeNotStageTemplate(contextType) &&
                (template ? (
                  <NameId
                    identifierProps={{
                      inputLabel: getString('stageNameLabel'),
                      inputGroupProps: {
                        disabled: isReadonly,
                        placeholder: getString('pipeline.aboutYourStage.stageNamePlaceholder')
                      }
                    }}
                  />
                ) : (
                  <NameIdDescriptionTags
                    formikProps={formikProps}
                    identifierProps={{
                      inputLabel: getString('stageNameLabel'),
                      inputGroupProps: {
                        disabled: isReadonly,
                        placeholder: getString('pipeline.aboutYourStage.stageNamePlaceholder')
                      }
                    }}
                    descriptionProps={{ disabled: isReadonly }}
                    tagsProps={{ disabled: isReadonly }}
                  />
                ))}
              {template ? (
                <Text
                  icon={'template-library'}
                  margin={{ top: 'medium', bottom: 'medium' }}
                  font={{ size: 'small' }}
                  iconProps={{ size: 12, margin: { right: 'xsmall' } }}
                  color={Color.BLACK}
                >
                  {`Using Template: ${getTemplateNameWithLabel(template)}`}
                </Text>
              ) : (
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 'var(--spacing-small)' }}>
                  <Switch
                    label={getString('cloneCodebaseLabel')}
                    onChange={e => formikProps.setFieldValue('cloneCodebase', e.currentTarget.checked)}
                    defaultChecked={formikProps.values.cloneCodebase}
                    disabled={isReadonly}
                    tooltipProps={{ tooltipId: 'cloneCodebase' }}
                  />
                </div>
              )}
              {/* We don't need to configure CI Codebase if it is already configured or we are skipping Clone Codebase step */}
              {!codebase && formikProps.values.cloneCodebase && isContextTypeNotStageTemplate(contextType) && (
                <div className={css.configureCodebase}>
                  <Text
                    font={{ size: 'normal', weight: 'semi-bold' }}
                    icon="cog"
                    iconProps={{ size: 16 }}
                    margin={{ bottom: 'medium' }}
                    style={{ color: 'var(--grey-700)' }}
                  >
                    {getString('pipelineSteps.build.create.configureCodebase')}
                  </Text>
                  <Text margin={{ bottom: 'medium' }}>
                    {getString('pipelineSteps.build.create.configureCodebaseHelperText')}
                  </Text>
                  <ConnectorReferenceField
                    className={css.connector}
                    error={
                      formikProps.submitCount && formikProps.errors.connectorRef
                        ? formikProps.errors.connectorRef
                        : undefined
                    }
                    name="connectorRef"
                    type={['Git', 'Github', 'Gitlab', 'Bitbucket', 'Codecommit']}
                    selected={formikProps.values.connectorRef}
                    label={getString('connector')}
                    width={366}
                    placeholder={loading ? getString('loading') : getString('connectors.selectConnector')}
                    disabled={loading || isReadonly}
                    accountIdentifier={accountId}
                    projectIdentifier={projectIdentifier}
                    orgIdentifier={orgIdentifier}
                    onChange={(value, scope) => {
                      setConnectionType(value.type === 'Git' ? value.spec.connectionType : value.spec.type)
                      setConnectorUrl(value.spec.url)
 
                      formikProps.setFieldValue('connectorRef', {
                        label: value.name || '',
                        value: `${scope !== Scope.PROJECT ? `${scope}.` : ''}${value.identifier}`,
                        scope: scope,
                        live: value?.status?.status === 'SUCCESS',
                        connector: value
                      })
                    }}
                    gitScope={{ repo: repoIdentifier || '', branch, getDefaultFromOtherRepo: true }}
                  />
                  {connectionType === 'Repo' ? (
                    <>
                      <Text margin={{ bottom: 'xsmall' }}>{repositoryNameLabel}</Text>
                      <TextInput name="repoName" value={connectorUrl} style={{ flexGrow: 1 }} disabled />
                    </>
                  ) : (
                    <>
                      <FormInput.Text
                        className={css.repositoryUrl}
                        label={repositoryNameLabel}
                        name="repoName"
                        style={{ flexGrow: 1 }}
                        disabled={isReadonly}
                        placeholder={getString('pipeline.manifestType.repoNamePlaceholder')}
                      />
                      {connectorUrl.length > 0 ? (
                        <Text className={css.predefinedValue} width={380} lineClamp={1}>
                          {(connectorUrl[connectorUrl.length - 1] === '/' ? connectorUrl : connectorUrl + '/') +
                            (formikProps.values.repoName ? formikProps.values.repoName : '')}
                        </Text>
                      ) : null}
                    </>
                  )}
                </div>
              )}
              <Button
                type="submit"
                intent="primary"
                text={getString('pipelineSteps.build.create.setupStage')}
                margin={{ top: 'small' }}
              />
            </FormikForm>
          )}
        </Formik>
      </Container>
    </div>
  )
}