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

88.89% Statements 16/18
50% Branches 2/4
100% Functions 2/2
88.24% Lines 15/17

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 415x       12x 12x 12x   12x 12x                 12x 12x                 12x 12x   12x 12x   12x   12x     5x  
import merge from 'merge-deep'
import { FileGenerator } from '@/internal'
 
 
const mergeJson: FileGenerator = async file => {
  let { content } = file
  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.projectPath}`,
    ].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'))
  }
 
  const beginMatched = file.content.match(/^\s*/g)
  const beginBlank = beginMatched ? beginMatched[0] : ''
 
  const endMatched = file.content.match(/\s*$/g)
  const endBlank = endMatched ? endMatched[0] : ''
 
  const result = JSON.stringify(merge(projectContent, content), null, '  ')
 
  file.content = `${beginBlank}${result}${endBlank}`
}
 
export default mergeJson