All files / modules/72-triggers/pages/triggers/views WebhookPipelineInputPanel.tsx

45.56% Statements 41/90
25.8% Branches 105/407
42.86% Functions 6/14
45.56% Lines 41/90

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              5x 5x 5x 5x 5x 5x   5x         5x 5x 5x 5x 5x 5x 5x               5x           5x                                                                               5x                                                                                 5x           68x   68x             68x                     68x 68x 68x 68x   68x   15x 1x     15x                                                           15x     68x 15x     68x                 68x 15x 8x                                   8x                                                                               68x                                                                                                         5x 62x           5x  
/*
 * 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 } from 'react'
import { useParams } from 'react-router-dom'
import { Layout, Text, NestedAccordionProvider, HarnessDocTooltip, PageSpinner } from '@wings-software/uicore'
import { parse } from 'yaml'
import { pick, merge, cloneDeep, isEmpty, defaultTo } from 'lodash-es'
import { InputSetSelector, InputSetSelectorProps } from '@pipeline/components/InputSetSelector/InputSetSelector'
import type { PipelineInfoConfig } from 'services/cd-ng'
import {
  useGetTemplateFromPipeline,
  getInputSetForPipelinePromise,
  useGetMergeInputSetFromPipelineTemplateWithListInput
} from 'services/pipeline-ng'
import { PipelineInputSetForm } from '@pipeline/components/PipelineInputSetForm/PipelineInputSetForm'
import { useStrings } from 'framework/strings'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import { clearRuntimeInput } from '@pipeline/components/PipelineStudio/StepUtil'
import { StepViewType } from '@pipeline/components/AbstractSteps/Step'
import { useMutateAsGet } from '@common/hooks'
import {
  ciCodebaseBuild,
  ciCodebaseBuildPullRequest,
  filterArtifactIndex,
  getFilteredStage,
  TriggerTypes,
  eventTypes
} from '../utils/TriggersWizardPageUtils'
import css from './WebhookPipelineInputPanel.module.scss'
 
interface WebhookPipelineInputPanelPropsInterface {
  formikProps?: any
}
 
const applyArtifactToPipeline = (newPipelineObject: any, formikProps: any) => {
  const artifactIndex = filterArtifactIndex({
    runtimeData: newPipelineObject?.stages,
    stageId: formikProps?.values?.stageId,
    artifactId: formikProps?.values?.selectedArtifact?.identifier,
    isManifest: false
  })
  const filteredStage = getFilteredStage(newPipelineObject?.stages, formikProps?.values?.stageId)
  if (artifactIndex >= 0) {
    const selectedArtifact = {
      sidecar: {
        type: formikProps?.values?.selectedArtifact?.type,
        spec: {
          ...formikProps?.values?.selectedArtifact?.spec
        }
      }
    }
 
    const filteredStageArtifacts =
      filteredStage.stage?.spec?.serviceConfig?.serviceDefinition?.spec?.artifacts?.sidecars
    filteredStageArtifacts[artifactIndex] = selectedArtifact
  } else if (artifactIndex < 0) {
    const selectedArtifact = {
      type: formikProps?.values?.selectedArtifact?.type,
      spec: {
        ...formikProps?.values?.selectedArtifact?.spec
      }
    }
 
    const filteredStageArtifacts = defaultTo(
      filteredStage.stage?.spec?.serviceConfig?.serviceDefinition?.spec?.artifacts,
      {}
    )
    filteredStageArtifacts.primary = selectedArtifact
  }
  return newPipelineObject
}
// Selected Artifact is applied to inputYaml on Pipeline Input Panel in KubernetesManifests.tsx
// This is to apply the selected artifact values
// to the applied input sets pipeline stage values
const applySelectedArtifactToPipelineObject = (pipelineObj: any, formikProps: any) => {
  // Cloning or making into a new object
  // so the original pipeline is not effected
  const newPipelineObject = { ...pipelineObj }
  if (!newPipelineObject) {
    return {}
  }
 
  const { triggerType } = formikProps.values
 
  if (triggerType === TriggerTypes.MANIFEST) {
    const artifactIndex = filterArtifactIndex({
      runtimeData: newPipelineObject?.stages,
      stageId: formikProps?.values?.stageId,
      artifactId: formikProps?.values?.selectedArtifact?.identifier,
      isManifest: true
    })
    if (artifactIndex >= 0) {
      const filteredStage =
        (newPipelineObject?.stages || []).find(
          (stage: any) => stage.stage.identifier === formikProps?.values?.stageId
        ) || {}
 
      const selectedArtifact = {
        manifest: {
          type: formikProps?.values?.selectedArtifact?.type,
          spec: {
            ...formikProps?.values?.selectedArtifact?.spec
          }
        }
      }
 
      const filteredStageManifests = filteredStage.stage?.spec?.serviceConfig?.serviceDefinition?.spec?.manifests
      filteredStageManifests[artifactIndex] = selectedArtifact
    }
  } else if (triggerType === TriggerTypes.ARTIFACT && newPipelineObject) {
    return applyArtifactToPipeline(newPipelineObject, formikProps)
  }
  return newPipelineObject
}
 
const WebhookPipelineInputPanelForm: React.FC<WebhookPipelineInputPanelPropsInterface> = ({
  formikProps
}): JSX.Element => {
  const {
    values: { inputSetSelected, pipeline, resolvedPipeline },
    values
  } = formikProps
 
  const { orgIdentifier, accountId, projectIdentifier, pipelineIdentifier } = useParams<{
    projectIdentifier: string
    orgIdentifier: string
    accountId: string
    pipelineIdentifier: string
    triggerIdentifier: string
  }>()
  const { data: template, loading } = useMutateAsGet(useGetTemplateFromPipeline, {
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      pipelineIdentifier,
      projectIdentifier
    },
    body: {
      stageIdentifiers: []
    }
  })
  const [selectedInputSets, setSelectedInputSets] = useState<InputSetSelectorProps['value']>(inputSetSelected)
  const { getString } = useStrings()
  const ciCodebaseBuildValue = formikProps.values?.pipeline?.properties?.ci?.codebase?.build
  let hasEverRendered = typeof ciCodebaseBuildValue === 'object' && !isEmpty(ciCodebaseBuildValue)
 
  useEffect(() => {
    const shouldInjectCloneCodebase =
      !isEmpty(resolvedPipeline?.properties?.ci?.codebase) &&
      (resolvedPipeline?.stages?.some((stage: any) => stage?.stage?.spec?.cloneCodebase) ||
        resolvedPipeline?.stages?.[0]?.parallel?.some((stage: any) => stage?.stage?.spec?.cloneCodebase))
 
    Iif (!hasEverRendered && shouldInjectCloneCodebase) {
      const formikValues = cloneDeep(formikProps.values)
 
      if (formikValues.event === eventTypes.PULL_REQUEST) {
        formikValues.pipeline = {
          ...formikValues.pipeline,
          properties: {
            ci: {
              codebase: {
                build: ciCodebaseBuildPullRequest
              }
            }
          }
        }
      } else {
        formikValues.pipeline = {
          ...formikValues.pipeline,
          properties: {
            ci: {
              codebase: {
                build: ciCodebaseBuild
              }
            }
          }
        }
      }
 
      formikProps.setValues(formikValues)
    }
 
    hasEverRendered = true
  }, [hasEverRendered])
 
  useEffect(() => {
    setSelectedInputSets(inputSetSelected)
  }, [inputSetSelected])
 
  const { mutate: mergeInputSet } = useGetMergeInputSetFromPipelineTemplateWithListInput({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      pipelineIdentifier
    }
  })
 
  useEffect(() => {
    if (template?.data?.inputSetTemplateYaml) {
      Iif ((selectedInputSets && selectedInputSets.length > 1) || selectedInputSets?.[0]?.type === 'OVERLAY_INPUT_SET') {
        const fetchData = async (): Promise<void> => {
          const data = await mergeInputSet({
            inputSetReferences: selectedInputSets.map(item => item.value as string)
          })
          if (data?.data?.pipelineYaml) {
            const pipelineObject = parse(data.data.pipelineYaml) as {
              pipeline: PipelineInfoConfig | any
            }
            const newPipelineObject = applySelectedArtifactToPipelineObject(pipelineObject.pipeline, formikProps)
            formikProps.setValues({
              ...values,
              inputSetSelected: selectedInputSets,
              pipeline: clearRuntimeInput(merge(pipeline, newPipelineObject))
            })
          }
        }
        fetchData()
      } else Iif (selectedInputSets && selectedInputSets.length === 1) {
        const fetchData = async (): Promise<void> => {
          const data = await getInputSetForPipelinePromise({
            inputSetIdentifier: selectedInputSets[0].value as string,
            queryParams: {
              accountIdentifier: accountId,
              projectIdentifier,
              orgIdentifier,
              pipelineIdentifier
            }
          })
          if (data?.data?.inputSetYaml) {
            if (selectedInputSets[0].type === 'INPUT_SET') {
              const pipelineObject = pick(parse(data.data.inputSetYaml)?.inputSet, 'pipeline') as {
                pipeline: PipelineInfoConfig | any
              }
 
              const newPipelineObject = applySelectedArtifactToPipelineObject(pipelineObject.pipeline, formikProps)
 
              formikProps.setValues({
                ...values,
                inputSetSelected: selectedInputSets,
                pipeline: clearRuntimeInput(merge(pipeline, newPipelineObject))
              })
            }
          }
        }
        fetchData()
      }
    }
  }, [
    template?.data?.inputSetTemplateYaml,
    selectedInputSets?.length,
    selectedInputSets,
    accountId,
    projectIdentifier,
    orgIdentifier,
    pipelineIdentifier
  ])
 
  return (
    <Layout.Vertical className={css.webhookPipelineInputContainer} spacing="large" padding="none">
      {loading && (
        <div style={{ position: 'relative', height: 'calc(100vh - 128px)' }}>
          <PageSpinner />
        </div>
      )}
      {pipeline && template?.data?.inputSetTemplateYaml ? (
        <div className={css.inputsetGrid}>
          <div className={css.inputSetContent}>
            <div className={css.pipelineInputRow}>
              <Text className={css.formContentTitle} inline={true} data-tooltip-id="pipelineInputLabel">
                {getString('triggers.pipelineInputLabel')}
                <HarnessDocTooltip tooltipId="pipelineInputLabel" useStandAlone={true} />
              </Text>
              <GitSyncStoreProvider>
                <InputSetSelector
                  pipelineIdentifier={pipelineIdentifier}
                  onChange={value => {
                    setSelectedInputSets(value)
                  }}
                  value={selectedInputSets}
                  selectedValueClass={css.inputSetSelectedValue}
                />
              </GitSyncStoreProvider>
              <div className={css.divider} />
            </div>
            <PipelineInputSetForm
              originalPipeline={resolvedPipeline}
              template={
                (template?.data?.inputSetTemplateYaml && parse(template.data.inputSetTemplateYaml).pipeline) || {}
              }
              path="pipeline"
              viewType={StepViewType.InputSet}
              maybeContainerClass={css.pipelineInputSetForm}
            />
          </div>
        </div>
      ) : (
        <Layout.Vertical style={{ padding: '0 var(--spacing-small)' }} margin="large" spacing="large">
          <Text className={css.formContentTitle} inline={true} data-tooltip-id="pipelineInputLabel">
            {getString('triggers.pipelineInputLabel')}
            <HarnessDocTooltip tooltipId="pipelineInputLabel" useStandAlone={true} />
          </Text>
          <Layout.Vertical className={css.formContent}>
            <Text>{getString('pipeline.pipelineInputPanel.noRuntimeInputs')}</Text>
          </Layout.Vertical>
        </Layout.Vertical>
      )}
    </Layout.Vertical>
  )
}
 
const WebhookPipelineInputPanel: React.FC<WebhookPipelineInputPanelPropsInterface> = props => {
  return (
    <NestedAccordionProvider>
      <WebhookPipelineInputPanelForm {...props} />
    </NestedAccordionProvider>
  )
}
export default WebhookPipelineInputPanel