All files / modules/72-triggers/pages/triggers/views/modals SelectArtifactModal.tsx

90.91% Statements 90/99
67.87% Branches 245/361
93.75% Functions 15/16
90.82% Lines 89/98

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              7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x                   7x   7x 51x 34x 34x   17x 17x       7x 4x 4x             7x 17x 17x     7x 34x 34x                       7x 7x 7x     7x 2x         7x 2x 1x   1x 1x       1x 1x           7x 4x 2x 2x 2x   2x 1x     1x       7x                         4x                       4x   4x 4x 4x   1x     3x 1x         4x 4x                           4x             7x               51x 51x 51x 51x 51x       51x   51x 2x 2x 2x 2x 2x 2x           51x 51x 29x 22x             22x   51x 51x             51x 51x       51x               51x                                                                       1x                                                                                     4x             4x                               7x  
/*
 * 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 } from 'react'
import { Button, ButtonVariation, Layout, MultiTypeInputType } from '@wings-software/uicore'
import { defaultTo, isEmpty, merge } from 'lodash-es'
import cx from 'classnames'
import { Dialog } from '@blueprintjs/core'
import { useStrings } from 'framework/strings'
import { TriggerFormType } from '@pipeline/factories/ArtifactTriggerInputFactory/types'
import TriggerFactory from '@pipeline/factories/ArtifactTriggerInputFactory'
import { PipelineVariablesContextProvider } from '@pipeline/components/PipelineVariablesContext/PipelineVariablesContext'
 
import { StepViewType } from '@pipeline/components/AbstractSteps/Step'
import ArtifactTableInfo from '../subviews/ArtifactTableInfo'
import {
  clearRuntimeInputValue,
  filterArtifact,
  getPathString,
  getTemplateObject,
  PRIMARY_ARTIFACT,
  replaceTriggerDefaultBuild,
  updatePipelineArtifact,
  updatePipelineManifest
} from '../../utils/TriggersWizardPageUtils'
import css from './SelectArtifactModal.module.scss'
 
const getFormComponent = (isManifest: boolean) => {
  if (isManifest) {
    const formDetails = TriggerFactory.getTriggerFormDetails(TriggerFormType.Manifest)
    return formDetails.component
  } else {
    const artifactForm = TriggerFactory.getTriggerFormDetails(TriggerFormType.Artifact)
    return artifactForm.component
  }
}
 
const getArtifactId = (isManifest: boolean, selectedArtifactId: string) => {
  Eif (isManifest || selectedArtifactId) {
    return selectedArtifactId
  } else if (!isManifest) {
    return PRIMARY_ARTIFACT
  }
  return ''
}
 
const getArtifactBasefactory = () => {
  const artifactForm = TriggerFactory.getTriggerFormDetails(TriggerFormType.Artifact)
  return artifactForm.baseFactory
}
 
const getManifesttBasefactory = () => {
  const manifestForm = TriggerFactory.getTriggerFormDetails(TriggerFormType.Manifest)
  return manifestForm.baseFactory
}
 
interface SelectArtifactModalPropsInterface {
  isModalOpen: boolean
  isManifest: boolean
  artifactTableData?: any
  formikProps: any
  closeModal: () => void
  runtimeData: any
}
 
enum ModalState {
  SELECT = 'SELECT',
  RUNTIME_INPUT = 'RUNTIME_INPUT'
}
 
const getManifests = (filterFormStages: any) => {
  return filterFormStages && filterFormStages.length
    ? filterFormStages[0]?.stage?.spec?.serviceConfig?.serviceDefinition?.spec?.manifests[0]
    : {}
}
 
const getArtifacts = (filterFormStages: any) => {
  if (!filterFormStages) {
    return {}
  }
  Eif (filterFormStages.length) {
    Iif (filterFormStages[0]?.stage?.spec?.serviceConfig?.serviceDefinition?.spec?.artifacts?.sidecars?.length) {
      return filterFormStages && filterFormStages.length
        ? filterFormStages[0]?.stage?.spec?.serviceConfig?.serviceDefinition?.spec?.artifacts?.sidecars[0]
        : {}
    } else Eif (filterFormStages[0]?.stage?.spec?.serviceConfig?.serviceDefinition?.spec?.artifacts?.primary) {
      return filterFormStages[0]?.stage?.spec?.serviceConfig?.serviceDefinition?.spec?.artifacts?.primary
    }
  }
  return {}
}
 
const mergeArtifactManifest = (isManifest: boolean, originalArtifact: any, formFilteredArtifact: any) => {
  if (isManifest) {
    return merge({}, originalArtifact, formFilteredArtifact)?.['manifest']
  } else Eif (!isManifest) {
    Iif (originalArtifact?.sidecars?.length && originalArtifact?.sidecars[0]?.sidecar) {
      return merge({}, originalArtifact?.sidecars[0]?.sidecar, formFilteredArtifact?.sidecar)
    } else if (originalArtifact?.primary) {
      return merge({}, originalArtifact.primary, formFilteredArtifact)
    }
  }
  return {}
}
 
/*isManifest: boolean, selectedStageId: string, selectedArtifactId: string, formikProps: any */
const onSubmit = ({
  isManifest,
  selectedStageId,
  selectedArtifactId,
  runtimeData,
  formikProps
}: {
  isManifest: boolean
  selectedStageId: string
  selectedArtifactId: string
  runtimeData: any
  formikProps: any
}) => {
  const orginalArtifact = filterArtifact({
    runtimeData,
    stageId: selectedStageId,
    artifactId: getArtifactId(isManifest, selectedArtifactId),
    isManifest
  })
 
  /*
              when we have multiple stages - need to filter undefined values
              in this case formikprops.values.stages will be [undefined, [stage obj]]
              when chartVersion alone is runtime input, stages array could be empty
  */
  const filterFormStages = formikProps?.values?.stages?.filter((item: any) => item)
  // when stages is empty array, filteredArtifact will be empty object
  const formFilteredArtifact = isManifest ? getManifests(filterFormStages) : getArtifacts(filterFormStages)
  const finalArtifact = mergeArtifactManifest(isManifest, orginalArtifact, formFilteredArtifact)
  if (finalArtifact?.spec?.chartVersion && isManifest) {
    // hardcode manifest chart version to default
    finalArtifact.spec.chartVersion = replaceTriggerDefaultBuild({
      chartVersion: finalArtifact.spec.chartVersion
    })
  } else if (!isManifest && finalArtifact?.spec?.tag) {
    finalArtifact.spec.tag = replaceTriggerDefaultBuild({
      build: finalArtifact?.spec?.tag
    })
  }
 
  const { pipeline, selectedArtifact } = formikProps.values
  const newPipelineObj = isManifest
    ? updatePipelineManifest({
        pipeline,
        stageIdentifier: selectedStageId,
        selectedArtifact,
        newArtifact: clearRuntimeInputValue(finalArtifact)
      })
    : updatePipelineArtifact({
        pipeline,
        stageIdentifier: selectedStageId,
        selectedArtifact,
        newArtifact: clearRuntimeInputValue(finalArtifact)
      })
 
  formikProps.setValues({
    ...formikProps.values,
    pipeline: newPipelineObj,
    selectedArtifact: clearRuntimeInputValue(finalArtifact),
    stageId: selectedStageId
  })
}
const SelectArtifactModal: React.FC<SelectArtifactModalPropsInterface> = ({
  isModalOpen,
  formikProps,
  closeModal,
  isManifest,
  artifactTableData,
  runtimeData
}) => {
  const { values } = formikProps
  const [selectedArtifactLabel, setSelectedArtifactLabel] = useState(undefined) // artifactLabel is unique
  const [selectedStageId, setSelectedStageId] = useState(values?.stageId)
  const [selectedArtifactId, setSelectedArtifactId] = useState(values?.selectedArtifact?.identifier)
  const [modalState, setModalState] = useState<ModalState>(
    !isEmpty(values?.selectedArtifact) ? ModalState.RUNTIME_INPUT : ModalState.SELECT
  )
 
  const { getString } = useStrings()
 
  const closeAndReset = () => {
    closeModal()
    setSelectedArtifactId(undefined)
    setSelectedArtifactLabel(undefined)
    setSelectedStageId(undefined)
    setModalState(!isEmpty(values?.selectedArtifact) ? ModalState.RUNTIME_INPUT : ModalState.SELECT)
    Iif (isEmpty(values?.selectedArtifact || {}) && values?.stages) {
      // cancelling without applying should clear
      formikProps.setFieldValue('stages', undefined)
    }
  }
 
  const getSelectedArtifactId = () => {
    if (selectedArtifactId) {
      return selectedArtifactId
    } else Iif (
      values?.selectedArtifact &&
      Object.keys(values?.selectedArtifact).length &&
      !values?.selectedArtifact?.identifier
    ) {
      return PRIMARY_ARTIFACT
    }
    return ''
  }
  const FormComponent = getFormComponent(isManifest)
  const filteredArtifact = filterArtifact({
    runtimeData,
    stageId: selectedStageId,
    artifactId: getSelectedArtifactId(),
    isManifest
  })
 
  const templateObject = isManifest ? getTemplateObject(filteredArtifact, []) : getTemplateObject([], filteredArtifact)
  const artifactOrManifestText = isManifest
    ? getString('manifestsText')
    : getString('pipeline.artifactTriggerConfigPanel.artifact')
 
  const formComponentProps = isManifest
    ? { manifestSourceBaseFactory: getManifesttBasefactory(), manifests: templateObject?.manifests }
    : {
        artifactSourceBaseFactory: getArtifactBasefactory(),
        type: defaultTo(templateObject?.artifacts?.primary?.type, ''),
        artifacts: templateObject?.artifacts
      }
 
  return (
    <Dialog
      className={cx(css.selectArtifactModal, 'padded-dialog', modalState !== ModalState.SELECT && css.runtimeInputs)}
      isOpen={isModalOpen}
      enforceFocus={false}
      title={
        modalState === ModalState.SELECT
          ? isManifest
            ? getString('pipeline.artifactTriggerConfigPanel.selectAManifest')
            : getString('pipeline.artifactTriggerConfigPanel.selectAnArtifact')
          : getString('pipeline.artifactTriggerConfigPanel.configureArtifactRuntimeInputs', {
              artifact: artifactOrManifestText
            })
      }
      onClose={closeAndReset}
    >
      {modalState === ModalState.SELECT ? (
        <>
          <ArtifactTableInfo
            setSelectedArtifact={setSelectedArtifactId}
            selectedArtifact={selectedArtifactId}
            setSelectedStage={setSelectedStageId}
            selectedStage={selectedStageId}
            setSelectedArtifactLabel={setSelectedArtifactLabel}
            selectedArtifactLabel={selectedArtifactLabel}
            isManifest={isManifest}
            formikProps={formikProps}
            artifactTableData={artifactTableData}
          />
          <Layout.Horizontal spacing="medium" className={css.footer}>
            <Button
              text={getString('select')}
              variation={ButtonVariation.PRIMARY}
              disabled={!selectedArtifactId}
              data-name="selectBtn"
              onClick={() => {
                setModalState(ModalState.RUNTIME_INPUT)
              }}
            />
            <Button
              className={css.cancel}
              variation={ButtonVariation.TERTIARY}
              onClick={closeAndReset}
              text={getString('cancel')}
            />
          </Layout.Horizontal>
        </>
      ) : (
        <>
          <PipelineVariablesContextProvider pipeline={formikProps.values.originalPipeline}>
            <FormComponent
              template={templateObject}
              path={getPathString(runtimeData, selectedStageId)}
              initialValues={runtimeData}
              allowableTypes={[MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION]}
              readonly={false}
              stageIdentifier={selectedStageId}
              formik={formikProps}
              fromTrigger={true}
              stepViewType={StepViewType.InputSet}
              {...formComponentProps}
            />
          </PipelineVariablesContextProvider>
          <Layout.Horizontal spacing="medium" className={css.footer}>
            {isEmpty(values?.selectedArtifact) && (
              <Button
                text={getString('back')}
                icon="chevron-left"
                variation={ButtonVariation.SECONDARY}
                minimal
                onClick={() => {
                  setModalState(ModalState.SELECT)
                }}
              />
            )}
            <Button
              text={getString('filters.apply')}
              variation={ButtonVariation.PRIMARY}
              onClick={() => {
                onSubmit({
                  isManifest,
                  selectedStageId,
                  selectedArtifactId,
                  formikProps,
                  runtimeData
                })
                closeModal()
              }}
            />
            <Button
              className={css.cancel}
              variation={ButtonVariation.TERTIARY}
              onClick={closeAndReset}
              text={getString('cancel')}
            />
          </Layout.Horizontal>
        </>
      )}
    </Dialog>
  )
}
 
export default SelectArtifactModal