All files / src/class/file file.ts

100% Statements 25/25
80% Branches 4/5
100% Functions 3/3
100% Lines 24/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 535x 5x 5x   5x     5x               80x 80x 80x       80x 80x   80x 80x 80x   80x 72x     80x 80x   80x   80x   80x   80x       160x 160x 160x          
import fs from 'fs-extra'
import { relative, join } from 'path'
import { Handler, Resource, CompiledFile } from '@/internal'
import { InferEncodingFunc } from '@/consts'
import { inferEncodingNormally } from '@/infer-encoding'
 
 
export class File {
  public templatePath: string
 
  public inferEncoding: InferEncodingFunc
 
  public handler?: Handler
 
  constructor(path: string, inferEncoding: InferEncodingFunc = inferEncodingNormally, handler?: Handler) {
    this.templatePath = path
    this.inferEncoding = inferEncoding
    this.handler = handler
  }
 
  public async compile(resource: Resource): Promise<CompiledFile> {
    await this.readTemplateFile()
    const { templatePath } = this
 
    let projectPath = templatePath
    projectPath = relative(resource.template.path, this.templatePath)
    projectPath = join(resource.project.path, projectPath)
 
    if (this.handler) {
      projectPath = await this.handler.genPath(projectPath, resource)
    }
 
    const content = await this.readTemplateFile()
    const encoding = this.inferEncoding(this.templatePath)
 
    const projectFileExisted = await fs.pathExists(projectPath)
 
    const compiledFile = new CompiledFile(templatePath, content, encoding, projectPath, resource, projectFileExisted)
 
    if (this.handler) await this.handler.genFile(compiledFile, resource)
 
    return compiledFile
  }
 
  private async readTemplateFile(): Promise<string> {
    const { templatePath, inferEncoding } = this
    const encoding = inferEncoding(templatePath)
    return await fs.readFile(templatePath, encoding)
  }
}
 
export type Files = File[]