All files / modules/40-gitsync/components/GitSyncErrorMessage GitSyncErrorMessage.tsx

92.45% Statements 49/53
48.89% Branches 22/45
100% Functions 13/13
92% Lines 46/50

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              1x 1x 1x 1x 1x 1x 1x 1x 1x       1x   1x   1x   1x 96x 84x   12x     1x 14x                   1x             47x                                   1x 16x                       1x 21x             1x 17x 16x   16x   16x 16x     16x 10x 10x 10x   10x   10x 1x 1x 1x                     1x 1x               1x 1x           10x                         16x                                                           22x              
/*
 * 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, { useEffect, useState } from 'react'
import ReactTimeago from 'react-timeago'
import { useParams } from 'react-router-dom'
import { defaultTo } from 'lodash-es'
import cx from 'classnames'
import { Card, Icon, IconName, Layout, Text, useToaster } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { GitSyncErrorDTO, listGitToHarnessErrorsForCommitPromise } from 'services/cd-ng'
import {
  GitSyncErrorMessageItem,
  GitSyncErrorMessageProps
} from '@gitsync/components/GitSyncErrorMessage/GitSyncErrorMessageItem'
import { useStrings } from 'framework/strings'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import styles from '@gitsync/components/GitSyncErrorMessage/GitSyncErrorMessage.module.scss'
 
const MESSAGE_LIMIT = 5
 
const renderComponentConditionally = (Component: React.ReactElement, condition: boolean): React.ReactElement => {
  if (condition) {
    return Component
  }
  return <></>
}
 
const CountComponent: React.FC<{ count?: number }> = ({ count }) => {
  return (
    <Layout.Horizontal margin={{ right: 'medium' }}>
      <Icon name="warning-sign" color={Color.RED_600} padding={{ right: 'small' }} />
      <Text font={{ weight: 'bold' }} color={Color.RED_600} data-testid="gitSyncErrorCount">
        {count}
      </Text>
    </Layout.Horizontal>
  )
}
 
const IconValue: React.FC<{ icon: IconName; value?: string; background?: Color; color?: Color; type: string }> = ({
  icon,
  value,
  background,
  color,
  type
}) => {
  return (
    <Layout.Horizontal
      background={background || Color.GREY_100}
      padding={{ left: 'small', right: 'small', top: 'small', bottom: 'small' }}
      margin={{ right: 'medium' }}
    >
      <Icon name={icon} color={color || Color.GREY_600} size={14} padding={{ right: 'small' }}></Icon>
      <Text
        font={{ weight: 'semi-bold', size: 'small' }}
        color={color || Color.GREY_900}
        data-testid={`gitSyncErrorIconValue${type}`}
      >
        {value}
      </Text>
    </Layout.Horizontal>
  )
}
 
const TimestampComponent: React.FC<{ timestamp?: number }> = ({ timestamp }) => {
  return (
    <Layout.Horizontal
      className={styles.timestamp}
      padding={{ left: 'medium' }}
      data-testid="gitSyncErrorTimestamp"
      data-value={timestamp}
    >
      <ReactTimeago date={timestamp || 0} />
    </Layout.Horizontal>
  )
}
 
export const parseCommitItems = (items: GitSyncErrorDTO[]): GitSyncErrorMessageProps['items'] => {
  return items.map(error => ({
    title: error.completeFilePath,
    reason: error.failureReason || '',
    ...(error.status === 'RESOLVED' ? { fixCommit: error.additionalErrorDetails?.['resolvedByCommitId'] } : {})
  }))
}
 
export const GitSyncErrorMessage: React.FC<GitSyncErrorMessageProps> = props => {
  const { mode, title, count, repo, branch, commitId = '', timestamp, items } = props
  const { showError } = useToaster()
 
  const [messageItems, setMessageItems] = useState(items)
 
  useEffect(() => {
    setMessageItems(items)
  }, [items])
 
  const SeeMore: React.FC = () => {
    const [isLoading, setIsLoading] = useState(false)
    const { getString } = useStrings()
    const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
 
    const expandMode = messageItems.length <= MESSAGE_LIMIT
 
    const onClick = (): void => {
      Eif (expandMode) {
        setIsLoading(true)
        listGitToHarnessErrorsForCommitPromise({
          queryParams: {
            accountIdentifier: accountId,
            orgIdentifier,
            projectIdentifier,
            branch,
            repoIdentifier: repo
          },
          commitId
        })
          .then(commitData => {
            setIsLoading(false)
            if (commitData.status === 'ERROR') {
              throw new Error()
            }
            if (defaultTo(commitData.data?.content, []).length > 0) {
              setMessageItems(parseCommitItems(defaultTo(commitData.data?.content, [])))
            }
          })
          .catch(() => {
            setIsLoading(false)
            showError(getString('gitsync.failedToLoadData'))
          })
      } else {
        setMessageItems(messageItems.splice(0, MESSAGE_LIMIT))
      }
    }
    return (
      <Layout.Horizontal margin={{ top: 'small' }}>
        {!isLoading ? (
          <Text color={Color.PRIMARY_7} onClick={onClick} className={styles.seeMore} data-testid="seeMore">
            {expandMode ? getString('gitsync.seeMore') : getString('gitsync.seeLess')}
          </Text>
        ) : (
          <Icon name="spinner" />
        )}
      </Layout.Horizontal>
    )
  }
 
  return (
    <Card className={styles.gitSyncErrorMessage} data-testid="gitSyncErrorMessage">
      <Layout.Vertical>
        <Layout.Horizontal className={styles.section} flex={{ justifyContent: 'space-between' }}>
          <Text
            font={{ weight: 'bold' }}
            color={Color.GREY_900}
            className={cx(styles.title, { [styles.titleDirection]: mode === 'FILE' })}
            data-testid="gitSyncErrorTitle"
          >
            {title}
          </Text>
          <Layout.Horizontal flex={{ alignItems: 'center' }}>
            {renderComponentConditionally(<CountComponent count={count} />, !!count)}
            {renderComponentConditionally(<IconValue type="Repo" icon={'repository'} value={repo} />, !!repo)}
            {renderComponentConditionally(<IconValue type="Branch" icon={'git-new-branch'} value={branch} />, !!branch)}
            {renderComponentConditionally(
              <IconValue
                icon={'git-commit'}
                type="CommitId"
                value={commitId?.slice(0, 7)}
                background={Color.PRIMARY_1}
                color={Color.PRIMARY_7}
              />,
              !!commitId
            )}
            {renderComponentConditionally(<TimestampComponent timestamp={timestamp} />, !!timestamp)}
          </Layout.Horizontal>
        </Layout.Horizontal>
        {(messageItems || []).map((item, key) => (
          <GitSyncErrorMessageItem key={key} {...item} />
        ))}
        {renderComponentConditionally(<SeeMore />, mode === 'COMMIT' && defaultTo(count, 0) > MESSAGE_LIMIT)}
      </Layout.Vertical>
    </Card>
  )
}