react-starter-kit-cli-cars
Version:
cli companion to react-starter-kit
69 lines (57 loc) • 2.12 kB
JavaScript
import config from 'config.js'
import fs from 'fs-extra'
import path from 'path'
import chalk from 'chalk'
import { execPromise, fileExists, findDir } from 'lib/utils'
import { replaceFilenameRecursive, replaceInFileRecursive } from 'es-replace-text'
import textTransforms from 'lib/text-transforms'
module.exports = {
key: 'comp',
command: 'comp <name> [path]',
helpText: 'scaffold files in src/components/<name>' + '\n' +
' optional path can be specified or else default is src/components/<name>' + '\n' +
' note: only run this inside client dir',
fn(opts) {
const args = opts.args
const name = args._[1]
const specifiedPath = args._[2]
const defaultFolder = 'components'
const templateToCopy = path.resolve(config.COMPONENTS_PATH, 'component')
if (!name) {
return Promise.reject('name required')
}
return execPromise('git rev-parse --show-toplevel')
.then(data => {
const projectRootDir = path.resolve(data.trim())
let destinationDir = (specifiedPath)
? path.resolve('.', specifiedPath)
: findDir(projectRootDir, defaultFolder)
if (!destinationDir) {
destinationDir = path.resolve(projectRootDir, 'src', defaultFolder)
fs.mkdirSync(destinationDir)
}
const targetPath = path.resolve(destinationDir, textTransforms.camelCaseTo(name, '-'))
if (fileExists(targetPath)) {
return Promise.reject(`${targetPath} already exists`)
}
fs.mkdirSync(targetPath)
fs.copySync(templateToCopy, targetPath)
console.log(`created component folder ${name} in ${targetPath}`)
replaceFilenameRecursive(targetPath, {
keyword: /name/,
transform() {
return textTransforms.camelCaseTo(name, '-')
},
})
replaceInFileRecursive(targetPath, {
keyword: /%\[name.*\]/,
filetype: /\.(js|scss)$/,
transform(config) {
const templateStr = config.match[0]
const transformed = textTransforms.commandsFromTemplate(name, templateStr)
return transformed
},
})
})
},
}