# All files / src/Site template.ts

69.56% Statements 16/23
100% Branches 2/2
37.5% Functions 3/8
68.18% Lines 15/22

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
    571x
    1x
    1x

    1x

    1x

    1x

    1x
    1x

    1x
    2x
    2x

    2x
    1x

    1x
    1x

     import fs from 'fs-extra';
    import path from 'path';
    import * as fsUtil from '../utils/fsUtil';

    const requiredFiles = ['index.md', 'site.json', '_markbind/'];

    const PATH_TO_TEMPLATE = '../../template';

    export class Template {
      root: string;
      template: string;

      constructor(rootPath: string, templatePath: string) {
        this.root = rootPath;
        this.template = path.join(__dirname, PATH_TO_TEMPLATE, templatePath);
      }

      validateTemplateFromPath() {
        for (let i = 0; i < requiredFiles.length; i += 1) {
          const requiredFile = requiredFiles[i];
          const requiredFilePath = path.join(this.template, requiredFile);

          if (!fs.existsSync(requiredFilePath)) {
            return false;
          }
        }

        return true;
      }

      generateSiteWithTemplate() {
        return new Promise((resolve, reject) => {
          fs.access(this.root)
            .catch(() => fs.mkdirSync(this.root))
            .then(() => fsUtil.copySyncWithOptions(this.template, this.root, { overwrite: false }))
            .then(resolve)
            .catch(reject);
        });
      }

      /**
       * A method for initializing a markbind site according to the given template.
       * Generate the site.json and an index.md file.
       */
      async init() {
        if (!this.validateTemplateFromPath()) {
          throw new Error('Template validation failed. Required files does not exist.');
        }

        return new Promise((resolve, reject) => {
          this.generateSiteWithTemplate()
            .then(resolve)
            .catch(reject);
        });
      }
    }