Skip to content

Commit

Permalink
feat(cli): add Button codemods (#596)
Browse files Browse the repository at this point in the history
* feat(utils): compile JSX

* chore(configs): add CJS output

* chore(configs): set up codemod tooling

* feat(cli): add codemods for button props

* feat(cli): add migrate command to CLI

* chore(configs): update commit scopes

* feat(cli): include LoadingButton in transform

* docs(cli): update the --migrate option descriptions

* feat(cli): remove instead of replace flat variant

The flat variant could be used with the primary and secondary variants. It affected the border and shadow, not the color. Mapping it the secondary variant was therefore inaccurate.

* refactor(cli): change transform name to be more specific

* refactor(configs): use specific path for Eslint override
  • Loading branch information
connor-baer authored Jun 4, 2020
1 parent 67fc95c commit 0a6454f
Show file tree
Hide file tree
Showing 11 changed files with 488 additions and 7 deletions.
5 changes: 2 additions & 3 deletions .cz-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@ module.exports = {
{ name: 'components' },
{ name: 'utils' },
{ name: 'docs' },
{ name: 'theme' },
{ name: 'configs' },
{ name: 'scripts' }
{ name: 'cli' },
{ name: 'configs' }
],

allowCustomScopes: true,
Expand Down
15 changes: 14 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ module.exports = require('@sumup/foundry/eslint')(
},
parserOptions: {
project: ['./tsconfig.eslint.json']
}
},
overrides: [
{
files: [
'src/cli/migrate/__testfixtures__/**/*.input.*',
'src/cli/migrate/__testfixtures__/**/*.output.*'
],
rules: {
'import/no-unresolved': 'off',
'notice/notice': 'off',
'@typescript-eslint/no-unused-vars': 'off'
}
}
]
}
);
9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"description": "SumUp's React UI component library",
"main": "dist/cjs/index.js",
"module": "dist/es/index.js",
"bin": {
"circuit-ui": "./dist/cjs/cli/index.js"
},
"files": [
"dist",
"README.md"
Expand All @@ -13,7 +16,7 @@
"commit": "git-cz",
"start": "start-storybook -p 6006 -s .storybook/public",
"dev": "tsc --watch",
"build": "tsc && tsc --project tsconfig.cjs.json",
"build": "tsc && tsc --project tsconfig.cjs.json && chmod +x ./dist/cjs/cli/index.js",
"create:component": "foundry run plop component",
"static-styles": "cross-env BABEL_ENV=static babel-node --extensions '.js,.ts,.tsx' ./scripts/static-styles/cli.js",
"build:docs": "yarn build:storybook && yarn build:stylesheets",
Expand Down Expand Up @@ -54,6 +57,8 @@
},
"homepage": "https://github.com/sumup-oss/circuit-ui#readme",
"dependencies": {
"cross-spawn": "^7.0.3",
"jscodeshift": "^0.9.0",
"lodash": "^4.17.11",
"moment": "^2.24.0",
"no-scroll": "^2.1.1",
Expand Down Expand Up @@ -104,8 +109,10 @@
"@testing-library/react": "^9.1.4",
"@testing-library/react-hooks": "^3.2.1",
"@testing-library/user-event": "^7.0.1",
"@types/cross-spawn": "^6.0.2",
"@types/jest": "^25.2.1",
"@types/jest-axe": "^3.2.2",
"@types/jscodeshift": "^0.7.1",
"@types/lodash": "^4.14.149",
"@types/react": "^16.9.32",
"@types/react-dom": "^16.9.6",
Expand Down
64 changes: 64 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#!/usr/bin/env node

/**
* Copyright 2020, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import yargs from 'yargs';

import { migrate, listTransforms } from './migrate';

type CommandType = 'migrate';

// eslint-disable-next-line @typescript-eslint/no-unused-expressions
yargs
.command(
'migrate',
"Automatically transforms your source code to Circuit UI's latest APIs",
yrgs =>
yrgs
.option('transform', {
alias: 't',
desc: 'The transform to be applied to the source code',
choices: listTransforms(),
type: 'string',
required: true
})
.option('language', {
alias: 'l',
desc: 'The programming language of the files to be transformed',
choices: ['TypeScript', 'JavaScript'],
type: 'string',
required: true
})
.option('path', {
alias: 'p',
desc:
'A path to the folder that contains the files to be transformed',
type: 'string',
default: '.'
}),
args => execute('migrate', args)
)
.showHelpOnFail(true)
.demandCommand(1, '')
.help()
.version().argv;

function execute(command: CommandType, args: any): void {
const commands = { migrate };
const commandFn = commands[command];

commandFn(args);
}
34 changes: 34 additions & 0 deletions src/cli/migrate/__testfixtures__/button-variant-enum.input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React from 'react';
import styled from '@emotion/styled';
import { Button, LoadingButton, Text } from '@sumup/circuit-ui';

const Primary = () => <Button primary>primary</Button>;

const Secondary = () => <Button secondary>Secondary</Button>;

const RedButton = styled(Button)`
color: red;
`;

const BlueButton = styled(Button)`
color: blue;
`;

const BlueText = styled(Text)`
color: blue;
`;

const Styled = () => (
<>
<RedButton secondary>Secondary red</RedButton>
<BlueButton primary>Primary blue</BlueButton>
<Text secondary>Text</Text>
<BlueText secondary>Text blue</BlueText>
</>
);

const Flat = () => <Button flat>Flat</Button>;

const Loading = () => (
<LoadingButton secondary>Secondary Loading Button</LoadingButton>
);
34 changes: 34 additions & 0 deletions src/cli/migrate/__testfixtures__/button-variant-enum.output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React from 'react';
import styled from '@emotion/styled';
import { Button, LoadingButton, Text } from '@sumup/circuit-ui';

const Primary = () => <Button variant="primary">primary</Button>;

const Secondary = () => <Button variant="secondary">Secondary</Button>;

const RedButton = styled(Button)`
color: red;
`;

const BlueButton = styled(Button)`
color: blue;
`;

const BlueText = styled(Text)`
color: blue;
`;

const Styled = () => (
<>
<RedButton variant="secondary">Secondary red</RedButton>
<BlueButton variant="primary">Primary blue</BlueButton>
<Text secondary>Text</Text>
<BlueText secondary>Text blue</BlueText>
</>
);

const Flat = () => <Button>Flat</Button>;

const Loading = () => (
<LoadingButton variant="secondary">Secondary Loading Button</LoadingButton>
);
20 changes: 20 additions & 0 deletions src/cli/migrate/__tests__/transforms.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Copyright 2020, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { defineTest } from 'jscodeshift/dist/testUtils';

jest.autoMockOff();

defineTest(__dirname, 'button-variant-enum');
80 changes: 80 additions & 0 deletions src/cli/migrate/button-variant-enum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* Copyright 2020, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { Transform, JSCodeshift, Collection } from 'jscodeshift';

import { findImportsByPath, findStyledComponentNames } from './utils';

function transformFactory(
j: JSCodeshift,
root: Collection,
buttonName: string
): void {
const imports = findImportsByPath(j, root, '@sumup/circuit-ui');

const buttonImport = imports.find(i => i.name === buttonName);

if (!buttonImport) {
return;
}

const localName = buttonImport.local;

const styledButtons = findStyledComponentNames(j, root, localName);

const components = [localName, ...styledButtons];

components.forEach(component => {
// Change variants from boolean to enum prop
['primary', 'secondary'].forEach(variant => {
root
.findJSXElements(component)
.find(j.JSXAttribute, {
name: {
type: 'JSXIdentifier',
name: variant
}
})
.replaceWith(() =>
j.jsxAttribute(j.jsxIdentifier('variant'), j.stringLiteral(variant))
);
});

// Remove flat variant
root
.findJSXElements(component)
.find(j.JSXAttribute, {
name: {
type: 'JSXIdentifier',
name: 'flat'
}
})
.remove();

// TODO: Replace plain variant with Anchor component
});
}

const transform: Transform = (file, api) => {
const j = api.jscodeshift;
const root = j(file.source);

transformFactory(j, root, 'Button');
transformFactory(j, root, 'LoadingButton');

return root.toSource();
};

export default transform;
64 changes: 64 additions & 0 deletions src/cli/migrate/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Copyright 2020, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import fs from 'fs';
import { sync as spawn } from 'cross-spawn';

export interface MigrateArgs {
transform: string;
language: 'TypeScript' | 'JavaScript';
path: string;
}

const TRANSFORM_DIR = __dirname;
const PARSERS = {
JavaScript: 'babel',
TypeScript: 'tsx'
};

export function migrate({ transform, language, path }: MigrateArgs): void {
const availableTransforms = listTransforms();

if (!availableTransforms.includes(transform)) {
throw new Error(`Unknown codemod ${transform}. Run --help for options.`);
}

if (!['TypeScript', 'JavaScript'].includes(language)) {
throw new Error(`Unknown language ${language}. Run --help for options.`);
}

const parser = PARSERS[language];

spawn(
'npx',
[
'jscodeshift',
'--transform',
`${TRANSFORM_DIR}/${transform}.js`,
'--parser',
parser,
path
],
{ stdio: 'inherit' }
);
}

export function listTransforms(): string[] {
return fs
.readdirSync(TRANSFORM_DIR)
.filter(filename => filename.endsWith('.js'))
.filter(filename => filename !== 'index.js')
.map(filename => filename.replace('.js', ''));
}
Loading

0 comments on commit 0a6454f

Please sign in to comment.