All files template.ts

100% Statements 153/153
100% Branches 32/32
100% Functions 33/33
100% Lines 126/126

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 198 199 200 201 202 203 204 205 206 207 208 209 2101x 1x 1x 1x 1x   1x 1x   1x                             1x 1x 1x   16x 15x   1x     1x   10x 1x   9x     1x 10x 10x 10x 10x 10x 8x 8x           8x   1x 7x 8x 8x     42x 42x 31x 61x 2x   30x     16x   14x 7x   1x 265x 265x 604x 604x       530x 530x   1x 33x 33x 33x   288x   288x   255x   510x   2x         1x   8x 16x       8x   1x 25x 25x   1x         8x 8x   1x 6x 16x 16x 10x     1x 7x 7x 1x             6x 6x   1x 8x 8x 3x 3x 3x 3x 3x 3x 3x 5x 1x 1x 2x 2x   4x 2x 2x 4x 4x     16x   1x 10x 16x 16x 11x 5x 22x 22x 44x 44x   5x   4x 2x 2x 8x 8x 16x 16x   2x   1x   1x 10x 10x   20x 7x   3x 3x     1x  
import * as path from 'path';
import * as fs from 'fs';
import {exec} from 'child_process';
import * as util from 'util';
const execAsync = util.promisify(exec);
 
const COMMIT = 'commit';
const PULL = 'pull';
 
const defaultIgnore = ['.git', '.template'];
 
type Any = {};
 
export interface ConfigJson {
  name: string;
  ignoreKeys: string[];
}
 
export interface Config {
  source: string;
  ignore: string[];
  json?: ConfigJson[];
}
 
export class Template {
  static execAsync = execAsync;
  static async readJson(filePath: string) {
    try {
      const content = await fs.promises.readFile(filePath, 'utf8');
      return JSON.parse(content);
    } catch (e) {
      return {};
    }
  }
  static async readGitIgnore(filePath: string): Promise<string[]> {
    try {
      const content = await fs.promises.readFile(filePath, 'utf8');
      return content.split('\n').filter(i => i);
    } catch (e) {
      return [];
    }
  }
  static async config(location: string): Promise<Config> {
    const configPath = path.join(location, 'template.json');
    const ignorePath = path.join(location, '.gitignore');
    const config = await Template.readJson(configPath);
    const gitignore = await Template.readGitIgnore(ignorePath);
    if (!config.source) throw new Error('config is missing source');
    const ignoreJson = (config.json || []).map((j: ConfigJson) => j.name);
    const ignore = [
      ...gitignore,
      ...ignoreJson,
      ...defaultIgnore,
      ...(config.ignore || []),
    ];
    return {...config, ignore} as Config;
  }
  static async files(location: string, ignore: string[]) {
    const files: string[] = [];
    const recursive = async (location: string) => {
      const entries = await fs.promises.readdir(location, {
        withFileTypes: true,
      });
      const promises = entries.map(async entry => {
        if (ignore.includes(entry.name)) return;
        const fullLocation = path.join(location, entry.name);
        if (entry.isDirectory()) {
          await recursive(fullLocation);
        } else {
          files.push(fullLocation);
        }
      });
      await Promise.all(promises);
    };
    await recursive(location);
    return files;
  }
  static async rmdir(location: string) {
    const entries = await fs.promises.readdir(location, {withFileTypes: true});
    const promises = entries.map(entry => {
      const fullLocation = path.join(location, entry.name);
      return entry.isDirectory()
        ? Template.rmdir(fullLocation)
        : fs.promises.unlink(fullLocation);
    });
    await Promise.all(promises);
    await fs.promises.rmdir(location);
  }
  static async mkdirp(location: string) {
    location = path.resolve(location);
    const locationSplit = location.split(path.sep);
    return locationSplit
      .map((i, index) => {
        return path.join('/', ...locationSplit.slice(0, index + 1));
      })
      .filter(i => i !== '/')
      .reduce((resolve, segment) => {
        return resolve.then(async () => {
          try {
            await fs.promises.stat(segment);
          } catch (e) {
            await fs.promises.mkdir(segment);
          }
        });
      }, Promise.resolve());
  }
  static async clone(repo: string, location: string) {
    try {
      const templateDir = path.join(location, '.template');
      await Template.rmdir(templateDir);
    } catch (e) {
      // noop
    }
    return execAsync(`git -C ${location} clone ${repo} .template`);
  }
  static templateFile(file: string, location: string) {
    const chopped = file.replace(new RegExp(`^${location}`), '');
    return path.join(location, path.join('.template', chopped));
  }
  static normalFile(
    templateFile: string,
    templateDir: string,
    location: string
  ) {
    const chopped = templateFile.replace(new RegExp(`^${templateDir}`), '');
    return path.join(location, chopped);
  }
  static omit(keys: string[], obj: {[key: string]: Any}): {[key: string]: Any} {
    return Object.keys(obj).reduce((prev, curr) => {
      const value = obj[curr];
      if (!keys.includes(curr)) return {...prev, [curr]: value};
      return prev;
    }, {});
  }
  static deepMerge(target: {[key: string]: Any}, source: {[key: string]: Any}) {
    for (const key of Object.keys(source)) {
      if (source[key] instanceof Object) {
        Object.assign(
          source[key],
          Template.deepMerge(target[key], source[key])
        );
      }
    }
    // Join `target` and modified `source`
    Object.assign(target, source);
    return target;
  }
  static async mergeJson(json: Config['json'], location: string, cmd: string) {
    const jsonFiles = json || [];
    const promises = jsonFiles.map(async jsonFile => {
      const {ignoreKeys} = jsonFile;
      const file = path.join(location, jsonFile.name);
      const templateFile = Template.templateFile(file, location);
      const fileJSON = await Template.readJson(file);
      const templateFileJSON = await Template.readJson(templateFile);
      const iFileJSON = Template.omit(ignoreKeys, fileJSON);
      const iTemplateFileJSON = Template.omit(ignoreKeys, templateFileJSON);
      if (cmd === COMMIT) {
        const json = Template.deepMerge(templateFileJSON, iFileJSON);
        const output = JSON.stringify(json, null, 2);
        await Template.mkdirp(path.dirname(templateFile));
        await fs.promises.writeFile(templateFile, output, 'utf-8');
      }
      if (cmd === PULL) {
        const json = Template.deepMerge(fileJSON, iTemplateFileJSON);
        const output = JSON.stringify(json, null, 2);
        await Template.mkdirp(path.dirname(file));
        await fs.promises.writeFile(file, output, 'utf-8');
      }
    });
    await Promise.all(promises);
  }
  static async main(location: string, cmd: string) {
    const {source, ignore, json} = await Template.config(location);
    await Template.clone(source, location);
    await Template.mergeJson(json, location, cmd);
    if (cmd === COMMIT) {
      const files = await Template.files(location, ignore);
      const promises = files.map(async file => {
        const templateFile = Template.templateFile(file, location);
        await Template.mkdirp(path.dirname(templateFile));
        await fs.promises.copyFile(file, templateFile);
      });
      return await Promise.all(promises);
    }
    if (cmd === PULL) {
      const templateDir = path.join(location, '.template');
      const files = await Template.files(templateDir, ignore);
      const promises = files.map(async templateFile => {
        const file = Template.normalFile(templateFile, templateDir, location);
        await Template.mkdirp(path.dirname(file));
        await fs.promises.copyFile(templateFile, file);
      });
      return Promise.all(promises);
    }
    throw new Error('invalid sub-command');
  }
  static async cli(process: NodeJS.Process) {
    const location = process.cwd();
    const cmd = process.argv.slice(2)[0];
    try {
      await Template.main(location, cmd);
      process.exit(0);
    } catch (e) {
      process.stderr.write(e.message + '\n');
      process.exit(1);
    }
  }
}