UNPKG

create-snippet

Version:
211 lines (210 loc) 8.89 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ModuleSnippet = void 0; const chalk_1 = __importDefault(require("chalk")); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const prompts_1 = require("prompts"); const recursive_readdir_1 = __importDefault(require("recursive-readdir")); const constants_1 = require("../../constants"); const enums_1 = require("../../enums"); const cache_1 = require("../cache"); const config_1 = require("../config"); const path_2 = require("../path"); const string_1 = require("../string"); class ModuleSnippet { moduleConfig; moduleString; rootDirConfig; options; modulePath; moduleCache; constructor() { this.moduleConfig = new config_1.ModuleConfig(); this.moduleString = new string_1.ModuleString(); this.modulePath = new path_2.ModulePath(); this.moduleCache = new cache_1.ModuleCache(); this.rootDirConfig = constants_1.CONSTANTS.ROOT_DIR_CONFIG; this.options = { snippetName: '', name: '', path: '', isFlat: false, suffix: '', prefix: '', }; } async addOptions() { const createQuestions = () => [ { type: 'select', name: 'snippetName', message: 'Pick a snippet', choices: fs_1.default.readdirSync(this.rootDirConfig).map((path) => { return { title: path, value: path }; }), initial: 0, }, { type: 'text', name: 'name', message: `Pick a name`, }, { type: 'text', name: 'path', message: `Pick a path`, initial: (_, values) => this.moduleCache.get(`${values.snippetName}-path`), }, { type: 'toggle', name: 'isFlat', message: 'Create a flat file structure?', initial: false, active: 'yes', inactive: 'no', }, { type: async (_, values) => (await this.check(values.snippetName)).isPrefix ? 'text' : null, name: 'prefix', message: 'Pick a prefix', initial: (_, values) => this.moduleCache.get(`${values.snippetName}-prefix`), }, { type: async (_, values) => (await this.check(values.snippetName)).isSuffix ? 'text' : null, name: 'suffix', message: 'Pick a suffix', initial: (_, values) => this.moduleCache.get(`${values.snippetName}-suffix`), }, ]; const questions = createQuestions(); const options = await (0, prompts_1.prompt)(questions); this.options = { ...this.options, ...options }; } isSnippet(pathDirectoryCreatedSnippet) { return fs_1.default.existsSync(pathDirectoryCreatedSnippet); } createMatches(object, replace) { let matches = {}; Object.keys(object).map((item) => { const stringConversionMethod = `to${item.charAt(0).toUpperCase() + item.slice(1)}`; const myKey = `${object[item]}`; const myValue = this.moduleString[stringConversionMethod](replace); matches = { ...matches, [myKey]: myValue }; }); return matches; } getNumberMatchesString(arraySearchStrings, data) { let counter = 0; arraySearchStrings.forEach((searchString) => { if (new RegExp(searchString).test(data)) counter += 1; }); return counter; } formatSnippet(pathToSnippet) { const matches = { ...this.createMatches(enums_1.enumPrefixName, this.options.prefix), ...this.createMatches(enums_1.enumSnippetName, this.options.name), ...this.createMatches(enums_1.enumSuffixName, this.options.suffix), }; const unformattedSnippet = JSON.stringify(fs_1.default.readFileSync(path_1.default.join(pathToSnippet), 'utf-8')); const regexp = new RegExp(Object.keys(matches).join('|'), 'g'); const formattedSnippet = unformattedSnippet.replace(regexp, (match) => matches[match]); return JSON.parse(formattedSnippet); } async check(pathToSnippet) { const myPaths = await (0, recursive_readdir_1.default)(path_1.default.join(...[this.rootDirConfig, pathToSnippet])); let isPrefix = false; let isSuffix = false; myPaths.forEach((item) => { const data = JSON.stringify(fs_1.default.readFileSync(item, 'utf-8')); const arrayPrefixes = Object.values(enums_1.enumPrefixName); const arraySuffixes = Object.values(enums_1.enumSuffixName); isPrefix = this.getNumberMatchesString(arrayPrefixes, data) > 0; isSuffix = this.getNumberMatchesString(arraySuffixes, data) > 0; }); return { isPrefix, isSuffix }; } async getSnippetVariables(pathToSnippet) { function createRegExp() { return Object.values(enums_1.enumSnippetVariable).map((item) => new RegExp(`${item}\\d+`, 'g')); } const myPaths = await (0, recursive_readdir_1.default)(path_1.default.join(...[this.rootDirConfig, pathToSnippet])); let snippetVariables = []; myPaths.forEach((item) => { const data = JSON.stringify(fs_1.default.readFileSync(item, 'utf-8')); snippetVariables = [ ...createRegExp() .map((item) => data.match(item)) .flat(Infinity) .filter((item) => typeof item === 'string'), ]; }); return snippetVariables; } addOptionsCache() { const { snippetName, path, prefix, suffix } = this.options; const expiration = 30 * 24 * 60 * 60 * 1000; for (const [key, value] of Object.entries({ path, prefix, suffix })) { this.moduleCache.set(`${snippetName}-${key}`, value, expiration); } } async generate() { if (!fs_1.default.existsSync(path_1.default.join(...[this.rootDirConfig]))) throw new Error('npx create-snippet --init'); await this.addOptions(); const { snippetName, name, path } = this.options; if (snippetName === '') throw new Error(`specify the required argument snippet=example`); if (name === '') throw new Error(`specify the required argument name=example`); if (path === '') throw new Error(`specify the required argument path=example`); const config = this.moduleConfig .get() .find((item) => item.snippetName === snippetName); if (!config) throw new Error('config'); (0, recursive_readdir_1.default)(config.pathToSnippet, (error, paths) => { if (error) throw new Error(error.message); paths.forEach((pathToSnippet) => { const data = this.formatSnippet(pathToSnippet); const myPath = this.modulePath.generate({ config, name, path, pathToSnippet, }); const pathSnippetFile = this.options.isFlat ? myPath.pathFlatSnippetFile : myPath.pathSnippetFile; const pathWriteSnippetFile = this.options.isFlat ? myPath.pathFlatWriteSnippetFile : myPath.pathWriteSnippetFile; if (this.isSnippet(pathWriteSnippetFile)) { // eslint-disable-next-line no-console console.log(`${chalk_1.default.red(enums_1.enumSymbol.cross)} ${chalk_1.default.gray(`The files ${myPath.snippetFileName} on the path ${pathWriteSnippetFile} already exist`)}`); } else { fs_1.default.mkdirSync(pathSnippetFile, { recursive: true, }); fs_1.default.writeFileSync(pathWriteSnippetFile, data); this.addOptionsCache(); // eslint-disable-next-line no-console console.log(`${chalk_1.default.green(enums_1.enumSymbol.check)} ${chalk_1.default.gray(myPath.snippetFileName)}`); } }); }); } } exports.ModuleSnippet = ModuleSnippet;