all files / tool/ scaffold.js

50.68% Statements 37/73
40% Branches 8/20
50% Functions 4/8
50.68% Lines 37/73
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                                                                                                                                                                                                                                                                                                                         
/**
 * @file
 * @desc scaffold handlers
 * @author liuyuanyangscript@gmail.com
 * @date  2017/08/11
 */
 
const fs = require('fs');
const path = require('path');
 
const fse = require('fs-extra');
const mergeDirs = require('merge-dirs');
 
const pathUtil = require('./path');
const npm = require('./npm');
 
const getNpmPackageVersion = require('get-npm-package-version');
 
const createExecPackageJsonFile = (execInstallFolder, scaffoldName) => {
    const pkgJsonPath = path.join(execInstallFolder, 'package.json');
 
    fse.ensureFileSync(pkgJsonPath);
    fse.writeFileSync(pkgJsonPath, JSON.stringify({
        name: `installing-${scaffoldName}`,
        version: '1.0.0',
    }));
};
 
const getMaps = (() => {
    let shortNameMap = null;
    let fullNameMap = null;
 
    return (scaffoldList) => {
        if (shortNameMap && fullNameMap) {
            return {
                shortNameMap,
                fullNameMap,
            };
        }
 
        shortNameMap = {};
        scaffoldList.forEach((item) => {
            shortNameMap[item.fullName] = item.value;
        });
 
        fullNameMap = {};
        scaffoldList.forEach((item) => {
            fullNameMap[item.value] = item.fullName;
        });
 
        return {
            shortNameMap,
            fullNameMap,
        };
    };
})();
 
module.exports = {
    preInstall() {},
 
    getFullName(scaffoldName) {
        const maps = getMaps(this.scaffoldList);
        const { fullNameMap } = maps;
 
        return fullNameMap[scaffoldName] ? fullNameMap[scaffoldName] : scaffoldName;
    },
 
    getShortName(scaffoldName) {
        const maps = getMaps(this.scaffoldList);
        const { shortNameMap } = maps;
 
        return shortNameMap[scaffoldName] ? shortNameMap[scaffoldName] : scaffoldName;
    },
 
    scaffoldList: [], // TODO: add default scaffolds
 
    /**
     * @func
     * @desc get scaffold name for current project from config file
     * @param {String} cwd: current project dir path
     * @return {String} scaffold name
     */
    getScaffoldName(cwd) {
        const { configName } = pathUtil;
        const configPath = path.join(cwd, configName);
 
        const content = fs.readFileSync(configPath).toString();
 
        const contentObj = JSON.parse(content);
 
        return contentObj.scaffold;
    },
 
    /**
     * @func
     * @desc ensure scaffold latest
     * @param {String} scaffoldName
     */
    ensureScaffoldLatest(scaffoldName) {
        if (!this.isScaffoldExists(scaffoldName)) {
            console.log(`installing scaffold ${scaffoldName}...`);
            this.installScaffold(scaffoldName);
            console.log(`scaffold ${scaffoldName} installed successfully`);
            return;
        }
 
        if (this._isScaffoldOutdate(scaffoldName)) {
            console.log(`updating scaffold ${scaffoldName}...`);
            this.installScaffold(scaffoldName);
            console.log(`scaffold ${scaffoldName} updated successfully`);
        }
    },
 
    /**
     * @func
     * @desc check whether scaffold exists
     * @param {String} scaffoldName
     * @return {Boolean}
     */
    isScaffoldExists(scaffoldName) {
        const pkg = path.join(pathUtil.getScaffoldFolder(scaffoldName), 'package.json');
        Eif (!fs.existsSync(pkg)) {
            console.log(`\n${scaffoldName}/package.json is not found at local\n`);
            return false;
        }
 
        return true;
    },
 
    /**
     * @func
     * @private
     * @desc check whether scaffold is outdated
     * @param {String} scaffoldName
     * @return {Boolean}
     */
    _isScaffoldOutdate(scaffoldName) {
        const packagejsonFilePath = path.join(pathUtil.getScaffoldFolder(scaffoldName), 'package.json');
 
        const obj = JSON.parse(fs.readFileSync(packagejsonFilePath).toString());
 
        const currentVersion = obj.version;
        const latestVersion = getNpmPackageVersion(scaffoldName, { registry: npm.scaffoldRegistry, timeout: 2000 });
 
        if (latestVersion) {
            if (currentVersion !== latestVersion) {
                return true;
            }
            return false;
        }
 
        return false;
    },
 
    /**
     * @func
     * @desc install scaffold
     * @param {String} scaffoldName
     */
    installScaffold(scaffoldName) {
        const execInstallFolder = pathUtil.getScaffoldExecInstallFolder(scaffoldName);
        const scaffoldFolder = pathUtil.getScaffoldFolder(scaffoldName);
        const scaffoldWrapper = pathUtil.getScaffoldWrapper(scaffoldName);
 
        // ensure exec dir
        fse.ensureDirSync(execInstallFolder);
 
        // ensure package.json exists
        createExecPackageJsonFile(execInstallFolder, scaffoldName);
        this.preInstall(execInstallFolder);
 
        require('child_process').execSync(`cd ${execInstallFolder} && npm --registry ${npm.scaffoldRegistry} install ${scaffoldName}@latest`, {
            stdio: 'inherit',
        });
 
        if (fs.existsSync(scaffoldFolder)) {
            fse.removeSync(scaffoldFolder);
        }
 
        // move node_modules
        fse.moveSync(path.join(execInstallFolder, 'node_modules', scaffoldName), path.join(scaffoldWrapper, scaffoldName), {
            overwrite: true,
        });
 
        // merge node_modules
        console.log('merging node_modules...');
        mergeDirs.default(path.join(execInstallFolder, 'node_modules'), path.join(scaffoldFolder, 'node_modules'), 'overwrite');
        console.log('merge node_modules done.');
 
        // remove exec dir
        fse.removeSync(execInstallFolder);
    },
};