UNPKG

script-launcher

Version:

Enhance your package.json scripts with features like: menus, functions, arrays, concurrency and many more.

121 lines (120 loc) 3.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Config = void 0; const fs_1 = require("fs"); const path_1 = require("path"); const deepmerge = require("deepmerge"); const scripts_1 = require("./scripts"); const path = require("path"); class Config { constructor(config) { this.scripts = new scripts_1.Scripts(config.scripts); this.menu = config.menu; this.options = config.options; this.settings = config.settings; } get customFile() { const match = this.options.files.reverse().find(item => (0, path_1.basename)(item) === 'launcher-custom.json'); if (match) return match; return 'launcher-custom.json'; } static load(directory) { const hash = new Set(); let config = new Config(Config.default); let files = Config.default.options.files; let loaded; const loadedFiles = []; if (!(0, fs_1.existsSync)(directory)) throw Error('Directory "' + directory + '" not found.'); do { loaded = 0; for (const file of files) { if (file && !hash.has(file)) { const fullPath = path.join(directory, file); try { if ((0, fs_1.existsSync)((0, path_1.resolve)(fullPath))) { config = config.merge(fullPath); loadedFiles.push(fullPath); } } catch (error) { throw new Error('Error loading config file "' + fullPath + '" ' + error); } hash.add(file); loaded++; } } files = config.options.files; } while (loaded > 0); return { files: loadedFiles, config: config }; } static evaluateShellOption(shellOption, defaultOption) { if (typeof shellOption !== 'object') return shellOption; let shell = shellOption[process.platform]; if (shell !== undefined) return shell; shell = shellOption.default; if (shell !== undefined) return shell; return defaultOption; } merge(file) { const absolutePath = (0, path_1.resolve)(file); const current = { menu: this.menu, options: this.options, scripts: this.scripts.scripts, settings: this.settings }; const config = deepmerge(current, require(absolutePath)); Config.verifyScriptNames(config.scripts); return new Config(config); } static verifyScriptNames(scripts) { const hash = new Set(); for (const key of Object.keys(scripts)) { const value = key.replace(/\$\w+(\:|$)/g, '$1'); if (hash.has(value)) throw new Error("Duplicate object key: '" + key + "'"); hash.add(value); } } static loadConfig(file) { const absolutePath = (0, path_1.resolve)(file); if ((0, fs_1.existsSync)(absolutePath)) { return require(absolutePath); } return {}; } } exports.Config = Config; Config.default = { scripts: {}, menu: { description: '' }, options: { logLevel: 0, limit: 0, dry: false, files: ['launcher-config.json', 'launcher-scripts.json', 'launcher-settings.json', 'launcher-menu.json', 'launcher-custom.json'], script: { shell: true }, glob: {}, menu: { defaultChoice: '', defaultScript: '', defaultSelect: '', confirm: true, timeout: 0, pageSize: 7 } }, settings: {} };