All files / src/handlers/merge merge-json.ts

87.5% Statements 21/24
66.67% Branches 4/6
100% Functions 2/2
86.96% Lines 20/23

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 5615x       16x 16x   16x 16x   16x 16x 16x   16x 4x 4x 4x                 12x   12x 12x                 12x 12x                 12x     16x     15x  
import merge from 'merge-deep'
import { FileGenerator } from '@/internal'
 
 
const mergeJson: FileGenerator = async file => {
  let { content } = file
 
  const beginMatched = content.match(/^\s*/g)
  const beginBlank = beginMatched ? beginMatched[0] : ''
 
  const endMatched = content.match(/\s*$/g)
  const endBlank = endMatched ? endMatched[0] : ''
  let result = content
 
  if (!file.projectFileExisted) {
    try {
      content = JSON.parse(file.content)
      result = JSON.stringify(content, null, '  ')
    } catch (e) {
      throw new Error([
        'The template file and the current file failed to merge due to a json syntax error in the template file.',
        'The current file will be overwritten directly by the template file.',
        `path: ${file.templatePath}`,
      ].join('\n'))
    }
  } else {
    let projectContent = await file.getProjectContent()
 
    try {
      content = JSON.parse(file.content)
    } catch (e) {
      throw new Error([
        'The template file and the current file failed to merge due to a json syntax error in the template file.',
        'The current file will be overwritten directly by the template file.',
        `path: ${file.templatePath}`,
      ].join('\n'))
    }
 
    try {
      projectContent = JSON.parse(projectContent)
    } catch (e) {
      throw new Error([
        'The template file and the current file failed to merge due to a json syntax error in the current file.',
        'The current file will be overwritten directly by the template file.',
        `path: ${file.projectPath}`,
      ].join('\n'))
    }
 
    result = JSON.stringify(merge(projectContent, content), null, '  ')
  }
 
  file.content = `${beginBlank}${result}${endBlank}`
}
 
export default mergeJson