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

88% Statements 22/25
66.67% Branches 4/6
100% Functions 2/2
87.5% Lines 21/24

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 5815x 15x       16x 16x   16x 16x   16x 16x 16x   16x 4x 4x 4x                 12x   12x 12x                 12x 12x                 12x       16x     15x  
import yaml from 'js-yaml'
import merge from 'merge-deep'
import { FileGenerator } from '@/internal'
 
 
const mergeYaml: FileGenerator = async file => {
  let content = file.content
 
  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 = yaml.load(file.content)
      result = yaml.dump(content).replace(/\s*$/, '')
    } catch (e) {
      throw new Error([
        'The template file and the project file failed to merge due to a json syntax error in the template file.',
        'The project file will be overwritten directly by the template file.',
        `path: ${file.templatePath}`,
      ].join('\n'))
    }
  } else {
    let projectContent = await file.getProjectContent()
 
    try {
      content = yaml.load(file.content)
    } catch (e) {
      throw new Error([
        'The template file and the project file failed to merge due to a json syntax error in the template file.',
        'The project file will be overwritten directly by the template file.',
        `path: ${file.templatePath}`,
      ].join('\n'))
    }
 
    try {
      projectContent = yaml.load(projectContent)
    } catch (e) {
      throw new Error([
        'The template file and the project file failed to merge due to a yaml syntax error in the project file.',
        'The project file will be overwritten directly by the template file.',
        `path: ${file.projectPath}`,
      ].join('\n'))
    }
 
    result = yaml.dump(merge(projectContent, content))
      .replace(/\s*$/, '')
  }
 
  file.content = `${beginBlank}${result}${endBlank}`
}
 
export default mergeYaml