All files / src/class template.ts

90.2% Statements 92/102
60.87% Branches 14/23
91.67% Functions 22/24
93.41% Lines 85/91

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 19815x 15x 15x 15x 15x 15x 15x 15x 15x 15x                                   15x 15x 15x         15x                           8x 8x 8x 8x 8x 8x       8x 80x 8x       40x 35x 35x 35x 35x   40x       5x 5x 50x 50x 50x 305x 305x 305x   305x 305x       5x       5x 5x 5x   50x 5x       3x   3x 30x 30x 30x           3x   3x             8x   8x   8x 8x         8x 8x             8x   8x   8x               8x     8x 56x 56x 8x   8x     8x 8x     8x 8x 8x 16x       8x         16x 88x 88x   432x   88x 72x   88x 8x     80x     16x 16x      
import Ajv from 'ajv'
import ajvKeywords from 'ajv-keywords'
import { join, dirname } from 'path'
import cosmiconfig from 'cosmiconfig'
import { unnest } from 'ramda'
import { loadNpmConfig } from '@/loader'
import { TemplateSchema, RuleSchema, QuestionSchema } from '@/schema'
import { isDirectory, logger } from '@/utils'
import { UpgradeType } from '@/consts'
import {
  Repository,
  Hook,
  Hooks,
  Listener,
  Resource,
  File,
  Files,
  CheckOptions,
  Question,
  Questions,
  Rule,
  Effect,
  CompiledFile,
  CompiledFiles,
} from '@/internal'
 
 
const ajv = new Ajv({ useDefaults: true, $data: true })
ajvKeywords(ajv)
const validateTemplateConfig = ajv
  .addSchema([RuleSchema, QuestionSchema])
  .compile(TemplateSchema)
 
 
export class Template {
  public readonly repository: Repository
 
  public path: string
 
  public engines: string
 
  public files: Files
 
  public questions: Questions
 
  public hooks: Hooks
 
  constructor(repo: Repository, path: string, engines: string, files: Files, questions: Questions = [], hooks: Hooks = []) {
    this.path = path
    this.repository = repo
    this.engines = engines
    this.files = files
    this.questions = questions
    this.hooks = hooks
  }
 
  private async compile(resource: Resource): Promise<CompiledFiles> {
    logger.info('compile template')
    const promises = this.files.map(file => file.compile(resource))
    return await Promise.all(promises)
  }
 
  private async ensureFolder(folders, prefix = ''): Promise<void> {
    const promises = Object.entries(folders)
      .map(async([name, child]) => {
        const dir = join(prefix, name)
        await Effect.fs.ensureDir(dir)
        await this.ensureFolder(child, dir)
      })
    await Promise.all(promises)
  }
 
  private async ensureDir(files: CompiledFile[]): Promise<void> {
    const folders = {}
    files.forEach(file => {
      const dir = dirname(file.projectPath)
      let parent = folders
      dir.split('/').forEach(name => {
        const pair = name || '/'
        let next = parent[pair]
        if (!next) next = {}
 
        parent[pair] = next
        parent = next
      })
    })
 
    await this.ensureFolder(folders)
  }
 
  public async render(resource: Resource): Promise<void> {
    const files = await this.compile(resource)
    logger.info('rendering')
    await this.ensureDir(files)
 
    const promises = files.map(file => file.render())
    await Promise.all(promises)
  }
 
  public async check(resource: Resource, options?: CheckOptions): Promise<void> {
    const files = await this.compile(resource)
 
    const errors: string[] = []
    const promises = files.map(async file => {
      try {
        await file.check(options)
      } catch (e) {
        errors.push(e.message)
      }
    })
 
    await Promise.all(promises)
 
    Iif (errors.length) {
      errors.forEach(message => logger.error(message))
      throw new Error('Check failed')
    }
  }
 
  public static async load(repo: Repository): Promise<Template> {
    const cwd = repo.storage
 
    let entry = join(cwd, 'index.js')
 
    try {
      const npmConfig = await loadNpmConfig(cwd)
      if (npmConfig.main) entry = join(cwd, npmConfig.main)
    } catch (e) {
    }
 
    const result = await cosmiconfig('template').load(entry)
    Iif (!result) {
      throw new Error([
        'Cannot load template config',
        `Maybe syntax error in ${entry}`,
      ].join('\n'))
    }
 
    const config = result.config
 
    const valid = validateTemplateConfig(config)
 
    Iif (!valid) {
      throw new Error([
        'There is some error in template config: ',
        ajv.errorsText(validateTemplateConfig.errors, { dataVar: 'template' }),
      ].join('\n'))
    }
 
    /** absoult template path */
    config.path = join(cwd, config.path)
 
    /** generate files */
    const rules = config.rules
      .map(item => ({ ...item, path: join(config.path, item.path) }))
      .map(item => Rule.format(item))
    const rootRule = new Rule(config.path, UpgradeType.Cover, true)
 
    const files = await this.searchDirFile(config.path, rootRule, rules)
 
    /** generate questions */
    let questions: Questions = []
    Iif (config.questions) questions = config.questions.map(question => new Question(question))
 
    /** generate hooks */
    let hooks: Hook[] = []
    Eif (config.hooks) {
      hooks = Object.entries(config.hooks)
        .map(([name, listener]) => new Hook(name, listener as (Listener | string)))
    }
 
 
    return new Template(repo, config.path, config.engines, files, questions, hooks)
  }
 
 
  private static async searchDirFile(path: string, rule: Rule, rules: Rule[]): Promise<Files> {
    const files = await Effect.fs.readdir(path)
    const promises = files.map(async(filename: string): Promise<File | Files> => {
      const subPath = join(path, filename)
 
      let subRule = rules.find(rule => rule.match(subPath))
 
      if (!subRule) subRule = rule
      else subRule = Rule.merge(rule, subRule)
 
      if (await isDirectory(subPath)) {
        return await this.searchDirFile(subPath, subRule, rules)
      }
 
      return subRule.createFile(subPath)
    })
 
    const subFiles = await Promise.all(promises)
    return unnest(subFiles) as Files
  }
}