Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cli): make all CLI options available in config #445

Merged
merged 2 commits into from
Apr 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ npx @svgr/cli --icon --replace-attr-values "#063855=currentColor" icon.svg
```js
import * as React from 'react'

const SvgComponent = props => (
const SvgComponent = (props) => (
<svg width="1em" height="1em" viewBox="0 0 48 1" {...props}>
<path d="M0 0h48v1H0z" fill="currentColor" fillRule="evenodd" />
</svg>
Expand Down
4 changes: 2 additions & 2 deletions api/svgr.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ module.exports = (req, res) => {
return
}
svgr(req.body.code, { ...req.body.options, plugins: [svgo, jsx, prettier] })
.then(output => {
.then((output) => {
res.status(200).json({ output })
})
.catch(error => {
.catch((error) => {
res.status(400).json({ error: error.message })
})
}
4 changes: 2 additions & 2 deletions packages/babel-plugin-add-jsx-attribute/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,15 @@ const addJSXAttribute = ({ types: t, template }, opts) => {
const newAttribute = getAttribute({ spread, name, value, literal })
const attributes = path.get('attributes')

const isEqualAttribute = attribute => {
const isEqualAttribute = (attribute) => {
if (spread) {
return attribute.get('argument').isIdentifier({ name })
}

return attribute.get('name').isJSXIdentifier({ name })
}

const replaced = attributes.some(attribute => {
const replaced = attributes.some((attribute) => {
if (!isEqualAttribute(attribute)) return false
attribute.replaceWith(newAttribute)
return true
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-plugin-remove-jsx-attribute/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const removeJSXAttribute = (api, opts) => ({
JSXOpeningElement(path) {
if (!opts.elements.includes(path.node.name.name)) return

path.get('attributes').forEach(attribute => {
path.get('attributes').forEach((attribute) => {
const nodeName = attribute.node.name
if (nodeName && opts.attributes.includes(nodeName.name)) {
attribute.remove()
Expand Down
6 changes: 3 additions & 3 deletions packages/babel-plugin-svg-dynamic-title/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const plugin = ({ types: t }) => ({
visitor: {
JSXElement(path) {
if (
!elements.some(element =>
!elements.some((element) =>
path.get('openingElement.name').isJSXIdentifier({ name: element }),
)
) {
Expand All @@ -28,7 +28,7 @@ const plugin = ({ types: t }) => ({

function enhanceAttributes(attributes) {
const existingId = attributes.find(
attribute => attribute.name.name === 'id',
(attribute) => attribute.name.name === 'id',
)
if (!existingId) {
return [...attributes, createTitleIdAttribute()]
Expand Down Expand Up @@ -89,7 +89,7 @@ const plugin = ({ types: t }) => ({
// store the title element
let titleElement

const hasTitle = path.get('children').some(childPath => {
const hasTitle = path.get('children').some((childPath) => {
if (!childPath.isJSXElement()) return false
if (childPath.node === titleElement) return false
if (childPath.node.openingElement.name.name !== 'title') return false
Expand Down
6 changes: 3 additions & 3 deletions packages/babel-plugin-svg-em-dimensions/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const plugin = ({ types: t }) => ({
JSXOpeningElement: {
enter(path) {
if (
!elements.some(element =>
!elements.some((element) =>
path.get('name').isJSXIdentifier({ name: element }),
)
)
Expand All @@ -14,7 +14,7 @@ const plugin = ({ types: t }) => ({
const requiredAttributes = ['width', 'height']
const attributeValue = '1em'

path.get('attributes').forEach(attributePath => {
path.get('attributes').forEach((attributePath) => {
if (!attributePath.isJSXAttribute()) return
const index = requiredAttributes.indexOf(attributePath.node.name.name)

Expand All @@ -25,7 +25,7 @@ const plugin = ({ types: t }) => ({
requiredAttributes.splice(index, 1)
})

requiredAttributes.forEach(attribute => {
requiredAttributes.forEach((attribute) => {
path.pushContainer(
'attributes',
t.jsxAttribute(
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-plugin-transform-react-native-svg/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ const plugin = ({ types: t }, { expo }) => {
const importDeclarationVisitor = {
ImportDeclaration(path, state) {
if (path.get('source').isStringLiteral({ value: 'react-native-svg' })) {
state.replacedComponents.forEach(component => {
state.replacedComponents.forEach((component) => {
if (
path
.get('specifiers')
.some(specifier =>
.some((specifier) =>
specifier.get('local').isIdentifier({ name: component }),
)
) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { transform } from '@babel/core'
import plugin from '.'

const testPlugin = language => (code, options) => {
const testPlugin = (language) => (code, options) => {
const result = transform(code, {
plugins: [
'@babel/plugin-syntax-jsx',
Expand All @@ -14,7 +14,7 @@ const testPlugin = language => (code, options) => {
}

describe('plugin', () => {
describe.each(['javascript', 'typescript'])('%s', language => {
describe.each(['javascript', 'typescript'])('%s', (language) => {
it('transforms whole program', () => {
const { code } = testPlugin(language)('<svg><g /></svg>', {
state: { componentName: 'SvgComponent' },
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-preset/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ function getAttributeValue(value) {
}

function propsToAttributes(props) {
return Object.keys(props).map(name => {
return Object.keys(props).map((name) => {
const { literal, value } = getAttributeValue(props[name])
return { name, literal, value }
})
}

function replaceMapToValues(replaceMap) {
return Object.keys(replaceMap).map(value => {
return Object.keys(replaceMap).map((value) => {
const { literal, value: newValue } = getAttributeValue(replaceMap[value])
return { value, newValue, literal }
})
Expand Down
38 changes: 27 additions & 11 deletions packages/cli/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,28 @@ import program from 'commander'
import path from 'path'
import glob from 'glob'
import fs from 'fs'
import { loadConfig } from '@svgr/core'
import pkg from '../package.json'
import fileCommand from './fileCommand'
import dirCommand from './dirCommand'
import { stat, exitError } from './util'

function noUndefinedKeys(obj) {
return Object.entries(obj).reduce((obj, [key, value]) => {
if (value !== undefined) {
obj[key] = value
}
return obj
}, {})
}

function parseObject(arg, accumulation = {}) {
const [name, value] = arg.split('=')
return { ...accumulation, [name]: value }
}

function parseObjectList(arg, accumulation = {}) {
const args = arg.split(',').map(str => str.trim())
const args = arg.split(',').map((str) => str.trim())
return args.reduce((acc, arg) => parseObject(arg, acc), accumulation)
}

Expand All @@ -27,7 +37,7 @@ function isFile(filePath) {
}
}

const parseConfig = name => arg => {
const parseConfig = (name) => (arg) => {
const json = isFile(arg) ? fs.readFileSync(arg) : arg
try {
return JSON.parse(json)
Expand Down Expand Up @@ -117,7 +127,7 @@ async function run() {
}, [])

await Promise.all(
filenames.map(async filename => {
filenames.map(async (filename) => {
try {
await stat(filename)
} catch (error) {
Expand All @@ -131,25 +141,30 @@ async function run() {
process.exit(2)
}

const config = { ...program }
const opts = noUndefinedKeys(program.opts())

if (config.expandProps === 'none') {
const config = await loadConfig(opts, { filePath: process.cwd() })

// Back config file
config.configFile = opts.configFile

if (program.expandProps === 'none') {
config.expandProps = false
}

if (config.dimensions === true) {
if (program.dimensions === true) {
delete config.dimensions
}

if (config.svgo === true) {
if (program.svgo === true) {
delete config.svgo
}

if (config.prettier === true) {
if (program.prettier === true) {
delete config.prettier
}

if (config.template) {
if (program.template) {
try {
// eslint-disable-next-line global-require, import/no-dynamic-require
const template = require(path.join(process.cwd(), program.template))
Expand All @@ -165,7 +180,7 @@ async function run() {
}
}

if (config.indexTemplate) {
if (program.indexTemplate) {
try {
// eslint-disable-next-line global-require, import/no-dynamic-require
const indexTemplate = require(path.join(
Expand All @@ -187,10 +202,11 @@ async function run() {
}

const command = program.outDir ? dirCommand : fileCommand

await command(program, filenames, config)
}

run().catch(error => {
run().catch((error) => {
setTimeout(() => {
throw error
})
Expand Down
13 changes: 5 additions & 8 deletions packages/cli/src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const svgr = path.join(__dirname, 'index.js')
const babelNode = path.join(__dirname, '../../../node_modules/.bin/babel-node')

describe('cli', () => {
const cli = async args => {
const cli = async (args) => {
const { stdout } = await exec(`${babelNode} -- ${svgr} ${args}`)
return stdout
}
Expand Down Expand Up @@ -60,7 +60,7 @@ describe('cli', () => {
const sorted = result
.split(/\n/)
.sort()
.map(x => x.toLowerCase())
.map((x) => x.toLowerCase())
.join('\n')
expect(sorted).toMatchSnapshot()
}, 10000)
Expand All @@ -72,7 +72,7 @@ describe('cli', () => {
const sorted = result
.split(/\n/)
.sort()
.map(x => x.toLowerCase())
.map((x) => x.toLowerCase())
.join('\n')
expect(sorted).toMatchSnapshot()
}, 10000)
Expand All @@ -81,10 +81,7 @@ describe('cli', () => {
const result = await cli(
'--silent --out-dir __fixtures_build__/whole __fixtures__',
)
const sorted = result
.split(/\n/)
.sort()
.join('\n')
const sorted = result.split(/\n/).sort().join('\n')
expect(sorted).toMatchSnapshot()
}, 10000)

Expand Down Expand Up @@ -136,7 +133,7 @@ describe('cli', () => {
['--typescript --ref --title-prop'],
])(
'should support various args',
async args => {
async (args) => {
const result = await cli(`${args} __fixtures__/simple/file.svg`)
expect(result).toMatchSnapshot(args)
},
Expand Down
10 changes: 6 additions & 4 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ const svgCode = `
</svg>
`

svgr(svgCode, { icon: true }, { componentName: 'MyComponent' }).then(jsCode => {
console.log(jsCode)
})
svgr(svgCode, { icon: true }, { componentName: 'MyComponent' }).then(
(jsCode) => {
console.log(jsCode)
},
)
```

Use `svgr.sync(code, config, state)` if you would like to use sync version.
Expand All @@ -37,7 +39,7 @@ By default `@svgr/core` doesn't include `svgo` and `prettier` plugins, if you wa
```js
svgr(svgCode, {
plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx', '@svgr/plugin-prettier'],
}).then(jsCode => {
}).then((jsCode) => {
console.log(jsCode)
})
```
Expand Down
8 changes: 0 additions & 8 deletions packages/core/src/__snapshots__/config.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ exports[`svgo async #loadConfig [async] should load config using filePath 1`] =
Object {
"dimensions": true,
"expandProps": "end",
"h2xConfig": null,
"icon": true,
"memo": false,
"native": false,
Expand Down Expand Up @@ -33,7 +32,6 @@ exports[`svgo async #loadConfig [async] should not load config with "runtimeConf
Object {
"dimensions": true,
"expandProps": "end",
"h2xConfig": null,
"icon": true,
"memo": false,
"native": false,
Expand Down Expand Up @@ -63,7 +61,6 @@ exports[`svgo async #loadConfig [async] should use default config without state.
Object {
"dimensions": false,
"expandProps": "end",
"h2xConfig": null,
"icon": false,
"memo": false,
"native": false,
Expand All @@ -86,7 +83,6 @@ exports[`svgo async #loadConfig [async] should work with custom config path 1`]
Object {
"dimensions": true,
"expandProps": "end",
"h2xConfig": null,
"icon": true,
"memo": false,
"native": false,
Expand Down Expand Up @@ -115,7 +111,6 @@ exports[`svgo sync #loadConfig [sync] should load config using filePath 1`] = `
Object {
"dimensions": true,
"expandProps": "end",
"h2xConfig": null,
"icon": true,
"memo": false,
"native": false,
Expand Down Expand Up @@ -144,7 +139,6 @@ exports[`svgo sync #loadConfig [sync] should not load config with "runtimeConfig
Object {
"dimensions": true,
"expandProps": "end",
"h2xConfig": null,
"icon": true,
"memo": false,
"native": false,
Expand Down Expand Up @@ -174,7 +168,6 @@ exports[`svgo sync #loadConfig [sync] should use default config without state.fi
Object {
"dimensions": false,
"expandProps": "end",
"h2xConfig": null,
"icon": false,
"memo": false,
"native": false,
Expand All @@ -197,7 +190,6 @@ exports[`svgo sync #loadConfig [sync] should work with custom config path 1`] =
Object {
"dimensions": true,
"expandProps": "end",
"h2xConfig": null,
"icon": true,
"memo": false,
"native": false,
Expand Down
Loading