All files / modules/70-pipeline/components/PipelineStudio/PipelineTemplateBuilder/TemplatePipelineSpecifications TemplatePipelineSpecifications.tsx

26.58% Statements 21/79
0% Branches 0/140
0% Functions 0/12
26.58% Lines 21/79

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              8x 8x 8x 8x 8x 8x   8x 8x   8x 8x         8x 8x 8x 8x   8x 8x 8x 8x 8x 8x   8x                                                                                                                                                                                                                                                                                                                                                                                                
/*
 * 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 { cloneDeep, debounce, defaultTo, isEqual, merge, noop, set } from 'lodash-es'
import { useParams } from 'react-router-dom'
import React, { useRef } from 'react'
import { parse } from 'yaml'
import { Container, Formik, FormikForm, Heading, Layout, PageError } from '@wings-software/uicore'
import { Color } from '@wings-software/design-system'
import type { FormikProps, FormikErrors } from 'formik'
import { useToaster } from '@common/exports'
import { setTemplateInputs, TEMPLATE_INPUT_PATH } from '@pipeline/utils/templateUtils'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useGetTemplateInputSetYaml, useGetYamlWithTemplateRefsResolved } from 'services/template-ng'
import {
  getIdentifierFromValue,
  getScopeBasedProjectPathParams,
  getScopeFromValue
} from '@common/components/EntityReference/EntityReference'
import { usePipelineContext } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import { PageSpinner } from '@common/components'
import { PipelineInputSetFormInternal } from '@pipeline/components/PipelineInputSetForm/PipelineInputSetForm'
import { StepViewType } from '@pipeline/components/AbstractSteps/Step'
import type { Error, PipelineInfoConfig } from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import { validatePipeline } from '@pipeline/components/PipelineStudio/StepUtil'
import { ErrorsStrip } from '@pipeline/components/ErrorsStrip/ErrorsStrip'
import { useMutateAsGet } from '@common/hooks'
import { yamlStringify } from '@common/utils/YamlHelperMethods'
import css from './TemplatePipelineSpecifications.module.scss'
 
export function TemplatePipelineSpecifications(): JSX.Element {
  const {
    state: { pipeline, schemaErrors, gitDetails },
    allowableTypes,
    updatePipeline,
    isReadonly
  } = usePipelineContext()
  const queryParams = useParams<ProjectPathProps>()
  const templateRef = getIdentifierFromValue(defaultTo(pipeline.template?.templateRef, ''))
  const scope = getScopeFromValue(defaultTo(pipeline.template?.templateRef, ''))
  const { showError } = useToaster()
  const { getString } = useStrings()
  const formikRef = React.useRef<FormikProps<unknown> | null>(null)
  const formRefDom = React.useRef<HTMLElement | undefined>()
  const [inputsTemplate, setInputsTemplate] = React.useState<PipelineInfoConfig>()
  const [allValues, setAllValues] = React.useState<PipelineInfoConfig>()
  const [initialValues, setInitialValues] = React.useState<PipelineInfoConfig>()
  const [formikErrors, setFormikErrors] = React.useState<FormikErrors<PipelineInfoConfig>>()
  const [showFormError, setShowFormError] = React.useState<boolean>()
  const dummyPipeline = useRef(pipeline)
 
  const onChange = React.useCallback(
    debounce(async (values: PipelineInfoConfig): Promise<void> => {
      await updatePipeline({ ...pipeline, ...values })
    }, 300),
    [pipeline, updatePipeline]
  )
 
  const {
    data: pipelineResponse,
    error: pipelineError,
    refetch: refetchPipeline,
    loading: pipelineLoading
  } = useMutateAsGet(useGetYamlWithTemplateRefsResolved, {
    queryParams: {
      ...getScopeBasedProjectPathParams(queryParams, scope),
      pipelineIdentifier: pipeline.identifier,
      repoIdentifier: gitDetails.repoIdentifier,
      branch: gitDetails.branch,
      getDefaultFromOtherRepo: true
    },
    body: {
      originalEntityYaml: yamlStringify(dummyPipeline.current)
    }
  })
 
  const {
    data: templateInputSetYaml,
    error: templateInputSetError,
    refetch: refetchTemplateInputSet,
    loading: templateInputSetLoading
  } = useGetTemplateInputSetYaml({
    templateIdentifier: templateRef,
    queryParams: {
      ...getScopeBasedProjectPathParams(queryParams, scope),
      versionLabel: defaultTo(pipeline.template?.versionLabel, ''),
      repoIdentifier: gitDetails.repoIdentifier,
      branch: gitDetails.branch,
      getDefaultFromOtherRepo: true
    }
  })
 
  React.useEffect(() => {
    if (!templateInputSetLoading) {
      try {
        const templateInputs = parse(defaultTo(templateInputSetYaml?.data, ''))
        setInputsTemplate(templateInputs)
      } catch (error) {
        showError(error.message, undefined, 'template.parse.inputSet.error')
      }
    }
  }, [templateInputSetLoading, templateInputSetYaml?.data])
 
  React.useEffect(() => {
    if (pipelineResponse?.data?.mergedPipelineYaml) {
      setAllValues(parse(pipelineResponse?.data?.mergedPipelineYaml))
    }
  }, [pipelineResponse?.data?.mergedPipelineYaml])
 
  React.useEffect(() => {
    try {
      const mergedTemplateInputs = merge({}, inputsTemplate, pipeline.template?.templateInputs)
      setTemplateInputs(pipeline, mergedTemplateInputs)
      updatePipeline(pipeline)
      setInitialValues(cloneDeep(pipeline))
    } catch (error) {
      showError(error.message, undefined, 'template.parse.inputSet.error')
    }
  }, [inputsTemplate])
 
  React.useEffect(() => {
    dummyPipeline.current = pipeline
    setFormikErrors({})
  }, [pipeline.template?.templateRef, pipeline.template?.versionLabel])
 
  React.useEffect(() => {
    if (schemaErrors) {
      formikRef.current?.submitForm()
      setShowFormError(true)
    }
  }, [schemaErrors])
 
  const validateForm = (values: PipelineInfoConfig) => {
    if (
      isEqual(values.template?.templateRef, pipeline.template?.templateRef) &&
      isEqual(values.template?.versionLabel, pipeline.template?.versionLabel) &&
      inputsTemplate
    ) {
      onChange?.(values)
      const errorsResponse = validatePipeline({
        pipeline: values.template?.templateInputs as PipelineInfoConfig,
        template: inputsTemplate,
        originalPipeline: allValues,
        getString,
        viewType: StepViewType.DeploymentForm
      })
      const newFormikErrors = set({}, TEMPLATE_INPUT_PATH, errorsResponse)
      setFormikErrors(newFormikErrors)
      return newFormikErrors
    } else {
      setFormikErrors({})
      return {}
    }
  }
 
  const refetch = () => {
    refetchPipeline()
    refetchTemplateInputSet()
  }
 
  return (
    <Container className={css.contentSection} height={'100%'} background={Color.FORM_BG}>
      {(pipelineLoading || templateInputSetLoading) && <PageSpinner />}
      {!pipelineLoading && !templateInputSetLoading && (pipelineError || templateInputSetError) && (
        <PageError
          message={
            defaultTo((pipelineError?.data as Error)?.message, pipelineError?.message) ||
            defaultTo((templateInputSetError?.data as Error)?.message, templateInputSetError?.message)
          }
          onClick={() => refetch()}
        />
      )}
      {!pipelineLoading &&
        !templateInputSetLoading &&
        !pipelineError &&
        !templateInputSetError &&
        inputsTemplate &&
        allValues &&
        initialValues && (
          <>
            {showFormError && formikErrors && <ErrorsStrip formErrors={formikErrors} domRef={formRefDom} />}
            <Formik<PipelineInfoConfig>
              initialValues={initialValues}
              formName="templateStageOverview"
              onSubmit={noop}
              validate={validateForm}
            >
              {(formik: FormikProps<PipelineInfoConfig>) => {
                formikRef.current = formik
                return (
                  <FormikForm>
                    <Container
                      className={css.inputsContainer}
                      ref={ref => {
                        formRefDom.current = ref as HTMLElement
                      }}
                    >
                      <Layout.Vertical padding={{ bottom: 'large' }} spacing={'xlarge'}>
                        <Heading level={5} color={Color.BLACK}>
                          Template Inputs
                        </Heading>
                        <Container>
                          <PipelineInputSetFormInternal
                            template={inputsTemplate}
                            originalPipeline={allValues}
                            path={TEMPLATE_INPUT_PATH}
                            readonly={isReadonly}
                            viewType={StepViewType.InputSet}
                            allowableTypes={allowableTypes}
                          />
                        </Container>
                      </Layout.Vertical>
                    </Container>
                  </FormikForm>
                )
              }}
            </Formik>
          </>
        )}
    </Container>
  )
}